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