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