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