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