Allow outgoing TCP connections to home servers.
[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
33 #include <freeradius-devel/vmps.h>
34 #include <freeradius-devel/detail.h>
35
36 #ifdef WITH_UDPFROMTO
37 #include <freeradius-devel/udpfromto.h>
38 #endif
39
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif
43
44 #ifdef HAVE_NET_IF_H
45 #include <net/if.h>
46 #endif
47
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51
52
53 /*
54  *      We'll use this below.
55  */
56 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
57 typedef void (*rad_listen_free_t)(rad_listen_t *);
58
59 typedef struct rad_listen_master_t {
60         rad_listen_parse_t      parse;
61         rad_listen_free_t       free;
62         rad_listen_recv_t       recv;
63         rad_listen_send_t       send;
64         rad_listen_print_t      print;
65         rad_listen_encode_t     encode;
66         rad_listen_decode_t     decode;
67 } rad_listen_master_t;
68
69 typedef struct listen_socket_t {
70         /*
71          *      For normal sockets.
72          */
73         fr_ipaddr_t     ipaddr;
74         int             port;
75
76 #ifdef SO_BINDTODEVICE
77         const char              *interface;
78 #endif
79         
80 #ifdef WITH_TCP
81         int             proto;
82
83         int             max_connections;
84         int             num_connections;
85         struct listen_socket_t *parent;
86
87         fr_ipaddr_t     src_ipaddr;
88         int             src_port;
89         RADCLIENT       *client; /* for server sockets */
90
91         fr_tcp_radius_t *tcp;   /* for RAD_LISTEN_PROXY */
92         home_server     *home;
93         RADIUS_PACKET   *packet; /* for reading partial packets */
94 #endif
95         RADCLIENT_LIST  *clients;
96 } listen_socket_t;
97
98 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type);
99
100 /*
101  *      Find a per-socket client.
102  */
103 RADCLIENT *client_listener_find(const rad_listen_t *listener,
104                                 const fr_ipaddr_t *ipaddr, int src_port)
105 {
106 #ifdef WITH_DYNAMIC_CLIENTS
107         int rcode;
108         REQUEST *request;
109         RADCLIENT *created;
110 #endif
111         time_t now;
112         RADCLIENT *client;
113         RADCLIENT_LIST *clients;
114
115         rad_assert(listener != NULL);
116         rad_assert(ipaddr != NULL);
117
118         clients = ((listen_socket_t *)listener->data)->clients;
119
120         /*
121          *      This HAS to have been initialized previously.
122          */
123         rad_assert(clients != NULL);
124
125         client = client_find(clients, ipaddr
126 #ifdef WITH_TCP
127                              , IPPROTO_UDP
128 #endif
129                              );
130         if (!client) {
131                 static time_t last_printed = 0;
132                 char name[256], buffer[128];
133                                         
134 #ifdef WITH_DYNAMIC_CLIENTS
135         unknown:                /* used only for dynamic clients */
136 #endif
137
138                 /*
139                  *      DoS attack quenching, but only in debug mode.
140                  *      If they're running in debug mode, show them
141                  *      every packet.
142                  */
143                 if (debug_flag == 0) {
144                         now = time(NULL);
145                         if (last_printed == now) return NULL;
146                         
147                         last_printed = now;
148                 }
149
150                 listener->print(listener, name, sizeof(name));
151
152                 radlog(L_ERR, "Ignoring request to %s from unknown client %s port %d",
153                        name, inet_ntop(ipaddr->af, &ipaddr->ipaddr,
154                                        buffer, sizeof(buffer)),
155                        src_port);
156                 return NULL;
157         }
158
159 #ifndef WITH_DYNAMIC_CLIENTS
160         return client;          /* return the found client. */
161 #else
162
163         /*
164          *      No server defined, and it's not dynamic.  Return it.
165          */
166         if (!client->client_server && !client->dynamic) return client;
167
168         now = time(NULL);
169         
170         /*
171          *      It's a dynamically generated client, check it.
172          */
173         if (client->dynamic && (src_port != 0)) {
174                 /*
175                  *      Lives forever.  Return it.
176                  */
177                 if (client->lifetime == 0) return client;
178                 
179                 /*
180                  *      Rate-limit the deletion of known clients.
181                  *      This makes them last a little longer, but
182                  *      prevents the server from melting down if (say)
183                  *      10k clients all expire at once.
184                  */
185                 if (now == client->last_new_client) return client;
186
187                 /*
188                  *      It's not dead yet.  Return it.
189                  */
190                 if ((client->created + client->lifetime) > now) return client;
191                 
192                 /*
193                  *      This really puts them onto a queue for later
194                  *      deletion.
195                  */
196                 client_delete(clients, client);
197
198                 /*
199                  *      Go find the enclosing network again.
200                  */
201                 client = client_find(clients, ipaddr
202 #ifdef WITH_TCP
203                                      , IPPROTO_UDP
204 #endif
205                                      );
206
207                 /*
208                  *      WTF?
209                  */
210                 if (!client) goto unknown;
211                 if (!client->client_server) goto unknown;
212
213                 /*
214                  *      At this point, 'client' is the enclosing
215                  *      network that configures where dynamic clients
216                  *      can be defined.
217                  */
218                 rad_assert(client->dynamic == 0);
219         } else {
220                 /*
221                  *      The IP is unknown, so we've found an enclosing
222                  *      network.  Enable DoS protection.  We only
223                  *      allow one new client per second.  Known
224                  *      clients aren't subject to this restriction.
225                  */
226                 if (now == client->last_new_client) goto unknown;
227         }
228
229         client->last_new_client = now;
230
231         request = request_alloc();
232         if (!request) goto unknown;
233
234         request->listener = listener;
235         request->client = client;
236         request->packet = rad_recv(listener->fd, 0x02); /* MSG_PEEK */
237         if (!request->packet) {                         /* badly formed, etc */
238                 request_free(&request);
239                 goto unknown;
240         }
241         request->reply = rad_alloc_reply(request->packet);
242         if (!request->reply) {
243                 request_free(&request);
244                 goto unknown;
245         }
246         request->packet->timestamp = request->timestamp;
247         request->number = 0;
248         request->priority = listener->type;
249         request->server = client->client_server;
250         request->root = &mainconfig;
251
252         /*
253          *      Run a fake request through the given virtual server.
254          *      Look for FreeRADIUS-Client-IP-Address
255          *               FreeRADIUS-Client-Secret
256          *              ...
257          *
258          *      and create the RADCLIENT structure from that.
259          */
260         DEBUG("server %s {", request->server);
261
262         rcode = module_authorize(0, request);
263
264         DEBUG("} # server %s", request->server);
265
266         if (rcode != RLM_MODULE_OK) {
267                 request_free(&request);
268                 goto unknown;
269         }
270
271         /*
272          *      If the client was updated by rlm_dynamic_clients,
273          *      don't create the client from attribute-value pairs.
274          */
275         if (request->client == client) {
276                 created = client_create(clients, request);
277         } else {
278                 created = request->client;
279
280                 /*
281                  *      This frees the client if it isn't valid.
282                  */
283                 if (!client_validate(clients, client, created)) goto unknown;
284         }
285         request_free(&request);
286
287         if (!created) goto unknown;
288
289         return created;
290 #endif
291 }
292
293 static int listen_bind(rad_listen_t *this);
294
295
296 /*
297  *      Process and reply to a server-status request.
298  *      Like rad_authenticate and rad_accounting this should
299  *      live in it's own file but it's so small we don't bother.
300  */
301 static int rad_status_server(REQUEST *request)
302 {
303         int rcode = RLM_MODULE_OK;
304         DICT_VALUE *dval;
305
306         switch (request->listener->type) {
307 #ifdef WITH_STATS
308         case RAD_LISTEN_NONE:
309 #endif
310         case RAD_LISTEN_AUTH:
311                 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
312                 if (dval) {
313                         rcode = module_authorize(dval->value, request);
314                 } else {
315                         rcode = RLM_MODULE_OK;
316                 }
317
318                 switch (rcode) {
319                 case RLM_MODULE_OK:
320                 case RLM_MODULE_UPDATED:
321                         request->reply->code = PW_AUTHENTICATION_ACK;
322                         break;
323
324                 case RLM_MODULE_FAIL:
325                 case RLM_MODULE_HANDLED:
326                         request->reply->code = 0; /* don't reply */
327                         break;
328
329                 default:
330                 case RLM_MODULE_REJECT:
331                         request->reply->code = PW_AUTHENTICATION_REJECT;
332                         break;
333                 }
334                 break;
335
336 #ifdef WITH_ACCOUNTING
337         case RAD_LISTEN_ACCT:
338                 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
339                 if (dval) {
340                         rcode = module_accounting(dval->value, request);
341                 } else {
342                         rcode = RLM_MODULE_OK;
343                 }
344
345                 switch (rcode) {
346                 case RLM_MODULE_OK:
347                 case RLM_MODULE_UPDATED:
348                         request->reply->code = PW_ACCOUNTING_RESPONSE;
349                         break;
350
351                 default:
352                         request->reply->code = 0; /* don't reply */
353                         break;
354                 }
355                 break;
356 #endif
357
358 #ifdef WITH_COA
359                 /*
360                  *      This is a vendor extension.  Suggested by Glen
361                  *      Zorn in IETF 72, and rejected by the rest of
362                  *      the WG.  We like it, so it goes in here.
363                  */
364         case RAD_LISTEN_COA:
365                 dval = dict_valbyname(PW_RECV_COA_TYPE, "Status-Server");
366                 if (dval) {
367                         rcode = module_recv_coa(dval->value, request);
368                 } else {
369                         rcode = RLM_MODULE_OK;
370                 }
371
372                 switch (rcode) {
373                 case RLM_MODULE_OK:
374                 case RLM_MODULE_UPDATED:
375                         request->reply->code = PW_COA_ACK;
376                         break;
377
378                 default:
379                         request->reply->code = 0; /* don't reply */
380                         break;
381                 }
382                 break;
383 #endif
384
385         default:
386                 return 0;
387         }
388
389 #ifdef WITH_STATS
390         /*
391          *      Full statistics are available only on a statistics
392          *      socket.
393          */
394         if (request->listener->type == RAD_LISTEN_NONE) {
395                 request_stats_reply(request);
396         }
397 #endif
398
399         return 0;
400 }
401
402
403 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
404 {
405         size_t len;
406         listen_socket_t *sock = this->data;
407         const char *name;
408
409         switch (this->type) {
410 #ifdef WITH_STATS
411         case RAD_LISTEN_NONE:   /* what a hack... */
412                 name = "status";
413                 break;
414 #endif
415
416         case RAD_LISTEN_AUTH:
417                 name = "authentication";
418                 break;
419
420 #ifdef WITH_ACCOUNTING
421         case RAD_LISTEN_ACCT:
422                 name = "accounting";
423                 break;
424 #endif
425
426 #ifdef WITH_PROXY
427         case RAD_LISTEN_PROXY:
428                 name = "proxy";
429                 break;
430 #endif
431
432 #ifdef WITH_VMPS
433         case RAD_LISTEN_VQP:
434                 name = "vmps";
435                 break;
436 #endif
437
438 #ifdef WITH_DHCP
439         case RAD_LISTEN_DHCP:
440                 name = "dhcp";
441                 break;
442 #endif
443
444 #ifdef WITH_COA
445         case RAD_LISTEN_COA:
446                 name = "coa";
447                 break;
448 #endif
449
450         default:
451                 name = "??";
452                 break;
453         }
454
455 #define FORWARD len = strlen(buffer); if (len >= (bufsize + 1)) return 0;buffer += len;bufsize -= len
456 #define ADDSTRING(_x) strlcpy(buffer, _x, bufsize);FORWARD
457
458         ADDSTRING(name);
459
460 #ifdef SO_BINDTODEVICE
461         if (sock->interface) {
462                 ADDSTRING(" interface ");
463                 ADDSTRING(sock->interface);
464         }
465 #endif
466
467         ADDSTRING(" address ");
468         
469         if ((sock->ipaddr.af == AF_INET) &&
470             (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
471                 strlcpy(buffer, "*", bufsize);
472         } else {
473                 ip_ntoh(&sock->ipaddr, buffer, bufsize);
474         }
475         FORWARD;
476
477         ADDSTRING(" port ");
478         snprintf(buffer, bufsize, "%d", sock->port);
479         FORWARD;
480
481         if (this->server) {
482                 ADDSTRING(" as server ");
483                 ADDSTRING(this->server);
484         }
485
486 #undef ADDSTRING
487 #undef FORWARD
488
489         return 1;
490 }
491
492
493 /*
494  *      Parse an authentication or accounting socket.
495  */
496 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
497 {
498         int             rcode;
499         int             listen_port;
500         fr_ipaddr_t     ipaddr;
501         listen_socket_t *sock = this->data;
502         char            *section_name = NULL;
503         CONF_SECTION    *client_cs, *parentcs;
504
505         /*
506          *      Try IPv4 first
507          */
508         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
509         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
510                               &ipaddr.ipaddr.ip4addr, NULL);
511         if (rcode < 0) return -1;
512
513         if (rcode == 0) { /* successfully parsed IPv4 */
514                 ipaddr.af = AF_INET;
515
516         } else {        /* maybe IPv6? */
517                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
518                                       &ipaddr.ipaddr.ip6addr, NULL);
519                 if (rcode < 0) return -1;
520
521                 if (rcode == 1) {
522                         cf_log_err(cf_sectiontoitem(cs),
523                                    "No address specified in listen section");
524                         return -1;
525                 }
526                 ipaddr.af = AF_INET6;
527         }
528
529         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
530                               &listen_port, "0");
531         if (rcode < 0) return -1;
532
533         if ((listen_port < 0) || (listen_port > 65535)) {
534                         cf_log_err(cf_sectiontoitem(cs),
535                                    "Invalid value for \"port\"");
536                         return -1;
537         }
538
539         sock->ipaddr = ipaddr;
540         sock->port = listen_port;
541
542         /*
543          *      If we can bind to interfaces, do so,
544          *      else don't.
545          */
546         if (cf_pair_find(cs, "interface")) {
547 #ifndef SO_BINDTODEVICE
548                 cf_log_err(cf_sectiontoitem(cs),
549                            "System does not support binding to interfaces.  Delete this line from the configuration file.");
550                 return -1;
551 #else
552                 const char *value;
553                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
554
555                 rad_assert(cp != NULL);
556                 value = cf_pair_value(cp);
557                 if (!value) {
558                         cf_log_err(cf_sectiontoitem(cs),
559                                    "No interface name given");
560                         return -1;
561                 }
562                 sock->interface = value;
563 #endif
564         }
565
566         /*
567          *      And bind it to the port.
568          */
569         if (listen_bind(this) < 0) {
570                 char buffer[128];
571                 cf_log_err(cf_sectiontoitem(cs),
572                            "Error binding to port for %s port %d",
573                            ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
574                            sock->port);
575                 return -1;
576         }
577
578 #ifdef WITH_PROXY
579         /*
580          *      Proxy sockets don't have clients.
581          */
582         if (this->type == RAD_LISTEN_PROXY) return 0;
583 #endif
584         
585         /*
586          *      The more specific configurations are preferred to more
587          *      generic ones.
588          */
589         client_cs = NULL;
590         parentcs = cf_top_section(cs);
591         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
592                               &section_name, NULL);
593         if (rcode < 0) return -1; /* bad string */
594         if (rcode == 0) {
595                 /*
596                  *      Explicit list given: use it.
597                  */
598                 client_cs = cf_section_sub_find_name2(parentcs,
599                                                       "clients",
600                                                       section_name);
601                 if (!client_cs) {
602                         client_cs = cf_section_find(section_name);
603                 }
604                 if (!client_cs) {
605                         cf_log_err(cf_sectiontoitem(cs),
606                                    "Failed to find clients %s {...}",
607                                    section_name);
608                         free(section_name);
609                         return -1;
610                 }
611                 free(section_name);
612         } /* else there was no "clients = " entry. */
613
614         if (!client_cs) {
615                 CONF_SECTION *server_cs;
616
617                 server_cs = cf_section_sub_find_name2(parentcs,
618                                                       "server",
619                                                       this->server);
620                 /*
621                  *      Found a "server foo" section.  If there are clients
622                  *      in it, use them.
623                  */
624                 if (server_cs &&
625                     (cf_section_sub_find(server_cs, "client") != NULL)) {
626                         client_cs = server_cs;
627                 }
628         }
629
630         /*
631          *      Still nothing.  Look for global clients.
632          */
633         if (!client_cs) client_cs = parentcs;
634
635         sock->clients = clients_parse_section(client_cs);
636         if (!sock->clients) {
637                 cf_log_err(cf_sectiontoitem(cs),
638                            "Failed to load clients for this listen section");
639                 return -1;
640         }
641
642         return 0;
643 }
644
645 /*
646  *      Send an authentication response packet
647  */
648 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
649 {
650         rad_assert(request->listener == listener);
651         rad_assert(listener->send == auth_socket_send);
652
653         return rad_send(request->reply, request->packet,
654                         request->client->secret);
655 }
656
657
658 #ifdef WITH_ACCOUNTING
659 /*
660  *      Send an accounting response packet (or not)
661  */
662 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
663 {
664         rad_assert(request->listener == listener);
665         rad_assert(listener->send == acct_socket_send);
666
667         /*
668          *      Accounting reject's are silently dropped.
669          *
670          *      We do it here to avoid polluting the rest of the
671          *      code with this knowledge
672          */
673         if (request->reply->code == 0) return 0;
674
675         return rad_send(request->reply, request->packet,
676                         request->client->secret);
677 }
678 #endif
679
680 #ifdef WITH_PROXY
681 /*
682  *      Send a packet to a home server.
683  *
684  *      FIXME: have different code for proxy auth & acct!
685  */
686 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
687 {
688         listen_socket_t *sock = listener->data;
689
690         rad_assert(request->proxy_listener == listener);
691         rad_assert(listener->send == proxy_socket_send);
692
693         request->proxy->src_ipaddr = sock->ipaddr;
694         request->proxy->src_port = sock->port;
695
696         return rad_send(request->proxy, request->packet,
697                         request->home_server->secret);
698 }
699 #endif
700
701 #ifdef WITH_STATS
702 /*
703  *      Check if an incoming request is "ok"
704  *
705  *      It takes packets, not requests.  It sees if the packet looks
706  *      OK.  If so, it does a number of sanity checks on it.
707   */
708 static int stats_socket_recv(rad_listen_t *listener,
709                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
710 {
711         ssize_t         rcode;
712         int             code, src_port;
713         RADIUS_PACKET   *packet;
714         RADCLIENT       *client;
715         fr_ipaddr_t     src_ipaddr;
716
717         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
718         if (rcode < 0) return 0;
719
720         RAD_STATS_TYPE_INC(listener, total_requests);
721
722         if (rcode < 20) {       /* AUTH_HDR_LEN */
723                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
724                 return 0;
725         }
726
727         if ((client = client_listener_find(listener,
728                                            &src_ipaddr, src_port)) == NULL) {
729                 rad_recv_discard(listener->fd);
730                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
731                 return 0;
732         }
733
734         /*
735          *      We only understand Status-Server on this socket.
736          */
737         if (code != PW_STATUS_SERVER) {
738                 DEBUG("Ignoring packet code %d sent to Status-Server port",
739                       code);
740                 rad_recv_discard(listener->fd);
741                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
742                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
743                 return 0;
744         }
745
746         /*
747          *      Now that we've sanity checked everything, receive the
748          *      packet.
749          */
750         packet = rad_recv(listener->fd, 1); /* require message authenticator */
751         if (!packet) {
752                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
753                 DEBUG("%s", fr_strerror());
754                 return 0;
755         }
756
757         if (!received_request(listener, packet, prequest, client)) {
758                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
759                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
760                 rad_free(&packet);
761                 return 0;
762         }
763
764         *pfun = rad_status_server;
765         return 1;
766 }
767 #endif
768
769
770 /*
771  *      Check if an incoming request is "ok"
772  *
773  *      It takes packets, not requests.  It sees if the packet looks
774  *      OK.  If so, it does a number of sanity checks on it.
775   */
776 static int auth_socket_recv(rad_listen_t *listener,
777                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
778 {
779         ssize_t         rcode;
780         int             code, src_port;
781         RADIUS_PACKET   *packet;
782         RAD_REQUEST_FUNP fun = NULL;
783         RADCLIENT       *client;
784         fr_ipaddr_t     src_ipaddr;
785
786         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
787         if (rcode < 0) return 0;
788
789         RAD_STATS_TYPE_INC(listener, total_requests);
790
791         if (rcode < 20) {       /* AUTH_HDR_LEN */
792                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
793                 return 0;
794         }
795
796         if ((client = client_listener_find(listener,
797                                            &src_ipaddr, src_port)) == NULL) {
798                 rad_recv_discard(listener->fd);
799                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
800                 return 0;
801         }
802
803         /*
804          *      Some sanity checks, based on the packet code.
805          */
806         switch(code) {
807         case PW_AUTHENTICATION_REQUEST:
808                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
809                 fun = rad_authenticate;
810                 break;
811
812         case PW_STATUS_SERVER:
813                 if (!mainconfig.status_server) {
814                         rad_recv_discard(listener->fd);
815                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
816                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
817                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
818                         return 0;
819                 }
820                 fun = rad_status_server;
821                 break;
822
823         default:
824                 rad_recv_discard(listener->fd);
825                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
826                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
827
828                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
829                       code, client->shortname, src_port);
830                 return 0;
831                 break;
832         } /* switch over packet types */
833
834         /*
835          *      Now that we've sanity checked everything, receive the
836          *      packet.
837          */
838         packet = rad_recv(listener->fd, client->message_authenticator);
839         if (!packet) {
840                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
841                 DEBUG("%s", fr_strerror());
842                 return 0;
843         }
844
845         if (!received_request(listener, packet, prequest, client)) {
846                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
847                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
848                 rad_free(&packet);
849                 return 0;
850         }
851
852         *pfun = fun;
853         return 1;
854 }
855
856
857 #ifdef WITH_ACCOUNTING
858 /*
859  *      Receive packets from an accounting socket
860  */
861 static int acct_socket_recv(rad_listen_t *listener,
862                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
863 {
864         ssize_t         rcode;
865         int             code, src_port;
866         RADIUS_PACKET   *packet;
867         RAD_REQUEST_FUNP fun = NULL;
868         RADCLIENT       *client;
869         fr_ipaddr_t     src_ipaddr;
870
871         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
872         if (rcode < 0) return 0;
873
874         RAD_STATS_TYPE_INC(listener, total_requests);
875
876         if (rcode < 20) {       /* AUTH_HDR_LEN */
877                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
878                 return 0;
879         }
880
881         if ((client = client_listener_find(listener,
882                                            &src_ipaddr, src_port)) == NULL) {
883                 rad_recv_discard(listener->fd);
884                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
885                 return 0;
886         }
887
888         /*
889          *      Some sanity checks, based on the packet code.
890          */
891         switch(code) {
892         case PW_ACCOUNTING_REQUEST:
893                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
894                 fun = rad_accounting;
895                 break;
896
897         case PW_STATUS_SERVER:
898                 if (!mainconfig.status_server) {
899                         rad_recv_discard(listener->fd);
900                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
901                         RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
902
903                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
904                         return 0;
905                 }
906                 fun = rad_status_server;
907                 break;
908
909         default:
910                 rad_recv_discard(listener->fd);
911                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
912                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
913
914                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
915                       code, client->shortname, src_port);
916                 return 0;
917         } /* switch over packet types */
918
919         /*
920          *      Now that we've sanity checked everything, receive the
921          *      packet.
922          */
923         packet = rad_recv(listener->fd, 0);
924         if (!packet) {
925                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
926                 radlog(L_ERR, "%s", fr_strerror());
927                 return 0;
928         }
929
930         /*
931          *      There can be no duplicate accounting packets.
932          */
933         if (!received_request(listener, packet, prequest, client)) {
934                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
935                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
936                 rad_free(&packet);
937                 return 0;
938         }
939
940         *pfun = fun;
941         return 1;
942 }
943 #endif
944
945
946 #ifdef WITH_COA
947 /*
948  *      For now, all CoA requests are *only* originated, and not
949  *      proxied.  So all of the necessary work is done in the
950  *      post-proxy section, which is automatically handled by event.c.
951  *      As a result, we don't have to do anything here.
952  */
953 static int rad_coa_reply(REQUEST *request)
954 {
955         VALUE_PAIR *s1, *s2;
956
957         /*
958          *      Inform the user about RFC requirements.
959          */
960         s1 = pairfind(request->proxy->vps, PW_STATE);
961         if (s1) {
962                 s2 = pairfind(request->proxy_reply->vps, PW_STATE);
963
964                 if (!s2) {
965                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with State.");
966
967                 } else if ((s1->length != s2->length) ||
968                            (memcmp(s1->vp_octets, s2->vp_octets,
969                                    s1->length) != 0)) {
970                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with the same State.");
971                 }
972         }
973
974         return RLM_MODULE_OK;
975 }
976
977 /*
978  *      Receive a CoA packet.
979  */
980 static int rad_coa_recv(REQUEST *request)
981 {
982         int rcode = RLM_MODULE_OK;
983         int ack, nak;
984         VALUE_PAIR *vp;
985
986         /*
987          *      Get the correct response
988          */
989         switch (request->packet->code) {
990         case PW_COA_REQUEST:
991                 ack = PW_COA_ACK;
992                 nak = PW_COA_NAK;
993                 break;
994
995         case PW_DISCONNECT_REQUEST:
996                 ack = PW_DISCONNECT_ACK;
997                 nak = PW_DISCONNECT_NAK;
998                 break;
999
1000         default:                /* shouldn't happen */
1001                 return RLM_MODULE_FAIL;
1002         }
1003
1004 #ifdef WITH_PROXY
1005 #define WAS_PROXIED (request->proxy)
1006 #else
1007 #define WAS_PROXIED (0)
1008 #endif
1009
1010         if (!WAS_PROXIED) {
1011                 /*
1012                  *      RFC 5176 Section 3.3.  If we have a CoA-Request
1013                  *      with Service-Type = Authorize-Only, it MUST
1014                  *      have a State attribute in it.
1015                  */
1016                 vp = pairfind(request->packet->vps, PW_SERVICE_TYPE);
1017                 if (request->packet->code == PW_COA_REQUEST) {
1018                         if (vp && (vp->vp_integer == 17)) {
1019                                 vp = pairfind(request->packet->vps, PW_STATE);
1020                                 if (!vp || (vp->length == 0)) {
1021                                         RDEBUG("ERROR: CoA-Request with Service-Type = Authorize-Only MUST contain a State attribute");
1022                                         request->reply->code = PW_COA_NAK;
1023                                         return RLM_MODULE_FAIL;
1024                                 }
1025                         }
1026                 } else if (vp) {
1027                         /*
1028                          *      RFC 5176, Section 3.2.
1029                          */
1030                         RDEBUG("ERROR: Disconnect-Request MUST NOT contain a Service-Type attribute");
1031                         request->reply->code = PW_DISCONNECT_NAK;
1032                         return RLM_MODULE_FAIL;
1033                 }
1034
1035                 rcode = module_recv_coa(0, request);
1036                 switch (rcode) {
1037                 case RLM_MODULE_FAIL:
1038                 case RLM_MODULE_INVALID:
1039                 case RLM_MODULE_REJECT:
1040                 case RLM_MODULE_USERLOCK:
1041                 default:
1042                         request->reply->code = nak;
1043                         break;
1044                         
1045                 case RLM_MODULE_HANDLED:
1046                         return rcode;
1047                         
1048                 case RLM_MODULE_NOOP:
1049                 case RLM_MODULE_NOTFOUND:
1050                 case RLM_MODULE_OK:
1051                 case RLM_MODULE_UPDATED:
1052                         request->reply->code = ack;
1053                         break;
1054                 }
1055         } else {
1056                 /*
1057                  *      Start the reply code with the proxy reply
1058                  *      code.
1059                  */
1060                 request->reply->code = request->proxy_reply->code;
1061         }
1062
1063         /*
1064          *      Copy State from the request to the reply.
1065          *      See RFC 5176 Section 3.3.
1066          */
1067         vp = paircopy2(request->packet->vps, PW_STATE);
1068         if (vp) pairadd(&request->reply->vps, vp);
1069
1070         /*
1071          *      We may want to over-ride the reply.
1072          */
1073         rcode = module_send_coa(0, request);
1074         switch (rcode) {
1075                 /*
1076                  *      We need to send CoA-NAK back if Service-Type
1077                  *      is Authorize-Only.  Rely on the user's policy
1078                  *      to do that.  We're not a real NAS, so this
1079                  *      restriction doesn't (ahem) apply to us.
1080                  */
1081                 case RLM_MODULE_FAIL:
1082                 case RLM_MODULE_INVALID:
1083                 case RLM_MODULE_REJECT:
1084                 case RLM_MODULE_USERLOCK:
1085                 default:
1086                         /*
1087                          *      Over-ride an ACK with a NAK
1088                          */
1089                         request->reply->code = nak;
1090                         break;
1091                         
1092                 case RLM_MODULE_HANDLED:
1093                         return rcode;
1094                         
1095                 case RLM_MODULE_NOOP:
1096                 case RLM_MODULE_NOTFOUND:
1097                 case RLM_MODULE_OK:
1098                 case RLM_MODULE_UPDATED:
1099                         /*
1100                          *      Do NOT over-ride a previously set value.
1101                          *      Otherwise an "ok" here will re-write a
1102                          *      NAK to an ACK.
1103                          */
1104                         if (request->reply->code == 0) {
1105                                 request->reply->code = ack;
1106                         }
1107                         break;
1108
1109         }
1110
1111         return RLM_MODULE_OK;
1112 }
1113
1114
1115 /*
1116  *      Check if an incoming request is "ok"
1117  *
1118  *      It takes packets, not requests.  It sees if the packet looks
1119  *      OK.  If so, it does a number of sanity checks on it.
1120   */
1121 static int coa_socket_recv(rad_listen_t *listener,
1122                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1123 {
1124         ssize_t         rcode;
1125         int             code, src_port;
1126         RADIUS_PACKET   *packet;
1127         RAD_REQUEST_FUNP fun = NULL;
1128         char            buffer[128];
1129         RADCLIENT       *client;
1130         fr_ipaddr_t     src_ipaddr;
1131
1132         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1133         if (rcode < 0) return 0;
1134
1135         RAD_STATS_TYPE_INC(listener, total_requests);
1136
1137         if (rcode < 20) {       /* AUTH_HDR_LEN */
1138                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1139                 return 0;
1140         }
1141
1142         if ((client = client_listener_find(listener,
1143                                            &src_ipaddr, src_port)) == NULL) {
1144                 rad_recv_discard(listener->fd);
1145                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1146
1147                 if (debug_flag > 0) {
1148                         char name[1024];
1149
1150                         listener->print(listener, name, sizeof(name));
1151
1152                         /*
1153                          *      This is debugging rather than logging, so that
1154                          *      DoS attacks don't affect us.
1155                          */
1156                         DEBUG("Ignoring request to %s from unknown client %s port %d",
1157                               name,
1158                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
1159                                         buffer, sizeof(buffer)), src_port);
1160                 }
1161
1162                 return 0;
1163         }
1164
1165         /*
1166          *      Some sanity checks, based on the packet code.
1167          */
1168         switch(code) {
1169         case PW_COA_REQUEST:
1170         case PW_DISCONNECT_REQUEST:
1171                 fun = rad_coa_recv;
1172                 break;
1173
1174         default:
1175                 rad_recv_discard(listener->fd);
1176                 DEBUG("Invalid packet code %d sent to coa port from client %s port %d : IGNORED",
1177                       code, client->shortname, src_port);
1178                 return 0;
1179                 break;
1180         } /* switch over packet types */
1181
1182         /*
1183          *      Now that we've sanity checked everything, receive the
1184          *      packet.
1185          */
1186         packet = rad_recv(listener->fd, client->message_authenticator);
1187         if (!packet) {
1188                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1189                 DEBUG("%s", fr_strerror());
1190                 return 0;
1191         }
1192
1193         if (!received_request(listener, packet, prequest, client)) {
1194                 rad_free(&packet);
1195                 return 0;
1196         }
1197
1198         *pfun = fun;
1199         return 1;
1200 }
1201 #endif
1202
1203 #ifdef WITH_PROXY
1204 /*
1205  *      Recieve packets from a proxy socket.
1206  */
1207 static int proxy_socket_recv(rad_listen_t *listener,
1208                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1209 {
1210         REQUEST         *request;
1211         RADIUS_PACKET   *packet;
1212         RAD_REQUEST_FUNP fun = NULL;
1213         char            buffer[128];
1214
1215         packet = rad_recv(listener->fd, 0);
1216         if (!packet) {
1217                 radlog(L_ERR, "%s", fr_strerror());
1218                 return 0;
1219         }
1220
1221         /*
1222          *      FIXME: Client MIB updates?
1223          */
1224         switch(packet->code) {
1225         case PW_AUTHENTICATION_ACK:
1226         case PW_ACCESS_CHALLENGE:
1227         case PW_AUTHENTICATION_REJECT:
1228                 fun = rad_authenticate;
1229                 break;
1230
1231 #ifdef WITH_ACCOUNTING
1232         case PW_ACCOUNTING_RESPONSE:
1233                 fun = rad_accounting;
1234                 break;
1235 #endif
1236
1237 #ifdef WITH_COA
1238         case PW_DISCONNECT_ACK:
1239         case PW_DISCONNECT_NAK:
1240         case PW_COA_ACK:
1241         case PW_COA_NAK:
1242                 fun = rad_coa_reply;
1243                 break;
1244 #endif
1245
1246         default:
1247                 /*
1248                  *      FIXME: Update MIB for packet types?
1249                  */
1250                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1251                        "from home server %s port %d - ID %d : IGNORED",
1252                        packet->code,
1253                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1254                        packet->src_port, packet->id);
1255                 rad_free(&packet);
1256                 return 0;
1257         }
1258
1259         request = received_proxy_response(packet);
1260         if (!request) {
1261                 rad_free(&packet);
1262                 return 0;
1263         }
1264
1265 #ifdef WITH_COA
1266         /*
1267          *      Distinguish proxied CoA requests from ones we
1268          *      originate.
1269          */
1270         if ((fun == rad_coa_reply) &&
1271             (request->packet->code == request->proxy->code)) {
1272                 fun = rad_coa_recv;
1273         }
1274 #endif
1275
1276         rad_assert(fun != NULL);
1277         *pfun = fun;
1278         *prequest = request;
1279
1280         return 1;
1281 }
1282
1283 #ifdef WITH_TCP
1284 /*
1285  *      Recieve packets from a proxy socket.
1286  */
1287 static int proxy_socket_tcp_recv(rad_listen_t *listener,
1288                                  RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1289 {
1290         REQUEST         *request;
1291         RADIUS_PACKET   *packet;
1292         RAD_REQUEST_FUNP fun = NULL;
1293         char            buffer[128];
1294
1295         packet = fr_tcp_recv(listener->fd, 0);
1296         if (!packet) {
1297                 proxy_close_tcp_listener(listener);
1298                 return 0;
1299         }
1300
1301         /*
1302          *      FIXME: Client MIB updates?
1303          */
1304         switch(packet->code) {
1305         case PW_AUTHENTICATION_ACK:
1306         case PW_ACCESS_CHALLENGE:
1307         case PW_AUTHENTICATION_REJECT:
1308                 fun = rad_authenticate;
1309                 break;
1310
1311 #ifdef WITH_ACCOUNTING
1312         case PW_ACCOUNTING_RESPONSE:
1313                 fun = rad_accounting;
1314                 break;
1315 #endif
1316
1317         default:
1318                 /*
1319                  *      FIXME: Update MIB for packet types?
1320                  */
1321                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1322                        "from home server %s port %d - ID %d : IGNORED",
1323                        packet->code,
1324                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1325                        packet->src_port, packet->id);
1326                 rad_free(&packet);
1327                 return 0;
1328         }
1329
1330         request = received_proxy_tcp_response(packet,
1331                                               fr_listen2tcp(listener));
1332         if (!request) {
1333                 return 0;
1334         }
1335
1336         rad_assert(fun != NULL);
1337         *pfun = fun;
1338         *prequest = request;
1339
1340         return 1;
1341 }
1342 #endif
1343 #endif
1344
1345
1346 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1347 {
1348         if (!request->reply->code) return 0;
1349
1350         rad_encode(request->reply, request->packet,
1351                    request->client->secret);
1352         rad_sign(request->reply, request->packet,
1353                  request->client->secret);
1354
1355         return 0;
1356 }
1357
1358
1359 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1360 {
1361         if (rad_verify(request->packet, NULL,
1362                        request->client->secret) < 0) {
1363                 return -1;
1364         }
1365
1366         return rad_decode(request->packet, NULL,
1367                           request->client->secret);
1368 }
1369
1370 #ifdef WITH_PROXY
1371 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1372 {
1373         rad_encode(request->proxy, NULL, request->home_server->secret);
1374         rad_sign(request->proxy, NULL, request->home_server->secret);
1375
1376         return 0;
1377 }
1378
1379
1380 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1381 {
1382         /*
1383          *      rad_verify is run in event.c, received_proxy_response()
1384          */
1385
1386         return rad_decode(request->proxy_reply, request->proxy,
1387                            request->home_server->secret);
1388 }
1389 #endif
1390
1391 #include "dhcpd.c"
1392
1393 #include "command.c"
1394
1395 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1396 #ifdef WITH_STATS
1397         { common_socket_parse, NULL,
1398           stats_socket_recv, auth_socket_send,
1399           socket_print, client_socket_encode, client_socket_decode },
1400 #else
1401         /*
1402          *      This always gets defined.
1403          */
1404         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1405 #endif
1406
1407 #ifdef WITH_PROXY
1408         /* proxying */
1409         { common_socket_parse, NULL,
1410           proxy_socket_recv, proxy_socket_send,
1411           socket_print, proxy_socket_encode, proxy_socket_decode },
1412 #endif
1413
1414         /* authentication */
1415         { common_socket_parse, NULL,
1416           auth_socket_recv, auth_socket_send,
1417           socket_print, client_socket_encode, client_socket_decode },
1418
1419 #ifdef WITH_ACCOUNTING
1420         /* accounting */
1421         { common_socket_parse, NULL,
1422           acct_socket_recv, acct_socket_send,
1423           socket_print, client_socket_encode, client_socket_decode},
1424 #endif
1425
1426 #ifdef WITH_DETAIL
1427         /* detail */
1428         { detail_parse, detail_free,
1429           detail_recv, detail_send,
1430           detail_print, detail_encode, detail_decode },
1431 #endif
1432
1433 #ifdef WITH_VMPS
1434         /* vlan query protocol */
1435         { common_socket_parse, NULL,
1436           vqp_socket_recv, vqp_socket_send,
1437           socket_print, vqp_socket_encode, vqp_socket_decode },
1438 #endif
1439
1440 #ifdef WITH_DHCP
1441         /* dhcp query protocol */
1442         { dhcp_socket_parse, NULL,
1443           dhcp_socket_recv, dhcp_socket_send,
1444           socket_print, dhcp_socket_encode, dhcp_socket_decode },
1445 #endif
1446
1447 #ifdef WITH_COMMAND_SOCKET
1448         /* TCP command socket */
1449         { command_socket_parse, NULL,
1450           command_domain_accept, command_domain_send,
1451           command_socket_print, command_socket_encode, command_socket_decode },
1452 #endif
1453
1454 #ifdef WITH_COA
1455         /* Change of Authorization */
1456         { common_socket_parse, NULL,
1457           coa_socket_recv, auth_socket_send, /* CoA packets are same as auth */
1458           socket_print, client_socket_encode, client_socket_decode },
1459 #endif
1460
1461 };
1462
1463
1464
1465 /*
1466  *      Binds a listener to a socket.
1467  */
1468 static int listen_bind(rad_listen_t *this)
1469 {
1470         int rcode;
1471         struct sockaddr_storage salocal;
1472         socklen_t       salen;
1473         listen_socket_t *sock = this->data;
1474
1475         /*
1476          *      If the port is zero, then it means the appropriate
1477          *      thing from /etc/services.
1478          */
1479         if (sock->port == 0) {
1480                 struct servent  *svp;
1481
1482                 switch (this->type) {
1483                 case RAD_LISTEN_AUTH:
1484                         svp = getservbyname ("radius", "udp");
1485                         if (svp != NULL) {
1486                                 sock->port = ntohs(svp->s_port);
1487                         } else {
1488                                 sock->port = PW_AUTH_UDP_PORT;
1489                         }
1490                         break;
1491
1492 #ifdef WITH_ACCOUNTING
1493                 case RAD_LISTEN_ACCT:
1494                         svp = getservbyname ("radacct", "udp");
1495                         if (svp != NULL) {
1496                                 sock->port = ntohs(svp->s_port);
1497                         } else {
1498                                 sock->port = PW_ACCT_UDP_PORT;
1499                         }
1500                         break;
1501 #endif
1502
1503 #ifdef WITH_PROXY
1504                 case RAD_LISTEN_PROXY:
1505                         sock->port = 0;
1506                         break;
1507 #endif
1508
1509 #ifdef WITH_VMPS
1510                 case RAD_LISTEN_VQP:
1511                         sock->port = 1589;
1512                         break;
1513 #endif
1514
1515 #ifdef WITH_COA
1516                 case RAD_LISTEN_COA:
1517                         sock->port = PW_COA_UDP_PORT;
1518                         break;
1519 #endif
1520
1521                 default:
1522                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1523                         return -1;
1524                 }
1525         }
1526
1527         /*
1528          *      Copy fr_socket() here, as we may need to bind to a device.
1529          */
1530         this->fd = socket(sock->ipaddr.af, SOCK_DGRAM, 0);
1531         if (this->fd < 0) {
1532                 radlog(L_ERR, "Failed opening socket: %s", strerror(errno));
1533                 return -1;
1534         }
1535                 
1536 #ifdef SO_BINDTODEVICE
1537         /*
1538          *      Bind to a device BEFORE touching IP addresses.
1539          */
1540         if (sock->interface) {
1541                 struct ifreq ifreq;
1542                 strcpy(ifreq.ifr_name, sock->interface);
1543
1544                 fr_suid_up();
1545                 rcode = setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
1546                                    (char *)&ifreq, sizeof(ifreq));
1547                 fr_suid_down();
1548                 if (rcode < 0) {
1549                         close(this->fd);
1550                         radlog(L_ERR, "Failed binding to interface %s: %s",
1551                                sock->interface, strerror(errno));
1552                         return -1;
1553                 } /* else it worked. */
1554         }
1555 #endif
1556
1557 #ifdef WITH_UDPFROMTO
1558         /*
1559          *      Initialize udpfromto for all sockets.
1560          */
1561         if (udpfromto_init(this->fd) != 0) {
1562                 close(this->fd);
1563                 return -1;
1564         }
1565 #endif
1566         
1567         /*
1568          *      Set up sockaddr stuff.
1569          */
1570         if (!fr_ipaddr2sockaddr(&sock->ipaddr, sock->port, &salocal, &salen)) {
1571                 close(this->fd);
1572                 return -1;
1573         }
1574                 
1575 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1576         if (sock->ipaddr.af == AF_INET6) {
1577                 /*
1578                  *      Listening on '::' does NOT get you IPv4 to
1579                  *      IPv6 mapping.  You've got to listen on an IPv4
1580                  *      address, too.  This makes the rest of the server
1581                  *      design a little simpler.
1582                  */
1583 #ifdef IPV6_V6ONLY
1584                 
1585                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->ipaddr.ipaddr.ip6addr)) {
1586                         int on = 1;
1587                         
1588                         setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
1589                                    (char *)&on, sizeof(on));
1590                 }
1591 #endif /* IPV6_V6ONLY */
1592         }
1593 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
1594
1595
1596         if (sock->ipaddr.af == AF_INET) {
1597                 UNUSED int flag;
1598                 
1599 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1600                 /*
1601                  *      Disable PMTU discovery.  On Linux, this
1602                  *      also makes sure that the "don't fragment"
1603                  *      flag is zero.
1604                  */
1605                 flag = IP_PMTUDISC_DONT;
1606                 setsockopt(this->fd, IPPROTO_IP, IP_MTU_DISCOVER,
1607                            &flag, sizeof(flag));
1608 #endif
1609
1610 #if defined(IP_DONTFRAG)
1611                 /*
1612                  *      Ensure that the "don't fragment" flag is zero.
1613                  */
1614                 flag = 0;
1615                 setsockopt(this->fd, IPPROTO_IP, IP_DONTFRAG,
1616                            &flag, sizeof(flag));
1617 #endif
1618         }
1619
1620         /*
1621          *      May be binding to priviledged ports.
1622          */
1623         fr_suid_up();
1624         rcode = bind(this->fd, (struct sockaddr *) &salocal, salen);
1625         fr_suid_down();
1626         if (rcode < 0) {
1627                 char buffer[256];
1628                 close(this->fd);
1629                 
1630                 this->print(this, buffer, sizeof(buffer));
1631                 radlog(L_ERR, "Failed binding to %s: %s\n",
1632                        buffer, strerror(errno));
1633                 return -1;
1634         }
1635         
1636         /*
1637          *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
1638          *      kernel instead binds us to a 1.2.3.4.  If this
1639          *      happens, notice, and remember our real IP.
1640          */
1641         {
1642                 struct sockaddr_storage src;
1643                 socklen_t               sizeof_src = sizeof(src);
1644
1645                 memset(&src, 0, sizeof_src);
1646                 if (getsockname(this->fd, (struct sockaddr *) &src,
1647                                 &sizeof_src) < 0) {
1648                         radlog(L_ERR, "Failed getting socket name: %s",
1649                                strerror(errno));
1650                         return -1;
1651                 }
1652
1653                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
1654                                         &sock->ipaddr, &sock->port)) {
1655                         radlog(L_ERR, "Socket has unsupported address family");
1656                         return -1;
1657                 }
1658         }
1659
1660 #ifdef O_NONBLOCK
1661         {
1662                 int flags;
1663                 
1664                 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  {
1665                         radlog(L_ERR, "Failure getting socket flags: %s)\n",
1666                                strerror(errno));
1667                         return -1;
1668                 }
1669                 
1670                 flags |= O_NONBLOCK;
1671                 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1672                         radlog(L_ERR, "Failure setting socket flags: %s)\n",
1673                                strerror(errno));
1674                         return -1;
1675                 }
1676         }
1677 #endif
1678
1679         return 0;
1680 }
1681
1682
1683 /*
1684  *      Allocate & initialize a new listener.
1685  */
1686 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1687 {
1688         rad_listen_t *this;
1689
1690         this = rad_malloc(sizeof(*this));
1691         memset(this, 0, sizeof(*this));
1692
1693         this->type = type;
1694         this->recv = master_listen[this->type].recv;
1695         this->send = master_listen[this->type].send;
1696         this->print = master_listen[this->type].print;
1697         this->encode = master_listen[this->type].encode;
1698         this->decode = master_listen[this->type].decode;
1699
1700         switch (type) {
1701 #ifdef WITH_STATS
1702         case RAD_LISTEN_NONE:
1703 #endif
1704         case RAD_LISTEN_AUTH:
1705 #ifdef WITH_ACCOUNTING
1706         case RAD_LISTEN_ACCT:
1707 #endif
1708 #ifdef WITH_PROXY
1709         case RAD_LISTEN_PROXY:
1710 #endif
1711 #ifdef WITH_VMPS
1712         case RAD_LISTEN_VQP:
1713 #endif
1714 #ifdef WITH_COA
1715         case RAD_LISTEN_COA:
1716 #endif
1717                 this->data = rad_malloc(sizeof(listen_socket_t));
1718                 memset(this->data, 0, sizeof(listen_socket_t));
1719                 break;
1720
1721 #ifdef WITH_DHCP
1722         case RAD_LISTEN_DHCP:
1723                 this->data = rad_malloc(sizeof(dhcp_socket_t));
1724                 memset(this->data, 0, sizeof(dhcp_socket_t));
1725                 break;
1726 #endif
1727
1728 #ifdef WITH_DETAIL
1729         case RAD_LISTEN_DETAIL:
1730                 this->data = NULL;
1731                 break;
1732 #endif
1733
1734 #ifdef WITH_COMMAND_SOCKET
1735         case RAD_LISTEN_COMMAND:
1736                 this->data = rad_malloc(sizeof(fr_command_socket_t));
1737                 memset(this->data, 0, sizeof(fr_command_socket_t));
1738                 break;
1739 #endif
1740
1741         default:
1742                 rad_assert("Unsupported option!" == NULL);
1743                 break;
1744         }
1745
1746         return this;
1747 }
1748
1749
1750 #ifdef WITH_PROXY
1751 /*
1752  *      Externally visible function for creating a new proxy LISTENER.
1753  *
1754  *      Not thread-safe, but all calls to it are protected by the
1755  *      proxy mutex in event.c
1756  */
1757 rad_listen_t *proxy_new_listener(fr_ipaddr_t *ipaddr, int exists)
1758 {
1759         int last_proxy_port, port;
1760         rad_listen_t *this, *tmp, **last;
1761         listen_socket_t *sock, *old;
1762
1763         /*
1764          *      Find an existing proxy socket to copy.
1765          */
1766         last_proxy_port = 0;
1767         old = NULL;
1768         last = &mainconfig.listen;
1769         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1770                 /*
1771                  *      Not proxy, ignore it.
1772                  */
1773                 if (tmp->type != RAD_LISTEN_PROXY) continue;
1774
1775                 sock = tmp->data;
1776
1777                 /*
1778                  *      If we were asked to copy a specific one, do
1779                  *      so.  If we're just finding one that already
1780                  *      exists, return a pointer to it.  Otherwise,
1781                  *      create ANOTHER one with the same IP address.
1782                  */
1783                 if ((ipaddr->af != AF_UNSPEC) &&
1784                     (fr_ipaddr_cmp(&sock->ipaddr, ipaddr) != 0)) {
1785                         if (exists) return tmp;
1786                         continue;
1787                 }
1788                 
1789                 if (sock->port > last_proxy_port) {
1790                         last_proxy_port = sock->port + 1;
1791                 }
1792                 if (!old) old = sock;
1793
1794                 last = &(tmp->next);
1795         }
1796
1797         if (!old) {
1798                 /*
1799                  *      The socket MUST already exist if we're binding
1800                  *      to an address while proxying.
1801                  *
1802                  *      If we're initializing the server, it's OK for the
1803                  *      socket to NOT exist.
1804                  */
1805                 if (!exists) return NULL;
1806
1807                 this = listen_alloc(RAD_LISTEN_PROXY);
1808
1809                 sock = this->data;
1810                 sock->ipaddr = *ipaddr;
1811
1812         } else {
1813                 this = listen_alloc(RAD_LISTEN_PROXY);
1814                 
1815                 sock = this->data;
1816                 sock->ipaddr = old->ipaddr;
1817         }
1818
1819         /*
1820          *      Keep going until we find an unused port.
1821          */
1822         for (port = last_proxy_port; port < 64000; port++) {
1823                 int rcode;
1824
1825                 sock->port = port;
1826
1827                 rcode = listen_bind(this);
1828                 if (rcode < 0) {
1829                         listen_free(&this);
1830                         return NULL;
1831                 }
1832                 
1833                 /*
1834                  *      Add the new listener to the list of
1835                  *      listeners.
1836                  */
1837                 *last = this;
1838                 return this;
1839         }
1840
1841         listen_free(&this);
1842         return NULL;
1843 }
1844 #endif
1845
1846 static const FR_NAME_NUMBER listen_compare[] = {
1847 #ifdef WITH_STATS
1848         { "status",     RAD_LISTEN_NONE },
1849 #endif
1850         { "auth",       RAD_LISTEN_AUTH },
1851 #ifdef WITH_ACCOUNTING
1852         { "acct",       RAD_LISTEN_ACCT },
1853 #endif
1854 #ifdef WITH_DETAIL
1855         { "detail",     RAD_LISTEN_DETAIL },
1856 #endif
1857 #ifdef WITH_PROXY
1858         { "proxy",      RAD_LISTEN_PROXY },
1859 #endif
1860 #ifdef WITH_VMPS
1861         { "vmps",       RAD_LISTEN_VQP },
1862 #endif
1863 #ifdef WITH_DHCP
1864         { "dhcp",       RAD_LISTEN_DHCP },
1865 #endif
1866 #ifdef WITH_COMMAND_SOCKET
1867         { "control",    RAD_LISTEN_COMMAND },
1868 #endif
1869 #ifdef WITH_COA
1870         { "coa",        RAD_LISTEN_COA },
1871 #endif
1872         { NULL, 0 },
1873 };
1874
1875
1876 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1877 {
1878         int             type, rcode;
1879         char            *listen_type;
1880         rad_listen_t    *this;
1881
1882         listen_type = NULL;
1883         
1884         cf_log_info(cs, "listen {");
1885
1886         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1887                               &listen_type, "");
1888         if (rcode < 0) return NULL;
1889         if (rcode == 1) {
1890                 free(listen_type);
1891                 cf_log_err(cf_sectiontoitem(cs),
1892                            "No type specified in listen section");
1893                 return NULL;
1894         }
1895
1896         type = fr_str2int(listen_compare, listen_type, -1);
1897         if (type < 0) {
1898                 cf_log_err(cf_sectiontoitem(cs),
1899                            "Invalid type \"%s\" in listen section.",
1900                            listen_type);
1901                 free(listen_type);
1902                 return NULL;
1903         }
1904         free(listen_type);
1905         
1906         /*
1907          *      Allow listen sections in the default config to
1908          *      refer to a server.
1909          */
1910         if (!server) {
1911                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1912                                       &server, NULL);
1913                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1914                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1915                                               &server, NULL);
1916                 }
1917                 if (rcode < 0) return NULL;
1918         }
1919
1920         /*
1921          *      Set up cross-type data.
1922          */
1923         this = listen_alloc(type);
1924         this->server = server;
1925         this->fd = -1;
1926
1927         /*
1928          *      Call per-type parser.
1929          */
1930         if (master_listen[type].parse(cs, this) < 0) {
1931                 listen_free(&this);
1932                 return NULL;
1933         }
1934
1935         cf_log_info(cs, "}");
1936
1937         return this;
1938 }
1939
1940 /*
1941  *      Generate a list of listeners.  Takes an input list of
1942  *      listeners, too, so we don't close sockets with waiting packets.
1943  */
1944 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1945 {
1946         int             override = FALSE;
1947         int             rcode;
1948         CONF_SECTION    *cs = NULL;
1949         rad_listen_t    **last;
1950         rad_listen_t    *this;
1951         fr_ipaddr_t     server_ipaddr;
1952         int             auth_port = 0;
1953 #ifdef WITH_PROXY
1954         int             defined_proxy = 0;
1955 #endif
1956
1957         /*
1958          *      We shouldn't be called with a pre-existing list.
1959          */
1960         rad_assert(head && (*head == NULL));
1961
1962         last = head;
1963         server_ipaddr.af = AF_UNSPEC;
1964
1965         /*
1966          *      If the port is specified on the command-line,
1967          *      it over-rides the configuration file.
1968          *
1969          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1970          */
1971         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1972
1973         /*
1974          *      If the IP address was configured on the command-line,
1975          *      use that as the "bind_address"
1976          */
1977         if (mainconfig.myip.af != AF_UNSPEC) {
1978                 memcpy(&server_ipaddr, &mainconfig.myip,
1979                        sizeof(server_ipaddr));
1980                 override = TRUE;
1981                 goto bind_it;
1982         }
1983
1984         /*
1985          *      Else look for bind_address and/or listen sections.
1986          */
1987         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1988         rcode = cf_item_parse(config, "bind_address",
1989                               PW_TYPE_IPADDR,
1990                               &server_ipaddr.ipaddr.ip4addr, NULL);
1991         if (rcode < 0) return -1; /* error parsing it */
1992
1993         if (rcode == 0) { /* successfully parsed IPv4 */
1994                 listen_socket_t *sock;
1995                 server_ipaddr.af = AF_INET;
1996
1997                 radlog(L_INFO, "WARNING: The directive 'bind_adress' is deprecated, and will be removed in future versions of FreeRADIUS. Please edit the configuration files to use the directive 'listen'.");
1998
1999         bind_it:
2000 #ifdef WITH_VMPS
2001                 if (strcmp(progname, "vmpsd") == 0) {
2002                         this = listen_alloc(RAD_LISTEN_VQP);
2003                         if (!auth_port) auth_port = 1589;
2004                 } else
2005 #endif
2006                         this = listen_alloc(RAD_LISTEN_AUTH);
2007
2008                 sock = this->data;
2009
2010                 sock->ipaddr = server_ipaddr;
2011                 sock->port = auth_port;
2012
2013                 sock->clients = clients_parse_section(config);
2014                 if (!sock->clients) {
2015                         cf_log_err(cf_sectiontoitem(config),
2016                                    "Failed to find any clients for this listen section");
2017                         listen_free(&this);
2018                         return -1;
2019                 }
2020
2021                 if (listen_bind(this) < 0) {
2022                         listen_free(head);
2023                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
2024                         listen_free(&this);
2025                         return -1;
2026                 }
2027                 auth_port = sock->port; /* may have been updated in listen_bind */
2028                 if (override) {
2029                         cs = cf_section_sub_find_name2(config, "server",
2030                                                        mainconfig.name);
2031                         if (cs) this->server = mainconfig.name;
2032                 }
2033
2034                 *last = this;
2035                 last = &(this->next);
2036
2037 #ifdef WITH_VMPS
2038                 /*
2039                  *      No acct for vmpsd
2040                  */
2041                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
2042 #endif
2043
2044 #ifdef WITH_ACCOUNTING
2045                 /*
2046                  *      Open Accounting Socket.
2047                  *
2048                  *      If we haven't already gotten acct_port from
2049                  *      /etc/services, then make it auth_port + 1.
2050                  */
2051                 this = listen_alloc(RAD_LISTEN_ACCT);
2052                 sock = this->data;
2053
2054                 /*
2055                  *      Create the accounting socket.
2056                  *
2057                  *      The accounting port is always the
2058                  *      authentication port + 1
2059                  */
2060                 sock->ipaddr = server_ipaddr;
2061                 sock->port = auth_port + 1;
2062
2063                 sock->clients = clients_parse_section(config);
2064                 if (!sock->clients) {
2065                         cf_log_err(cf_sectiontoitem(config),
2066                                    "Failed to find any clients for this listen section");
2067                         return -1;
2068                 }
2069
2070                 if (listen_bind(this) < 0) {
2071                         listen_free(&this);
2072                         listen_free(head);
2073                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
2074                         return -1;
2075                 }
2076
2077                 if (override) {
2078                         cs = cf_section_sub_find_name2(config, "server",
2079                                                        mainconfig.name);
2080                         if (cs) this->server = mainconfig.name;
2081                 }
2082
2083                 *last = this;
2084                 last = &(this->next);
2085 #endif
2086         } else if (mainconfig.port > 0) { /* no bind address, but a port */
2087                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
2088                        mainconfig.port);
2089                 return -1;
2090         }
2091
2092         /*
2093          *      They specified an IP on the command-line, ignore
2094          *      all listen sections except the one in '-n'.
2095          */
2096         if (mainconfig.myip.af != AF_UNSPEC) {
2097                 CONF_SECTION *subcs;
2098                 const char *name2 = cf_section_name2(cs);
2099
2100                 cs = cf_section_sub_find_name2(config, "server",
2101                                                mainconfig.name);
2102                 if (!cs) goto do_proxy;
2103
2104                 /*
2105                  *      Should really abstract this code...
2106                  */
2107                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2108                      subcs != NULL;
2109                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2110                         this = listen_parse(subcs, name2);
2111                         if (!this) {
2112                                 listen_free(head);
2113                                 return -1;
2114                         }
2115
2116 #ifdef WITH_PROXY
2117                         if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
2118 #endif
2119                         
2120                         *last = this;
2121                         last = &(this->next);
2122                 } /* loop over "listen" directives in server <foo> */
2123
2124                 goto do_proxy;
2125         }
2126
2127         /*
2128          *      Walk through the "listen" sections, if they exist.
2129          */
2130         for (cs = cf_subsection_find_next(config, NULL, "listen");
2131              cs != NULL;
2132              cs = cf_subsection_find_next(config, cs, "listen")) {
2133                 this = listen_parse(cs, NULL);
2134                 if (!this) {
2135                         listen_free(head);
2136                         return -1;
2137                 }
2138
2139 #ifdef WITH_PROXY
2140                 if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
2141 #endif
2142
2143                 *last = this;
2144                 last = &(this->next);
2145         }
2146
2147         /*
2148          *      Check virtual servers for "listen" sections, too.
2149          *
2150          *      FIXME: Move to virtual server init?
2151          */
2152         for (cs = cf_subsection_find_next(config, NULL, "server");
2153              cs != NULL;
2154              cs = cf_subsection_find_next(config, cs, "server")) {
2155                 CONF_SECTION *subcs;
2156                 const char *name2 = cf_section_name2(cs);
2157                 
2158                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2159                      subcs != NULL;
2160                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2161                         this = listen_parse(subcs, name2);
2162                         if (!this) {
2163                                 listen_free(head);
2164                                 return -1;
2165                         }
2166                         
2167 #ifdef WITH_PROXY
2168                         if (this->type == RAD_LISTEN_PROXY) {
2169                                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
2170                                 listen_free(head);
2171                                 return -1;
2172                         }
2173 #endif
2174
2175                         *last = this;
2176                         last = &(this->next);
2177                 } /* loop over "listen" directives in virtual servers */
2178         } /* loop over virtual servers */
2179
2180         /*
2181          *      If we're proxying requests, open the proxy FD.
2182          *      Otherwise, don't do anything.
2183          */
2184  do_proxy:
2185 #ifdef WITH_PROXY
2186         if (mainconfig.proxy_requests == TRUE) {
2187                 int             port = -1;
2188                 listen_socket_t *sock = NULL;
2189
2190                 /*
2191                  *      No sockets to receive packets, therefore
2192                  *      proxying is pointless.
2193                  */
2194                 if (!*head) return -1;
2195
2196                 if (defined_proxy) goto check_home_servers;
2197
2198                 /*
2199                  *      Find the first authentication port,
2200                  *      and use it
2201                  */
2202                 for (this = *head; this != NULL; this = this->next) {
2203                         if (this->type == RAD_LISTEN_AUTH) {
2204                                 sock = this->data;
2205                                 if (server_ipaddr.af == AF_UNSPEC) {
2206                                         server_ipaddr = sock->ipaddr;
2207                                 }
2208                                 port = sock->port + 2; /* skip acct port */
2209                                 break;
2210                         }
2211 #ifdef WITH_VMPS
2212                         if (this->type == RAD_LISTEN_VQP) {
2213                                 sock = this->data;
2214                                 if (server_ipaddr.af == AF_UNSPEC) {
2215                                         server_ipaddr = sock->ipaddr;
2216                                 }
2217                                 port = sock->port + 1;
2218                                 break;
2219                         }
2220 #endif
2221                 }
2222
2223                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
2224
2225                 /*
2226                  *      Address is still unspecified, use IPv4.
2227                  */
2228                 if (server_ipaddr.af == AF_UNSPEC) {
2229                         server_ipaddr.af = AF_INET;
2230                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
2231                 }
2232
2233                 this = listen_alloc(RAD_LISTEN_PROXY);
2234                 sock = this->data;
2235
2236                 /*
2237                  *      Create the first proxy socket.
2238                  */
2239                 sock->ipaddr = server_ipaddr;
2240
2241                 /*
2242                  *      Try to find a proxy port (value doesn't matter)
2243                  */
2244                 for (sock->port = port;
2245                      sock->port < 64000;
2246                      sock->port++) {
2247                         if (listen_bind(this) == 0) {
2248                                 *last = this;
2249                                 last = &(this->next); /* just in case */
2250                                 break;
2251                         }
2252                 }
2253
2254                 if (sock->port >= 64000) {
2255                         listen_free(head);
2256                         listen_free(&this);
2257                         radlog(L_ERR, "Failed to open socket for proxying");
2258                         return -1;
2259                 }
2260                 
2261                 /*
2262                  *      Create *additional* proxy listeners, based
2263                  *      on their src_ipaddr.
2264                  */
2265         check_home_servers:
2266                 if (home_server_create_listeners(*head) != 0) return -1;
2267         }
2268 #endif
2269
2270         return 0;
2271 }
2272
2273 /*
2274  *      Free a linked list of listeners;
2275  */
2276 void listen_free(rad_listen_t **head)
2277 {
2278         rad_listen_t *this;
2279
2280         if (!head || !*head) return;
2281
2282         this = *head;
2283         while (this) {
2284                 rad_listen_t *next = this->next;
2285
2286                 /*
2287                  *      Other code may have eaten the FD.
2288                  */
2289                 if (this->fd >= 0) close(this->fd);
2290
2291                 if (master_listen[this->type].free) {
2292                         master_listen[this->type].free(this);
2293                 }
2294                 free(this->data);
2295                 free(this);
2296
2297                 this = next;
2298         }
2299
2300         *head = NULL;
2301 }
2302
2303 #ifdef WITH_TCP
2304 fr_tcp_radius_t *fr_listen2tcp(rad_listen_t *this)
2305 {
2306         listen_socket_t *sock;
2307
2308         if (!this || (this->type != RAD_LISTEN_PROXY) || !this->data) {
2309                 return NULL;
2310         }
2311
2312         sock = this->data;
2313         return sock->tcp;
2314 }
2315
2316 rad_listen_t *proxy_new_tcp_listener(home_server *home)
2317 {
2318         int i;
2319         fr_tcp_radius_t *tcp;
2320         struct sockaddr_storage src;
2321         socklen_t sizeof_src = sizeof(src);
2322         rad_listen_t *this;
2323         listen_socket_t *sock;
2324
2325         if (!home ||
2326             ((home->max_connections > 0) &&
2327              (home->num_connections >= home->max_connections))) {
2328                 DEBUG("WARNING: Home server has too many open connections (%d)",
2329                       home->max_connections);
2330                 return NULL;
2331         }
2332
2333         this = NULL;
2334
2335         /*
2336          *      FIXME: Move to RBTrees.
2337          */
2338         for (i = 0; i < home->max_connections; i++) {
2339                 if (home->listeners[i]) continue;
2340
2341                 this = home->listeners[i] = listen_alloc(RAD_LISTEN_PROXY);
2342                 if (!this) {
2343                         DEBUG("WARNING: Failed allocating memory");
2344                         return NULL;
2345                 }
2346                 break;
2347         }
2348
2349         if (!this) {
2350                 DEBUG("WARNING: Failed to find a free connection slot");
2351                 return NULL;
2352         }
2353         sock = this->data;
2354
2355         tcp = sock->tcp = rad_malloc(sizeof(*tcp));
2356         memset(tcp, 0, sizeof(*tcp));
2357
2358         /*
2359          *      Initialize th
2360          *
2361          *      Open a new socket...
2362          *
2363          *      Do stuff...
2364          */
2365         tcp->dst_ipaddr = home->ipaddr;
2366         tcp->dst_port = home->port;
2367         tcp->lifetime = home->lifetime;
2368         tcp->opened = time(NULL);       
2369
2370         /*
2371          *      FIXME: connect() is blocking!
2372          *      We do this with the proxy mutex locked, which may
2373          *      cause large delays!
2374          *
2375          *      http://www.developerweb.net/forum/showthread.php?p=13486
2376          */
2377         this->fd = tcp->fd = fr_tcp_client_socket(&tcp->dst_ipaddr, tcp->dst_port);
2378         if (tcp->fd < 0) {
2379                 listen_free(&this);
2380                 DEBUG("WARNING: Failed opening socket to home server");
2381                 return NULL;
2382         }
2383         memset(&src, 0, sizeof_src);
2384         if (getsockname(tcp->fd, (struct sockaddr *) &src, &sizeof_src) < 0) {
2385                 close(tcp->fd);
2386                 listen_free(&this);
2387                 return NULL;
2388         }
2389
2390         if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2391                                 &tcp->src_ipaddr, &tcp->src_port)) {
2392                 close(tcp->fd);
2393                 listen_free(&this);
2394                 return NULL;
2395         }
2396
2397         /*
2398          *      Fill in socket information.
2399          */
2400         sock->proto = IPPROTO_TCP;
2401         sock->tcp = tcp;
2402
2403         sock->ipaddr = tcp->src_ipaddr;
2404         sock->port = tcp->src_port;
2405
2406         /*
2407          *      Don't ask.  Just don't ask.
2408          */
2409         sock->src_ipaddr = tcp->dst_ipaddr;
2410         sock->src_port = tcp->dst_port;
2411         sock->home = home;
2412         sock->home->num_connections++;
2413
2414         this->recv = proxy_socket_tcp_recv;
2415
2416         /*
2417          *      Tell the event handler about the new socket.
2418          *
2419          *      It keeps track of "this", so we don't have to insert
2420          *      it into the main list of listeners.
2421          */
2422         event_new_fd(this);
2423
2424         return this;
2425 }
2426
2427 void proxy_close_tcp_listener(rad_listen_t *listener)
2428 {
2429         int i;
2430         listen_socket_t *sock = listener->data;
2431         
2432         /*
2433          *      This is the second time around for the socket.  Free
2434          *      the memory now.
2435          */
2436         if (listener->status != RAD_LISTEN_STATUS_KNOWN) {
2437                 listen_free(&listener);
2438                 return;
2439         }
2440
2441         listener->status = RAD_LISTEN_STATUS_CLOSED;
2442         event_new_fd(listener);
2443         
2444         /*
2445          *      Find the home server, and mark this listener as
2446          *      no longer being active.
2447          */
2448         for (i = 0; i < sock->home->max_connections; i++) {
2449                 if (sock->home->listeners[i] == listener) {
2450                         sock->home->listeners[i] = NULL;
2451                         sock->home->num_connections--;
2452                         break;
2453                 }
2454         }
2455
2456         /*
2457          *      There are still one or more requests using this socket.
2458          *      leave it marked as "closed", but don't free it.  When the
2459          *      last requeast using it is cleaned up, it will be deleted.
2460          */
2461         if (sock->tcp->used > 0) return;
2462         
2463         listen_free(&listener);
2464 }
2465 #endif
2466
2467 #ifdef WITH_STATS
2468 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
2469                                           int port)
2470 {
2471         rad_listen_t *this;
2472
2473         for (this = mainconfig.listen; this != NULL; this = this->next) {
2474                 listen_socket_t *sock;
2475
2476                 if ((this->type != RAD_LISTEN_AUTH) &&
2477                     (this->type != RAD_LISTEN_ACCT)) continue;
2478                 
2479                 sock = this->data;
2480
2481                 if ((sock->port == port) &&
2482                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
2483                         return sock->clients;
2484                 }
2485         }
2486
2487         return NULL;
2488 }
2489 #endif
2490
2491 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
2492 {
2493         rad_listen_t *this;
2494
2495         for (this = mainconfig.listen; this != NULL; this = this->next) {
2496                 listen_socket_t *sock;
2497
2498                 /*
2499                  *      FIXME: For TCP, ignore the *secondary*
2500                  *      listeners associated with the main socket.
2501                  */
2502                 if ((this->type != RAD_LISTEN_AUTH) &&
2503                     (this->type != RAD_LISTEN_ACCT)) continue;
2504                 
2505                 sock = this->data;
2506
2507                 if ((sock->port == port) &&
2508                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
2509                         return this;
2510                 }
2511
2512                 if ((sock->port == port) &&
2513                     ((sock->ipaddr.af == AF_INET) &&
2514                      (sock->ipaddr.ipaddr.ip4addr.s_addr == INADDR_ANY))) {
2515                         return this;
2516                 }
2517
2518 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2519                 if ((sock->port == port) &&
2520                     (sock->ipaddr.af == AF_INET6) &&
2521                     (IN6_IS_ADDR_UNSPECIFIED(&sock->ipaddr.ipaddr.ip6addr))) {
2522                         return this;
2523                 }
2524 #endif
2525         }
2526
2527         return NULL;
2528 }