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