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