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