Use macro for terminating CONF_PARSER arrays
[freeradius.git] / src / main / listen.c
1 /*
2  * listen.c     Handle socket stuff
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2005,2006  The FreeRADIUS server project
21  * Copyright 2005  Alan DeKok <aland@ox.org>
22  */
23
24 RCSID("$Id$")
25
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/modules.h>
28 #include <freeradius-devel/rad_assert.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/protocol.h>
31 #include <freeradius-devel/modpriv.h>
32
33 #include <freeradius-devel/detail.h>
34
35 #ifdef WITH_UDPFROMTO
36 #include <freeradius-devel/udpfromto.h>
37 #endif
38
39 #ifdef HAVE_SYS_RESOURCE_H
40 #include <sys/resource.h>
41 #endif
42
43 #ifdef HAVE_NET_IF_H
44 #include <net/if.h>
45 #endif
46
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50
51 #ifdef HAVE_SYS_STAT_H
52 #include <sys/stat.h>
53 #endif
54
55 #ifdef DEBUG_PRINT_PACKET
56 static void print_packet(RADIUS_PACKET *packet)
57 {
58         char src[256], dst[256];
59
60         ip_ntoh(&packet->src_ipaddr, src, sizeof(src));
61         ip_ntoh(&packet->dst_ipaddr, dst, sizeof(dst));
62
63         fprintf(stderr, "ID %d: %s %d -> %s %d\n", packet->id,
64                 src, packet->src_port, dst, packet->dst_port);
65
66 }
67 #endif
68
69
70 static rad_listen_t *listen_alloc(TALLOC_CTX *ctx, RAD_LISTEN_TYPE type);
71
72 #ifdef WITH_COMMAND_SOCKET
73 static int command_tcp_recv(rad_listen_t *listener);
74 static int command_tcp_send(rad_listen_t *listener, REQUEST *request);
75 static int command_write_magic(int newfd, listen_socket_t *sock);
76 #endif
77
78 static fr_protocol_t master_listen[];
79
80 /*
81  *      Xlat for %{listen:foo}
82  */
83 static ssize_t xlat_listen(UNUSED void *instance, REQUEST *request,
84                            char const *fmt, char *out,
85                            size_t outlen)
86 {
87         char const *value = NULL;
88         CONF_PAIR *cp;
89
90         if (!fmt || !out || (outlen < 1)) return 0;
91
92         if (!request->listener) {
93                 RWDEBUG("No listener associated with this request");
94                 *out = '\0';
95                 return 0;
96         }
97
98         cp = cf_pair_find(request->listener->cs, fmt);
99         if (!cp || !(value = cf_pair_value(cp))) {
100                 RDEBUG("Listener does not contain config item \"%s\"", fmt);
101                 *out = '\0';
102                 return 0;
103         }
104
105         strlcpy(out, value, outlen);
106
107         return strlen(out);
108 }
109
110 /*
111  *      Find a per-socket client.
112  */
113 RADCLIENT *client_listener_find(rad_listen_t *listener,
114                                 fr_ipaddr_t const *ipaddr, uint16_t src_port)
115 {
116 #ifdef WITH_DYNAMIC_CLIENTS
117         int rcode;
118         REQUEST *request;
119         RADCLIENT *created;
120 #endif
121         time_t now;
122         RADCLIENT *client;
123         RADCLIENT_LIST *clients;
124         listen_socket_t *sock;
125
126         rad_assert(listener != NULL);
127         rad_assert(ipaddr != NULL);
128
129         sock = listener->data;
130         clients = sock->clients;
131
132         /*
133          *      This HAS to have been initialized previously.
134          */
135         rad_assert(clients != NULL);
136
137         client = client_find(clients, ipaddr, sock->proto);
138         if (!client) {
139                 char name[256], buffer[128];
140
141 #ifdef WITH_DYNAMIC_CLIENTS
142         unknown:                /* used only for dynamic clients */
143 #endif
144
145                 /*
146                  *      DoS attack quenching, but only in daemon mode.
147                  *      If they're running in debug mode, show them
148                  *      every packet.
149                  */
150                 if (rad_debug_lvl == 0) {
151                         static time_t last_printed = 0;
152
153                         now = time(NULL);
154                         if (last_printed == now) return NULL;
155
156                         last_printed = now;
157                 }
158
159                 listener->print(listener, name, sizeof(name));
160
161                 radlog(L_ERR, "Ignoring request to %s from unknown client %s port %d"
162 #ifdef WITH_TCP
163                        " proto %s"
164 #endif
165                        , name, inet_ntop(ipaddr->af, &ipaddr->ipaddr,
166                                          buffer, sizeof(buffer)), src_port
167 #ifdef WITH_TCP
168                        , (sock->proto == IPPROTO_UDP) ? "udp" : "tcp"
169 #endif
170                        );
171                 return NULL;
172         }
173
174 #ifndef WITH_DYNAMIC_CLIENTS
175         return client;          /* return the found client. */
176 #else
177
178         /*
179          *      No server defined, and it's not dynamic.  Return it.
180          */
181         if (!client->client_server && !client->dynamic) return client;
182
183         now = time(NULL);
184
185         /*
186          *      It's a dynamically generated client, check it.
187          */
188         if (client->dynamic && (src_port != 0)) {
189 #ifdef HAVE_SYS_STAT_H
190                 char const *filename;
191 #endif
192
193                 /*
194                  *      Lives forever.  Return it.
195                  */
196                 if (client->lifetime == 0) return client;
197
198                 /*
199                  *      Rate-limit the deletion of known clients.
200                  *      This makes them last a little longer, but
201                  *      prevents the server from melting down if (say)
202                  *      10k clients all expire at once.
203                  */
204                 if (now == client->last_new_client) return client;
205
206                 /*
207                  *      It's not dead yet.  Return it.
208                  */
209                 if ((client->created + client->lifetime) > now) return client;
210
211 #ifdef HAVE_SYS_STAT_H
212                 /*
213                  *      The client was read from a file, and the file
214                  *      hasn't changed since the client was created.
215                  *      Just renew the creation time, and continue.
216                  *      We don't need to re-load the same information.
217                  */
218                 if (client->cs &&
219                     (filename = cf_section_filename(client->cs)) != NULL) {
220                         struct stat buf;
221
222                         if ((stat(filename, &buf) >= 0) &&
223                             (buf.st_mtime < client->created)) {
224                                 client->created = now;
225                                 return client;
226                         }
227                 }
228 #endif
229
230
231                 /*
232                  *      This really puts them onto a queue for later
233                  *      deletion.
234                  */
235                 client_delete(clients, client);
236
237                 /*
238                  *      Go find the enclosing network again.
239                  */
240                 client = client_find(clients, ipaddr, sock->proto);
241
242                 /*
243                  *      WTF?
244                  */
245                 if (!client) goto unknown;
246                 if (!client->client_server) goto unknown;
247
248                 /*
249                  *      At this point, 'client' is the enclosing
250                  *      network that configures where dynamic clients
251                  *      can be defined.
252                  */
253                 rad_assert(client->dynamic == 0);
254
255         } else if (!client->dynamic && client->rate_limit) {
256                 /*
257                  *      The IP is unknown, so we've found an enclosing
258                  *      network.  Enable DoS protection.  We only
259                  *      allow one new client per second.  Known
260                  *      clients aren't subject to this restriction.
261                  */
262                 if (now == client->last_new_client) goto unknown;
263         }
264
265         client->last_new_client = now;
266
267         request = request_alloc(NULL);
268         if (!request) goto unknown;
269
270         request->listener = listener;
271         request->client = client;
272         request->packet = rad_recv(NULL, listener->fd, 0x02); /* MSG_PEEK */
273         if (!request->packet) {                         /* badly formed, etc */
274                 talloc_free(request);
275                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
276                 goto unknown;
277         }
278         (void) talloc_steal(request, request->packet);
279         request->reply = rad_alloc_reply(request, request->packet);
280         if (!request->reply) {
281                 talloc_free(request);
282                 goto unknown;
283         }
284         gettimeofday(&request->packet->timestamp, NULL);
285         request->number = 0;
286         request->priority = listener->type;
287         request->server = client->client_server;
288         request->root = &main_config;
289
290         /*
291          *      Run a fake request through the given virtual server.
292          *      Look for FreeRADIUS-Client-IP-Address
293          *               FreeRADIUS-Client-Secret
294          *              ...
295          *
296          *      and create the RADCLIENT structure from that.
297          */
298         RDEBUG("server %s {", request->server);
299
300         rcode = process_authorize(0, request);
301
302         RDEBUG("} # server %s", request->server);
303
304         switch (rcode) {
305         case RLM_MODULE_OK:
306         case RLM_MODULE_UPDATED:
307                 break;
308
309         /*
310          *      Likely a fatal error we want to warn the user about
311          */
312         case RLM_MODULE_INVALID:
313         case RLM_MODULE_FAIL:
314                 ERROR("Virtual-Server %s returned %s, creating dynamic client failed", request->server,
315                       fr_int2str(mod_rcode_table, rcode, "<INVALID>"));
316                 talloc_free(request);
317                 goto unknown;
318
319         /*
320          *      Probably the result of policy, or the client not existing.
321          */
322         default:
323                 DEBUG("Virtual-Server %s returned %s, ignoring client", request->server,
324                       fr_int2str(mod_rcode_table, rcode, "<INVALID>"));
325                 talloc_free(request);
326                 goto unknown;
327         }
328
329         /*
330          *      If the client was updated by rlm_dynamic_clients,
331          *      don't create the client from attribute-value pairs.
332          */
333         if (request->client == client) {
334                 created = client_afrom_request(clients, request);
335         } else {
336                 created = request->client;
337
338                 /*
339                  *      This frees the client if it isn't valid.
340                  */
341                 if (!client_add_dynamic(clients, client, created)) goto unknown;
342         }
343
344         request->server = client->server;
345         exec_trigger(request, NULL, "server.client.add", false);
346
347         talloc_free(request);
348
349         if (!created) goto unknown;
350
351         return created;
352 #endif
353 }
354
355 static int listen_bind(rad_listen_t *this);
356
357
358 /*
359  *      Process and reply to a server-status request.
360  *      Like rad_authenticate and rad_accounting this should
361  *      live in it's own file but it's so small we don't bother.
362  */
363 int rad_status_server(REQUEST *request)
364 {
365         int rcode = RLM_MODULE_OK;
366         DICT_VALUE *dval;
367
368         switch (request->listener->type) {
369 #ifdef WITH_STATS
370         case RAD_LISTEN_NONE:
371 #endif
372         case RAD_LISTEN_AUTH:
373                 dval = dict_valbyname(PW_AUTZ_TYPE, 0, "Status-Server");
374                 if (dval) {
375                         rcode = process_authorize(dval->value, request);
376                 } else {
377                         rcode = RLM_MODULE_OK;
378                 }
379
380                 switch (rcode) {
381                 case RLM_MODULE_OK:
382                 case RLM_MODULE_UPDATED:
383                         request->reply->code = PW_CODE_ACCESS_ACCEPT;
384                         break;
385
386                 case RLM_MODULE_FAIL:
387                 case RLM_MODULE_HANDLED:
388                         request->reply->code = 0; /* don't reply */
389                         break;
390
391                 default:
392                 case RLM_MODULE_REJECT:
393                         request->reply->code = PW_CODE_ACCESS_REJECT;
394                         break;
395                 }
396                 break;
397
398 #ifdef WITH_ACCOUNTING
399         case RAD_LISTEN_ACCT:
400                 dval = dict_valbyname(PW_ACCT_TYPE, 0, "Status-Server");
401                 if (dval) {
402                         rcode = process_accounting(dval->value, request);
403                 } else {
404                         rcode = RLM_MODULE_OK;
405                 }
406
407                 switch (rcode) {
408                 case RLM_MODULE_OK:
409                 case RLM_MODULE_UPDATED:
410                         request->reply->code = PW_CODE_ACCOUNTING_RESPONSE;
411                         break;
412
413                 default:
414                         request->reply->code = 0; /* don't reply */
415                         break;
416                 }
417                 break;
418 #endif
419
420 #ifdef WITH_COA
421                 /*
422                  *      This is a vendor extension.  Suggested by Glen
423                  *      Zorn in IETF 72, and rejected by the rest of
424                  *      the WG.  We like it, so it goes in here.
425                  */
426         case RAD_LISTEN_COA:
427                 dval = dict_valbyname(PW_RECV_COA_TYPE, 0, "Status-Server");
428                 if (dval) {
429                         rcode = process_recv_coa(dval->value, request);
430                 } else {
431                         rcode = RLM_MODULE_OK;
432                 }
433
434                 switch (rcode) {
435                 case RLM_MODULE_OK:
436                 case RLM_MODULE_UPDATED:
437                         request->reply->code = PW_CODE_COA_ACK;
438                         break;
439
440                 default:
441                         request->reply->code = 0; /* don't reply */
442                         break;
443                 }
444                 break;
445 #endif
446
447         default:
448                 return 0;
449         }
450
451 #ifdef WITH_STATS
452         /*
453          *      Full statistics are available only on a statistics
454          *      socket.
455          */
456         if (request->listener->type == RAD_LISTEN_NONE) {
457                 request_stats_reply(request);
458         }
459 #endif
460
461         return 0;
462 }
463
464 #ifdef WITH_TCP
465 static int dual_tcp_recv(rad_listen_t *listener)
466 {
467         int rcode;
468         RADIUS_PACKET   *packet;
469         RAD_REQUEST_FUNP fun = NULL;
470         listen_socket_t *sock = listener->data;
471         RADCLIENT       *client = sock->client;
472
473         rad_assert(client != NULL);
474
475         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
476
477         /*
478          *      Allocate a packet for partial reads.
479          */
480         if (!sock->packet) {
481                 sock->packet = rad_alloc(sock, false);
482                 if (!sock->packet) return 0;
483
484                 sock->packet->sockfd = listener->fd;
485                 sock->packet->src_ipaddr = sock->other_ipaddr;
486                 sock->packet->src_port = sock->other_port;
487                 sock->packet->dst_ipaddr = sock->my_ipaddr;
488                 sock->packet->dst_port = sock->my_port;
489                 sock->packet->proto = sock->proto;
490         }
491
492         /*
493          *      Grab the packet currently being processed.
494          */
495         packet = sock->packet;
496
497         rcode = fr_tcp_read_packet(packet, 0);
498
499         /*
500          *      Still only a partial packet.  Put it back, and return,
501          *      so that we'll read more data when it's ready.
502          */
503         if (rcode == 0) {
504                 return 0;
505         }
506
507         if (rcode == -1) {      /* error reading packet */
508                 char buffer[256];
509
510                 ERROR("Invalid packet from %s port %d, closing socket: %s",
511                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
512                        packet->src_port, fr_strerror());
513         }
514
515         if (rcode < 0) {        /* error or connection reset */
516                 listener->status = RAD_LISTEN_STATUS_EOL;
517
518                 /*
519                  *      Tell the event handler that an FD has disappeared.
520                  */
521                 DEBUG("Client has closed connection");
522                 radius_update_listener(listener);
523
524                 /*
525                  *      Do NOT free the listener here.  It's in use by
526                  *      a request, and will need to hang around until
527                  *      all of the requests are done.
528                  *
529                  *      It is instead free'd in remove_from_request_hash()
530                  */
531                 return 0;
532         }
533
534         /*
535          *      Some sanity checks, based on the packet code.
536          */
537         switch (packet->code) {
538         case PW_CODE_ACCESS_REQUEST:
539                 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
540                 FR_STATS_INC(auth, total_requests);
541                 fun = rad_authenticate;
542                 break;
543
544 #ifdef WITH_ACCOUNTING
545         case PW_CODE_ACCOUNTING_REQUEST:
546                 if (listener->type != RAD_LISTEN_ACCT) goto bad_packet;
547                 FR_STATS_INC(acct, total_requests);
548                 fun = rad_accounting;
549                 break;
550 #endif
551
552         case PW_CODE_STATUS_SERVER:
553                 if (!main_config.status_server) {
554                         FR_STATS_INC(auth, total_unknown_types);
555                         WARN("Ignoring Status-Server request due to security configuration");
556                         rad_free(&sock->packet);
557                         return 0;
558                 }
559                 fun = rad_status_server;
560                 break;
561
562         default:
563         bad_packet:
564                 FR_STATS_INC(auth, total_unknown_types);
565
566                 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
567                       packet->code, client->shortname, packet->src_port);
568                 rad_free(&sock->packet);
569                 return 0;
570         } /* switch over packet types */
571
572         if (!request_receive(NULL, listener, packet, client, fun)) {
573                 FR_STATS_INC(auth, total_packets_dropped);
574                 rad_free(&sock->packet);
575                 return 0;
576         }
577
578         sock->packet = NULL;    /* we have no need for more partial reads */
579         return 1;
580 }
581
582
583 static int dual_tcp_accept(rad_listen_t *listener)
584 {
585         int newfd;
586         uint16_t src_port;
587         rad_listen_t *this;
588         socklen_t salen;
589         struct sockaddr_storage src;
590         listen_socket_t *sock;
591         fr_ipaddr_t src_ipaddr;
592         RADCLIENT *client = NULL;
593
594         salen = sizeof(src);
595
596         DEBUG2(" ... new connection request on TCP socket");
597
598         newfd = accept(listener->fd, (struct sockaddr *) &src, &salen);
599         if (newfd < 0) {
600                 /*
601                  *      Non-blocking sockets must handle this.
602                  */
603 #ifdef EWOULDBLOCK
604                 if (errno == EWOULDBLOCK) {
605                         return 0;
606                 }
607 #endif
608
609                 DEBUG2(" ... failed to accept connection");
610                 return -1;
611         }
612
613         if (!fr_sockaddr2ipaddr(&src, salen, &src_ipaddr, &src_port)) {
614                 close(newfd);
615                 DEBUG2(" ... unknown address family");
616                 return 0;
617         }
618
619         /*
620          *      Enforce client IP address checks on accept, not on
621          *      every packet.
622          */
623         if ((client = client_listener_find(listener,
624                                            &src_ipaddr, src_port)) == NULL) {
625                 close(newfd);
626                 FR_STATS_INC(auth, total_invalid_requests);
627                 return 0;
628         }
629
630 #ifdef WITH_TLS
631         /*
632          *      Enforce security restrictions.
633          *
634          *      This shouldn't be necessary in practice.  However, it
635          *      serves as a double-check on configurations.  Marking a
636          *      client as "tls required" means that any accidental
637          *      exposure of the client to non-TLS traffic is
638          *      prevented.
639          */
640         if (client->tls_required && !listener->tls) {
641                 INFO("Ignoring connection to TLS socket from non-TLS client");
642                 close(newfd);
643                 return 0;
644         }
645 #endif
646
647         /*
648          *      Enforce max_connections on client && listen section.
649          */
650         if ((client->limit.max_connections != 0) &&
651             (client->limit.max_connections == client->limit.num_connections)) {
652                 /*
653                  *      FIXME: Print client IP/port, and server IP/port.
654                  */
655                 INFO("Ignoring new connection due to client max_connections (%d)", client->limit.max_connections);
656                 close(newfd);
657                 return 0;
658         }
659
660         sock = listener->data;
661         if ((sock->limit.max_connections != 0) &&
662             (sock->limit.max_connections == sock->limit.num_connections)) {
663                 /*
664                  *      FIXME: Print client IP/port, and server IP/port.
665                  */
666                 INFO("Ignoring new connection due to socket max_connections");
667                 close(newfd);
668                 return 0;
669         }
670         client->limit.num_connections++;
671         sock->limit.num_connections++;
672
673         /*
674          *      Add the new listener.  We require a new context here,
675          *      because the allocations for the packet, etc. in the
676          *      child listener will be done in a child thread.
677          */
678         this = listen_alloc(NULL, listener->type);
679         if (!this) return -1;
680
681         /*
682          *      Copy everything, including the pointer to the socket
683          *      information.
684          */
685         sock = this->data;
686         memcpy(this->data, listener->data, sizeof(*sock));
687         memcpy(this, listener, sizeof(*this));
688         this->next = NULL;
689         this->data = sock;      /* fix it back */
690
691         sock->parent = listener->data;
692         sock->other_ipaddr = src_ipaddr;
693         sock->other_port = src_port;
694         sock->client = client;
695         sock->opened = sock->last_packet = time(NULL);
696
697         /*
698          *      Set the limits.  The defaults are the parent limits.
699          *      Client limits on max_connections are enforced dynamically.
700          *      Set the MINIMUM of client/socket idle timeout or lifetime.
701          */
702         memcpy(&sock->limit, &sock->parent->limit, sizeof(sock->limit));
703
704         if (client->limit.idle_timeout &&
705             ((sock->limit.idle_timeout == 0) ||
706              (client->limit.idle_timeout < sock->limit.idle_timeout))) {
707                 sock->limit.idle_timeout = client->limit.idle_timeout;
708         }
709
710         if (client->limit.lifetime &&
711             ((sock->limit.lifetime == 0) ||
712              (client->limit.lifetime < sock->limit.lifetime))) {
713                 sock->limit.lifetime = client->limit.lifetime;
714         }
715
716         this->fd = newfd;
717         this->status = RAD_LISTEN_STATUS_INIT;
718
719         this->parent = listener;
720         if (!rbtree_insert(listener->children, this)) {
721                 ERROR("Failed inserting TCP socket into parent list.");
722         }
723
724 #ifdef WITH_COMMAND_SOCKET
725         if (this->type == RAD_LISTEN_COMMAND) {
726                 this->recv = command_tcp_recv;
727                 this->send = command_tcp_send;
728                 command_write_magic(this->fd, sock);
729         } else
730 #endif
731         {
732
733                 this->recv = dual_tcp_recv;
734
735 #ifdef WITH_TLS
736                 if (this->tls) {
737                         this->recv = dual_tls_recv;
738                         this->send = dual_tls_send;
739                 }
740 #endif
741         }
742
743         /*
744          *      FIXME: set O_NONBLOCK on the accept'd fd.
745          *      See djb's portability rants for details.
746          */
747
748         /*
749          *      Tell the event loop that we have a new FD.
750          *      This can be called from a child thread...
751          */
752         radius_update_listener(this);
753
754         return 0;
755 }
756 #endif
757
758 /*
759  *      Ensure that we always keep the correct counters.
760  */
761 #ifdef WITH_TCP
762 static void common_socket_free(rad_listen_t *this)
763 {
764         listen_socket_t *sock = this->data;
765
766         if (sock->proto != IPPROTO_TCP) return;
767
768         /*
769          *      Decrement the number of connections.
770          */
771         if (sock->parent && (sock->parent->limit.num_connections > 0)) {
772                 sock->parent->limit.num_connections--;
773         }
774         if (sock->client && sock->client->limit.num_connections > 0) {
775                 sock->client->limit.num_connections--;
776         }
777         if (sock->home && sock->home->limit.num_connections > 0) {
778                 sock->home->limit.num_connections--;
779         }
780 }
781 #else
782 #define common_socket_free NULL
783 #endif
784
785 /*
786  *      This function is stupid and complicated.
787  */
788 int common_socket_print(rad_listen_t const *this, char *buffer, size_t bufsize)
789 {
790         size_t len;
791         listen_socket_t *sock = this->data;
792         char const *name = master_listen[this->type].name;
793
794 #define FORWARD len = strlen(buffer); if (len >= (bufsize + 1)) return 0;buffer += len;bufsize -= len
795 #define ADDSTRING(_x) strlcpy(buffer, _x, bufsize);FORWARD
796
797         ADDSTRING(name);
798
799         if (this->dual) {
800                 ADDSTRING("+acct");
801         }
802
803         if (sock->interface) {
804                 ADDSTRING(" interface ");
805                 ADDSTRING(sock->interface);
806         }
807
808 #ifdef WITH_TCP
809         if (this->recv == dual_tcp_accept) {
810                 ADDSTRING(" proto tcp");
811         }
812 #endif
813
814 #ifdef WITH_TCP
815         /*
816          *      TCP sockets get printed a little differently, to make
817          *      it clear what's going on.
818          */
819         if (sock->client) {
820                 ADDSTRING(" from client (");
821                 ip_ntoh(&sock->other_ipaddr, buffer, bufsize);
822                 FORWARD;
823
824                 ADDSTRING(", ");
825                 snprintf(buffer, bufsize, "%d", sock->other_port);
826                 FORWARD;
827                 ADDSTRING(") -> (");
828
829                 if ((sock->my_ipaddr.af == AF_INET) &&
830                     (sock->my_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
831                         strlcpy(buffer, "*", bufsize);
832                 } else {
833                         ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
834                 }
835                 FORWARD;
836
837                 ADDSTRING(", ");
838                 snprintf(buffer, bufsize, "%d", sock->my_port);
839                 FORWARD;
840
841                 if (this->server) {
842                         ADDSTRING(", virtual-server=");
843                         ADDSTRING(this->server);
844                 }
845
846                 ADDSTRING(")");
847
848                 return 1;
849         }
850
851 #ifdef WITH_PROXY
852         /*
853          *      Maybe it's a socket that we opened to a home server.
854          */
855         if ((sock->proto == IPPROTO_TCP) &&
856             (this->type == RAD_LISTEN_PROXY)) {
857                 ADDSTRING(" (");
858                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
859                 FORWARD;
860
861                 ADDSTRING(", ");
862                 snprintf(buffer, bufsize, "%d", sock->my_port);
863                 FORWARD;
864                 ADDSTRING(") -> home_server (");
865
866                 if ((sock->other_ipaddr.af == AF_INET) &&
867                     (sock->other_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
868                         strlcpy(buffer, "*", bufsize);
869                 } else {
870                         ip_ntoh(&sock->other_ipaddr, buffer, bufsize);
871                 }
872                 FORWARD;
873
874                 ADDSTRING(", ");
875                 snprintf(buffer, bufsize, "%d", sock->other_port);
876                 FORWARD;
877
878                 ADDSTRING(")");
879
880                 return 1;
881         }
882 #endif  /* WITH_PROXY */
883 #endif  /* WITH_TCP */
884
885         ADDSTRING(" address ");
886
887         if ((sock->my_ipaddr.af == AF_INET) &&
888             (sock->my_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
889                 strlcpy(buffer, "*", bufsize);
890         } else {
891                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
892         }
893         FORWARD;
894
895         ADDSTRING(" port ");
896         snprintf(buffer, bufsize, "%d", sock->my_port);
897         FORWARD;
898
899 #ifdef WITH_TLS
900         if (this->tls) {
901                 ADDSTRING(" (TLS)");
902                 FORWARD;
903         }
904 #endif
905
906         if (this->server) {
907                 ADDSTRING(" bound to server ");
908                 strlcpy(buffer, this->server, bufsize);
909         }
910
911 #undef ADDSTRING
912 #undef FORWARD
913
914         return 1;
915 }
916
917 static CONF_PARSER performance_config[] = {
918         { "skip_duplicate_checks", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rad_listen_t, nodup), NULL },
919
920         { "synchronous", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rad_listen_t, synchronous), NULL },
921
922         { "workers", FR_CONF_OFFSET(PW_TYPE_INTEGER, rad_listen_t, workers), NULL },
923         CONF_PARSER_TERMINATOR
924 };
925
926
927 static CONF_PARSER limit_config[] = {
928         { "max_pps", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, max_rate), NULL },
929
930 #ifdef WITH_TCP
931         { "max_connections", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.max_connections), "16" },
932         { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.lifetime), "0" },
933         { "idle_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.idle_timeout), STRINGIFY(30) },
934 #endif
935         CONF_PARSER_TERMINATOR
936 };
937
938
939 #ifdef WITH_TCP
940 /*
941  *      TLS requires child threads to handle the listeners.  Which
942  *      means that we need a separate talloc context per child thread.
943  *      Which means that we need to manually clean up the child
944  *      listeners.  Which means we need to manually track them.
945  *
946  *      All child thread linking/unlinking is done in the master
947  *      thread.  If we care, we can later add a mutex for the parent
948  *      listener.
949  */
950 static int listener_cmp(void const *one, void const *two)
951 {
952         if (one < two) return -1;
953         if (one > two) return +1;
954         return 0;
955 }
956
957 static int listener_unlink(UNUSED void *ctx, UNUSED void *data)
958 {
959         return 2;               /* unlink this node from the tree */
960 }
961 #endif
962
963
964 /*
965  *      Parse an authentication or accounting socket.
966  */
967 int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
968 {
969         int             rcode;
970         uint16_t        listen_port;
971         fr_ipaddr_t     ipaddr;
972         listen_socket_t *sock = this->data;
973         char const      *section_name = NULL;
974         CONF_SECTION    *client_cs, *parentcs;
975         CONF_SECTION    *subcs;
976         CONF_PAIR       *cp;
977
978         this->cs = cs;
979
980         /*
981          *      Try IPv4 first
982          */
983         memset(&ipaddr, 0, sizeof(ipaddr));
984         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
985
986         rcode = cf_item_parse(cs, "ipaddr", FR_ITEM_POINTER(PW_TYPE_COMBO_IP_ADDR, &ipaddr), NULL);
987         if (rcode < 0) return -1;
988         if (rcode != 0) rcode = cf_item_parse(cs, "ipv4addr", FR_ITEM_POINTER(PW_TYPE_IPV4_ADDR, &ipaddr), NULL);
989         if (rcode < 0) return -1;
990         if (rcode != 0) rcode = cf_item_parse(cs, "ipv6addr", FR_ITEM_POINTER(PW_TYPE_IPV6_ADDR, &ipaddr), NULL);
991         if (rcode < 0) return -1;
992         if (rcode != 0) {
993                 cf_log_err_cs(cs, "No address specified in listen section");
994                 return -1;
995         }
996
997         rcode = cf_item_parse(cs, "port", FR_ITEM_POINTER(PW_TYPE_SHORT, &listen_port), "0");
998         if (rcode < 0) return -1;
999
1000         sock->proto = IPPROTO_UDP;
1001
1002         if (cf_pair_find(cs, "proto")) {
1003 #ifndef WITH_TCP
1004                 cf_log_err_cs(cs,
1005                            "System does not support the TCP protocol.  Delete this line from the configuration file");
1006                 return -1;
1007 #else
1008                 char const *proto = NULL;
1009 #ifdef WITH_TLS
1010                 CONF_SECTION *tls;
1011 #endif
1012
1013                 rcode = cf_item_parse(cs, "proto", FR_ITEM_POINTER(PW_TYPE_STRING, &proto), "udp");
1014                 if (rcode < 0) return -1;
1015
1016                 if (!proto || strcmp(proto, "udp") == 0) {
1017                         sock->proto = IPPROTO_UDP;
1018
1019                 } else if (strcmp(proto, "tcp") == 0) {
1020                         sock->proto = IPPROTO_TCP;
1021                 } else {
1022                         cf_log_err_cs(cs,
1023                                    "Unknown proto name \"%s\"", proto);
1024                         return -1;
1025                 }
1026
1027                 /*
1028                  *      TCP requires a destination IP for sockets.
1029                  *      UDP doesn't, so it's allowed.
1030                  */
1031 #ifdef WITH_PROXY
1032                 if ((this->type == RAD_LISTEN_PROXY) &&
1033                     (sock->proto != IPPROTO_UDP)) {
1034                         cf_log_err_cs(cs,
1035                                    "Proxy listeners can only listen on proto = udp");
1036                         return -1;
1037                 }
1038 #endif  /* WITH_PROXY */
1039
1040 #ifdef WITH_TLS
1041                 tls = cf_section_sub_find(cs, "tls");
1042
1043                 if (tls) {
1044                         /*
1045                          *      Don't allow TLS configurations for UDP sockets.
1046                          */
1047                         if (sock->proto != IPPROTO_TCP) {
1048                                 cf_log_err_cs(cs,
1049                                               "TLS transport is not available for UDP sockets");
1050                                 return -1;
1051                         }
1052
1053                         /*
1054                          *      If unset, set to default.
1055                          */
1056                         if (listen_port == 0) listen_port = PW_RADIUS_TLS_PORT;
1057
1058                         this->tls = tls_server_conf_parse(tls);
1059                         if (!this->tls) {
1060                                 return -1;
1061                         }
1062
1063 #ifdef HAVE_PTRHEAD_H
1064                         if (pthread_mutex_init(&sock->mutex, NULL) < 0) {
1065                                 rad_assert(0 == 1);
1066                                 listen_free(&this);
1067                                 return 0;
1068                         }
1069 #endif
1070
1071                 }
1072 #else  /* WITH_TLS */
1073                 /*
1074                  *      Built without TLS.  Disallow it.
1075                  */
1076                 if (cf_section_sub_find(cs, "tls")) {
1077                         cf_log_err_cs(cs,
1078                                    "TLS transport is not available in this executable");
1079                         return -1;
1080                 }
1081 #endif  /* WITH_TLS */
1082
1083 #endif  /* WITH_TCP */
1084
1085                 /*
1086                  *      No "proto" field.  Disallow TLS.
1087                  */
1088         } else if (cf_section_sub_find(cs, "tls")) {
1089                 cf_log_err_cs(cs,
1090                            "TLS transport is not available in this \"listen\" section");
1091                 return -1;
1092         }
1093
1094         /*
1095          *      Magical tuning methods!
1096          */
1097         subcs = cf_section_sub_find(cs, "performance");
1098         if (subcs) {
1099                 rcode = cf_section_parse(subcs, this,
1100                                          performance_config);
1101                 if (rcode < 0) return -1;
1102
1103                 if (this->synchronous && sock->max_rate) {
1104                         WARN("Setting 'max_pps' is incompatible with 'synchronous'.  Disabling 'max_pps'");
1105                         sock->max_rate = 0;
1106                 }
1107
1108                 if (!this->synchronous && this->workers) {
1109                         WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
1110                         this->workers = 0;
1111                 }
1112         }
1113
1114         subcs = cf_section_sub_find(cs, "limit");
1115         if (subcs) {
1116                 rcode = cf_section_parse(subcs, sock,
1117                                          limit_config);
1118                 if (rcode < 0) return -1;
1119
1120                 if (sock->max_rate && ((sock->max_rate < 10) || (sock->max_rate > 1000000))) {
1121                         cf_log_err_cs(cs,
1122                                       "Invalid value for \"max_pps\"");
1123                         return -1;
1124                 }
1125
1126 #ifdef WITH_TCP
1127                 if ((sock->limit.idle_timeout > 0) && (sock->limit.idle_timeout < 5)) {
1128                         WARN("Setting idle_timeout to 5");
1129                         sock->limit.idle_timeout = 5;
1130                 }
1131
1132                 if ((sock->limit.lifetime > 0) && (sock->limit.lifetime < 5)) {
1133                         WARN("Setting lifetime to 5");
1134                         sock->limit.lifetime = 5;
1135                 }
1136
1137                 if ((sock->limit.lifetime > 0) && (sock->limit.idle_timeout > sock->limit.lifetime)) {
1138                         WARN("Setting idle_timeout to 0");
1139                         sock->limit.idle_timeout = 0;
1140                 }
1141
1142                 /*
1143                  *      Force no duplicate detection for TCP sockets.
1144                  */
1145                 if (sock->proto == IPPROTO_TCP) {
1146                         this->nodup = true;
1147                 }
1148
1149         } else {
1150                 sock->limit.max_connections = 60;
1151                 sock->limit.idle_timeout = 30;
1152                 sock->limit.lifetime = 0;
1153 #endif
1154         }
1155
1156         sock->my_ipaddr = ipaddr;
1157         sock->my_port = listen_port;
1158
1159 #ifdef WITH_PROXY
1160         if (check_config) {
1161                 /*
1162                  *      Until there is a side effects free way of forwarding a
1163                  *      request to another virtual server, this check is invalid,
1164                  *      and should be left disabled.
1165                  */
1166 #if 0
1167                 if (home_server_find(&sock->my_ipaddr, sock->my_port, sock->proto)) {
1168                                 char buffer[128];
1169
1170                                 ERROR("We have been asked to listen on %s port %d, which is also listed as a "
1171                                        "home server.  This can create a proxy loop",
1172                                        ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)), sock->my_port);
1173                                 return -1;
1174                 }
1175 #endif
1176                 return 0;       /* don't do anything */
1177         }
1178 #endif
1179
1180         /*
1181          *      If we can bind to interfaces, do so,
1182          *      else don't.
1183          */
1184         cp = cf_pair_find(cs, "interface");
1185         if (cp) {
1186                 char const *value = cf_pair_value(cp);
1187                 if (!value) {
1188                         cf_log_err_cs(cs,
1189                                    "No interface name given");
1190                         return -1;
1191                 }
1192                 sock->interface = value;
1193         }
1194
1195 #ifdef WITH_DHCP
1196         /*
1197          *      If we can do broadcasts..
1198          */
1199         cp = cf_pair_find(cs, "broadcast");
1200         if (cp) {
1201 #ifndef SO_BROADCAST
1202                 cf_log_err_cs(cs,
1203                            "System does not support broadcast sockets.  Delete this line from the configuration file");
1204                 return -1;
1205 #else
1206                 if (this->type != RAD_LISTEN_DHCP) {
1207                         cf_log_err_cp(cp,
1208                                    "Broadcast can only be set for DHCP listeners.  Delete this line from the configuration file");
1209                         return -1;
1210                 }
1211
1212                 char const *value = cf_pair_value(cp);
1213                 if (!value) {
1214                         cf_log_err_cs(cs,
1215                                    "No broadcast value given");
1216                         return -1;
1217                 }
1218
1219                 /*
1220                  *      Hack... whatever happened to cf_section_parse?
1221                  */
1222                 sock->broadcast = (strcmp(value, "yes") == 0);
1223 #endif
1224         }
1225 #endif
1226
1227         /*
1228          *      And bind it to the port.
1229          */
1230         if (listen_bind(this) < 0) {
1231                 char buffer[128];
1232                 cf_log_err_cs(cs,
1233                            "Error binding to port for %s port %d",
1234                            ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)),
1235                            sock->my_port);
1236                 return -1;
1237         }
1238
1239 #ifdef WITH_PROXY
1240         /*
1241          *      Proxy sockets don't have clients.
1242          */
1243         if (this->type == RAD_LISTEN_PROXY) return 0;
1244 #endif
1245
1246         /*
1247          *      The more specific configurations are preferred to more
1248          *      generic ones.
1249          */
1250         client_cs = NULL;
1251         parentcs = cf_top_section(cs);
1252         rcode = cf_item_parse(cs, "clients", FR_ITEM_POINTER(PW_TYPE_STRING, &section_name), NULL);
1253         if (rcode < 0) return -1; /* bad string */
1254         if (rcode == 0) {
1255                 /*
1256                  *      Explicit list given: use it.
1257                  */
1258                 client_cs = cf_section_sub_find_name2(parentcs, "clients", section_name);
1259                 if (!client_cs) {
1260                         client_cs = cf_section_find(section_name);
1261                 }
1262                 if (!client_cs) {
1263                         cf_log_err_cs(cs,
1264                                    "Failed to find clients %s {...}",
1265                                    section_name);
1266                         return -1;
1267                 }
1268         } /* else there was no "clients = " entry. */
1269
1270         /*
1271          *      The "listen" section wasn't given an explicit client list.
1272          *      Look for (a) clients in this virtual server, or
1273          *      (b) the global client list.
1274          */
1275         if (!client_cs) {
1276                 CONF_SECTION *server_cs;
1277
1278                 server_cs = cf_section_sub_find_name2(parentcs,
1279                                                       "server",
1280                                                       this->server);
1281                 /*
1282                  *      Found a "server foo" section.  If there are clients
1283                  *      in it, use them.
1284                  */
1285                 if (server_cs &&
1286                     (cf_section_sub_find(server_cs, "client") != NULL)) {
1287                         client_cs = server_cs;
1288                 }
1289         }
1290
1291         /*
1292          *      Still nothing.  Look for global clients.
1293          */
1294         if (!client_cs) client_cs = parentcs;
1295
1296 #ifdef WITH_TLS
1297         sock->clients = client_list_parse_section(client_cs, (this->tls != NULL));
1298 #else
1299         sock->clients = client_list_parse_section(client_cs, false);
1300 #endif
1301         if (!sock->clients) {
1302                 cf_log_err_cs(cs,
1303                            "Failed to load clients for this listen section");
1304                 return -1;
1305         }
1306
1307 #ifdef WITH_TCP
1308         if (sock->proto == IPPROTO_TCP) {
1309                 /*
1310                  *      Re-write the listener receive function to
1311                  *      allow us to accept the socket.
1312                  */
1313                 this->recv = dual_tcp_accept;
1314
1315                 this->children = rbtree_create(this, listener_cmp, NULL, 0);
1316                 if (!this->children) {
1317                         cf_log_err_cs(cs, "Failed to create child list for TCP socket.");
1318                         return -1;
1319                 }
1320         }
1321 #endif
1322
1323         return 0;
1324 }
1325
1326 /*
1327  *      Send an authentication response packet
1328  */
1329 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
1330 {
1331         rad_assert(request->listener == listener);
1332         rad_assert(listener->send == auth_socket_send);
1333
1334         if (request->reply->code == 0) return 0;
1335
1336 #ifdef WITH_UDPFROMTO
1337         /*
1338          *      Overwrite the src ip address on the outbound packet
1339          *      with the one specified by the client.
1340          *      This is useful to work around broken DSR implementations
1341          *      and other routing issues.
1342          */
1343         if (request->client->src_ipaddr.af != AF_UNSPEC) {
1344                 request->reply->src_ipaddr = request->client->src_ipaddr;
1345         }
1346 #endif
1347
1348         if (rad_send(request->reply, request->packet,
1349                      request->client->secret) < 0) {
1350                 RERROR("Failed sending reply: %s",
1351                                fr_strerror());
1352                 return -1;
1353         }
1354
1355         return 0;
1356 }
1357
1358
1359 #ifdef WITH_ACCOUNTING
1360 /*
1361  *      Send an accounting response packet (or not)
1362  */
1363 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
1364 {
1365         rad_assert(request->listener == listener);
1366         rad_assert(listener->send == acct_socket_send);
1367
1368         /*
1369          *      Accounting reject's are silently dropped.
1370          *
1371          *      We do it here to avoid polluting the rest of the
1372          *      code with this knowledge
1373          */
1374         if (request->reply->code == 0) return 0;
1375
1376 #ifdef WITH_UDPFROMTO
1377         /*
1378          *      Overwrite the src ip address on the outbound packet
1379          *      with the one specified by the client.
1380          *      This is useful to work around broken DSR implementations
1381          *      and other routing issues.
1382          */
1383         if (request->client->src_ipaddr.af != AF_UNSPEC) {
1384                 request->reply->src_ipaddr = request->client->src_ipaddr;
1385         }
1386 #endif
1387
1388         if (rad_send(request->reply, request->packet,
1389                      request->client->secret) < 0) {
1390                 RERROR("Failed sending reply: %s",
1391                                fr_strerror());
1392                 return -1;
1393         }
1394
1395         return 0;
1396 }
1397 #endif
1398
1399 #ifdef WITH_PROXY
1400 /*
1401  *      Send a packet to a home server.
1402  *
1403  *      FIXME: have different code for proxy auth & acct!
1404  */
1405 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
1406 {
1407         rad_assert(request->proxy_listener == listener);
1408         rad_assert(listener->send == proxy_socket_send);
1409
1410         if (rad_send(request->proxy, NULL,
1411                      request->home_server->secret) < 0) {
1412                 RERROR("Failed sending proxied request: %s",
1413                                fr_strerror());
1414                 return -1;
1415         }
1416
1417         return 0;
1418 }
1419 #endif
1420
1421 #ifdef WITH_STATS
1422 /*
1423  *      Check if an incoming request is "ok"
1424  *
1425  *      It takes packets, not requests.  It sees if the packet looks
1426  *      OK.  If so, it does a number of sanity checks on it.
1427   */
1428 static int stats_socket_recv(rad_listen_t *listener)
1429 {
1430         ssize_t         rcode;
1431         int             code;
1432         uint16_t        src_port;
1433         RADIUS_PACKET   *packet;
1434         RADCLIENT       *client = NULL;
1435         fr_ipaddr_t     src_ipaddr;
1436
1437         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1438         if (rcode < 0) return 0;
1439
1440         FR_STATS_INC(auth, total_requests);
1441
1442         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1443                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1444                 FR_STATS_INC(auth, total_malformed_requests);
1445                 return 0;
1446         }
1447
1448         if ((client = client_listener_find(listener,
1449                                            &src_ipaddr, src_port)) == NULL) {
1450                 rad_recv_discard(listener->fd);
1451                 FR_STATS_INC(auth, total_invalid_requests);
1452                 return 0;
1453         }
1454
1455         FR_STATS_TYPE_INC(client->auth.total_requests);
1456
1457         /*
1458          *      We only understand Status-Server on this socket.
1459          */
1460         if (code != PW_CODE_STATUS_SERVER) {
1461                 DEBUG("Ignoring packet code %d sent to Status-Server port",
1462                       code);
1463                 rad_recv_discard(listener->fd);
1464                 FR_STATS_INC(auth, total_unknown_types);
1465                 return 0;
1466         }
1467
1468         /*
1469          *      Now that we've sanity checked everything, receive the
1470          *      packet.
1471          */
1472         packet = rad_recv(NULL, listener->fd, 1); /* require message authenticator */
1473         if (!packet) {
1474                 FR_STATS_INC(auth, total_malformed_requests);
1475                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1476                 return 0;
1477         }
1478
1479         if (!request_receive(NULL, listener, packet, client, rad_status_server)) {
1480                 FR_STATS_INC(auth, total_packets_dropped);
1481                 rad_free(&packet);
1482                 return 0;
1483         }
1484
1485         return 1;
1486 }
1487 #endif
1488
1489
1490 /*
1491  *      Check if an incoming request is "ok"
1492  *
1493  *      It takes packets, not requests.  It sees if the packet looks
1494  *      OK.  If so, it does a number of sanity checks on it.
1495   */
1496 static int auth_socket_recv(rad_listen_t *listener)
1497 {
1498         ssize_t         rcode;
1499         int             code;
1500         uint16_t        src_port;
1501         RADIUS_PACKET   *packet;
1502         RAD_REQUEST_FUNP fun = NULL;
1503         RADCLIENT       *client = NULL;
1504         fr_ipaddr_t     src_ipaddr;
1505         TALLOC_CTX      *ctx;
1506
1507         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1508         if (rcode < 0) return 0;
1509
1510         FR_STATS_INC(auth, total_requests);
1511
1512         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1513                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1514                 FR_STATS_INC(auth, total_malformed_requests);
1515                 return 0;
1516         }
1517
1518         if ((client = client_listener_find(listener,
1519                                            &src_ipaddr, src_port)) == NULL) {
1520                 rad_recv_discard(listener->fd);
1521                 FR_STATS_INC(auth, total_invalid_requests);
1522                 return 0;
1523         }
1524
1525         FR_STATS_TYPE_INC(client->auth.total_requests);
1526
1527         /*
1528          *      Some sanity checks, based on the packet code.
1529          */
1530         switch (code) {
1531         case PW_CODE_ACCESS_REQUEST:
1532                 fun = rad_authenticate;
1533                 break;
1534
1535         case PW_CODE_STATUS_SERVER:
1536                 if (!main_config.status_server) {
1537                         rad_recv_discard(listener->fd);
1538                         FR_STATS_INC(auth, total_unknown_types);
1539                         WARN("Ignoring Status-Server request due to security configuration");
1540                         return 0;
1541                 }
1542                 fun = rad_status_server;
1543                 break;
1544
1545         default:
1546                 rad_recv_discard(listener->fd);
1547                 FR_STATS_INC(auth, total_unknown_types);
1548
1549                 if (DEBUG_ENABLED) ERROR("Receive - Invalid packet code %d sent to authentication port from "
1550                                          "client %s port %d", code, client->shortname, src_port);
1551                 return 0;
1552         } /* switch over packet types */
1553
1554         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1555         if (!ctx) {
1556                 rad_recv_discard(listener->fd);
1557                 FR_STATS_INC(auth, total_packets_dropped);
1558                 return 0;
1559         }
1560         talloc_set_name_const(ctx, "auth_listener_pool");
1561
1562         /*
1563          *      Now that we've sanity checked everything, receive the
1564          *      packet.
1565          */
1566         packet = rad_recv(ctx, listener->fd, client->message_authenticator);
1567         if (!packet) {
1568                 FR_STATS_INC(auth, total_malformed_requests);
1569                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1570                 talloc_free(ctx);
1571                 return 0;
1572         }
1573
1574 #ifdef __APPLE__
1575 #ifdef WITH_UDPFROMTO
1576         /*
1577          *      This is a NICE Mac OSX bug.  Create an interface with
1578          *      two IP address, and then configure one listener for
1579          *      each IP address.  Send thousands of packets to one
1580          *      address, and some will show up on the OTHER socket.
1581          *
1582          *      This hack works ONLY if the clients are global.  If
1583          *      each listener has the same client IP, but with
1584          *      different secrets, then it will fail the rad_recv()
1585          *      check above, and there's nothing you can do.
1586          */
1587         {
1588                 listen_socket_t *sock = listener->data;
1589                 rad_listen_t *other;
1590
1591                 other = listener_find_byipaddr(&packet->dst_ipaddr,
1592                                                packet->dst_port, sock->proto);
1593                 if (other) listener = other;
1594         }
1595 #endif
1596 #endif
1597
1598         if (!request_receive(ctx, listener, packet, client, fun)) {
1599                 FR_STATS_INC(auth, total_packets_dropped);
1600                 talloc_free(ctx);
1601                 return 0;
1602         }
1603
1604         return 1;
1605 }
1606
1607
1608 #ifdef WITH_ACCOUNTING
1609 /*
1610  *      Receive packets from an accounting socket
1611  */
1612 static int acct_socket_recv(rad_listen_t *listener)
1613 {
1614         ssize_t         rcode;
1615         int             code;
1616         uint16_t        src_port;
1617         RADIUS_PACKET   *packet;
1618         RAD_REQUEST_FUNP fun = NULL;
1619         RADCLIENT       *client = NULL;
1620         fr_ipaddr_t     src_ipaddr;
1621         TALLOC_CTX      *ctx;
1622
1623         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1624         if (rcode < 0) return 0;
1625
1626         FR_STATS_INC(acct, total_requests);
1627
1628         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1629                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1630                 FR_STATS_INC(acct, total_malformed_requests);
1631                 return 0;
1632         }
1633
1634         if ((client = client_listener_find(listener,
1635                                            &src_ipaddr, src_port)) == NULL) {
1636                 rad_recv_discard(listener->fd);
1637                 FR_STATS_INC(acct, total_invalid_requests);
1638                 return 0;
1639         }
1640
1641         FR_STATS_TYPE_INC(client->acct.total_requests);
1642
1643         /*
1644          *      Some sanity checks, based on the packet code.
1645          */
1646         switch (code) {
1647         case PW_CODE_ACCOUNTING_REQUEST:
1648                 fun = rad_accounting;
1649                 break;
1650
1651         case PW_CODE_STATUS_SERVER:
1652                 if (!main_config.status_server) {
1653                         rad_recv_discard(listener->fd);
1654                         FR_STATS_INC(acct, total_unknown_types);
1655
1656                         WARN("Ignoring Status-Server request due to security configuration");
1657                         return 0;
1658                 }
1659                 fun = rad_status_server;
1660                 break;
1661
1662         default:
1663                 rad_recv_discard(listener->fd);
1664                 FR_STATS_INC(acct, total_unknown_types);
1665
1666                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
1667                       code, client->shortname, src_port);
1668                 return 0;
1669         } /* switch over packet types */
1670
1671         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1672         if (!ctx) {
1673                 rad_recv_discard(listener->fd);
1674                 FR_STATS_INC(acct, total_packets_dropped);
1675                 return 0;
1676         }
1677         talloc_set_name_const(ctx, "acct_listener_pool");
1678
1679         /*
1680          *      Now that we've sanity checked everything, receive the
1681          *      packet.
1682          */
1683         packet = rad_recv(ctx, listener->fd, 0);
1684         if (!packet) {
1685                 FR_STATS_INC(acct, total_malformed_requests);
1686                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1687                 talloc_free(ctx);
1688                 return 0;
1689         }
1690
1691         /*
1692          *      There can be no duplicate accounting packets.
1693          */
1694         if (!request_receive(ctx, listener, packet, client, fun)) {
1695                 FR_STATS_INC(acct, total_packets_dropped);
1696                 rad_free(&packet);
1697                 talloc_free(ctx);
1698                 return 0;
1699         }
1700
1701         return 1;
1702 }
1703 #endif
1704
1705
1706 #ifdef WITH_COA
1707 static int do_proxy(REQUEST *request)
1708 {
1709         VALUE_PAIR *vp;
1710
1711         if (request->in_proxy_hash ||
1712             (request->proxy_reply && (request->proxy_reply->code != 0))) {
1713                 return 0;
1714         }
1715
1716         vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY);
1717
1718         if (vp) {
1719                 if (!home_pool_byname(vp->vp_strvalue, HOME_TYPE_COA)) {
1720                         REDEBUG2("Cannot proxy to unknown pool %s",
1721                                  vp->vp_strvalue);
1722                         return 0;
1723                 }
1724
1725                 return 1;
1726         }
1727
1728         /*
1729          *      We have a destination IP address.  It will (later) proxied.
1730          */
1731         vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
1732         if (!vp) vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY);
1733
1734         if (!vp) return 0;
1735
1736         return 1;
1737 }
1738
1739 /*
1740  *      Receive a CoA packet.
1741  */
1742 int rad_coa_recv(REQUEST *request)
1743 {
1744         int rcode = RLM_MODULE_OK;
1745         int ack, nak;
1746         VALUE_PAIR *vp;
1747
1748         /*
1749          *      Get the correct response
1750          */
1751         switch (request->packet->code) {
1752         case PW_CODE_COA_REQUEST:
1753                 ack = PW_CODE_COA_ACK;
1754                 nak = PW_CODE_COA_NAK;
1755                 break;
1756
1757         case PW_CODE_DISCONNECT_REQUEST:
1758                 ack = PW_CODE_DISCONNECT_ACK;
1759                 nak = PW_CODE_DISCONNECT_NAK;
1760                 break;
1761
1762         default:                /* shouldn't happen */
1763                 return RLM_MODULE_FAIL;
1764         }
1765
1766 #ifdef WITH_PROXY
1767 #define WAS_PROXIED (request->proxy)
1768 #else
1769 #define WAS_PROXIED (0)
1770 #endif
1771
1772         if (!WAS_PROXIED) {
1773                 /*
1774                  *      RFC 5176 Section 3.3.  If we have a CoA-Request
1775                  *      with Service-Type = Authorize-Only, it MUST
1776                  *      have a State attribute in it.
1777                  */
1778                 vp = fr_pair_find_by_num(request->packet->vps, PW_SERVICE_TYPE, 0, TAG_ANY);
1779                 if (request->packet->code == PW_CODE_COA_REQUEST) {
1780                         if (vp && (vp->vp_integer == PW_AUTHORIZE_ONLY)) {
1781                                 vp = fr_pair_find_by_num(request->packet->vps, PW_STATE, 0, TAG_ANY);
1782                                 if (!vp || (vp->vp_length == 0)) {
1783                                         REDEBUG("CoA-Request with Service-Type = Authorize-Only MUST contain a State attribute");
1784                                         request->reply->code = PW_CODE_COA_NAK;
1785                                         return RLM_MODULE_FAIL;
1786                                 }
1787                         }
1788                 } else if (vp) {
1789                         /*
1790                          *      RFC 5176, Section 3.2.
1791                          */
1792                         REDEBUG("Disconnect-Request MUST NOT contain a Service-Type attribute");
1793                         request->reply->code = PW_CODE_DISCONNECT_NAK;
1794                         return RLM_MODULE_FAIL;
1795                 }
1796
1797                 rcode = process_recv_coa(0, request);
1798                 switch (rcode) {
1799                 case RLM_MODULE_FAIL:
1800                 case RLM_MODULE_INVALID:
1801                 case RLM_MODULE_REJECT:
1802                 case RLM_MODULE_USERLOCK:
1803                 default:
1804                         request->reply->code = nak;
1805                         break;
1806
1807                 case RLM_MODULE_HANDLED:
1808                         return rcode;
1809
1810                 case RLM_MODULE_NOOP:
1811                 case RLM_MODULE_NOTFOUND:
1812                 case RLM_MODULE_OK:
1813                 case RLM_MODULE_UPDATED:
1814                         if (do_proxy(request)) return RLM_MODULE_OK;
1815                         request->reply->code = ack;
1816                         break;
1817                 }
1818
1819         }
1820
1821 #ifdef WITH_PROXY
1822         else if (request->proxy_reply) {
1823                 /*
1824                  *      Start the reply code with the proxy reply
1825                  *      code.
1826                  */
1827                 request->reply->code = request->proxy_reply->code;
1828         }
1829 #endif
1830
1831         /*
1832          *      Copy State from the request to the reply.
1833          *      See RFC 5176 Section 3.3.
1834          */
1835         vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps, PW_STATE, 0, TAG_ANY);
1836         if (vp) fr_pair_add(&request->reply->vps, vp);
1837
1838         /*
1839          *      We may want to over-ride the reply.
1840          */
1841         if (request->reply->code) {
1842                 rcode = process_send_coa(0, request);
1843                 switch (rcode) {
1844                         /*
1845                          *      We need to send CoA-NAK back if Service-Type
1846                          *      is Authorize-Only.  Rely on the user's policy
1847                          *      to do that.  We're not a real NAS, so this
1848                          *      restriction doesn't (ahem) apply to us.
1849                          */
1850                 case RLM_MODULE_FAIL:
1851                 case RLM_MODULE_INVALID:
1852                 case RLM_MODULE_REJECT:
1853                 case RLM_MODULE_USERLOCK:
1854                 default:
1855                         /*
1856                          *      Over-ride an ACK with a NAK
1857                          */
1858                         request->reply->code = nak;
1859                         break;
1860
1861                 case RLM_MODULE_HANDLED:
1862                         return rcode;
1863
1864                 case RLM_MODULE_NOOP:
1865                 case RLM_MODULE_NOTFOUND:
1866                 case RLM_MODULE_OK:
1867                 case RLM_MODULE_UPDATED:
1868                         /*
1869                          *      Do NOT over-ride a previously set value.
1870                          *      Otherwise an "ok" here will re-write a
1871                          *      NAK to an ACK.
1872                          */
1873                         if (request->reply->code == 0) {
1874                                 request->reply->code = ack;
1875                         }
1876                         break;
1877                 }
1878         }
1879
1880         return RLM_MODULE_OK;
1881 }
1882
1883
1884 /*
1885  *      Check if an incoming request is "ok"
1886  *
1887  *      It takes packets, not requests.  It sees if the packet looks
1888  *      OK.  If so, it does a number of sanity checks on it.
1889   */
1890 static int coa_socket_recv(rad_listen_t *listener)
1891 {
1892         ssize_t         rcode;
1893         int             code;
1894         uint16_t        src_port;
1895         RADIUS_PACKET   *packet;
1896         RAD_REQUEST_FUNP fun = NULL;
1897         RADCLIENT       *client = NULL;
1898         fr_ipaddr_t     src_ipaddr;
1899         TALLOC_CTX      *ctx;
1900
1901         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1902         if (rcode < 0) return 0;
1903
1904         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1905                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1906                 FR_STATS_INC(coa, total_malformed_requests);
1907                 return 0;
1908         }
1909
1910         if ((client = client_listener_find(listener,
1911                                            &src_ipaddr, src_port)) == NULL) {
1912                 rad_recv_discard(listener->fd);
1913                 FR_STATS_INC(coa, total_requests);
1914                 FR_STATS_INC(coa, total_invalid_requests);
1915                 return 0;
1916         }
1917
1918         /*
1919          *      Some sanity checks, based on the packet code.
1920          */
1921         switch (code) {
1922         case PW_CODE_COA_REQUEST:
1923                 FR_STATS_INC(coa, total_requests);
1924                 fun = rad_coa_recv;
1925                 break;
1926
1927         case PW_CODE_DISCONNECT_REQUEST:
1928                 FR_STATS_INC(dsc, total_requests);
1929                 fun = rad_coa_recv;
1930                 break;
1931
1932         default:
1933                 rad_recv_discard(listener->fd);
1934                 FR_STATS_INC(coa, total_unknown_types);
1935                 DEBUG("Invalid packet code %d sent to coa port from client %s port %d : IGNORED",
1936                       code, client->shortname, src_port);
1937                 return 0;
1938         } /* switch over packet types */
1939
1940         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1941         if (!ctx) {
1942                 rad_recv_discard(listener->fd);
1943                 FR_STATS_INC(coa, total_packets_dropped);
1944                 return 0;
1945         }
1946         talloc_set_name_const(ctx, "coa_socket_recv_pool");
1947
1948         /*
1949          *      Now that we've sanity checked everything, receive the
1950          *      packet.
1951          */
1952         packet = rad_recv(ctx, listener->fd, client->message_authenticator);
1953         if (!packet) {
1954                 FR_STATS_INC(coa, total_malformed_requests);
1955                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1956                 talloc_free(ctx);
1957                 return 0;
1958         }
1959
1960         if (!request_receive(ctx, listener, packet, client, fun)) {
1961                 FR_STATS_INC(coa, total_packets_dropped);
1962                 rad_free(&packet);
1963                 talloc_free(ctx);
1964                 return 0;
1965         }
1966
1967         return 1;
1968 }
1969 #endif
1970
1971 #ifdef WITH_PROXY
1972 /*
1973  *      Recieve packets from a proxy socket.
1974  */
1975 static int proxy_socket_recv(rad_listen_t *listener)
1976 {
1977         RADIUS_PACKET   *packet;
1978 #ifdef WITH_TCP
1979         listen_socket_t *sock;
1980 #endif
1981         char            buffer[128];
1982
1983         packet = rad_recv(NULL, listener->fd, 0);
1984         if (!packet) {
1985                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1986                 return 0;
1987         }
1988
1989         switch (packet->code) {
1990         case PW_CODE_ACCESS_ACCEPT:
1991         case PW_CODE_ACCESS_CHALLENGE:
1992         case PW_CODE_ACCESS_REJECT:
1993                 break;
1994
1995 #ifdef WITH_ACCOUNTING
1996         case PW_CODE_ACCOUNTING_RESPONSE:
1997                 break;
1998 #endif
1999
2000 #ifdef WITH_COA
2001         case PW_CODE_DISCONNECT_ACK:
2002         case PW_CODE_DISCONNECT_NAK:
2003         case PW_CODE_COA_ACK:
2004         case PW_CODE_COA_NAK:
2005                 break;
2006 #endif
2007
2008         default:
2009                 /*
2010                  *      FIXME: Update MIB for packet types?
2011                  */
2012                 ERROR("Invalid packet code %d sent to a proxy port "
2013                        "from home server %s port %d - ID %d : IGNORED",
2014                        packet->code,
2015                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2016                        packet->src_port, packet->id);
2017 #ifdef WITH_STATS
2018                 listener->stats.total_unknown_types++;
2019 #endif
2020                 rad_free(&packet);
2021                 return 0;
2022         }
2023
2024 #ifdef WITH_TCP
2025         sock = listener->data;
2026         packet->proto = sock->proto;
2027 #endif
2028
2029         if (!request_proxy_reply(packet)) {
2030 #ifdef WITH_STATS
2031                 listener->stats.total_packets_dropped++;
2032 #endif
2033                 rad_free(&packet);
2034                 return 0;
2035         }
2036
2037         return 1;
2038 }
2039
2040 #ifdef WITH_TCP
2041 /*
2042  *      Recieve packets from a proxy socket.
2043  */
2044 static int proxy_socket_tcp_recv(rad_listen_t *listener)
2045 {
2046         RADIUS_PACKET   *packet;
2047         listen_socket_t *sock = listener->data;
2048         char            buffer[128];
2049
2050         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
2051
2052         packet = fr_tcp_recv(listener->fd, 0);
2053         if (!packet) {
2054                 listener->status = RAD_LISTEN_STATUS_EOL;
2055                 radius_update_listener(listener);
2056                 return 0;
2057         }
2058
2059         /*
2060          *      FIXME: Client MIB updates?
2061          */
2062         switch (packet->code) {
2063         case PW_CODE_ACCESS_ACCEPT:
2064         case PW_CODE_ACCESS_CHALLENGE:
2065         case PW_CODE_ACCESS_REJECT:
2066                 break;
2067
2068 #ifdef WITH_ACCOUNTING
2069         case PW_CODE_ACCOUNTING_RESPONSE:
2070                 break;
2071 #endif
2072
2073         default:
2074                 /*
2075                  *      FIXME: Update MIB for packet types?
2076                  */
2077                 ERROR("Invalid packet code %d sent to a proxy port "
2078                        "from home server %s port %d - ID %d : IGNORED",
2079                        packet->code,
2080                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2081                        packet->src_port, packet->id);
2082                 rad_free(&packet);
2083                 return 0;
2084         }
2085
2086         packet->src_ipaddr = sock->other_ipaddr;
2087         packet->src_port = sock->other_port;
2088         packet->dst_ipaddr = sock->my_ipaddr;
2089         packet->dst_port = sock->my_port;
2090
2091         /*
2092          *      FIXME: Have it return an indication of packets that
2093          *      are OK to ignore (dups, too late), versus ones that
2094          *      aren't OK to ignore (unknown response, spoofed, etc.)
2095          *
2096          *      Close the socket on bad packets...
2097          */
2098         if (!request_proxy_reply(packet)) {
2099                 rad_free(&packet);
2100                 return 0;
2101         }
2102
2103         sock->opened = sock->last_packet = time(NULL);
2104
2105         return 1;
2106 }
2107 #endif
2108 #endif
2109
2110
2111 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
2112 {
2113         if (!request->reply->code) return 0;
2114
2115         if (rad_encode(request->reply, request->packet, request->client->secret) < 0) {
2116                 RERROR("Failed encoding packet: %s", fr_strerror());
2117
2118                 return -1;
2119         }
2120
2121         if (rad_sign(request->reply, request->packet, request->client->secret) < 0) {
2122                 RERROR("Failed signing packet: %s", fr_strerror());
2123
2124                 return -1;
2125         }
2126
2127         return 0;
2128 }
2129
2130
2131 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
2132 {
2133 #ifdef WITH_TLS
2134         listen_socket_t *sock;
2135 #endif
2136
2137         if (rad_verify(request->packet, NULL,
2138                        request->client->secret) < 0) {
2139                 return -1;
2140         }
2141
2142 #ifdef WITH_TLS
2143         sock = request->listener->data;
2144         rad_assert(sock != NULL);
2145
2146         /*
2147          *      FIXME: Add the rest of the TLS parameters, too?  But
2148          *      how do we separate EAP-TLS parameters from RADIUS/TLS
2149          *      parameters?
2150          */
2151         if (sock->ssn && sock->ssn->ssl) {
2152 #ifdef PSK_MAX_IDENTITY_LEN
2153                 const char *identity = SSL_get_psk_identity(sock->ssn->ssl);
2154                 if (identity) {
2155                         RDEBUG("Retrieved psk identity: %s", identity);
2156                         pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
2157                 }
2158 #endif
2159         }
2160 #endif
2161
2162         return rad_decode(request->packet, NULL,
2163                           request->client->secret);
2164 }
2165
2166 #ifdef WITH_PROXY
2167 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
2168 {
2169         if (rad_encode(request->proxy, NULL, request->home_server->secret) < 0) {
2170                 RERROR("Failed encoding proxied packet: %s", fr_strerror());
2171
2172                 return -1;
2173         }
2174
2175         if (rad_sign(request->proxy, NULL, request->home_server->secret) < 0) {
2176                 RERROR("Failed signing proxied packet: %s", fr_strerror());
2177
2178                 return -1;
2179         }
2180
2181         return 0;
2182 }
2183
2184
2185 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
2186 {
2187         /*
2188          *      rad_verify is run in event.c, received_proxy_response()
2189          */
2190
2191         return rad_decode(request->proxy_reply, request->proxy,
2192                            request->home_server->secret);
2193 }
2194 #endif
2195
2196 #include "command.c"
2197
2198 /*
2199  *      Temporarily NOT const!
2200  */
2201 static fr_protocol_t master_listen[RAD_LISTEN_MAX] = {
2202 #ifdef WITH_STATS
2203         { RLM_MODULE_INIT, "status", sizeof(listen_socket_t), NULL,
2204           common_socket_parse, NULL,
2205           stats_socket_recv, auth_socket_send,
2206           common_socket_print, client_socket_encode, client_socket_decode },
2207 #else
2208         /*
2209          *      This always gets defined.
2210          */
2211         { RLM_MODULE_INIT, "status", 0, NULL,
2212           NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
2213 #endif
2214
2215 #ifdef WITH_PROXY
2216         /* proxying */
2217         { RLM_MODULE_INIT, "proxy", sizeof(listen_socket_t), NULL,
2218           common_socket_parse, common_socket_free,
2219           proxy_socket_recv, proxy_socket_send,
2220           common_socket_print, proxy_socket_encode, proxy_socket_decode },
2221 #endif
2222
2223         /* authentication */
2224         { RLM_MODULE_INIT, "auth", sizeof(listen_socket_t), NULL,
2225           common_socket_parse, common_socket_free,
2226           auth_socket_recv, auth_socket_send,
2227           common_socket_print, client_socket_encode, client_socket_decode },
2228
2229 #ifdef WITH_ACCOUNTING
2230         /* accounting */
2231         { RLM_MODULE_INIT, "acct", sizeof(listen_socket_t), NULL,
2232           common_socket_parse, common_socket_free,
2233           acct_socket_recv, acct_socket_send,
2234           common_socket_print, client_socket_encode, client_socket_decode},
2235 #endif
2236
2237 #ifdef WITH_DETAIL
2238         /* detail */
2239         { RLM_MODULE_INIT, "detail", sizeof(listen_detail_t), NULL,
2240           detail_parse, detail_free,
2241           detail_recv, detail_send,
2242           detail_print, detail_encode, detail_decode },
2243 #endif
2244
2245 #ifdef WITH_VMPS
2246         /* vlan query protocol */
2247         { 0, "vmps", 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
2248 #endif
2249
2250 #ifdef WITH_DHCP
2251         /* dhcp query protocol */
2252         { 0, "dhcp", 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
2253 #endif
2254
2255 #ifdef WITH_COMMAND_SOCKET
2256         /* TCP command socket */
2257         { RLM_MODULE_INIT, "control", sizeof(fr_command_socket_t), NULL,
2258           command_socket_parse, command_socket_free,
2259           command_domain_accept, command_domain_send,
2260           command_socket_print, command_socket_encode, command_socket_decode },
2261 #endif
2262
2263 #ifdef WITH_COA
2264         /* Change of Authorization */
2265         { RLM_MODULE_INIT, "coa", sizeof(listen_socket_t), NULL,
2266           common_socket_parse, NULL,
2267           coa_socket_recv, auth_socket_send, /* CoA packets are same as auth */
2268           common_socket_print, client_socket_encode, client_socket_decode },
2269 #endif
2270
2271 };
2272
2273
2274
2275 /*
2276  *      Binds a listener to a socket.
2277  */
2278 static int listen_bind(rad_listen_t *this)
2279 {
2280         int rcode;
2281         struct sockaddr_storage salocal;
2282         socklen_t       salen;
2283         listen_socket_t *sock = this->data;
2284 #ifndef WITH_TCP
2285 #define proto_for_port "udp"
2286 #define sock_type SOCK_DGRAM
2287 #else
2288         char const *proto_for_port = "udp";
2289         int sock_type = SOCK_DGRAM;
2290
2291         if (sock->proto == IPPROTO_TCP) {
2292 #ifdef WITH_VMPS
2293                 if (this->type == RAD_LISTEN_VQP) {
2294                         ERROR("VQP does not support TCP transport");
2295                         return -1;
2296                 }
2297 #endif
2298
2299                 proto_for_port = "tcp";
2300                 sock_type = SOCK_STREAM;
2301         }
2302 #endif
2303
2304         /*
2305          *      If the port is zero, then it means the appropriate
2306          *      thing from /etc/services.
2307          */
2308         if (sock->my_port == 0) {
2309                 struct servent  *svp;
2310
2311                 switch (this->type) {
2312                 case RAD_LISTEN_AUTH:
2313                         svp = getservbyname ("radius", proto_for_port);
2314                         if (svp != NULL) {
2315                                 sock->my_port = ntohs(svp->s_port);
2316                         } else {
2317                                 sock->my_port = PW_AUTH_UDP_PORT;
2318                         }
2319                         break;
2320
2321 #ifdef WITH_ACCOUNTING
2322                 case RAD_LISTEN_ACCT:
2323                         svp = getservbyname ("radacct", proto_for_port);
2324                         if (svp != NULL) {
2325                                 sock->my_port = ntohs(svp->s_port);
2326                         } else {
2327                                 sock->my_port = PW_ACCT_UDP_PORT;
2328                         }
2329                         break;
2330 #endif
2331
2332 #ifdef WITH_PROXY
2333                 case RAD_LISTEN_PROXY:
2334                         /* leave it at zero */
2335                         break;
2336 #endif
2337
2338 #ifdef WITH_VMPS
2339                 case RAD_LISTEN_VQP:
2340                         sock->my_port = 1589;
2341                         break;
2342 #endif
2343
2344 #ifdef WITH_COMMAND_SOCKET
2345                 case RAD_LISTEN_COMMAND:
2346                         sock->my_port = PW_RADMIN_PORT;
2347                         break;
2348 #endif
2349
2350 #ifdef WITH_COA
2351                 case RAD_LISTEN_COA:
2352                         svp = getservbyname ("radius-dynauth", "udp");
2353                         if (svp != NULL) {
2354                                 sock->my_port = ntohs(svp->s_port);
2355                         } else {
2356                                 sock->my_port = PW_COA_UDP_PORT;
2357                         }
2358                         break;
2359 #endif
2360
2361                 default:
2362                         WARN("Internal sanity check failed in binding to socket.  Ignoring problem");
2363                         return -1;
2364                 }
2365         }
2366
2367         /*
2368          *      Don't open sockets if we're checking the config.
2369          */
2370         if (check_config) {
2371                 this->fd = -1;
2372                 return 0;
2373         }
2374
2375         /*
2376          *      Copy fr_socket() here, as we may need to bind to a device.
2377          */
2378         this->fd = socket(sock->my_ipaddr.af, sock_type, 0);
2379         if (this->fd < 0) {
2380                 char buffer[256];
2381
2382                 this->print(this, buffer, sizeof(buffer));
2383
2384                 ERROR("Failed opening %s: %s", buffer, fr_syserror(errno));
2385                 return -1;
2386         }
2387
2388 #ifdef FD_CLOEXEC
2389         /*
2390          *      We don't want child processes inheriting these
2391          *      file descriptors.
2392          */
2393         rcode = fcntl(this->fd, F_GETFD);
2394         if (rcode >= 0) {
2395                 if (fcntl(this->fd, F_SETFD, rcode | FD_CLOEXEC) < 0) {
2396                         close(this->fd);
2397                         ERROR("Failed setting close on exec: %s", fr_syserror(errno));
2398                         return -1;
2399                 }
2400         }
2401 #endif
2402
2403         /*
2404          *      Bind to a device BEFORE touching IP addresses.
2405          */
2406         if (sock->interface) {
2407 #ifdef SO_BINDTODEVICE
2408                 struct ifreq ifreq;
2409
2410                 memset(&ifreq, 0, sizeof(ifreq));
2411                 strlcpy(ifreq.ifr_name, sock->interface, sizeof(ifreq.ifr_name));
2412
2413                 rad_suid_up();
2414                 rcode = setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
2415                                    (char *)&ifreq, sizeof(ifreq));
2416                 rad_suid_down();
2417                 if (rcode < 0) {
2418                         close(this->fd);
2419                         ERROR("Failed binding to interface %s: %s",
2420                                sock->interface, fr_syserror(errno));
2421                         return -1;
2422                 } /* else it worked. */
2423 #else
2424 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2425 #ifdef HAVE_NET_IF_H
2426                 /*
2427                  *      Odds are that any system supporting "bind to
2428                  *      device" also supports IPv6, so this next bit
2429                  *      isn't necessary.  But it's here for
2430                  *      completeness.
2431                  *
2432                  *      If we're doing IPv6, and the scope hasn't yet
2433                  *      been defined, set the scope to the scope of
2434                  *      the interface.
2435                  */
2436                 if (sock->my_ipaddr.af == AF_INET6) {
2437                         if (sock->my_ipaddr.scope == 0) {
2438                                 sock->my_ipaddr.scope = if_nametoindex(sock->interface);
2439                                 if (sock->my_ipaddr.scope == 0) {
2440                                         close(this->fd);
2441                                         ERROR("Failed finding interface %s: %s",
2442                                                sock->interface, fr_syserror(errno));
2443                                         return -1;
2444                                 }
2445                         } /* else scope was defined: we're OK. */
2446                 } else
2447 #endif
2448 #endif
2449                                 /*
2450                                  *      IPv4: no link local addresses,
2451                                  *      and no bind to device.
2452                                  */
2453                 {
2454                         close(this->fd);
2455                         ERROR("Failed binding to interface %s: \"bind to device\" is unsupported", sock->interface);
2456                         return -1;
2457                 }
2458 #endif
2459         }
2460
2461 #ifdef WITH_TCP
2462         if (sock->proto == IPPROTO_TCP) {
2463                 int on = 1;
2464
2465                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
2466                         close(this->fd);
2467                         ERROR("Failed to reuse address: %s", fr_syserror(errno));
2468                         return -1;
2469                 }
2470         }
2471 #endif
2472
2473 #if defined(WITH_TCP) && defined(WITH_UDPFROMTO)
2474         else                    /* UDP sockets get UDPfromto */
2475 #endif
2476
2477 #ifdef WITH_UDPFROMTO
2478         /*
2479          *      Initialize udpfromto for all sockets.
2480          */
2481         if (udpfromto_init(this->fd) != 0) {
2482                 ERROR("Failed initializing udpfromto: %s",
2483                        fr_syserror(errno));
2484                 close(this->fd);
2485                 return -1;
2486         }
2487 #endif
2488
2489         /*
2490          *      Set up sockaddr stuff.
2491          */
2492         if (!fr_ipaddr2sockaddr(&sock->my_ipaddr, sock->my_port, &salocal, &salen)) {
2493                 close(this->fd);
2494                 return -1;
2495         }
2496
2497 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2498         if (sock->my_ipaddr.af == AF_INET6) {
2499                 /*
2500                  *      Listening on '::' does NOT get you IPv4 to
2501                  *      IPv6 mapping.  You've got to listen on an IPv4
2502                  *      address, too.  This makes the rest of the server
2503                  *      design a little simpler.
2504                  */
2505 #ifdef IPV6_V6ONLY
2506
2507                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->my_ipaddr.ipaddr.ip6addr)) {
2508                         int on = 1;
2509
2510                         if (setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2511                                        (char *)&on, sizeof(on)) < 0) {
2512                                 ERROR("Failed setting socket to IPv6 "
2513                                        "only: %s", fr_syserror(errno));
2514
2515                                 close(this->fd);
2516                                 return -1;
2517                         }
2518                 }
2519 #endif /* IPV6_V6ONLY */
2520         }
2521 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
2522
2523         if (sock->my_ipaddr.af == AF_INET) {
2524 #if (defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)) || defined(IP_DONTFRAG)
2525                 int flag;
2526 #endif
2527
2528 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2529
2530                 /*
2531                  *      Disable PMTU discovery.  On Linux, this
2532                  *      also makes sure that the "don't fragment"
2533                  *      flag is zero.
2534                  */
2535                 flag = IP_PMTUDISC_DONT;
2536                 if (setsockopt(this->fd, IPPROTO_IP, IP_MTU_DISCOVER,
2537                                &flag, sizeof(flag)) < 0) {
2538                         ERROR("Failed disabling PMTU discovery: %s",
2539                                fr_syserror(errno));
2540
2541                         close(this->fd);
2542                         return -1;
2543                 }
2544 #endif
2545
2546 #if defined(IP_DONTFRAG)
2547                 /*
2548                  *      Ensure that the "don't fragment" flag is zero.
2549                  */
2550                 flag = 0;
2551                 if (setsockopt(this->fd, IPPROTO_IP, IP_DONTFRAG,
2552                                &flag, sizeof(flag)) < 0) {
2553                         ERROR("Failed setting don't fragment flag: %s",
2554                                fr_syserror(errno));
2555
2556                         close(this->fd);
2557                         return -1;
2558                 }
2559 #endif
2560         }
2561
2562 #ifdef WITH_DHCP
2563 #ifdef SO_BROADCAST
2564         if (sock->broadcast) {
2565                 int on = 1;
2566
2567                 if (setsockopt(this->fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
2568                         ERROR("Can't set broadcast option: %s",
2569                                fr_syserror(errno));
2570                         return -1;
2571                 }
2572         }
2573 #endif
2574 #endif
2575
2576         /*
2577          *      May be binding to priviledged ports.
2578          */
2579         if (sock->my_port != 0) {
2580                 rad_suid_up();
2581                 rcode = bind(this->fd, (struct sockaddr *) &salocal, salen);
2582                 rad_suid_down();
2583                 if (rcode < 0) {
2584                         char buffer[256];
2585                         close(this->fd);
2586
2587                         this->print(this, buffer, sizeof(buffer));
2588                         ERROR("Failed binding to %s: %s\n",
2589                                buffer, fr_syserror(errno));
2590                         return -1;
2591                 }
2592
2593                 /*
2594                  *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
2595                  *      kernel instead binds us to a 1.2.3.4.  If this
2596                  *      happens, notice, and remember our real IP.
2597                  */
2598                 {
2599                         struct sockaddr_storage src;
2600                         socklen_t               sizeof_src = sizeof(src);
2601
2602                         memset(&src, 0, sizeof_src);
2603                         if (getsockname(this->fd, (struct sockaddr *) &src,
2604                                         &sizeof_src) < 0) {
2605                                 ERROR("Failed getting socket name: %s",
2606                                        fr_syserror(errno));
2607                                 return -1;
2608                         }
2609
2610                         if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2611                                                 &sock->my_ipaddr, &sock->my_port)) {
2612                                 ERROR("Socket has unsupported address family");
2613                                 return -1;
2614                         }
2615                 }
2616         }
2617
2618 #ifdef WITH_TCP
2619         if (sock->proto == IPPROTO_TCP) {
2620                 /*
2621                  *      If there are hard-coded worker threads, OR
2622                  *      it's a TLS connection, it's blocking.
2623                  *
2624                  *      Otherwise, they're non-blocking.
2625                  */
2626                 if (!this->workers
2627 #ifdef WITH_PROXY
2628 #ifdef WITH_TLS
2629                     && (this->type == RAD_LISTEN_PROXY) && !this->tls
2630 #endif
2631 #endif
2632                         ) {
2633                         if (fr_nonblock(this->fd) < 0) {
2634                                 close(this->fd);
2635                                 ERROR("Failed setting non-blocking on socket: %s",
2636                                       fr_syserror(errno));
2637                                 return -1;
2638                         }
2639                 }
2640
2641                 /*
2642                  *      Allow a backlog of 8 listeners, but only for incoming interfaces.
2643                  */
2644 #ifdef WITH_PROXY
2645                 if (this->type != RAD_LISTEN_PROXY)
2646 #endif
2647                 if (listen(this->fd, 8) < 0) {
2648                         close(this->fd);
2649                         ERROR("Failed in listen(): %s", fr_syserror(errno));
2650                         return -1;
2651                 }
2652         }
2653 #endif
2654
2655         /*
2656          *      Mostly for proxy sockets.
2657          */
2658         sock->other_ipaddr.af = sock->my_ipaddr.af;
2659
2660 /*
2661  *      Don't screw up other people.
2662  */
2663 #undef proto_for_port
2664 #undef sock_type
2665
2666         return 0;
2667 }
2668
2669
2670 static int _listener_free(rad_listen_t *this)
2671 {
2672         /*
2673          *      Other code may have eaten the FD.
2674          */
2675         if (this->fd >= 0) close(this->fd);
2676
2677         if (master_listen[this->type].free) {
2678                 master_listen[this->type].free(this);
2679         }
2680
2681 #ifdef WITH_TCP
2682         if ((this->type == RAD_LISTEN_AUTH)
2683 #ifdef WITH_ACCT
2684             || (this->type == RAD_LISTEN_ACCT)
2685 #endif
2686 #ifdef WITH_PROXY
2687             || (this->type == RAD_LISTEN_PROXY)
2688 #endif
2689 #ifdef WITH_COMMAND_SOCKET
2690             || ((this->type == RAD_LISTEN_COMMAND) &&
2691                 (((fr_command_socket_t *) this->data)->magic != COMMAND_SOCKET_MAGIC))
2692 #endif
2693                 ) {
2694                 listen_socket_t *sock = this->data;
2695
2696                 rad_assert(talloc_parent(sock) == this);
2697                 rad_assert(sock->ev == NULL);
2698
2699                 /*
2700                  *      Remove the child from the parent tree.
2701                  */
2702                 if (this->parent) {
2703                         rbtree_deletebydata(this->parent->children, this);
2704                 }
2705
2706                 /*
2707                  *      Delete / close all of the children, too!
2708                  */
2709                 if (this->children) {
2710                         rbtree_walk(this->children, RBTREE_DELETE_ORDER, listener_unlink, this);
2711                 }
2712
2713 #ifdef WITH_TLS
2714                 /*
2715                  *      Note that we do NOT free this->tls, as the
2716                  *      pointer is parented by its CONF_SECTION.  It
2717                  *      may be used by multiple listeners.
2718                  */
2719                 if (this->tls) {
2720                         rad_assert(!sock->ssn || (talloc_parent(sock->ssn) == sock));
2721                         rad_assert(!sock->request || (talloc_parent(sock->request) == sock));
2722 #ifdef HAVE_PTHREAD_H
2723                         pthread_mutex_destroy(&(sock->mutex));
2724 #endif
2725                 }
2726 #endif  /* WITH_TLS */
2727         }
2728 #endif                          /* WITH_TCP */
2729
2730         return 0;
2731 }
2732
2733
2734 /*
2735  *      Allocate & initialize a new listener.
2736  */
2737 static rad_listen_t *listen_alloc(TALLOC_CTX *ctx, RAD_LISTEN_TYPE type)
2738 {
2739         rad_listen_t *this;
2740
2741         this = talloc_zero(ctx, rad_listen_t);
2742
2743         this->type = type;
2744         this->recv = master_listen[this->type].recv;
2745         this->send = master_listen[this->type].send;
2746         this->print = master_listen[this->type].print;
2747         this->encode = master_listen[this->type].encode;
2748         this->decode = master_listen[this->type].decode;
2749
2750         talloc_set_destructor(this, _listener_free);
2751
2752         this->data = talloc_zero_array(this, uint8_t, master_listen[this->type].inst_size);
2753
2754         return this;
2755 }
2756
2757 #ifdef WITH_PROXY
2758 /*
2759  *      Externally visible function for creating a new proxy LISTENER.
2760  *
2761  *      Not thread-safe, but all calls to it are protected by the
2762  *      proxy mutex in event.c
2763  */
2764 rad_listen_t *proxy_new_listener(TALLOC_CTX *ctx, home_server_t *home, uint16_t src_port)
2765 {
2766         time_t now;
2767         rad_listen_t *this;
2768         listen_socket_t *sock;
2769         char buffer[256];
2770
2771         if (!home) return NULL;
2772
2773         rad_assert(home->server == NULL); /* we only open real sockets */
2774
2775         if ((home->limit.max_connections > 0) &&
2776             (home->limit.num_connections >= home->limit.max_connections)) {
2777                 RATE_LIMIT(INFO("Home server %s has too many open connections (%d)",
2778                                 home->log_name, home->limit.max_connections));
2779                 return NULL;
2780         }
2781
2782         now = time(NULL);
2783         if (home->last_failed_open == now) {
2784                 WARN("Suppressing attempt to open socket to 'down' home server");
2785                 return NULL;
2786         }
2787
2788         this = listen_alloc(ctx, RAD_LISTEN_PROXY);
2789
2790         sock = this->data;
2791         sock->other_ipaddr = home->ipaddr;
2792         sock->other_port = home->port;
2793         sock->home = home;
2794
2795         sock->my_ipaddr = home->src_ipaddr;
2796         sock->my_port = src_port;
2797         sock->proto = home->proto;
2798
2799         /*
2800          *      For error messages.
2801          */
2802         this->print(this, buffer, sizeof(buffer));
2803
2804         if (rad_debug_lvl >= 2) {
2805                 DEBUG("Opening new proxy socket '%s'", buffer);
2806         }
2807
2808 #ifdef WITH_TCP
2809         sock->opened = sock->last_packet = now;
2810
2811         if (home->proto == IPPROTO_TCP) {
2812                 this->recv = proxy_socket_tcp_recv;
2813
2814                 /*
2815                  *      FIXME: connect() is blocking!
2816                  *      We do this with the proxy mutex locked, which may
2817                  *      cause large delays!
2818                  *
2819                  *      http://www.developerweb.net/forum/showthread.php?p=13486
2820                  */
2821                 this->fd = fr_socket_client_tcp(&home->src_ipaddr,
2822                                                 &home->ipaddr, home->port, false);
2823         } else
2824 #endif
2825                 this->fd = fr_socket(&home->src_ipaddr, src_port);
2826
2827         if (this->fd < 0) {
2828                 this->print(this, buffer,sizeof(buffer));
2829                 ERROR("Failed opening proxy socket '%s' : %s",
2830                       buffer, fr_strerror());
2831                 home->last_failed_open = now;
2832                 listen_free(&this);
2833                 return NULL;
2834         }
2835
2836
2837 #ifdef WITH_TCP
2838 #ifdef WITH_TLS
2839         if ((home->proto == IPPROTO_TCP) && home->tls) {
2840                 DEBUG("Trying SSL to port %d\n", home->port);
2841                 sock->ssn = tls_new_client_session(sock, home->tls, this->fd);
2842                 if (!sock->ssn) {
2843                         ERROR("Failed starting SSL to '%s'", buffer);
2844                         home->last_failed_open = now;
2845                         listen_free(&this);
2846                         return NULL;
2847                 }
2848
2849                 this->recv = proxy_tls_recv;
2850                 this->send = proxy_tls_send;
2851         }
2852 #endif
2853 #endif
2854         /*
2855          *      Figure out which port we were bound to.
2856          */
2857         if (sock->my_port == 0) {
2858                 struct sockaddr_storage src;
2859                 socklen_t               sizeof_src = sizeof(src);
2860
2861                 memset(&src, 0, sizeof_src);
2862                 if (getsockname(this->fd, (struct sockaddr *) &src,
2863                                 &sizeof_src) < 0) {
2864                         ERROR("Failed getting socket name for '%s': %s",
2865                               buffer, fr_syserror(errno));
2866                         home->last_failed_open = now;
2867                         listen_free(&this);
2868                         return NULL;
2869                 }
2870
2871                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2872                                         &sock->my_ipaddr, &sock->my_port)) {
2873                         ERROR("Socket has unsupported address family for '%s'", buffer);
2874                         home->last_failed_open = now;
2875                         listen_free(&this);
2876                         return NULL;
2877                 }
2878         }
2879
2880         home->limit.num_connections++;
2881
2882         return this;
2883 }
2884 #endif
2885
2886 static const FR_NAME_NUMBER listen_compare[] = {
2887 #ifdef WITH_STATS
2888         { "status",     RAD_LISTEN_NONE },
2889 #endif
2890         { "auth",       RAD_LISTEN_AUTH },
2891 #ifdef WITH_ACCOUNTING
2892         { "acct",       RAD_LISTEN_ACCT },
2893         { "auth+acct",  RAD_LISTEN_AUTH },
2894 #endif
2895 #ifdef WITH_DETAIL
2896         { "detail",     RAD_LISTEN_DETAIL },
2897 #endif
2898 #ifdef WITH_PROXY
2899         { "proxy",      RAD_LISTEN_PROXY },
2900 #endif
2901 #ifdef WITH_VMPS
2902         { "vmps",       RAD_LISTEN_VQP },
2903 #endif
2904 #ifdef WITH_DHCP
2905         { "dhcp",       RAD_LISTEN_DHCP },
2906 #endif
2907 #ifdef WITH_COMMAND_SOCKET
2908         { "control",    RAD_LISTEN_COMMAND },
2909 #endif
2910 #ifdef WITH_COA
2911         { "coa",        RAD_LISTEN_COA },
2912 #endif
2913         { NULL, 0 },
2914 };
2915
2916 static int _free_proto_handle(lt_dlhandle *handle)
2917 {
2918         dlclose(*handle);
2919         return 0;
2920 }
2921
2922 static rad_listen_t *listen_parse(CONF_SECTION *cs, char const *server)
2923 {
2924         int             type, rcode;
2925         char const      *listen_type;
2926         rad_listen_t    *this;
2927         CONF_PAIR       *cp;
2928         char const      *value;
2929         lt_dlhandle     handle;
2930         CONF_SECTION    *server_cs;
2931         char            buffer[32];
2932
2933         cp = cf_pair_find(cs, "type");
2934         if (!cp) {
2935                 cf_log_err_cs(cs,
2936                            "No type specified in listen section");
2937                 return NULL;
2938         }
2939
2940         value = cf_pair_value(cp);
2941         if (!value) {
2942                 cf_log_err_cp(cp,
2943                               "Type cannot be empty");
2944                 return NULL;
2945         }
2946
2947         snprintf(buffer, sizeof(buffer), "proto_%s", value);
2948         handle = lt_dlopenext(buffer);
2949         if (handle) {
2950                 fr_protocol_t   *proto;
2951                 lt_dlhandle     *marker;
2952
2953                 proto = dlsym(handle, buffer);
2954                 if (!proto) {
2955                         cf_log_err_cs(cs,
2956                                       "Failed linking to protocol %s : %s\n",
2957                                       value, dlerror());
2958                         dlclose(handle);
2959                         return NULL;
2960                 }
2961
2962                 type = fr_str2int(listen_compare, value, -1);
2963                 rad_assert(type >= 0); /* shouldn't be able to compile an invalid type */
2964
2965                 memcpy(&master_listen[type], proto, sizeof(*proto));
2966
2967                 /*
2968                  *      Ensure handle gets closed if config section gets freed
2969                  */
2970                 marker = talloc(cs, lt_dlhandle);
2971                 *marker = handle;
2972                 talloc_set_destructor(marker, _free_proto_handle);
2973
2974                 if (master_listen[type].magic !=  RLM_MODULE_INIT) {
2975                         ERROR("Failed to load protocol '%s', it has the wrong version.",
2976                                master_listen[type].name);
2977                         return NULL;
2978                 }
2979         }
2980
2981         cf_log_info(cs, "listen {");
2982
2983         listen_type = NULL;
2984         rcode = cf_item_parse(cs, "type", FR_ITEM_POINTER(PW_TYPE_STRING, &listen_type), "");
2985         if (rcode < 0) return NULL;
2986         if (rcode == 1) {
2987                 cf_log_err_cs(cs,
2988                            "No type specified in listen section");
2989                 return NULL;
2990         }
2991
2992         type = fr_str2int(listen_compare, listen_type, -1);
2993         if (type < 0) {
2994                 cf_log_err_cs(cs,
2995                            "Invalid type \"%s\" in listen section.",
2996                            listen_type);
2997                 return NULL;
2998         }
2999
3000         /*
3001          *      DHCP and VMPS *must* be loaded dynamically.
3002          */
3003         if (master_listen[type].magic !=  RLM_MODULE_INIT) {
3004                 ERROR("Cannot load protocol '%s', as the required library does not exist",
3005                       master_listen[type].name);
3006                 return NULL;
3007         }
3008
3009         /*
3010          *      Allow listen sections in the default config to
3011          *      refer to a server.
3012          */
3013         if (!server) {
3014                 rcode = cf_item_parse(cs, "virtual_server", FR_ITEM_POINTER(PW_TYPE_STRING, &server), NULL);
3015                 if (rcode < 0) return NULL;
3016         }
3017
3018 #ifdef WITH_PROXY
3019         /*
3020          *      We were passed a virtual server, so the caller is
3021          *      defining a proxy listener inside of a virtual server.
3022          *      This isn't allowed right now.
3023          */
3024         else if (type == RAD_LISTEN_PROXY) {
3025                 ERROR("Error: listen type \"proxy\" Cannot appear in a virtual server section");
3026                 return NULL;
3027         }
3028 #endif
3029
3030         /*
3031          *      Set up cross-type data.
3032          */
3033         this = listen_alloc(cs, type);
3034         this->server = server;
3035         this->fd = -1;
3036
3037 #ifdef WITH_TCP
3038         /*
3039          *      Special-case '+' for "auth+acct".
3040          */
3041         if (strchr(listen_type, '+') != NULL) {
3042                 this->dual = true;
3043         }
3044 #endif
3045
3046         /*
3047          *      Call per-type parser.
3048          */
3049         if (master_listen[type].parse(cs, this) < 0) {
3050                 listen_free(&this);
3051                 return NULL;
3052         }
3053
3054         server_cs = cf_section_sub_find_name2(main_config.config, "server",
3055                                               this->server);
3056         if (!server_cs && this->server) {
3057                 cf_log_err_cs(cs, "No such server \"%s\"", this->server);
3058                 listen_free(&this);
3059                 return NULL;
3060         }
3061
3062         cf_log_info(cs, "}");
3063
3064         return this;
3065 }
3066
3067 #ifdef HAVE_PTHREAD_H
3068 /*
3069  *      A child thread which does NOTHING other than read and process
3070  *      packets.
3071  */
3072 static void *recv_thread(void *arg)
3073 {
3074         rad_listen_t *this = arg;
3075
3076         while (1) {
3077                 this->recv(this);
3078                 DEBUG("%p", &this);
3079         }
3080
3081         return NULL;
3082 }
3083 #endif
3084
3085
3086 /*
3087  *      Generate a list of listeners.  Takes an input list of
3088  *      listeners, too, so we don't close sockets with waiting packets.
3089  */
3090 int listen_init(CONF_SECTION *config, rad_listen_t **head, bool spawn_flag)
3091 {
3092         bool            override = false;
3093         CONF_SECTION    *cs = NULL;
3094         rad_listen_t    **last;
3095         rad_listen_t    *this;
3096         fr_ipaddr_t     server_ipaddr;
3097         uint16_t        auth_port = 0;
3098 #ifdef WITH_PROXY
3099         bool            defined_proxy = false;
3100 #endif
3101
3102         /*
3103          *      We shouldn't be called with a pre-existing list.
3104          */
3105         rad_assert(head && (*head == NULL));
3106
3107         memset(&server_ipaddr, 0, sizeof(server_ipaddr));
3108
3109         last = head;
3110         server_ipaddr.af = AF_UNSPEC;
3111
3112         /*
3113          *      If the port is specified on the command-line,
3114          *      it over-rides the configuration file.
3115          *
3116          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
3117          */
3118         if (main_config.port > 0) {
3119                 auth_port = main_config.port;
3120
3121                 /*
3122                  *      -p X but no -i Y on the command-line.
3123                  */
3124                 if (main_config.myip.af == AF_UNSPEC) {
3125                         ERROR("The command-line says \"-p %d\", but there is no associated IP address to use",
3126                               main_config.port);
3127                         return -1;
3128                 }
3129         }
3130
3131         /*
3132          *      If the IP address was configured on the command-line,
3133          *      use that as the "bind_address"
3134          */
3135         if (main_config.myip.af != AF_UNSPEC) {
3136                 listen_socket_t *sock;
3137
3138                 memcpy(&server_ipaddr, &main_config.myip,
3139                        sizeof(server_ipaddr));
3140                 override = true;
3141
3142 #ifdef WITH_VMPS
3143                 if (strcmp(progname, "vmpsd") == 0) {
3144                         this = listen_alloc(config, RAD_LISTEN_VQP);
3145                         if (!auth_port) auth_port = 1589;
3146                 } else
3147 #endif
3148                         this = listen_alloc(config, RAD_LISTEN_AUTH);
3149
3150                 sock = this->data;
3151
3152                 sock->my_ipaddr = server_ipaddr;
3153                 sock->my_port = auth_port;
3154
3155                 sock->clients = client_list_parse_section(config, false);
3156                 if (!sock->clients) {
3157                         cf_log_err_cs(config,
3158                                    "Failed to find any clients for this listen section");
3159                         listen_free(&this);
3160                         return -1;
3161                 }
3162
3163                 if (listen_bind(this) < 0) {
3164                         listen_free(head);
3165                         ERROR("There appears to be another RADIUS server running on the authentication port %d", sock->my_port);
3166                         listen_free(&this);
3167                         return -1;
3168                 }
3169                 auth_port = sock->my_port;      /* may have been updated in listen_bind */
3170                 if (override) {
3171                         cs = cf_section_sub_find_name2(config, "server",
3172                                                        main_config.name);
3173                         if (cs) this->server = main_config.name;
3174                 }
3175
3176                 *last = this;
3177                 last = &(this->next);
3178
3179 #ifdef WITH_VMPS
3180                 /*
3181                  *      No acct for vmpsd
3182                  */
3183                 if (strcmp(progname, "vmpsd") == 0) goto add_sockets;
3184 #endif
3185
3186 #ifdef WITH_ACCOUNTING
3187                 /*
3188                  *      Open Accounting Socket.
3189                  *
3190                  *      If we haven't already gotten acct_port from
3191                  *      /etc/services, then make it auth_port + 1.
3192                  */
3193                 this = listen_alloc(config, RAD_LISTEN_ACCT);
3194                 sock = this->data;
3195
3196                 /*
3197                  *      Create the accounting socket.
3198                  *
3199                  *      The accounting port is always the
3200                  *      authentication port + 1
3201                  */
3202                 sock->my_ipaddr = server_ipaddr;
3203                 sock->my_port = auth_port + 1;
3204
3205                 sock->clients = client_list_parse_section(config, false);
3206                 if (!sock->clients) {
3207                         cf_log_err_cs(config,
3208                                    "Failed to find any clients for this listen section");
3209                         return -1;
3210                 }
3211
3212                 if (listen_bind(this) < 0) {
3213                         listen_free(&this);
3214                         listen_free(head);
3215                         ERROR("There appears to be another RADIUS server running on the accounting port %d", sock->my_port);
3216                         return -1;
3217                 }
3218
3219                 if (override) {
3220                         cs = cf_section_sub_find_name2(config, "server",
3221                                                        main_config.name);
3222                         if (cs) this->server = main_config.name;
3223                 }
3224
3225                 *last = this;
3226                 last = &(this->next);
3227 #endif
3228         }
3229
3230         /*
3231          *      They specified an IP on the command-line, ignore
3232          *      all listen sections except the one in '-n'.
3233          */
3234         if (main_config.myip.af != AF_UNSPEC) {
3235                 CONF_SECTION *subcs;
3236                 char const *name2 = cf_section_name2(cs);
3237
3238                 cs = cf_section_sub_find_name2(config, "server",
3239                                                main_config.name);
3240                 if (!cs) goto add_sockets;
3241
3242                 /*
3243                  *      Should really abstract this code...
3244                  */
3245                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
3246                      subcs != NULL;
3247                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
3248                         this = listen_parse(subcs, name2);
3249                         if (!this) {
3250                                 listen_free(head);
3251                                 return -1;
3252                         }
3253
3254                         *last = this;
3255                         last = &(this->next);
3256                 } /* loop over "listen" directives in server <foo> */
3257
3258                 goto add_sockets;
3259         }
3260
3261         /*
3262          *      Walk through the "listen" sections, if they exist.
3263          */
3264         for (cs = cf_subsection_find_next(config, NULL, "listen");
3265              cs != NULL;
3266              cs = cf_subsection_find_next(config, cs, "listen")) {
3267                 this = listen_parse(cs, NULL);
3268                 if (!this) {
3269                         listen_free(head);
3270                         return -1;
3271                 }
3272
3273                 *last = this;
3274                 last = &(this->next);
3275         }
3276
3277         /*
3278          *      Check virtual servers for "listen" sections, too.
3279          *
3280          *      FIXME: Move to virtual server init?
3281          */
3282         for (cs = cf_subsection_find_next(config, NULL, "server");
3283              cs != NULL;
3284              cs = cf_subsection_find_next(config, cs, "server")) {
3285                 CONF_SECTION *subcs;
3286                 char const *name2 = cf_section_name2(cs);
3287
3288                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
3289                      subcs != NULL;
3290                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
3291                         this = listen_parse(subcs, name2);
3292                         if (!this) {
3293                                 listen_free(head);
3294                                 return -1;
3295                         }
3296
3297                         *last = this;
3298                         last = &(this->next);
3299                 } /* loop over "listen" directives in virtual servers */
3300         } /* loop over virtual servers */
3301
3302 add_sockets:
3303         /*
3304          *      No sockets to receive packets, this is an error.
3305          *      proxying is pointless.
3306          */
3307         if (!*head) {
3308                 ERROR("The server is not configured to listen on any ports.  Cannot start");
3309                 return -1;
3310         }
3311
3312         /*
3313          *      Print out which sockets we're listening on, and
3314          *      add them to the event list.
3315          */
3316         for (this = *head; this != NULL; this = this->next) {
3317 #ifdef WITH_PROXY
3318                 if (this->type == RAD_LISTEN_PROXY) {
3319                         defined_proxy = true;
3320                 }
3321
3322 #endif
3323
3324 #ifdef WITH_TLS
3325                 if (!check_config && !spawn_flag && this->tls) {
3326                         cf_log_err_cs(this->cs, "Threading must be enabled for TLS sockets to function properly");
3327                         cf_log_err_cs(this->cs, "You probably need to do '%s -fxx -l stdout' for debugging",
3328                                       progname);
3329                         return -1;
3330                 }
3331 #endif
3332                 if (!check_config) {
3333                         if (this->workers && !spawn_flag) {
3334                                 WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
3335                                 this->workers = 0;
3336                         }
3337
3338                         if (this->workers) {
3339 #ifdef HAVE_PTHREAD_H
3340                                 int rcode;
3341                                 uint32_t i;
3342                                 char buffer[256];
3343
3344                                 this->print(this, buffer, sizeof(buffer));
3345
3346                                 for (i = 0; i < this->workers; i++) {
3347                                         pthread_t id;
3348
3349                                         /*
3350                                          *      FIXME: create detached?
3351                                          */
3352                                         rcode = pthread_create(&id, 0, recv_thread, this);
3353                                         if (rcode != 0) {
3354                                                 ERROR("Thread create failed: %s",
3355                                                       fr_syserror(rcode));
3356                                                 fr_exit(1);
3357                                         }
3358
3359                                         DEBUG("Thread %d for %s\n", i, buffer);
3360                                 }
3361 #else
3362                                 WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
3363                                 this->workers = 0;
3364 #endif
3365
3366                         } else {
3367                                 radius_update_listener(this);
3368                         }
3369
3370                 }
3371         }
3372
3373 #ifdef WITH_TCP
3374         if (!home_servers_udp) defined_proxy = true;
3375 #endif
3376
3377         /*
3378          *      If we're proxying requests, open the proxy FD.
3379          *      Otherwise, don't do anything.
3380          */
3381 #ifdef WITH_PROXY
3382         if ((main_config.proxy_requests == true) &&
3383             !check_config &&
3384             (*head != NULL) && !defined_proxy) {
3385                 uint16_t        port = 0;
3386                 home_server_t   home;
3387
3388                 memset(&home, 0, sizeof(home));
3389
3390                 /*
3391                  *      Open a default UDP port
3392                  */
3393                 home.proto = IPPROTO_UDP;
3394                 home.src_ipaddr = server_ipaddr;
3395                 port = 0;
3396
3397                 /*
3398                  *      Address is still unspecified, use IPv4.
3399                  */
3400                 if (home.src_ipaddr.af == AF_UNSPEC) {
3401                         home.src_ipaddr.af = AF_INET;
3402                         /* everything else is already set to zero */
3403                 }
3404
3405                 home.ipaddr.af = home.src_ipaddr.af;
3406                 /* everything else is already set to zero */
3407
3408                 /*
3409                  *      It's OK to allocate a UDP listener from the
3410                  *      main config.  The listener will never be
3411                  *      deleted until the server stops and the config
3412                  *      is freed.
3413                  */
3414                 this = proxy_new_listener(config, &home, port);
3415                 if (!this) {
3416                         listen_free(head);
3417                         return -1;
3418                 }
3419
3420                 radius_update_listener(this);
3421         }
3422 #endif
3423
3424         /*
3425          *      Haven't defined any sockets.  Die.
3426          */
3427         if (!*head) return -1;
3428
3429         xlat_register("listen", xlat_listen, NULL, NULL);
3430
3431         return 0;
3432 }
3433
3434 /*
3435  *      Free a linked list of listeners;
3436  */
3437 void listen_free(rad_listen_t **head)
3438 {
3439         rad_listen_t *this;
3440
3441         if (!head || !*head) return;
3442
3443         this = *head;
3444         while (this) {
3445                 rad_listen_t *next = this->next;
3446                 talloc_free(this);
3447                 this = next;
3448         }
3449
3450         *head = NULL;
3451 }
3452
3453 #ifdef WITH_STATS
3454 RADCLIENT_LIST *listener_find_client_list(fr_ipaddr_t const *ipaddr, uint16_t port, int proto)
3455 {
3456         rad_listen_t *this;
3457
3458         for (this = main_config.listen; this != NULL; this = this->next) {
3459                 listen_socket_t *sock;
3460
3461                 if ((this->type != RAD_LISTEN_AUTH)
3462 #ifdef WITH_ACCOUNTING
3463                     && (this->type != RAD_LISTEN_ACCT)
3464 #endif
3465 #ifdef WITH_COA
3466                     && (this->type != RAD_LISTEN_COA)
3467 #endif
3468                     ) continue;
3469
3470                 sock = this->data;
3471
3472                 if (sock->my_port != port) continue;
3473                 if (sock->proto != proto) continue;
3474                 if (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) != 0) continue;
3475
3476                 return sock->clients;
3477         }
3478
3479         return NULL;
3480 }
3481 #endif
3482
3483 rad_listen_t *listener_find_byipaddr(fr_ipaddr_t const *ipaddr, uint16_t port, int proto)
3484 {
3485         rad_listen_t *this;
3486
3487         for (this = main_config.listen; this != NULL; this = this->next) {
3488                 listen_socket_t *sock;
3489
3490                 sock = this->data;
3491
3492                 if (sock->my_port != port) continue;
3493                 if (sock->proto != proto) continue;
3494                 if (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) != 0) continue;
3495
3496                 return this;
3497         }
3498
3499         /*
3500          *      Failed to find a specific one.  Find INADDR_ANY
3501          */
3502         for (this = main_config.listen; this != NULL; this = this->next) {
3503                 listen_socket_t *sock;
3504
3505                 sock = this->data;
3506
3507                 if (sock->my_port != port) continue;
3508                 if (sock->proto != proto) continue;
3509                 if (!fr_inaddr_any(&sock->my_ipaddr)) continue;
3510
3511                 return this;
3512         }
3513
3514         return NULL;
3515 }