ee0851dca65b51a06f620099f928bd8edea5e24e
[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
924         { NULL, -1, 0, NULL, NULL }             /* end the list */
925 };
926
927
928 static CONF_PARSER limit_config[] = {
929         { "max_pps", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, max_rate), NULL },
930
931 #ifdef WITH_TCP
932         { "max_connections", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.max_connections), "16" },
933         { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.lifetime), "0" },
934         { "idle_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, listen_socket_t, limit.idle_timeout), STRINGIFY(30) },
935 #endif
936
937         { NULL, -1, 0, NULL, NULL }             /* end the list */
938 };
939
940
941 #ifdef WITH_TCP
942 /*
943  *      TLS requires child threads to handle the listeners.  Which
944  *      means that we need a separate talloc context per child thread.
945  *      Which means that we need to manually clean up the child
946  *      listeners.  Which means we need to manually track them.
947  *
948  *      All child thread linking/unlinking is done in the master
949  *      thread.  If we care, we can later add a mutex for the parent
950  *      listener.
951  */
952 static int listener_cmp(void const *one, void const *two)
953 {
954         if (one < two) return -1;
955         if (one > two) return +1;
956         return 0;
957 }
958
959 static int listener_unlink(UNUSED void *ctx, UNUSED void *data)
960 {
961         return 2;               /* unlink this node from the tree */
962 }
963 #endif
964
965
966 /*
967  *      Parse an authentication or accounting socket.
968  */
969 int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
970 {
971         int             rcode;
972         uint16_t        listen_port;
973         fr_ipaddr_t     ipaddr;
974         listen_socket_t *sock = this->data;
975         char const      *section_name = NULL;
976         CONF_SECTION    *client_cs, *parentcs;
977         CONF_SECTION    *subcs;
978         CONF_PAIR       *cp;
979
980         this->cs = cs;
981
982         /*
983          *      Try IPv4 first
984          */
985         memset(&ipaddr, 0, sizeof(ipaddr));
986         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
987
988         rcode = cf_item_parse(cs, "ipaddr", FR_ITEM_POINTER(PW_TYPE_COMBO_IP_ADDR, &ipaddr), NULL);
989         if (rcode < 0) return -1;
990         if (rcode != 0) rcode = cf_item_parse(cs, "ipv4addr", FR_ITEM_POINTER(PW_TYPE_IPV4_ADDR, &ipaddr), NULL);
991         if (rcode < 0) return -1;
992         if (rcode != 0) rcode = cf_item_parse(cs, "ipv6addr", FR_ITEM_POINTER(PW_TYPE_IPV6_ADDR, &ipaddr), NULL);
993         if (rcode < 0) return -1;
994         if (rcode != 0) {
995                 cf_log_err_cs(cs, "No address specified in listen section");
996                 return -1;
997         }
998
999         rcode = cf_item_parse(cs, "port", FR_ITEM_POINTER(PW_TYPE_SHORT, &listen_port), "0");
1000         if (rcode < 0) return -1;
1001
1002         sock->proto = IPPROTO_UDP;
1003
1004         if (cf_pair_find(cs, "proto")) {
1005 #ifndef WITH_TCP
1006                 cf_log_err_cs(cs,
1007                            "System does not support the TCP protocol.  Delete this line from the configuration file");
1008                 return -1;
1009 #else
1010                 char const *proto = NULL;
1011 #ifdef WITH_TLS
1012                 CONF_SECTION *tls;
1013 #endif
1014
1015                 rcode = cf_item_parse(cs, "proto", FR_ITEM_POINTER(PW_TYPE_STRING, &proto), "udp");
1016                 if (rcode < 0) return -1;
1017
1018                 if (!proto || strcmp(proto, "udp") == 0) {
1019                         sock->proto = IPPROTO_UDP;
1020
1021                 } else if (strcmp(proto, "tcp") == 0) {
1022                         sock->proto = IPPROTO_TCP;
1023                 } else {
1024                         cf_log_err_cs(cs,
1025                                    "Unknown proto name \"%s\"", proto);
1026                         return -1;
1027                 }
1028
1029                 /*
1030                  *      TCP requires a destination IP for sockets.
1031                  *      UDP doesn't, so it's allowed.
1032                  */
1033 #ifdef WITH_PROXY
1034                 if ((this->type == RAD_LISTEN_PROXY) &&
1035                     (sock->proto != IPPROTO_UDP)) {
1036                         cf_log_err_cs(cs,
1037                                    "Proxy listeners can only listen on proto = udp");
1038                         return -1;
1039                 }
1040 #endif  /* WITH_PROXY */
1041
1042 #ifdef WITH_TLS
1043                 tls = cf_section_sub_find(cs, "tls");
1044
1045                 if (tls) {
1046                         /*
1047                          *      Don't allow TLS configurations for UDP sockets.
1048                          */
1049                         if (sock->proto != IPPROTO_TCP) {
1050                                 cf_log_err_cs(cs,
1051                                               "TLS transport is not available for UDP sockets");
1052                                 return -1;
1053                         }
1054
1055                         /*
1056                          *      If unset, set to default.
1057                          */
1058                         if (listen_port == 0) listen_port = PW_RADIUS_TLS_PORT;
1059
1060                         this->tls = tls_server_conf_parse(tls);
1061                         if (!this->tls) {
1062                                 return -1;
1063                         }
1064
1065 #ifdef HAVE_PTRHEAD_H
1066                         if (pthread_mutex_init(&sock->mutex, NULL) < 0) {
1067                                 rad_assert(0 == 1);
1068                                 listen_free(&this);
1069                                 return 0;
1070                         }
1071 #endif
1072
1073                 }
1074 #else  /* WITH_TLS */
1075                 /*
1076                  *      Built without TLS.  Disallow it.
1077                  */
1078                 if (cf_section_sub_find(cs, "tls")) {
1079                         cf_log_err_cs(cs,
1080                                    "TLS transport is not available in this executable");
1081                         return -1;
1082                 }
1083 #endif  /* WITH_TLS */
1084
1085 #endif  /* WITH_TCP */
1086
1087                 /*
1088                  *      No "proto" field.  Disallow TLS.
1089                  */
1090         } else if (cf_section_sub_find(cs, "tls")) {
1091                 cf_log_err_cs(cs,
1092                            "TLS transport is not available in this \"listen\" section");
1093                 return -1;
1094         }
1095
1096         /*
1097          *      Magical tuning methods!
1098          */
1099         subcs = cf_section_sub_find(cs, "performance");
1100         if (subcs) {
1101                 rcode = cf_section_parse(subcs, this,
1102                                          performance_config);
1103                 if (rcode < 0) return -1;
1104
1105                 if (this->synchronous && sock->max_rate) {
1106                         WARN("Setting 'max_pps' is incompatible with 'synchronous'.  Disabling 'max_pps'");
1107                         sock->max_rate = 0;
1108                 }
1109
1110                 if (!this->synchronous && this->workers) {
1111                         WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
1112                         this->workers = 0;
1113                 }
1114         }
1115
1116         subcs = cf_section_sub_find(cs, "limit");
1117         if (subcs) {
1118                 rcode = cf_section_parse(subcs, sock,
1119                                          limit_config);
1120                 if (rcode < 0) return -1;
1121
1122                 if (sock->max_rate && ((sock->max_rate < 10) || (sock->max_rate > 1000000))) {
1123                         cf_log_err_cs(cs,
1124                                       "Invalid value for \"max_pps\"");
1125                         return -1;
1126                 }
1127
1128 #ifdef WITH_TCP
1129                 if ((sock->limit.idle_timeout > 0) && (sock->limit.idle_timeout < 5)) {
1130                         WARN("Setting idle_timeout to 5");
1131                         sock->limit.idle_timeout = 5;
1132                 }
1133
1134                 if ((sock->limit.lifetime > 0) && (sock->limit.lifetime < 5)) {
1135                         WARN("Setting lifetime to 5");
1136                         sock->limit.lifetime = 5;
1137                 }
1138
1139                 if ((sock->limit.lifetime > 0) && (sock->limit.idle_timeout > sock->limit.lifetime)) {
1140                         WARN("Setting idle_timeout to 0");
1141                         sock->limit.idle_timeout = 0;
1142                 }
1143
1144                 /*
1145                  *      Force no duplicate detection for TCP sockets.
1146                  */
1147                 if (sock->proto == IPPROTO_TCP) {
1148                         this->nodup = true;
1149                 }
1150
1151         } else {
1152                 sock->limit.max_connections = 60;
1153                 sock->limit.idle_timeout = 30;
1154                 sock->limit.lifetime = 0;
1155 #endif
1156         }
1157
1158         sock->my_ipaddr = ipaddr;
1159         sock->my_port = listen_port;
1160
1161 #ifdef WITH_PROXY
1162         if (check_config) {
1163                 /*
1164                  *      Until there is a side effects free way of forwarding a
1165                  *      request to another virtual server, this check is invalid,
1166                  *      and should be left disabled.
1167                  */
1168 #if 0
1169                 if (home_server_find(&sock->my_ipaddr, sock->my_port, sock->proto)) {
1170                                 char buffer[128];
1171
1172                                 ERROR("We have been asked to listen on %s port %d, which is also listed as a "
1173                                        "home server.  This can create a proxy loop",
1174                                        ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)), sock->my_port);
1175                                 return -1;
1176                 }
1177 #endif
1178                 return 0;       /* don't do anything */
1179         }
1180 #endif
1181
1182         /*
1183          *      If we can bind to interfaces, do so,
1184          *      else don't.
1185          */
1186         cp = cf_pair_find(cs, "interface");
1187         if (cp) {
1188                 char const *value = cf_pair_value(cp);
1189                 if (!value) {
1190                         cf_log_err_cs(cs,
1191                                    "No interface name given");
1192                         return -1;
1193                 }
1194                 sock->interface = value;
1195         }
1196
1197 #ifdef WITH_DHCP
1198         /*
1199          *      If we can do broadcasts..
1200          */
1201         cp = cf_pair_find(cs, "broadcast");
1202         if (cp) {
1203 #ifndef SO_BROADCAST
1204                 cf_log_err_cs(cs,
1205                            "System does not support broadcast sockets.  Delete this line from the configuration file");
1206                 return -1;
1207 #else
1208                 if (this->type != RAD_LISTEN_DHCP) {
1209                         cf_log_err_cp(cp,
1210                                    "Broadcast can only be set for DHCP listeners.  Delete this line from the configuration file");
1211                         return -1;
1212                 }
1213
1214                 char const *value = cf_pair_value(cp);
1215                 if (!value) {
1216                         cf_log_err_cs(cs,
1217                                    "No broadcast value given");
1218                         return -1;
1219                 }
1220
1221                 /*
1222                  *      Hack... whatever happened to cf_section_parse?
1223                  */
1224                 sock->broadcast = (strcmp(value, "yes") == 0);
1225 #endif
1226         }
1227 #endif
1228
1229         /*
1230          *      And bind it to the port.
1231          */
1232         if (listen_bind(this) < 0) {
1233                 char buffer[128];
1234                 cf_log_err_cs(cs,
1235                            "Error binding to port for %s port %d",
1236                            ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)),
1237                            sock->my_port);
1238                 return -1;
1239         }
1240
1241 #ifdef WITH_PROXY
1242         /*
1243          *      Proxy sockets don't have clients.
1244          */
1245         if (this->type == RAD_LISTEN_PROXY) return 0;
1246 #endif
1247
1248         /*
1249          *      The more specific configurations are preferred to more
1250          *      generic ones.
1251          */
1252         client_cs = NULL;
1253         parentcs = cf_top_section(cs);
1254         rcode = cf_item_parse(cs, "clients", FR_ITEM_POINTER(PW_TYPE_STRING, &section_name), NULL);
1255         if (rcode < 0) return -1; /* bad string */
1256         if (rcode == 0) {
1257                 /*
1258                  *      Explicit list given: use it.
1259                  */
1260                 client_cs = cf_section_sub_find_name2(parentcs, "clients", section_name);
1261                 if (!client_cs) {
1262                         client_cs = cf_section_find(section_name);
1263                 }
1264                 if (!client_cs) {
1265                         cf_log_err_cs(cs,
1266                                    "Failed to find clients %s {...}",
1267                                    section_name);
1268                         return -1;
1269                 }
1270         } /* else there was no "clients = " entry. */
1271
1272         /*
1273          *      The "listen" section wasn't given an explicit client list.
1274          *      Look for (a) clients in this virtual server, or
1275          *      (b) the global client list.
1276          */
1277         if (!client_cs) {
1278                 CONF_SECTION *server_cs;
1279
1280                 server_cs = cf_section_sub_find_name2(parentcs,
1281                                                       "server",
1282                                                       this->server);
1283                 /*
1284                  *      Found a "server foo" section.  If there are clients
1285                  *      in it, use them.
1286                  */
1287                 if (server_cs &&
1288                     (cf_section_sub_find(server_cs, "client") != NULL)) {
1289                         client_cs = server_cs;
1290                 }
1291         }
1292
1293         /*
1294          *      Still nothing.  Look for global clients.
1295          */
1296         if (!client_cs) client_cs = parentcs;
1297
1298 #ifdef WITH_TLS
1299         sock->clients = client_list_parse_section(client_cs, (this->tls != NULL));
1300 #else
1301         sock->clients = client_list_parse_section(client_cs, false);
1302 #endif
1303         if (!sock->clients) {
1304                 cf_log_err_cs(cs,
1305                            "Failed to load clients for this listen section");
1306                 return -1;
1307         }
1308
1309 #ifdef WITH_TCP
1310         if (sock->proto == IPPROTO_TCP) {
1311                 /*
1312                  *      Re-write the listener receive function to
1313                  *      allow us to accept the socket.
1314                  */
1315                 this->recv = dual_tcp_accept;
1316
1317                 this->children = rbtree_create(this, listener_cmp, NULL, 0);
1318                 if (!this->children) {
1319                         cf_log_err_cs(cs, "Failed to create child list for TCP socket.");
1320                         return -1;
1321                 }
1322         }
1323 #endif
1324
1325         return 0;
1326 }
1327
1328 /*
1329  *      Send an authentication response packet
1330  */
1331 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
1332 {
1333         rad_assert(request->listener == listener);
1334         rad_assert(listener->send == auth_socket_send);
1335
1336         if (request->reply->code == 0) return 0;
1337
1338 #ifdef WITH_UDPFROMTO
1339         /*
1340          *      Overwrite the src ip address on the outbound packet
1341          *      with the one specified by the client.
1342          *      This is useful to work around broken DSR implementations
1343          *      and other routing issues.
1344          */
1345         if (request->client->src_ipaddr.af != AF_UNSPEC) {
1346                 request->reply->src_ipaddr = request->client->src_ipaddr;
1347         }
1348 #endif
1349
1350         if (rad_send(request->reply, request->packet,
1351                      request->client->secret) < 0) {
1352                 RERROR("Failed sending reply: %s",
1353                                fr_strerror());
1354                 return -1;
1355         }
1356
1357         return 0;
1358 }
1359
1360
1361 #ifdef WITH_ACCOUNTING
1362 /*
1363  *      Send an accounting response packet (or not)
1364  */
1365 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
1366 {
1367         rad_assert(request->listener == listener);
1368         rad_assert(listener->send == acct_socket_send);
1369
1370         /*
1371          *      Accounting reject's are silently dropped.
1372          *
1373          *      We do it here to avoid polluting the rest of the
1374          *      code with this knowledge
1375          */
1376         if (request->reply->code == 0) return 0;
1377
1378 #ifdef WITH_UDPFROMTO
1379         /*
1380          *      Overwrite the src ip address on the outbound packet
1381          *      with the one specified by the client.
1382          *      This is useful to work around broken DSR implementations
1383          *      and other routing issues.
1384          */
1385         if (request->client->src_ipaddr.af != AF_UNSPEC) {
1386                 request->reply->src_ipaddr = request->client->src_ipaddr;
1387         }
1388 #endif
1389
1390         if (rad_send(request->reply, request->packet,
1391                      request->client->secret) < 0) {
1392                 RERROR("Failed sending reply: %s",
1393                                fr_strerror());
1394                 return -1;
1395         }
1396
1397         return 0;
1398 }
1399 #endif
1400
1401 #ifdef WITH_PROXY
1402 /*
1403  *      Send a packet to a home server.
1404  *
1405  *      FIXME: have different code for proxy auth & acct!
1406  */
1407 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
1408 {
1409         rad_assert(request->proxy_listener == listener);
1410         rad_assert(listener->send == proxy_socket_send);
1411
1412         if (rad_send(request->proxy, NULL,
1413                      request->home_server->secret) < 0) {
1414                 RERROR("Failed sending proxied request: %s",
1415                                fr_strerror());
1416                 return -1;
1417         }
1418
1419         return 0;
1420 }
1421 #endif
1422
1423 #ifdef WITH_STATS
1424 /*
1425  *      Check if an incoming request is "ok"
1426  *
1427  *      It takes packets, not requests.  It sees if the packet looks
1428  *      OK.  If so, it does a number of sanity checks on it.
1429   */
1430 static int stats_socket_recv(rad_listen_t *listener)
1431 {
1432         ssize_t         rcode;
1433         int             code;
1434         uint16_t        src_port;
1435         RADIUS_PACKET   *packet;
1436         RADCLIENT       *client = NULL;
1437         fr_ipaddr_t     src_ipaddr;
1438
1439         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1440         if (rcode < 0) return 0;
1441
1442         FR_STATS_INC(auth, total_requests);
1443
1444         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1445                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1446                 FR_STATS_INC(auth, total_malformed_requests);
1447                 return 0;
1448         }
1449
1450         if ((client = client_listener_find(listener,
1451                                            &src_ipaddr, src_port)) == NULL) {
1452                 rad_recv_discard(listener->fd);
1453                 FR_STATS_INC(auth, total_invalid_requests);
1454                 return 0;
1455         }
1456
1457         FR_STATS_TYPE_INC(client->auth.total_requests);
1458
1459         /*
1460          *      We only understand Status-Server on this socket.
1461          */
1462         if (code != PW_CODE_STATUS_SERVER) {
1463                 DEBUG("Ignoring packet code %d sent to Status-Server port",
1464                       code);
1465                 rad_recv_discard(listener->fd);
1466                 FR_STATS_INC(auth, total_unknown_types);
1467                 return 0;
1468         }
1469
1470         /*
1471          *      Now that we've sanity checked everything, receive the
1472          *      packet.
1473          */
1474         packet = rad_recv(NULL, listener->fd, 1); /* require message authenticator */
1475         if (!packet) {
1476                 FR_STATS_INC(auth, total_malformed_requests);
1477                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1478                 return 0;
1479         }
1480
1481         if (!request_receive(NULL, listener, packet, client, rad_status_server)) {
1482                 FR_STATS_INC(auth, total_packets_dropped);
1483                 rad_free(&packet);
1484                 return 0;
1485         }
1486
1487         return 1;
1488 }
1489 #endif
1490
1491
1492 /*
1493  *      Check if an incoming request is "ok"
1494  *
1495  *      It takes packets, not requests.  It sees if the packet looks
1496  *      OK.  If so, it does a number of sanity checks on it.
1497   */
1498 static int auth_socket_recv(rad_listen_t *listener)
1499 {
1500         ssize_t         rcode;
1501         int             code;
1502         uint16_t        src_port;
1503         RADIUS_PACKET   *packet;
1504         RAD_REQUEST_FUNP fun = NULL;
1505         RADCLIENT       *client = NULL;
1506         fr_ipaddr_t     src_ipaddr;
1507         TALLOC_CTX      *ctx;
1508
1509         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1510         if (rcode < 0) return 0;
1511
1512         FR_STATS_INC(auth, total_requests);
1513
1514         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1515                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1516                 FR_STATS_INC(auth, total_malformed_requests);
1517                 return 0;
1518         }
1519
1520         if ((client = client_listener_find(listener,
1521                                            &src_ipaddr, src_port)) == NULL) {
1522                 rad_recv_discard(listener->fd);
1523                 FR_STATS_INC(auth, total_invalid_requests);
1524                 return 0;
1525         }
1526
1527         FR_STATS_TYPE_INC(client->auth.total_requests);
1528
1529         /*
1530          *      Some sanity checks, based on the packet code.
1531          */
1532         switch (code) {
1533         case PW_CODE_ACCESS_REQUEST:
1534                 fun = rad_authenticate;
1535                 break;
1536
1537         case PW_CODE_STATUS_SERVER:
1538                 if (!main_config.status_server) {
1539                         rad_recv_discard(listener->fd);
1540                         FR_STATS_INC(auth, total_unknown_types);
1541                         WARN("Ignoring Status-Server request due to security configuration");
1542                         return 0;
1543                 }
1544                 fun = rad_status_server;
1545                 break;
1546
1547         default:
1548                 rad_recv_discard(listener->fd);
1549                 FR_STATS_INC(auth, total_unknown_types);
1550
1551                 if (DEBUG_ENABLED) ERROR("Receive - Invalid packet code %d sent to authentication port from "
1552                                          "client %s port %d", code, client->shortname, src_port);
1553                 return 0;
1554         } /* switch over packet types */
1555
1556         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1557         if (!ctx) {
1558                 rad_recv_discard(listener->fd);
1559                 FR_STATS_INC(auth, total_packets_dropped);
1560                 return 0;
1561         }
1562         talloc_set_name_const(ctx, "auth_listener_pool");
1563
1564         /*
1565          *      Now that we've sanity checked everything, receive the
1566          *      packet.
1567          */
1568         packet = rad_recv(ctx, listener->fd, client->message_authenticator);
1569         if (!packet) {
1570                 FR_STATS_INC(auth, total_malformed_requests);
1571                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1572                 talloc_free(ctx);
1573                 return 0;
1574         }
1575
1576 #ifdef __APPLE__
1577 #ifdef WITH_UDPFROMTO
1578         /*
1579          *      This is a NICE Mac OSX bug.  Create an interface with
1580          *      two IP address, and then configure one listener for
1581          *      each IP address.  Send thousands of packets to one
1582          *      address, and some will show up on the OTHER socket.
1583          *
1584          *      This hack works ONLY if the clients are global.  If
1585          *      each listener has the same client IP, but with
1586          *      different secrets, then it will fail the rad_recv()
1587          *      check above, and there's nothing you can do.
1588          */
1589         {
1590                 listen_socket_t *sock = listener->data;
1591                 rad_listen_t *other;
1592
1593                 other = listener_find_byipaddr(&packet->dst_ipaddr,
1594                                                packet->dst_port, sock->proto);
1595                 if (other) listener = other;
1596         }
1597 #endif
1598 #endif
1599
1600         if (!request_receive(ctx, listener, packet, client, fun)) {
1601                 FR_STATS_INC(auth, total_packets_dropped);
1602                 talloc_free(ctx);
1603                 return 0;
1604         }
1605
1606         return 1;
1607 }
1608
1609
1610 #ifdef WITH_ACCOUNTING
1611 /*
1612  *      Receive packets from an accounting socket
1613  */
1614 static int acct_socket_recv(rad_listen_t *listener)
1615 {
1616         ssize_t         rcode;
1617         int             code;
1618         uint16_t        src_port;
1619         RADIUS_PACKET   *packet;
1620         RAD_REQUEST_FUNP fun = NULL;
1621         RADCLIENT       *client = NULL;
1622         fr_ipaddr_t     src_ipaddr;
1623         TALLOC_CTX      *ctx;
1624
1625         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1626         if (rcode < 0) return 0;
1627
1628         FR_STATS_INC(acct, total_requests);
1629
1630         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1631                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1632                 FR_STATS_INC(acct, total_malformed_requests);
1633                 return 0;
1634         }
1635
1636         if ((client = client_listener_find(listener,
1637                                            &src_ipaddr, src_port)) == NULL) {
1638                 rad_recv_discard(listener->fd);
1639                 FR_STATS_INC(acct, total_invalid_requests);
1640                 return 0;
1641         }
1642
1643         FR_STATS_TYPE_INC(client->acct.total_requests);
1644
1645         /*
1646          *      Some sanity checks, based on the packet code.
1647          */
1648         switch (code) {
1649         case PW_CODE_ACCOUNTING_REQUEST:
1650                 fun = rad_accounting;
1651                 break;
1652
1653         case PW_CODE_STATUS_SERVER:
1654                 if (!main_config.status_server) {
1655                         rad_recv_discard(listener->fd);
1656                         FR_STATS_INC(acct, total_unknown_types);
1657
1658                         WARN("Ignoring Status-Server request due to security configuration");
1659                         return 0;
1660                 }
1661                 fun = rad_status_server;
1662                 break;
1663
1664         default:
1665                 rad_recv_discard(listener->fd);
1666                 FR_STATS_INC(acct, total_unknown_types);
1667
1668                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
1669                       code, client->shortname, src_port);
1670                 return 0;
1671         } /* switch over packet types */
1672
1673         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1674         if (!ctx) {
1675                 rad_recv_discard(listener->fd);
1676                 FR_STATS_INC(acct, total_packets_dropped);
1677                 return 0;
1678         }
1679         talloc_set_name_const(ctx, "acct_listener_pool");
1680
1681         /*
1682          *      Now that we've sanity checked everything, receive the
1683          *      packet.
1684          */
1685         packet = rad_recv(ctx, listener->fd, 0);
1686         if (!packet) {
1687                 FR_STATS_INC(acct, total_malformed_requests);
1688                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1689                 talloc_free(ctx);
1690                 return 0;
1691         }
1692
1693         /*
1694          *      There can be no duplicate accounting packets.
1695          */
1696         if (!request_receive(ctx, listener, packet, client, fun)) {
1697                 FR_STATS_INC(acct, total_packets_dropped);
1698                 rad_free(&packet);
1699                 talloc_free(ctx);
1700                 return 0;
1701         }
1702
1703         return 1;
1704 }
1705 #endif
1706
1707
1708 #ifdef WITH_COA
1709 static int do_proxy(REQUEST *request)
1710 {
1711         VALUE_PAIR *vp;
1712
1713         if (request->in_proxy_hash ||
1714             (request->proxy_reply && (request->proxy_reply->code != 0))) {
1715                 return 0;
1716         }
1717
1718         vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY);
1719
1720         if (vp) {
1721                 if (!home_pool_byname(vp->vp_strvalue, HOME_TYPE_COA)) {
1722                         REDEBUG2("Cannot proxy to unknown pool %s",
1723                                  vp->vp_strvalue);
1724                         return 0;
1725                 }
1726
1727                 return 1;
1728         }
1729
1730         /*
1731          *      We have a destination IP address.  It will (later) proxied.
1732          */
1733         vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
1734         if (!vp) vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY);
1735
1736         if (!vp) return 0;
1737
1738         return 1;
1739 }
1740
1741 /*
1742  *      Receive a CoA packet.
1743  */
1744 int rad_coa_recv(REQUEST *request)
1745 {
1746         int rcode = RLM_MODULE_OK;
1747         int ack, nak;
1748         VALUE_PAIR *vp;
1749
1750         /*
1751          *      Get the correct response
1752          */
1753         switch (request->packet->code) {
1754         case PW_CODE_COA_REQUEST:
1755                 ack = PW_CODE_COA_ACK;
1756                 nak = PW_CODE_COA_NAK;
1757                 break;
1758
1759         case PW_CODE_DISCONNECT_REQUEST:
1760                 ack = PW_CODE_DISCONNECT_ACK;
1761                 nak = PW_CODE_DISCONNECT_NAK;
1762                 break;
1763
1764         default:                /* shouldn't happen */
1765                 return RLM_MODULE_FAIL;
1766         }
1767
1768 #ifdef WITH_PROXY
1769 #define WAS_PROXIED (request->proxy)
1770 #else
1771 #define WAS_PROXIED (0)
1772 #endif
1773
1774         if (!WAS_PROXIED) {
1775                 /*
1776                  *      RFC 5176 Section 3.3.  If we have a CoA-Request
1777                  *      with Service-Type = Authorize-Only, it MUST
1778                  *      have a State attribute in it.
1779                  */
1780                 vp = fr_pair_find_by_num(request->packet->vps, PW_SERVICE_TYPE, 0, TAG_ANY);
1781                 if (request->packet->code == PW_CODE_COA_REQUEST) {
1782                         if (vp && (vp->vp_integer == PW_AUTHORIZE_ONLY)) {
1783                                 vp = fr_pair_find_by_num(request->packet->vps, PW_STATE, 0, TAG_ANY);
1784                                 if (!vp || (vp->vp_length == 0)) {
1785                                         REDEBUG("CoA-Request with Service-Type = Authorize-Only MUST contain a State attribute");
1786                                         request->reply->code = PW_CODE_COA_NAK;
1787                                         return RLM_MODULE_FAIL;
1788                                 }
1789                         }
1790                 } else if (vp) {
1791                         /*
1792                          *      RFC 5176, Section 3.2.
1793                          */
1794                         REDEBUG("Disconnect-Request MUST NOT contain a Service-Type attribute");
1795                         request->reply->code = PW_CODE_DISCONNECT_NAK;
1796                         return RLM_MODULE_FAIL;
1797                 }
1798
1799                 rcode = process_recv_coa(0, request);
1800                 switch (rcode) {
1801                 case RLM_MODULE_FAIL:
1802                 case RLM_MODULE_INVALID:
1803                 case RLM_MODULE_REJECT:
1804                 case RLM_MODULE_USERLOCK:
1805                 default:
1806                         request->reply->code = nak;
1807                         break;
1808
1809                 case RLM_MODULE_HANDLED:
1810                         return rcode;
1811
1812                 case RLM_MODULE_NOOP:
1813                 case RLM_MODULE_NOTFOUND:
1814                 case RLM_MODULE_OK:
1815                 case RLM_MODULE_UPDATED:
1816                         if (do_proxy(request)) return RLM_MODULE_OK;
1817                         request->reply->code = ack;
1818                         break;
1819                 }
1820
1821         }
1822
1823 #ifdef WITH_PROXY
1824         else if (request->proxy_reply) {
1825                 /*
1826                  *      Start the reply code with the proxy reply
1827                  *      code.
1828                  */
1829                 request->reply->code = request->proxy_reply->code;
1830         }
1831 #endif
1832
1833         /*
1834          *      Copy State from the request to the reply.
1835          *      See RFC 5176 Section 3.3.
1836          */
1837         vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps, PW_STATE, 0, TAG_ANY);
1838         if (vp) fr_pair_add(&request->reply->vps, vp);
1839
1840         /*
1841          *      We may want to over-ride the reply.
1842          */
1843         if (request->reply->code) {
1844                 rcode = process_send_coa(0, request);
1845                 switch (rcode) {
1846                         /*
1847                          *      We need to send CoA-NAK back if Service-Type
1848                          *      is Authorize-Only.  Rely on the user's policy
1849                          *      to do that.  We're not a real NAS, so this
1850                          *      restriction doesn't (ahem) apply to us.
1851                          */
1852                 case RLM_MODULE_FAIL:
1853                 case RLM_MODULE_INVALID:
1854                 case RLM_MODULE_REJECT:
1855                 case RLM_MODULE_USERLOCK:
1856                 default:
1857                         /*
1858                          *      Over-ride an ACK with a NAK
1859                          */
1860                         request->reply->code = nak;
1861                         break;
1862
1863                 case RLM_MODULE_HANDLED:
1864                         return rcode;
1865
1866                 case RLM_MODULE_NOOP:
1867                 case RLM_MODULE_NOTFOUND:
1868                 case RLM_MODULE_OK:
1869                 case RLM_MODULE_UPDATED:
1870                         /*
1871                          *      Do NOT over-ride a previously set value.
1872                          *      Otherwise an "ok" here will re-write a
1873                          *      NAK to an ACK.
1874                          */
1875                         if (request->reply->code == 0) {
1876                                 request->reply->code = ack;
1877                         }
1878                         break;
1879                 }
1880         }
1881
1882         return RLM_MODULE_OK;
1883 }
1884
1885
1886 /*
1887  *      Check if an incoming request is "ok"
1888  *
1889  *      It takes packets, not requests.  It sees if the packet looks
1890  *      OK.  If so, it does a number of sanity checks on it.
1891   */
1892 static int coa_socket_recv(rad_listen_t *listener)
1893 {
1894         ssize_t         rcode;
1895         int             code;
1896         uint16_t        src_port;
1897         RADIUS_PACKET   *packet;
1898         RAD_REQUEST_FUNP fun = NULL;
1899         RADCLIENT       *client = NULL;
1900         fr_ipaddr_t     src_ipaddr;
1901         TALLOC_CTX      *ctx;
1902
1903         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1904         if (rcode < 0) return 0;
1905
1906         if (rcode < 20) {       /* RADIUS_HDR_LEN */
1907                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1908                 FR_STATS_INC(coa, total_malformed_requests);
1909                 return 0;
1910         }
1911
1912         if ((client = client_listener_find(listener,
1913                                            &src_ipaddr, src_port)) == NULL) {
1914                 rad_recv_discard(listener->fd);
1915                 FR_STATS_INC(coa, total_requests);
1916                 FR_STATS_INC(coa, total_invalid_requests);
1917                 return 0;
1918         }
1919
1920         /*
1921          *      Some sanity checks, based on the packet code.
1922          */
1923         switch (code) {
1924         case PW_CODE_COA_REQUEST:
1925                 FR_STATS_INC(coa, total_requests);
1926                 fun = rad_coa_recv;
1927                 break;
1928
1929         case PW_CODE_DISCONNECT_REQUEST:
1930                 FR_STATS_INC(dsc, total_requests);
1931                 fun = rad_coa_recv;
1932                 break;
1933
1934         default:
1935                 rad_recv_discard(listener->fd);
1936                 FR_STATS_INC(coa, total_unknown_types);
1937                 DEBUG("Invalid packet code %d sent to coa port from client %s port %d : IGNORED",
1938                       code, client->shortname, src_port);
1939                 return 0;
1940         } /* switch over packet types */
1941
1942         ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1943         if (!ctx) {
1944                 rad_recv_discard(listener->fd);
1945                 FR_STATS_INC(coa, total_packets_dropped);
1946                 return 0;
1947         }
1948         talloc_set_name_const(ctx, "coa_socket_recv_pool");
1949
1950         /*
1951          *      Now that we've sanity checked everything, receive the
1952          *      packet.
1953          */
1954         packet = rad_recv(ctx, listener->fd, client->message_authenticator);
1955         if (!packet) {
1956                 FR_STATS_INC(coa, total_malformed_requests);
1957                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1958                 talloc_free(ctx);
1959                 return 0;
1960         }
1961
1962         if (!request_receive(ctx, listener, packet, client, fun)) {
1963                 FR_STATS_INC(coa, total_packets_dropped);
1964                 rad_free(&packet);
1965                 talloc_free(ctx);
1966                 return 0;
1967         }
1968
1969         return 1;
1970 }
1971 #endif
1972
1973 #ifdef WITH_PROXY
1974 /*
1975  *      Recieve packets from a proxy socket.
1976  */
1977 static int proxy_socket_recv(rad_listen_t *listener)
1978 {
1979         RADIUS_PACKET   *packet;
1980 #ifdef WITH_TCP
1981         listen_socket_t *sock;
1982 #endif
1983         char            buffer[128];
1984
1985         packet = rad_recv(NULL, listener->fd, 0);
1986         if (!packet) {
1987                 if (DEBUG_ENABLED) ERROR("Receive - %s", fr_strerror());
1988                 return 0;
1989         }
1990
1991         switch (packet->code) {
1992         case PW_CODE_ACCESS_ACCEPT:
1993         case PW_CODE_ACCESS_CHALLENGE:
1994         case PW_CODE_ACCESS_REJECT:
1995                 break;
1996
1997 #ifdef WITH_ACCOUNTING
1998         case PW_CODE_ACCOUNTING_RESPONSE:
1999                 break;
2000 #endif
2001
2002 #ifdef WITH_COA
2003         case PW_CODE_DISCONNECT_ACK:
2004         case PW_CODE_DISCONNECT_NAK:
2005         case PW_CODE_COA_ACK:
2006         case PW_CODE_COA_NAK:
2007                 break;
2008 #endif
2009
2010         default:
2011                 /*
2012                  *      FIXME: Update MIB for packet types?
2013                  */
2014                 ERROR("Invalid packet code %d sent to a proxy port "
2015                        "from home server %s port %d - ID %d : IGNORED",
2016                        packet->code,
2017                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2018                        packet->src_port, packet->id);
2019 #ifdef WITH_STATS
2020                 listener->stats.total_unknown_types++;
2021 #endif
2022                 rad_free(&packet);
2023                 return 0;
2024         }
2025
2026 #ifdef WITH_TCP
2027         sock = listener->data;
2028         packet->proto = sock->proto;
2029 #endif
2030
2031         if (!request_proxy_reply(packet)) {
2032 #ifdef WITH_STATS
2033                 listener->stats.total_packets_dropped++;
2034 #endif
2035                 rad_free(&packet);
2036                 return 0;
2037         }
2038
2039         return 1;
2040 }
2041
2042 #ifdef WITH_TCP
2043 /*
2044  *      Recieve packets from a proxy socket.
2045  */
2046 static int proxy_socket_tcp_recv(rad_listen_t *listener)
2047 {
2048         RADIUS_PACKET   *packet;
2049         listen_socket_t *sock = listener->data;
2050         char            buffer[128];
2051
2052         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return 0;
2053
2054         packet = fr_tcp_recv(listener->fd, 0);
2055         if (!packet) {
2056                 listener->status = RAD_LISTEN_STATUS_EOL;
2057                 radius_update_listener(listener);
2058                 return 0;
2059         }
2060
2061         /*
2062          *      FIXME: Client MIB updates?
2063          */
2064         switch (packet->code) {
2065         case PW_CODE_ACCESS_ACCEPT:
2066         case PW_CODE_ACCESS_CHALLENGE:
2067         case PW_CODE_ACCESS_REJECT:
2068                 break;
2069
2070 #ifdef WITH_ACCOUNTING
2071         case PW_CODE_ACCOUNTING_RESPONSE:
2072                 break;
2073 #endif
2074
2075         default:
2076                 /*
2077                  *      FIXME: Update MIB for packet types?
2078                  */
2079                 ERROR("Invalid packet code %d sent to a proxy port "
2080                        "from home server %s port %d - ID %d : IGNORED",
2081                        packet->code,
2082                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
2083                        packet->src_port, packet->id);
2084                 rad_free(&packet);
2085                 return 0;
2086         }
2087
2088         packet->src_ipaddr = sock->other_ipaddr;
2089         packet->src_port = sock->other_port;
2090         packet->dst_ipaddr = sock->my_ipaddr;
2091         packet->dst_port = sock->my_port;
2092
2093         /*
2094          *      FIXME: Have it return an indication of packets that
2095          *      are OK to ignore (dups, too late), versus ones that
2096          *      aren't OK to ignore (unknown response, spoofed, etc.)
2097          *
2098          *      Close the socket on bad packets...
2099          */
2100         if (!request_proxy_reply(packet)) {
2101                 rad_free(&packet);
2102                 return 0;
2103         }
2104
2105         sock->opened = sock->last_packet = time(NULL);
2106
2107         return 1;
2108 }
2109 #endif
2110 #endif
2111
2112
2113 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
2114 {
2115         if (!request->reply->code) return 0;
2116
2117         if (rad_encode(request->reply, request->packet, request->client->secret) < 0) {
2118                 RERROR("Failed encoding packet: %s", fr_strerror());
2119
2120                 return -1;
2121         }
2122
2123         if (rad_sign(request->reply, request->packet, request->client->secret) < 0) {
2124                 RERROR("Failed signing packet: %s", fr_strerror());
2125
2126                 return -1;
2127         }
2128
2129         return 0;
2130 }
2131
2132
2133 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
2134 {
2135 #ifdef WITH_TLS
2136         listen_socket_t *sock;
2137 #endif
2138
2139         if (rad_verify(request->packet, NULL,
2140                        request->client->secret) < 0) {
2141                 return -1;
2142         }
2143
2144 #ifdef WITH_TLS
2145         sock = request->listener->data;
2146         rad_assert(sock != NULL);
2147
2148         /*
2149          *      FIXME: Add the rest of the TLS parameters, too?  But
2150          *      how do we separate EAP-TLS parameters from RADIUS/TLS
2151          *      parameters?
2152          */
2153         if (sock->ssn && sock->ssn->ssl) {
2154 #ifdef PSK_MAX_IDENTITY_LEN
2155                 const char *identity = SSL_get_psk_identity(sock->ssn->ssl);
2156                 if (identity) {
2157                         RDEBUG("Retrieved psk identity: %s", identity);
2158                         pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
2159                 }
2160 #endif
2161         }
2162 #endif
2163
2164         return rad_decode(request->packet, NULL,
2165                           request->client->secret);
2166 }
2167
2168 #ifdef WITH_PROXY
2169 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
2170 {
2171         if (rad_encode(request->proxy, NULL, request->home_server->secret) < 0) {
2172                 RERROR("Failed encoding proxied packet: %s", fr_strerror());
2173
2174                 return -1;
2175         }
2176
2177         if (rad_sign(request->proxy, NULL, request->home_server->secret) < 0) {
2178                 RERROR("Failed signing proxied packet: %s", fr_strerror());
2179
2180                 return -1;
2181         }
2182
2183         return 0;
2184 }
2185
2186
2187 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
2188 {
2189         /*
2190          *      rad_verify is run in event.c, received_proxy_response()
2191          */
2192
2193         return rad_decode(request->proxy_reply, request->proxy,
2194                            request->home_server->secret);
2195 }
2196 #endif
2197
2198 #include "command.c"
2199
2200 /*
2201  *      Temporarily NOT const!
2202  */
2203 static fr_protocol_t master_listen[RAD_LISTEN_MAX] = {
2204 #ifdef WITH_STATS
2205         { RLM_MODULE_INIT, "status", sizeof(listen_socket_t), NULL,
2206           common_socket_parse, NULL,
2207           stats_socket_recv, auth_socket_send,
2208           common_socket_print, client_socket_encode, client_socket_decode },
2209 #else
2210         /*
2211          *      This always gets defined.
2212          */
2213         { RLM_MODULE_INIT, "status", 0, NULL,
2214           NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
2215 #endif
2216
2217 #ifdef WITH_PROXY
2218         /* proxying */
2219         { RLM_MODULE_INIT, "proxy", sizeof(listen_socket_t), NULL,
2220           common_socket_parse, common_socket_free,
2221           proxy_socket_recv, proxy_socket_send,
2222           common_socket_print, proxy_socket_encode, proxy_socket_decode },
2223 #endif
2224
2225         /* authentication */
2226         { RLM_MODULE_INIT, "auth", sizeof(listen_socket_t), NULL,
2227           common_socket_parse, common_socket_free,
2228           auth_socket_recv, auth_socket_send,
2229           common_socket_print, client_socket_encode, client_socket_decode },
2230
2231 #ifdef WITH_ACCOUNTING
2232         /* accounting */
2233         { RLM_MODULE_INIT, "acct", sizeof(listen_socket_t), NULL,
2234           common_socket_parse, common_socket_free,
2235           acct_socket_recv, acct_socket_send,
2236           common_socket_print, client_socket_encode, client_socket_decode},
2237 #endif
2238
2239 #ifdef WITH_DETAIL
2240         /* detail */
2241         { RLM_MODULE_INIT, "detail", sizeof(listen_detail_t), NULL,
2242           detail_parse, detail_free,
2243           detail_recv, detail_send,
2244           detail_print, detail_encode, detail_decode },
2245 #endif
2246
2247 #ifdef WITH_VMPS
2248         /* vlan query protocol */
2249         { 0, "vmps", 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
2250 #endif
2251
2252 #ifdef WITH_DHCP
2253         /* dhcp query protocol */
2254         { 0, "dhcp", 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
2255 #endif
2256
2257 #ifdef WITH_COMMAND_SOCKET
2258         /* TCP command socket */
2259         { RLM_MODULE_INIT, "control", sizeof(fr_command_socket_t), NULL,
2260           command_socket_parse, command_socket_free,
2261           command_domain_accept, command_domain_send,
2262           command_socket_print, command_socket_encode, command_socket_decode },
2263 #endif
2264
2265 #ifdef WITH_COA
2266         /* Change of Authorization */
2267         { RLM_MODULE_INIT, "coa", sizeof(listen_socket_t), NULL,
2268           common_socket_parse, NULL,
2269           coa_socket_recv, auth_socket_send, /* CoA packets are same as auth */
2270           common_socket_print, client_socket_encode, client_socket_decode },
2271 #endif
2272
2273 };
2274
2275
2276
2277 /*
2278  *      Binds a listener to a socket.
2279  */
2280 static int listen_bind(rad_listen_t *this)
2281 {
2282         int rcode;
2283         struct sockaddr_storage salocal;
2284         socklen_t       salen;
2285         listen_socket_t *sock = this->data;
2286 #ifndef WITH_TCP
2287 #define proto_for_port "udp"
2288 #define sock_type SOCK_DGRAM
2289 #else
2290         char const *proto_for_port = "udp";
2291         int sock_type = SOCK_DGRAM;
2292
2293         if (sock->proto == IPPROTO_TCP) {
2294 #ifdef WITH_VMPS
2295                 if (this->type == RAD_LISTEN_VQP) {
2296                         ERROR("VQP does not support TCP transport");
2297                         return -1;
2298                 }
2299 #endif
2300
2301                 proto_for_port = "tcp";
2302                 sock_type = SOCK_STREAM;
2303         }
2304 #endif
2305
2306         /*
2307          *      If the port is zero, then it means the appropriate
2308          *      thing from /etc/services.
2309          */
2310         if (sock->my_port == 0) {
2311                 struct servent  *svp;
2312
2313                 switch (this->type) {
2314                 case RAD_LISTEN_AUTH:
2315                         svp = getservbyname ("radius", proto_for_port);
2316                         if (svp != NULL) {
2317                                 sock->my_port = ntohs(svp->s_port);
2318                         } else {
2319                                 sock->my_port = PW_AUTH_UDP_PORT;
2320                         }
2321                         break;
2322
2323 #ifdef WITH_ACCOUNTING
2324                 case RAD_LISTEN_ACCT:
2325                         svp = getservbyname ("radacct", proto_for_port);
2326                         if (svp != NULL) {
2327                                 sock->my_port = ntohs(svp->s_port);
2328                         } else {
2329                                 sock->my_port = PW_ACCT_UDP_PORT;
2330                         }
2331                         break;
2332 #endif
2333
2334 #ifdef WITH_PROXY
2335                 case RAD_LISTEN_PROXY:
2336                         /* leave it at zero */
2337                         break;
2338 #endif
2339
2340 #ifdef WITH_VMPS
2341                 case RAD_LISTEN_VQP:
2342                         sock->my_port = 1589;
2343                         break;
2344 #endif
2345
2346 #ifdef WITH_COMMAND_SOCKET
2347                 case RAD_LISTEN_COMMAND:
2348                         sock->my_port = PW_RADMIN_PORT;
2349                         break;
2350 #endif
2351
2352 #ifdef WITH_COA
2353                 case RAD_LISTEN_COA:
2354                         svp = getservbyname ("radius-dynauth", "udp");
2355                         if (svp != NULL) {
2356                                 sock->my_port = ntohs(svp->s_port);
2357                         } else {
2358                                 sock->my_port = PW_COA_UDP_PORT;
2359                         }
2360                         break;
2361 #endif
2362
2363                 default:
2364                         WARN("Internal sanity check failed in binding to socket.  Ignoring problem");
2365                         return -1;
2366                 }
2367         }
2368
2369         /*
2370          *      Don't open sockets if we're checking the config.
2371          */
2372         if (check_config) {
2373                 this->fd = -1;
2374                 return 0;
2375         }
2376
2377         /*
2378          *      Copy fr_socket() here, as we may need to bind to a device.
2379          */
2380         this->fd = socket(sock->my_ipaddr.af, sock_type, 0);
2381         if (this->fd < 0) {
2382                 char buffer[256];
2383
2384                 this->print(this, buffer, sizeof(buffer));
2385
2386                 ERROR("Failed opening %s: %s", buffer, fr_syserror(errno));
2387                 return -1;
2388         }
2389
2390 #ifdef FD_CLOEXEC
2391         /*
2392          *      We don't want child processes inheriting these
2393          *      file descriptors.
2394          */
2395         rcode = fcntl(this->fd, F_GETFD);
2396         if (rcode >= 0) {
2397                 if (fcntl(this->fd, F_SETFD, rcode | FD_CLOEXEC) < 0) {
2398                         close(this->fd);
2399                         ERROR("Failed setting close on exec: %s", fr_syserror(errno));
2400                         return -1;
2401                 }
2402         }
2403 #endif
2404
2405         /*
2406          *      Bind to a device BEFORE touching IP addresses.
2407          */
2408         if (sock->interface) {
2409 #ifdef SO_BINDTODEVICE
2410                 struct ifreq ifreq;
2411
2412                 memset(&ifreq, 0, sizeof(ifreq));
2413                 strlcpy(ifreq.ifr_name, sock->interface, sizeof(ifreq.ifr_name));
2414
2415                 rad_suid_up();
2416                 rcode = setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
2417                                    (char *)&ifreq, sizeof(ifreq));
2418                 rad_suid_down();
2419                 if (rcode < 0) {
2420                         close(this->fd);
2421                         ERROR("Failed binding to interface %s: %s",
2422                                sock->interface, fr_syserror(errno));
2423                         return -1;
2424                 } /* else it worked. */
2425 #else
2426 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2427 #ifdef HAVE_NET_IF_H
2428                 /*
2429                  *      Odds are that any system supporting "bind to
2430                  *      device" also supports IPv6, so this next bit
2431                  *      isn't necessary.  But it's here for
2432                  *      completeness.
2433                  *
2434                  *      If we're doing IPv6, and the scope hasn't yet
2435                  *      been defined, set the scope to the scope of
2436                  *      the interface.
2437                  */
2438                 if (sock->my_ipaddr.af == AF_INET6) {
2439                         if (sock->my_ipaddr.scope == 0) {
2440                                 sock->my_ipaddr.scope = if_nametoindex(sock->interface);
2441                                 if (sock->my_ipaddr.scope == 0) {
2442                                         close(this->fd);
2443                                         ERROR("Failed finding interface %s: %s",
2444                                                sock->interface, fr_syserror(errno));
2445                                         return -1;
2446                                 }
2447                         } /* else scope was defined: we're OK. */
2448                 } else
2449 #endif
2450 #endif
2451                                 /*
2452                                  *      IPv4: no link local addresses,
2453                                  *      and no bind to device.
2454                                  */
2455                 {
2456                         close(this->fd);
2457                         ERROR("Failed binding to interface %s: \"bind to device\" is unsupported", sock->interface);
2458                         return -1;
2459                 }
2460 #endif
2461         }
2462
2463 #ifdef WITH_TCP
2464         if (sock->proto == IPPROTO_TCP) {
2465                 int on = 1;
2466
2467                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
2468                         close(this->fd);
2469                         ERROR("Failed to reuse address: %s", fr_syserror(errno));
2470                         return -1;
2471                 }
2472         }
2473 #endif
2474
2475 #if defined(WITH_TCP) && defined(WITH_UDPFROMTO)
2476         else                    /* UDP sockets get UDPfromto */
2477 #endif
2478
2479 #ifdef WITH_UDPFROMTO
2480         /*
2481          *      Initialize udpfromto for all sockets.
2482          */
2483         if (udpfromto_init(this->fd) != 0) {
2484                 ERROR("Failed initializing udpfromto: %s",
2485                        fr_syserror(errno));
2486                 close(this->fd);
2487                 return -1;
2488         }
2489 #endif
2490
2491         /*
2492          *      Set up sockaddr stuff.
2493          */
2494         if (!fr_ipaddr2sockaddr(&sock->my_ipaddr, sock->my_port, &salocal, &salen)) {
2495                 close(this->fd);
2496                 return -1;
2497         }
2498
2499 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2500         if (sock->my_ipaddr.af == AF_INET6) {
2501                 /*
2502                  *      Listening on '::' does NOT get you IPv4 to
2503                  *      IPv6 mapping.  You've got to listen on an IPv4
2504                  *      address, too.  This makes the rest of the server
2505                  *      design a little simpler.
2506                  */
2507 #ifdef IPV6_V6ONLY
2508
2509                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->my_ipaddr.ipaddr.ip6addr)) {
2510                         int on = 1;
2511
2512                         if (setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2513                                        (char *)&on, sizeof(on)) < 0) {
2514                                 ERROR("Failed setting socket to IPv6 "
2515                                        "only: %s", fr_syserror(errno));
2516
2517                                 close(this->fd);
2518                                 return -1;
2519                         }
2520                 }
2521 #endif /* IPV6_V6ONLY */
2522         }
2523 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
2524
2525         if (sock->my_ipaddr.af == AF_INET) {
2526 #if (defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)) || defined(IP_DONTFRAG)
2527                 int flag;
2528 #endif
2529
2530 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2531
2532                 /*
2533                  *      Disable PMTU discovery.  On Linux, this
2534                  *      also makes sure that the "don't fragment"
2535                  *      flag is zero.
2536                  */
2537                 flag = IP_PMTUDISC_DONT;
2538                 if (setsockopt(this->fd, IPPROTO_IP, IP_MTU_DISCOVER,
2539                                &flag, sizeof(flag)) < 0) {
2540                         ERROR("Failed disabling PMTU discovery: %s",
2541                                fr_syserror(errno));
2542
2543                         close(this->fd);
2544                         return -1;
2545                 }
2546 #endif
2547
2548 #if defined(IP_DONTFRAG)
2549                 /*
2550                  *      Ensure that the "don't fragment" flag is zero.
2551                  */
2552                 flag = 0;
2553                 if (setsockopt(this->fd, IPPROTO_IP, IP_DONTFRAG,
2554                                &flag, sizeof(flag)) < 0) {
2555                         ERROR("Failed setting don't fragment flag: %s",
2556                                fr_syserror(errno));
2557
2558                         close(this->fd);
2559                         return -1;
2560                 }
2561 #endif
2562         }
2563
2564 #ifdef WITH_DHCP
2565 #ifdef SO_BROADCAST
2566         if (sock->broadcast) {
2567                 int on = 1;
2568
2569                 if (setsockopt(this->fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
2570                         ERROR("Can't set broadcast option: %s",
2571                                fr_syserror(errno));
2572                         return -1;
2573                 }
2574         }
2575 #endif
2576 #endif
2577
2578         /*
2579          *      May be binding to priviledged ports.
2580          */
2581         if (sock->my_port != 0) {
2582                 rad_suid_up();
2583                 rcode = bind(this->fd, (struct sockaddr *) &salocal, salen);
2584                 rad_suid_down();
2585                 if (rcode < 0) {
2586                         char buffer[256];
2587                         close(this->fd);
2588
2589                         this->print(this, buffer, sizeof(buffer));
2590                         ERROR("Failed binding to %s: %s\n",
2591                                buffer, fr_syserror(errno));
2592                         return -1;
2593                 }
2594
2595                 /*
2596                  *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
2597                  *      kernel instead binds us to a 1.2.3.4.  If this
2598                  *      happens, notice, and remember our real IP.
2599                  */
2600                 {
2601                         struct sockaddr_storage src;
2602                         socklen_t               sizeof_src = sizeof(src);
2603
2604                         memset(&src, 0, sizeof_src);
2605                         if (getsockname(this->fd, (struct sockaddr *) &src,
2606                                         &sizeof_src) < 0) {
2607                                 ERROR("Failed getting socket name: %s",
2608                                        fr_syserror(errno));
2609                                 return -1;
2610                         }
2611
2612                         if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2613                                                 &sock->my_ipaddr, &sock->my_port)) {
2614                                 ERROR("Socket has unsupported address family");
2615                                 return -1;
2616                         }
2617                 }
2618         }
2619
2620 #ifdef WITH_TCP
2621         if (sock->proto == IPPROTO_TCP) {
2622                 /*
2623                  *      If there are hard-coded worker threads, OR
2624                  *      it's a TLS connection, it's blocking.
2625                  *
2626                  *      Otherwise, they're non-blocking.
2627                  */
2628                 if (!this->workers
2629 #ifdef WITH_PROXY
2630 #ifdef WITH_TLS
2631                     && (this->type == RAD_LISTEN_PROXY) && !this->tls
2632 #endif
2633 #endif
2634                         ) {
2635                         if (fr_nonblock(this->fd) < 0) {
2636                                 close(this->fd);
2637                                 ERROR("Failed setting non-blocking on socket: %s",
2638                                       fr_syserror(errno));
2639                                 return -1;
2640                         }
2641                 }
2642
2643                 /*
2644                  *      Allow a backlog of 8 listeners, but only for incoming interfaces.
2645                  */
2646 #ifdef WITH_PROXY
2647                 if (this->type != RAD_LISTEN_PROXY)
2648 #endif
2649                 if (listen(this->fd, 8) < 0) {
2650                         close(this->fd);
2651                         ERROR("Failed in listen(): %s", fr_syserror(errno));
2652                         return -1;
2653                 }
2654         }
2655 #endif
2656
2657         /*
2658          *      Mostly for proxy sockets.
2659          */
2660         sock->other_ipaddr.af = sock->my_ipaddr.af;
2661
2662 /*
2663  *      Don't screw up other people.
2664  */
2665 #undef proto_for_port
2666 #undef sock_type
2667
2668         return 0;
2669 }
2670
2671
2672 static int _listener_free(rad_listen_t *this)
2673 {
2674         /*
2675          *      Other code may have eaten the FD.
2676          */
2677         if (this->fd >= 0) close(this->fd);
2678
2679         if (master_listen[this->type].free) {
2680                 master_listen[this->type].free(this);
2681         }
2682
2683 #ifdef WITH_TCP
2684         if ((this->type == RAD_LISTEN_AUTH)
2685 #ifdef WITH_ACCT
2686             || (this->type == RAD_LISTEN_ACCT)
2687 #endif
2688 #ifdef WITH_PROXY
2689             || (this->type == RAD_LISTEN_PROXY)
2690 #endif
2691 #ifdef WITH_COMMAND_SOCKET
2692             || ((this->type == RAD_LISTEN_COMMAND) &&
2693                 (((fr_command_socket_t *) this->data)->magic != COMMAND_SOCKET_MAGIC))
2694 #endif
2695                 ) {
2696                 listen_socket_t *sock = this->data;
2697
2698                 rad_assert(talloc_parent(sock) == this);
2699                 rad_assert(sock->ev == NULL);
2700
2701                 /*
2702                  *      Remove the child from the parent tree.
2703                  */
2704                 if (this->parent) {
2705                         rbtree_deletebydata(this->parent->children, this);
2706                 }
2707
2708                 /*
2709                  *      Delete / close all of the children, too!
2710                  */
2711                 if (this->children) {
2712                         rbtree_walk(this->children, RBTREE_DELETE_ORDER, listener_unlink, this);
2713                 }
2714
2715 #ifdef WITH_TLS
2716                 /*
2717                  *      Note that we do NOT free this->tls, as the
2718                  *      pointer is parented by its CONF_SECTION.  It
2719                  *      may be used by multiple listeners.
2720                  */
2721                 if (this->tls) {
2722                         rad_assert(!sock->ssn || (talloc_parent(sock->ssn) == sock));
2723                         rad_assert(!sock->request || (talloc_parent(sock->request) == sock));
2724 #ifdef HAVE_PTHREAD_H
2725                         pthread_mutex_destroy(&(sock->mutex));
2726 #endif
2727                 }
2728 #endif  /* WITH_TLS */
2729         }
2730 #endif                          /* WITH_TCP */
2731
2732         return 0;
2733 }
2734
2735
2736 /*
2737  *      Allocate & initialize a new listener.
2738  */
2739 static rad_listen_t *listen_alloc(TALLOC_CTX *ctx, RAD_LISTEN_TYPE type)
2740 {
2741         rad_listen_t *this;
2742
2743         this = talloc_zero(ctx, rad_listen_t);
2744
2745         this->type = type;
2746         this->recv = master_listen[this->type].recv;
2747         this->send = master_listen[this->type].send;
2748         this->print = master_listen[this->type].print;
2749         this->encode = master_listen[this->type].encode;
2750         this->decode = master_listen[this->type].decode;
2751
2752         talloc_set_destructor(this, _listener_free);
2753
2754         this->data = talloc_zero_array(this, uint8_t, master_listen[this->type].inst_size);
2755
2756         return this;
2757 }
2758
2759 #ifdef WITH_PROXY
2760 /*
2761  *      Externally visible function for creating a new proxy LISTENER.
2762  *
2763  *      Not thread-safe, but all calls to it are protected by the
2764  *      proxy mutex in event.c
2765  */
2766 rad_listen_t *proxy_new_listener(TALLOC_CTX *ctx, home_server_t *home, uint16_t src_port)
2767 {
2768         time_t now;
2769         rad_listen_t *this;
2770         listen_socket_t *sock;
2771         char buffer[256];
2772
2773         if (!home) return NULL;
2774
2775         rad_assert(home->server == NULL); /* we only open real sockets */
2776
2777         if ((home->limit.max_connections > 0) &&
2778             (home->limit.num_connections >= home->limit.max_connections)) {
2779                 RATE_LIMIT(INFO("Home server %s has too many open connections (%d)",
2780                                 home->log_name, home->limit.max_connections));
2781                 return NULL;
2782         }
2783
2784         now = time(NULL);
2785         if (home->last_failed_open == now) {
2786                 WARN("Suppressing attempt to open socket to 'down' home server");
2787                 return NULL;
2788         }
2789
2790         this = listen_alloc(ctx, RAD_LISTEN_PROXY);
2791
2792         sock = this->data;
2793         sock->other_ipaddr = home->ipaddr;
2794         sock->other_port = home->port;
2795         sock->home = home;
2796
2797         sock->my_ipaddr = home->src_ipaddr;
2798         sock->my_port = src_port;
2799         sock->proto = home->proto;
2800
2801         /*
2802          *      For error messages.
2803          */
2804         this->print(this, buffer, sizeof(buffer));
2805
2806         if (rad_debug_lvl >= 2) {
2807                 DEBUG("Opening new proxy socket '%s'", buffer);
2808         }
2809
2810 #ifdef WITH_TCP
2811         sock->opened = sock->last_packet = now;
2812
2813         if (home->proto == IPPROTO_TCP) {
2814                 this->recv = proxy_socket_tcp_recv;
2815
2816                 /*
2817                  *      FIXME: connect() is blocking!
2818                  *      We do this with the proxy mutex locked, which may
2819                  *      cause large delays!
2820                  *
2821                  *      http://www.developerweb.net/forum/showthread.php?p=13486
2822                  */
2823                 this->fd = fr_socket_client_tcp(&home->src_ipaddr,
2824                                                 &home->ipaddr, home->port, false);
2825         } else
2826 #endif
2827                 this->fd = fr_socket(&home->src_ipaddr, src_port);
2828
2829         if (this->fd < 0) {
2830                 this->print(this, buffer,sizeof(buffer));
2831                 ERROR("Failed opening proxy socket '%s' : %s",
2832                       buffer, fr_strerror());
2833                 home->last_failed_open = now;
2834                 listen_free(&this);
2835                 return NULL;
2836         }
2837
2838
2839 #ifdef WITH_TCP
2840 #ifdef WITH_TLS
2841         if ((home->proto == IPPROTO_TCP) && home->tls) {
2842                 DEBUG("Trying SSL to port %d\n", home->port);
2843                 sock->ssn = tls_new_client_session(sock, home->tls, this->fd);
2844                 if (!sock->ssn) {
2845                         ERROR("Failed starting SSL to '%s'", buffer);
2846                         home->last_failed_open = now;
2847                         listen_free(&this);
2848                         return NULL;
2849                 }
2850
2851                 this->recv = proxy_tls_recv;
2852                 this->send = proxy_tls_send;
2853         }
2854 #endif
2855 #endif
2856         /*
2857          *      Figure out which port we were bound to.
2858          */
2859         if (sock->my_port == 0) {
2860                 struct sockaddr_storage src;
2861                 socklen_t               sizeof_src = sizeof(src);
2862
2863                 memset(&src, 0, sizeof_src);
2864                 if (getsockname(this->fd, (struct sockaddr *) &src,
2865                                 &sizeof_src) < 0) {
2866                         ERROR("Failed getting socket name for '%s': %s",
2867                               buffer, fr_syserror(errno));
2868                         home->last_failed_open = now;
2869                         listen_free(&this);
2870                         return NULL;
2871                 }
2872
2873                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2874                                         &sock->my_ipaddr, &sock->my_port)) {
2875                         ERROR("Socket has unsupported address family for '%s'", buffer);
2876                         home->last_failed_open = now;
2877                         listen_free(&this);
2878                         return NULL;
2879                 }
2880         }
2881
2882         home->limit.num_connections++;
2883
2884         return this;
2885 }
2886 #endif
2887
2888 static const FR_NAME_NUMBER listen_compare[] = {
2889 #ifdef WITH_STATS
2890         { "status",     RAD_LISTEN_NONE },
2891 #endif
2892         { "auth",       RAD_LISTEN_AUTH },
2893 #ifdef WITH_ACCOUNTING
2894         { "acct",       RAD_LISTEN_ACCT },
2895         { "auth+acct",  RAD_LISTEN_AUTH },
2896 #endif
2897 #ifdef WITH_DETAIL
2898         { "detail",     RAD_LISTEN_DETAIL },
2899 #endif
2900 #ifdef WITH_PROXY
2901         { "proxy",      RAD_LISTEN_PROXY },
2902 #endif
2903 #ifdef WITH_VMPS
2904         { "vmps",       RAD_LISTEN_VQP },
2905 #endif
2906 #ifdef WITH_DHCP
2907         { "dhcp",       RAD_LISTEN_DHCP },
2908 #endif
2909 #ifdef WITH_COMMAND_SOCKET
2910         { "control",    RAD_LISTEN_COMMAND },
2911 #endif
2912 #ifdef WITH_COA
2913         { "coa",        RAD_LISTEN_COA },
2914 #endif
2915         { NULL, 0 },
2916 };
2917
2918 static int _free_proto_handle(lt_dlhandle *handle)
2919 {
2920         dlclose(*handle);
2921         return 0;
2922 }
2923
2924 static rad_listen_t *listen_parse(CONF_SECTION *cs, char const *server)
2925 {
2926         int             type, rcode;
2927         char const      *listen_type;
2928         rad_listen_t    *this;
2929         CONF_PAIR       *cp;
2930         char const      *value;
2931         lt_dlhandle     handle;
2932         CONF_SECTION    *server_cs;
2933         char            buffer[32];
2934
2935         cp = cf_pair_find(cs, "type");
2936         if (!cp) {
2937                 cf_log_err_cs(cs,
2938                            "No type specified in listen section");
2939                 return NULL;
2940         }
2941
2942         value = cf_pair_value(cp);
2943         if (!value) {
2944                 cf_log_err_cp(cp,
2945                               "Type cannot be empty");
2946                 return NULL;
2947         }
2948
2949         snprintf(buffer, sizeof(buffer), "proto_%s", value);
2950         handle = lt_dlopenext(buffer);
2951         if (handle) {
2952                 fr_protocol_t   *proto;
2953                 lt_dlhandle     *marker;
2954
2955                 proto = dlsym(handle, buffer);
2956                 if (!proto) {
2957                         cf_log_err_cs(cs,
2958                                       "Failed linking to protocol %s : %s\n",
2959                                       value, dlerror());
2960                         dlclose(handle);
2961                         return NULL;
2962                 }
2963
2964                 type = fr_str2int(listen_compare, value, -1);
2965                 rad_assert(type >= 0); /* shouldn't be able to compile an invalid type */
2966
2967                 memcpy(&master_listen[type], proto, sizeof(*proto));
2968
2969                 /*
2970                  *      Ensure handle gets closed if config section gets freed
2971                  */
2972                 marker = talloc(cs, lt_dlhandle);
2973                 *marker = handle;
2974                 talloc_set_destructor(marker, _free_proto_handle);
2975
2976                 if (master_listen[type].magic !=  RLM_MODULE_INIT) {
2977                         ERROR("Failed to load protocol '%s', it has the wrong version.",
2978                                master_listen[type].name);
2979                         return NULL;
2980                 }
2981         }
2982
2983         cf_log_info(cs, "listen {");
2984
2985         listen_type = NULL;
2986         rcode = cf_item_parse(cs, "type", FR_ITEM_POINTER(PW_TYPE_STRING, &listen_type), "");
2987         if (rcode < 0) return NULL;
2988         if (rcode == 1) {
2989                 cf_log_err_cs(cs,
2990                            "No type specified in listen section");
2991                 return NULL;
2992         }
2993
2994         type = fr_str2int(listen_compare, listen_type, -1);
2995         if (type < 0) {
2996                 cf_log_err_cs(cs,
2997                            "Invalid type \"%s\" in listen section.",
2998                            listen_type);
2999                 return NULL;
3000         }
3001
3002         /*
3003          *      DHCP and VMPS *must* be loaded dynamically.
3004          */
3005         if (master_listen[type].magic !=  RLM_MODULE_INIT) {
3006                 ERROR("Cannot load protocol '%s', as the required library does not exist",
3007                       master_listen[type].name);
3008                 return NULL;
3009         }
3010
3011         /*
3012          *      Allow listen sections in the default config to
3013          *      refer to a server.
3014          */
3015         if (!server) {
3016                 rcode = cf_item_parse(cs, "virtual_server", FR_ITEM_POINTER(PW_TYPE_STRING, &server), NULL);
3017                 if (rcode < 0) return NULL;
3018         }
3019
3020 #ifdef WITH_PROXY
3021         /*
3022          *      We were passed a virtual server, so the caller is
3023          *      defining a proxy listener inside of a virtual server.
3024          *      This isn't allowed right now.
3025          */
3026         else if (type == RAD_LISTEN_PROXY) {
3027                 ERROR("Error: listen type \"proxy\" Cannot appear in a virtual server section");
3028                 return NULL;
3029         }
3030 #endif
3031
3032         /*
3033          *      Set up cross-type data.
3034          */
3035         this = listen_alloc(cs, type);
3036         this->server = server;
3037         this->fd = -1;
3038
3039 #ifdef WITH_TCP
3040         /*
3041          *      Special-case '+' for "auth+acct".
3042          */
3043         if (strchr(listen_type, '+') != NULL) {
3044                 this->dual = true;
3045         }
3046 #endif
3047
3048         /*
3049          *      Call per-type parser.
3050          */
3051         if (master_listen[type].parse(cs, this) < 0) {
3052                 listen_free(&this);
3053                 return NULL;
3054         }
3055
3056         server_cs = cf_section_sub_find_name2(main_config.config, "server",
3057                                               this->server);
3058         if (!server_cs && this->server) {
3059                 cf_log_err_cs(cs, "No such server \"%s\"", this->server);
3060                 listen_free(&this);
3061                 return NULL;
3062         }
3063
3064         cf_log_info(cs, "}");
3065
3066         return this;
3067 }
3068
3069 #ifdef HAVE_PTHREAD_H
3070 /*
3071  *      A child thread which does NOTHING other than read and process
3072  *      packets.
3073  */
3074 static void *recv_thread(void *arg)
3075 {
3076         rad_listen_t *this = arg;
3077
3078         while (1) {
3079                 this->recv(this);
3080                 DEBUG("%p", &this);
3081         }
3082
3083         return NULL;
3084 }
3085 #endif
3086
3087
3088 /*
3089  *      Generate a list of listeners.  Takes an input list of
3090  *      listeners, too, so we don't close sockets with waiting packets.
3091  */
3092 int listen_init(CONF_SECTION *config, rad_listen_t **head, bool spawn_flag)
3093 {
3094         bool            override = false;
3095         CONF_SECTION    *cs = NULL;
3096         rad_listen_t    **last;
3097         rad_listen_t    *this;
3098         fr_ipaddr_t     server_ipaddr;
3099         uint16_t        auth_port = 0;
3100 #ifdef WITH_PROXY
3101         bool            defined_proxy = false;
3102 #endif
3103
3104         /*
3105          *      We shouldn't be called with a pre-existing list.
3106          */
3107         rad_assert(head && (*head == NULL));
3108
3109         memset(&server_ipaddr, 0, sizeof(server_ipaddr));
3110
3111         last = head;
3112         server_ipaddr.af = AF_UNSPEC;
3113
3114         /*
3115          *      If the port is specified on the command-line,
3116          *      it over-rides the configuration file.
3117          *
3118          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
3119          */
3120         if (main_config.port > 0) {
3121                 auth_port = main_config.port;
3122
3123                 /*
3124                  *      -p X but no -i Y on the command-line.
3125                  */
3126                 if (main_config.myip.af == AF_UNSPEC) {
3127                         ERROR("The command-line says \"-p %d\", but there is no associated IP address to use",
3128                               main_config.port);
3129                         return -1;
3130                 }
3131         }
3132
3133         /*
3134          *      If the IP address was configured on the command-line,
3135          *      use that as the "bind_address"
3136          */
3137         if (main_config.myip.af != AF_UNSPEC) {
3138                 listen_socket_t *sock;
3139
3140                 memcpy(&server_ipaddr, &main_config.myip,
3141                        sizeof(server_ipaddr));
3142                 override = true;
3143
3144 #ifdef WITH_VMPS
3145                 if (strcmp(progname, "vmpsd") == 0) {
3146                         this = listen_alloc(config, RAD_LISTEN_VQP);
3147                         if (!auth_port) auth_port = 1589;
3148                 } else
3149 #endif
3150                         this = listen_alloc(config, RAD_LISTEN_AUTH);
3151
3152                 sock = this->data;
3153
3154                 sock->my_ipaddr = server_ipaddr;
3155                 sock->my_port = auth_port;
3156
3157                 sock->clients = client_list_parse_section(config, false);
3158                 if (!sock->clients) {
3159                         cf_log_err_cs(config,
3160                                    "Failed to find any clients for this listen section");
3161                         listen_free(&this);
3162                         return -1;
3163                 }
3164
3165                 if (listen_bind(this) < 0) {
3166                         listen_free(head);
3167                         ERROR("There appears to be another RADIUS server running on the authentication port %d", sock->my_port);
3168                         listen_free(&this);
3169                         return -1;
3170                 }
3171                 auth_port = sock->my_port;      /* may have been updated in listen_bind */
3172                 if (override) {
3173                         cs = cf_section_sub_find_name2(config, "server",
3174                                                        main_config.name);
3175                         if (cs) this->server = main_config.name;
3176                 }
3177
3178                 *last = this;
3179                 last = &(this->next);
3180
3181 #ifdef WITH_VMPS
3182                 /*
3183                  *      No acct for vmpsd
3184                  */
3185                 if (strcmp(progname, "vmpsd") == 0) goto add_sockets;
3186 #endif
3187
3188 #ifdef WITH_ACCOUNTING
3189                 /*
3190                  *      Open Accounting Socket.
3191                  *
3192                  *      If we haven't already gotten acct_port from
3193                  *      /etc/services, then make it auth_port + 1.
3194                  */
3195                 this = listen_alloc(config, RAD_LISTEN_ACCT);
3196                 sock = this->data;
3197
3198                 /*
3199                  *      Create the accounting socket.
3200                  *
3201                  *      The accounting port is always the
3202                  *      authentication port + 1
3203                  */
3204                 sock->my_ipaddr = server_ipaddr;
3205                 sock->my_port = auth_port + 1;
3206
3207                 sock->clients = client_list_parse_section(config, false);
3208                 if (!sock->clients) {
3209                         cf_log_err_cs(config,
3210                                    "Failed to find any clients for this listen section");
3211                         return -1;
3212                 }
3213
3214                 if (listen_bind(this) < 0) {
3215                         listen_free(&this);
3216                         listen_free(head);
3217                         ERROR("There appears to be another RADIUS server running on the accounting port %d", sock->my_port);
3218                         return -1;
3219                 }
3220
3221                 if (override) {
3222                         cs = cf_section_sub_find_name2(config, "server",
3223                                                        main_config.name);
3224                         if (cs) this->server = main_config.name;
3225                 }
3226
3227                 *last = this;
3228                 last = &(this->next);
3229 #endif
3230         }
3231
3232         /*
3233          *      They specified an IP on the command-line, ignore
3234          *      all listen sections except the one in '-n'.
3235          */
3236         if (main_config.myip.af != AF_UNSPEC) {
3237                 CONF_SECTION *subcs;
3238                 char const *name2 = cf_section_name2(cs);
3239
3240                 cs = cf_section_sub_find_name2(config, "server",
3241                                                main_config.name);
3242                 if (!cs) goto add_sockets;
3243
3244                 /*
3245                  *      Should really abstract this code...
3246                  */
3247                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
3248                      subcs != NULL;
3249                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
3250                         this = listen_parse(subcs, name2);
3251                         if (!this) {
3252                                 listen_free(head);
3253                                 return -1;
3254                         }
3255
3256                         *last = this;
3257                         last = &(this->next);
3258                 } /* loop over "listen" directives in server <foo> */
3259
3260                 goto add_sockets;
3261         }
3262
3263         /*
3264          *      Walk through the "listen" sections, if they exist.
3265          */
3266         for (cs = cf_subsection_find_next(config, NULL, "listen");
3267              cs != NULL;
3268              cs = cf_subsection_find_next(config, cs, "listen")) {
3269                 this = listen_parse(cs, NULL);
3270                 if (!this) {
3271                         listen_free(head);
3272                         return -1;
3273                 }
3274
3275                 *last = this;
3276                 last = &(this->next);
3277         }
3278
3279         /*
3280          *      Check virtual servers for "listen" sections, too.
3281          *
3282          *      FIXME: Move to virtual server init?
3283          */
3284         for (cs = cf_subsection_find_next(config, NULL, "server");
3285              cs != NULL;
3286              cs = cf_subsection_find_next(config, cs, "server")) {
3287                 CONF_SECTION *subcs;
3288                 char const *name2 = cf_section_name2(cs);
3289
3290                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
3291                      subcs != NULL;
3292                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
3293                         this = listen_parse(subcs, name2);
3294                         if (!this) {
3295                                 listen_free(head);
3296                                 return -1;
3297                         }
3298
3299                         *last = this;
3300                         last = &(this->next);
3301                 } /* loop over "listen" directives in virtual servers */
3302         } /* loop over virtual servers */
3303
3304 add_sockets:
3305         /*
3306          *      No sockets to receive packets, this is an error.
3307          *      proxying is pointless.
3308          */
3309         if (!*head) {
3310                 ERROR("The server is not configured to listen on any ports.  Cannot start");
3311                 return -1;
3312         }
3313
3314         /*
3315          *      Print out which sockets we're listening on, and
3316          *      add them to the event list.
3317          */
3318         for (this = *head; this != NULL; this = this->next) {
3319 #ifdef WITH_PROXY
3320                 if (this->type == RAD_LISTEN_PROXY) {
3321                         defined_proxy = true;
3322                 }
3323
3324 #endif
3325
3326 #ifdef WITH_TLS
3327                 if (!check_config && !spawn_flag && this->tls) {
3328                         cf_log_err_cs(this->cs, "Threading must be enabled for TLS sockets to function properly");
3329                         cf_log_err_cs(this->cs, "You probably need to do '%s -fxx -l stdout' for debugging",
3330                                       progname);
3331                         return -1;
3332                 }
3333 #endif
3334                 if (!check_config) {
3335                         if (this->workers && !spawn_flag) {
3336                                 WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
3337                                 this->workers = 0;
3338                         }
3339
3340                         if (this->workers) {
3341 #ifdef HAVE_PTHREAD_H
3342                                 int rcode;
3343                                 uint32_t i;
3344                                 char buffer[256];
3345
3346                                 this->print(this, buffer, sizeof(buffer));
3347
3348                                 for (i = 0; i < this->workers; i++) {
3349                                         pthread_t id;
3350
3351                                         /*
3352                                          *      FIXME: create detached?
3353                                          */
3354                                         rcode = pthread_create(&id, 0, recv_thread, this);
3355                                         if (rcode != 0) {
3356                                                 ERROR("Thread create failed: %s",
3357                                                       fr_syserror(rcode));
3358                                                 fr_exit(1);
3359                                         }
3360
3361                                         DEBUG("Thread %d for %s\n", i, buffer);
3362                                 }
3363 #else
3364                                 WARN("Setting 'workers' requires 'synchronous'.  Disabling 'workers'");
3365                                 this->workers = 0;
3366 #endif
3367
3368                         } else {
3369                                 radius_update_listener(this);
3370                         }
3371
3372                 }
3373         }
3374
3375 #ifdef WITH_TCP
3376         if (!home_servers_udp) defined_proxy = true;
3377 #endif
3378
3379         /*
3380          *      If we're proxying requests, open the proxy FD.
3381          *      Otherwise, don't do anything.
3382          */
3383 #ifdef WITH_PROXY
3384         if ((main_config.proxy_requests == true) &&
3385             !check_config &&
3386             (*head != NULL) && !defined_proxy) {
3387                 uint16_t        port = 0;
3388                 home_server_t   home;
3389
3390                 memset(&home, 0, sizeof(home));
3391
3392                 /*
3393                  *      Open a default UDP port
3394                  */
3395                 home.proto = IPPROTO_UDP;
3396                 home.src_ipaddr = server_ipaddr;
3397                 port = 0;
3398
3399                 /*
3400                  *      Address is still unspecified, use IPv4.
3401                  */
3402                 if (home.src_ipaddr.af == AF_UNSPEC) {
3403                         home.src_ipaddr.af = AF_INET;
3404                         /* everything else is already set to zero */
3405                 }
3406
3407                 home.ipaddr.af = home.src_ipaddr.af;
3408                 /* everything else is already set to zero */
3409
3410                 /*
3411                  *      It's OK to allocate a UDP listener from the
3412                  *      main config.  The listener will never be
3413                  *      deleted until the server stops and the config
3414                  *      is freed.
3415                  */
3416                 this = proxy_new_listener(config, &home, port);
3417                 if (!this) {
3418                         listen_free(head);
3419                         return -1;
3420                 }
3421
3422                 radius_update_listener(this);
3423         }
3424 #endif
3425
3426         /*
3427          *      Haven't defined any sockets.  Die.
3428          */
3429         if (!*head) return -1;
3430
3431         xlat_register("listen", xlat_listen, NULL, NULL);
3432
3433         return 0;
3434 }
3435
3436 /*
3437  *      Free a linked list of listeners;
3438  */
3439 void listen_free(rad_listen_t **head)
3440 {
3441         rad_listen_t *this;
3442
3443         if (!head || !*head) return;
3444
3445         this = *head;
3446         while (this) {
3447                 rad_listen_t *next = this->next;
3448                 talloc_free(this);
3449                 this = next;
3450         }
3451
3452         *head = NULL;
3453 }
3454
3455 #ifdef WITH_STATS
3456 RADCLIENT_LIST *listener_find_client_list(fr_ipaddr_t const *ipaddr, uint16_t port, int proto)
3457 {
3458         rad_listen_t *this;
3459
3460         for (this = main_config.listen; this != NULL; this = this->next) {
3461                 listen_socket_t *sock;
3462
3463                 if ((this->type != RAD_LISTEN_AUTH)
3464 #ifdef WITH_ACCOUNTING
3465                     && (this->type != RAD_LISTEN_ACCT)
3466 #endif
3467 #ifdef WITH_COA
3468                     && (this->type != RAD_LISTEN_COA)
3469 #endif
3470                     ) continue;
3471
3472                 sock = this->data;
3473
3474                 if (sock->my_port != port) continue;
3475                 if (sock->proto != proto) continue;
3476                 if (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) != 0) continue;
3477
3478                 return sock->clients;
3479         }
3480
3481         return NULL;
3482 }
3483 #endif
3484
3485 rad_listen_t *listener_find_byipaddr(fr_ipaddr_t const *ipaddr, uint16_t port, int proto)
3486 {
3487         rad_listen_t *this;
3488
3489         for (this = main_config.listen; this != NULL; this = this->next) {
3490                 listen_socket_t *sock;
3491
3492                 sock = this->data;
3493
3494                 if (sock->my_port != port) continue;
3495                 if (sock->proto != proto) continue;
3496                 if (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) != 0) continue;
3497
3498                 return this;
3499         }
3500
3501         /*
3502          *      Failed to find a specific one.  Find INADDR_ANY
3503          */
3504         for (this = main_config.listen; this != NULL; this = this->next) {
3505                 listen_socket_t *sock;
3506
3507                 sock = this->data;
3508
3509                 if (sock->my_port != port) continue;
3510                 if (sock->proto != proto) continue;
3511                 if (!fr_inaddr_any(&sock->my_ipaddr)) continue;
3512
3513                 return this;
3514         }
3515
3516         return NULL;
3517 }