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