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