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