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