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