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