Replace fr_client_stats_t with fr_stats_t. They have the
[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/radius_snmp.h>
29 #include <freeradius-devel/modules.h>
30 #include <freeradius-devel/rad_assert.h>
31 #include <freeradius-devel/vqp.h>
32 #include <freeradius-devel/dhcp.h>
33
34 #include <freeradius-devel/vmps.h>
35 #include <freeradius-devel/detail.h>
36
37 #ifdef HAVE_SYS_RESOURCE_H
38 #include <sys/resource.h>
39 #endif
40
41 #ifdef HAVE_NET_IF_H
42 #include <net/if.h>
43 #endif
44
45 #ifdef HAVE_FCNTL_H
46 #include <fcntl.h>
47 #endif
48
49
50 /*
51  *      We'll use this below.
52  */
53 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
54 typedef void (*rad_listen_free_t)(rad_listen_t *);
55
56 typedef struct rad_listen_master_t {
57         rad_listen_parse_t      parse;
58         rad_listen_free_t       free;
59         rad_listen_recv_t       recv;
60         rad_listen_send_t       send;
61         rad_listen_print_t      print;
62         rad_listen_encode_t     encode;
63         rad_listen_decode_t     decode;
64 } rad_listen_master_t;
65
66 typedef struct listen_socket_t {
67         /*
68          *      For normal sockets.
69          */
70         fr_ipaddr_t     ipaddr;
71         int             port;
72 #ifdef SO_BINDTODEVICE
73         const char              *interface;
74 #endif
75         RADCLIENT_LIST  *clients;
76 } listen_socket_t;
77
78 /*
79  *      Find a per-socket client.
80  */
81 RADCLIENT *client_listener_find(const rad_listen_t *listener,
82                                        const fr_ipaddr_t *ipaddr)
83 {
84 #ifdef WITH_DYNAMIC_CLIENTS
85         int rcode;
86         time_t now;
87         listen_socket_t *sock;
88         REQUEST *request;
89         RADCLIENT *client, *created;
90 #endif
91         RADCLIENT_LIST *clients;
92
93         rad_assert(listener != NULL);
94         rad_assert(ipaddr != NULL);
95
96         rad_assert((listener->type == RAD_LISTEN_AUTH) ||
97 #ifdef WITH_STATS
98                    (listener->type == RAD_LISTEN_NONE) ||
99 #endif
100 #ifdef WITH_ACCOUNTING
101                    (listener->type == RAD_LISTEN_ACCT) ||
102 #endif
103 #ifdef WITH_VMPS
104                    (listener->type == RAD_LISTEN_VQP) ||
105 #endif
106                    (listener->type == RAD_LISTEN_DHCP));
107
108         clients = ((listen_socket_t *)listener->data)->clients;
109
110         /*
111          *      This HAS to have been initialized previously.
112          */
113         rad_assert(clients != NULL);
114
115 #ifdef WITH_DYNAMIC_CLIENTS
116         client = client_find(clients, ipaddr);
117         if (!client) return NULL;
118
119         /*
120          *      No server defined, and it's not dynamic.  Return it.
121          */
122         if (!client->client_server && !client->dynamic) return client;
123
124         now = time(NULL);
125         
126         /*
127          *      It's a dynamically generated client, check it.
128          */
129         if (client->dynamic) {
130                 /*
131                  *      Lives forever.  Return it.
132                  */
133                 if (client->lifetime == 0) return client;
134                 
135                 /*
136                  *      Rate-limit the deletion of known clients.
137                  *      This makes them last a little longer, but
138                  *      prevents the server from melting down if (say)
139                  *      10k clients all expire at once.
140                  */
141                 if (now == client->last_new_client) return client;
142
143                 /*
144                  *      It's not dead yet.  Return it.
145                  */
146                 if ((client->created + client->lifetime) > now) return client;
147                 
148                 /*
149                  *      It's dead, Jim.  Delete it.
150                  */
151                 client_delete(clients, client);
152
153                 /*
154                  *      Go find the enclosing network again.
155                  */
156                 client = client_find(clients, ipaddr);
157
158                 /*
159                  *      WTF?
160                  */
161                 if (!client) return NULL;
162                 if (!client->client_server) return NULL;
163
164                 /*
165                  *      At this point, 'client' is the enclosing
166                  *      network that configures where dynamic clients
167                  *      can be defined.
168                  */
169                 rad_assert(client->dynamic == 0);
170         } else {
171                 /*
172                  *      The IP is unknown, so we've found an enclosing
173                  *      network.  Enable DoS protection.  We only
174                  *      allow one new client per second.  Known
175                  *      clients aren't subject to this restriction.
176                  */
177                 if (now == client->last_new_client) return NULL;
178         }
179
180         client->last_new_client = now;
181
182         request = request_alloc();
183         if (!request) return NULL;
184
185         request->listener = listener;
186         request->client = client;
187         request->packet = rad_alloc(0);
188         if (!request->packet) {
189                 request_free(&request);
190                 return NULL;
191         }
192         request->reply = rad_alloc(0);
193         if (!request->reply) {
194                 request_free(&request);
195                 return NULL;
196         }
197         request->packet->timestamp = request->timestamp;
198         request->number = 0;
199         request->priority = listener->type;
200         request->server = client->client_server;
201         request->root = &mainconfig;
202
203         /*
204          *      Run a fake request through the given virtual server.
205          *      Look for FreeRADIUS-Client-IP-Address
206          *               FreeRADIUS-Client-Secret
207          *              ...
208          *
209          *      and create the RADCLIENT structure from that.
210          */
211
212         sock = listener->data;
213         request->packet->sockfd = listener->fd;
214         request->packet->src_ipaddr = *ipaddr;
215         request->packet->src_port = 0; /* who cares... */
216         request->packet->dst_ipaddr = sock->ipaddr;
217         request->packet->dst_port = sock->port;
218
219         request->reply->sockfd = request->packet->sockfd;
220         request->reply->dst_ipaddr = request->packet->src_ipaddr;
221         request->reply->src_ipaddr = request->packet->dst_ipaddr;
222         request->reply->dst_port = request->packet->src_port;
223         request->reply->src_port = request->packet->dst_port;
224         request->reply->id = request->packet->id;
225         request->reply->code = 0; /* UNKNOWN code */
226
227         
228         DEBUG("server %s {", request->server);
229
230         rcode = module_authorize(0, request);
231
232         DEBUG("} # server %s", request->server);
233
234         if (rcode != RLM_MODULE_OK) {
235                 request_free(&request);
236                 return NULL;
237         }
238
239         created = client_create(clients, request);
240
241         request_free(&request);
242
243         return created;         /* may be NULL */
244 #else
245         return client_find(clients, ipaddr);
246 #endif
247 }
248
249 static int listen_bind(rad_listen_t *this);
250
251
252 /*
253  *      Process and reply to a server-status request.
254  *      Like rad_authenticate and rad_accounting this should
255  *      live in it's own file but it's so small we don't bother.
256  */
257 static int rad_status_server(REQUEST *request)
258 {
259         int rcode = RLM_MODULE_OK;
260         DICT_VALUE *dval;
261
262         switch (request->listener->type) {
263 #ifdef WITH_STATS
264         case RAD_LISTEN_NONE:
265 #endif
266         case RAD_LISTEN_AUTH:
267                 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
268                 if (dval) {
269                         rcode = module_authorize(dval->value, request);
270                 } else {
271                         rcode = RLM_MODULE_OK;
272                 }
273
274                 switch (rcode) {
275                 case RLM_MODULE_OK:
276                 case RLM_MODULE_UPDATED:
277                         request->reply->code = PW_AUTHENTICATION_ACK;
278                         break;
279
280                 case RLM_MODULE_FAIL:
281                 case RLM_MODULE_HANDLED:
282                         request->reply->code = 0; /* don't reply */
283                         break;
284
285                 default:
286                 case RLM_MODULE_REJECT:
287                         request->reply->code = PW_AUTHENTICATION_REJECT;
288                         break;
289                 }
290                 break;
291
292 #ifdef WITH_ACCOUNTING
293         case RAD_LISTEN_ACCT:
294                 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
295                 if (dval) {
296                         rcode = module_accounting(dval->value, request);
297                 } else {
298                         rcode = RLM_MODULE_OK;
299                 }
300
301                 switch (rcode) {
302                 case RLM_MODULE_OK:
303                 case RLM_MODULE_UPDATED:
304                         request->reply->code = PW_ACCOUNTING_RESPONSE;
305                         break;
306
307                 default:
308                         request->reply->code = 0; /* don't reply */
309                         break;
310                 }
311                 break;
312 #endif
313
314         default:
315                 return 0;
316         }
317
318 #ifdef WITH_STATS
319         request_stats_reply(request);
320 #endif
321
322         return 0;
323 }
324
325
326 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
327 {
328         size_t len;
329         listen_socket_t *sock = this->data;
330         const char *name;
331
332         switch (this->type) {
333 #ifdef WITH_STATS
334         case RAD_LISTEN_NONE:   /* what a hack... */
335                 name = "status";
336                 break;
337 #endif
338
339         case RAD_LISTEN_AUTH:
340                 name = "authentication";
341                 break;
342
343 #ifdef WITH_ACCOUNTING
344         case RAD_LISTEN_ACCT:
345                 name = "accounting";
346                 break;
347 #endif
348
349 #ifdef WITH_PROXY
350         case RAD_LISTEN_PROXY:
351                 name = "proxy";
352                 break;
353 #endif
354
355 #ifdef WITH_VMPS
356         case RAD_LISTEN_VQP:
357                 name = "vmps";
358                 break;
359 #endif
360
361 #ifdef WITH_DHCP
362         case RAD_LISTEN_DHCP:
363                 name = "dhcp";
364                 break;
365 #endif
366
367         default:
368                 name = "??";
369                 break;
370         }
371
372 #define FORWARD len = strlen(buffer); if (len >= (bufsize + 1)) return 0;buffer += len;bufsize -= len
373 #define ADDSTRING(_x) strlcpy(buffer, _x, bufsize);FORWARD
374
375         ADDSTRING(name);
376
377 #ifdef SO_BINDTODEVICE
378         if (sock->interface) {
379                 ADDSTRING(" interface ");
380                 ADDSTRING(sock->interface);
381         }
382 #endif
383
384         ADDSTRING(" address ");
385         
386         if ((sock->ipaddr.af == AF_INET) &&
387             (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
388                 strlcpy(buffer, "*", bufsize);
389         } else {
390                 ip_ntoh(&sock->ipaddr, buffer, bufsize);
391         }
392         FORWARD;
393
394         ADDSTRING(" port ");
395         snprintf(buffer, bufsize, "%d", sock->port);
396         FORWARD;
397
398         if (this->server) {
399                 ADDSTRING(" as server ");
400                 ADDSTRING(this->server);
401         }
402
403 #undef ADDSTRING
404 #undef FORWARD
405
406         return 1;
407 }
408
409
410 /*
411  *      Parse an authentication or accounting socket.
412  */
413 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
414 {
415         int             rcode;
416         int             listen_port;
417         fr_ipaddr_t     ipaddr;
418         listen_socket_t *sock = this->data;
419         char            *section_name = NULL;
420         CONF_SECTION    *client_cs, *parentcs;
421
422         /*
423          *      Try IPv4 first
424          */
425         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
426         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
427                               &ipaddr.ipaddr.ip4addr, NULL);
428         if (rcode < 0) return -1;
429
430         if (rcode == 0) { /* successfully parsed IPv4 */
431                 ipaddr.af = AF_INET;
432
433         } else {        /* maybe IPv6? */
434                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
435                                       &ipaddr.ipaddr.ip6addr, NULL);
436                 if (rcode < 0) return -1;
437
438                 if (rcode == 1) {
439                         cf_log_err(cf_sectiontoitem(cs),
440                                    "No address specified in listen section");
441                         return -1;
442                 }
443                 ipaddr.af = AF_INET6;
444         }
445
446         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
447                               &listen_port, "0");
448         if (rcode < 0) return -1;
449
450         if ((listen_port < 0) || (listen_port > 65500)) {
451                         cf_log_err(cf_sectiontoitem(cs),
452                                    "Invalid value for \"port\"");
453                         return -1;
454         }
455
456         sock->ipaddr = ipaddr;
457         sock->port = listen_port;
458
459         /*
460          *      If we can bind to interfaces, do so,
461          *      else don't.
462          */
463         if (cf_pair_find(cs, "interface")) {
464 #ifndef SO_BINDTODEVICE
465                 cf_log_err(cf_sectiontoitem(cs),
466                            "System does not support binding to interfaces.  Delete this line from the configuration file.");
467                 return -1;
468 #else
469                 const char *value;
470                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
471
472                 rad_assert(cp != NULL);
473                 value = cf_pair_value(cp);
474                 if (!value) {
475                         cf_log_err(cf_sectiontoitem(cs),
476                                    "No interface name given");
477                         return -1;
478                 }
479                 sock->interface = value;
480 #endif
481         }
482
483         /*
484          *      And bind it to the port.
485          */
486         if (listen_bind(this) < 0) {
487                 char buffer[128];
488                 cf_log_err(cf_sectiontoitem(cs),
489                            "Error binding to port for %s port %d",
490                            ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
491                            sock->port);
492                 return -1;
493         }
494
495 #ifdef WITH_PROXY
496         /*
497          *      Proxy sockets don't have clients.
498          */
499         if (this->type == RAD_LISTEN_PROXY) return 0;
500 #endif
501         
502         /*
503          *      The more specific configurations are preferred to more
504          *      generic ones.
505          */
506         client_cs = NULL;
507         parentcs = cf_top_section(cs);
508         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
509                               &section_name, NULL);
510         if (rcode < 0) return -1; /* bad string */
511         if (rcode == 0) {
512                 /*
513                  *      Explicit list given: use it.
514                  */
515                 client_cs = cf_section_sub_find_name2(parentcs,
516                                                       "clients",
517                                                       section_name);
518                 if (!client_cs) {
519                         client_cs = cf_section_find(section_name);
520                 }
521                 if (!client_cs) {
522                         cf_log_err(cf_sectiontoitem(cs),
523                                    "Failed to find clients %s {...}",
524                                    section_name);
525                         free(section_name);
526                         return -1;
527                 }
528                 free(section_name);
529         } /* else there was no "clients = " entry. */
530
531         if (!client_cs) {
532                 CONF_SECTION *server_cs;
533
534                 server_cs = cf_section_sub_find_name2(parentcs,
535                                                       "server",
536                                                       this->server);
537                 /*
538                  *      Found a "server foo" section.  If there are clients
539                  *      in it, use them.
540                  */
541                 if (server_cs &&
542                     (cf_section_sub_find(server_cs, "client") != NULL)) {
543                         client_cs = server_cs;
544                 }
545         }
546
547         /*
548          *      Still nothing.  Look for global clients.
549          */
550         if (!client_cs) client_cs = parentcs;
551
552         sock->clients = clients_parse_section(client_cs);
553         if (!sock->clients) {
554                 cf_log_err(cf_sectiontoitem(cs),
555                            "Failed to find any clients for this listen section");
556                 return -1;
557         }
558
559         return 0;
560 }
561
562 /*
563  *      Send an authentication response packet
564  */
565 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
566 {
567         rad_assert(request->listener == listener);
568         rad_assert(listener->send == auth_socket_send);
569
570         return rad_send(request->reply, request->packet,
571                         request->client->secret);
572 }
573
574
575 #ifdef WITH_ACCOUNTING
576 /*
577  *      Send an accounting response packet (or not)
578  */
579 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
580 {
581         rad_assert(request->listener == listener);
582         rad_assert(listener->send == acct_socket_send);
583
584         /*
585          *      Accounting reject's are silently dropped.
586          *
587          *      We do it here to avoid polluting the rest of the
588          *      code with this knowledge
589          */
590         if (request->reply->code == 0) return 0;
591
592         return rad_send(request->reply, request->packet,
593                         request->client->secret);
594 }
595 #endif
596
597 #ifdef WITH_PROXY
598 /*
599  *      Send a packet to a home server.
600  *
601  *      FIXME: have different code for proxy auth & acct!
602  */
603 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
604 {
605         listen_socket_t *sock = listener->data;
606
607         rad_assert(request->proxy_listener == listener);
608         rad_assert(listener->send == proxy_socket_send);
609
610         request->proxy->src_ipaddr = sock->ipaddr;
611         request->proxy->src_port = sock->port;
612
613         return rad_send(request->proxy, request->packet,
614                         request->home_server->secret);
615 }
616 #endif
617
618 #ifdef WITH_STATS
619 /*
620  *      Check if an incoming request is "ok"
621  *
622  *      It takes packets, not requests.  It sees if the packet looks
623  *      OK.  If so, it does a number of sanity checks on it.
624   */
625 static int stats_socket_recv(rad_listen_t *listener,
626                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
627 {
628         ssize_t         rcode;
629         int             code, src_port;
630         RADIUS_PACKET   *packet;
631         char            buffer[128];
632         RADCLIENT       *client;
633         fr_ipaddr_t     src_ipaddr;
634
635         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
636         if (rcode < 0) return 0;
637
638         RAD_STATS_TYPE_INC(listener, total_requests);
639
640         if (rcode < 20) {       /* AUTH_HDR_LEN */
641                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
642                 return 0;
643         }
644
645         /*
646          *      We only understand Status-Server on this socket.
647          */
648         if (code != PW_STATUS_SERVER) {
649                 DEBUG("Ignoring packet code %d sent to Status-Server port",
650                       code);
651                 rad_recv_discard(listener->fd);
652                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
653                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
654                 return 0;
655         }
656
657         if ((client = client_listener_find(listener,
658                                            &src_ipaddr)) == NULL) {
659                 rad_recv_discard(listener->fd);
660                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
661
662                 if (debug_flag > 0) {
663                         char name[1024];
664
665                         listener->print(listener, name, sizeof(name));
666
667                         /*
668                          *      This is debugging rather than logging, so that
669                          *      DoS attacks don't affect us.
670                          */
671                         DEBUG("Ignoring request to %s from unknown client %s port %d",
672                               name,
673                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
674                                         buffer, sizeof(buffer)), src_port);
675                 }
676
677                 return 0;
678         }
679
680         /*
681          *      Now that we've sanity checked everything, receive the
682          *      packet.
683          */
684         packet = rad_recv(listener->fd, 1); /* require message authenticator */
685         if (!packet) {
686                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
687                 DEBUG("%s", librad_errstr);
688                 return 0;
689         }
690
691         if (!received_request(listener, packet, prequest, client)) {
692                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
693                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
694                 rad_free(&packet);
695                 return 0;
696         }
697
698         *pfun = rad_status_server;
699         return 1;
700 }
701 #endif
702
703
704 /*
705  *      Check if an incoming request is "ok"
706  *
707  *      It takes packets, not requests.  It sees if the packet looks
708  *      OK.  If so, it does a number of sanity checks on it.
709   */
710 static int auth_socket_recv(rad_listen_t *listener,
711                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
712 {
713         ssize_t         rcode;
714         int             code, src_port;
715         RADIUS_PACKET   *packet;
716         RAD_REQUEST_FUNP fun = NULL;
717         char            buffer[128];
718         RADCLIENT       *client;
719         fr_ipaddr_t     src_ipaddr;
720
721         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
722         if (rcode < 0) return 0;
723
724         RAD_STATS_TYPE_INC(listener, total_requests);
725
726         if (rcode < 20) {       /* AUTH_HDR_LEN */
727                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
728                 return 0;
729         }
730
731         if ((client = client_listener_find(listener,
732                                            &src_ipaddr)) == NULL) {
733                 rad_recv_discard(listener->fd);
734                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
735
736                 if (debug_flag > 0) {
737                         char name[1024];
738
739                         listener->print(listener, name, sizeof(name));
740
741                         /*
742                          *      This is debugging rather than logging, so that
743                          *      DoS attacks don't affect us.
744                          */
745                         DEBUG("Ignoring request to %s from unknown client %s port %d",
746                               name,
747                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
748                                         buffer, sizeof(buffer)), src_port);
749                 }
750
751                 return 0;
752         }
753
754         /*
755          *      Some sanity checks, based on the packet code.
756          */
757         switch(code) {
758         case PW_AUTHENTICATION_REQUEST:
759                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
760                 fun = rad_authenticate;
761                 break;
762
763         case PW_STATUS_SERVER:
764                 if (!mainconfig.status_server) {
765                         rad_recv_discard(listener->fd);
766                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
767                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
768                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
769                         return 0;
770                 }
771                 fun = rad_status_server;
772                 break;
773
774         default:
775                 rad_recv_discard(listener->fd);
776                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
777                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
778
779                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
780                       code, client->shortname, src_port);
781                 return 0;
782                 break;
783         } /* switch over packet types */
784
785         /*
786          *      Now that we've sanity checked everything, receive the
787          *      packet.
788          */
789         packet = rad_recv(listener->fd, client->message_authenticator);
790         if (!packet) {
791                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
792                 DEBUG("%s", librad_errstr);
793                 return 0;
794         }
795
796         if (!received_request(listener, packet, prequest, client)) {
797                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
798                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
799                 rad_free(&packet);
800                 return 0;
801         }
802
803         *pfun = fun;
804         return 1;
805 }
806
807
808 #ifdef WITH_ACCOUNTING
809 /*
810  *      Receive packets from an accounting socket
811  */
812 static int acct_socket_recv(rad_listen_t *listener,
813                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
814 {
815         ssize_t         rcode;
816         int             code, src_port;
817         RADIUS_PACKET   *packet;
818         RAD_REQUEST_FUNP fun = NULL;
819         char            buffer[128];
820         RADCLIENT       *client;
821         fr_ipaddr_t     src_ipaddr;
822
823         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
824         if (rcode < 0) return 0;
825
826         RAD_STATS_TYPE_INC(listener, total_requests);
827
828         if (rcode < 20) {       /* AUTH_HDR_LEN */
829                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
830                 return 0;
831         }
832
833         if ((client = client_listener_find(listener,
834                                            &src_ipaddr)) == NULL) {
835                 rad_recv_discard(listener->fd);
836                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
837
838                 /*
839                  *      This is debugging rather than logging, so that
840                  *      DoS attacks don't affect us.
841                  */
842                 if (debug_flag > 0) {
843                         char name[1024];
844
845                         listener->print(listener, name, sizeof(name));
846
847                         DEBUG("Ignoring request to %s from unknown client %s port %d",
848                               name,
849                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
850                                         buffer, sizeof(buffer)), src_port);
851                 }
852
853                 return 0;
854         }
855
856         /*
857          *      Some sanity checks, based on the packet code.
858          */
859         switch(code) {
860         case PW_ACCOUNTING_REQUEST:
861                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
862                 fun = rad_accounting;
863                 break;
864
865         case PW_STATUS_SERVER:
866                 if (!mainconfig.status_server) {
867                         rad_recv_discard(listener->fd);
868                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
869                         RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
870
871                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
872                         return 0;
873                 }
874                 fun = rad_status_server;
875                 break;
876
877         default:
878                 rad_recv_discard(listener->fd);
879                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
880                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
881
882                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
883                       code, client->shortname, src_port);
884                 return 0;
885         } /* switch over packet types */
886
887         /*
888          *      Now that we've sanity checked everything, receive the
889          *      packet.
890          */
891         packet = rad_recv(listener->fd, 0);
892         if (!packet) {
893                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
894                 radlog(L_ERR, "%s", librad_errstr);
895                 return 0;
896         }
897
898         /*
899          *      There can be no duplicate accounting packets.
900          */
901         if (!received_request(listener, packet, prequest, client)) {
902                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
903                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
904                 rad_free(&packet);
905                 return 0;
906         }
907
908         *pfun = fun;
909         return 1;
910 }
911 #endif
912
913 #ifdef WITH_PROXY
914 /*
915  *      Recieve packets from a proxy socket.
916  */
917 static int proxy_socket_recv(rad_listen_t *listener,
918                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
919 {
920         REQUEST         *request;
921         RADIUS_PACKET   *packet;
922         RAD_REQUEST_FUNP fun = NULL;
923         char            buffer[128];
924
925         packet = rad_recv(listener->fd, 0);
926         if (!packet) {
927                 radlog(L_ERR, "%s", librad_errstr);
928                 return 0;
929         }
930
931         /*
932          *      FIXME: Client MIB updates?
933          */
934         switch(packet->code) {
935         case PW_AUTHENTICATION_ACK:
936         case PW_ACCESS_CHALLENGE:
937         case PW_AUTHENTICATION_REJECT:
938                 fun = rad_authenticate;
939                 break;
940
941 #ifdef WITH_ACCOUNTING
942         case PW_ACCOUNTING_RESPONSE:
943                 fun = rad_accounting;
944                 break;
945 #endif
946
947         default:
948                 /*
949                  *      FIXME: Update MIB for packet types?
950                  */
951                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
952                        "from home server %s port %d - ID %d : IGNORED",
953                        packet->code,
954                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
955                        packet->src_port, packet->id);
956                 rad_free(&packet);
957                 return 0;
958         }
959
960         request = received_proxy_response(packet);
961         if (!request) {
962                 return 0;
963         }
964
965         rad_assert(fun != NULL);
966         *pfun = fun;
967         *prequest = request;
968
969         return 1;
970 }
971 #endif
972
973
974 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
975 {
976         if (!request->reply->code) return 0;
977
978         rad_encode(request->reply, request->packet,
979                    request->client->secret);
980         rad_sign(request->reply, request->packet,
981                  request->client->secret);
982
983         return 0;
984 }
985
986
987 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
988 {
989         if (rad_verify(request->packet, NULL,
990                        request->client->secret) < 0) {
991                 return -1;
992         }
993
994         return rad_decode(request->packet, NULL,
995                           request->client->secret);
996 }
997
998 #ifdef WITH_PROXY
999 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1000 {
1001         rad_encode(request->proxy, NULL, request->home_server->secret);
1002         rad_sign(request->proxy, NULL, request->home_server->secret);
1003
1004         return 0;
1005 }
1006
1007
1008 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1009 {
1010         if (rad_verify(request->proxy_reply, request->proxy,
1011                        request->home_server->secret) < 0) {
1012                 return -1;
1013         }
1014
1015         return rad_decode(request->proxy_reply, request->proxy,
1016                            request->home_server->secret);
1017 }
1018 #endif
1019
1020 #ifdef WITH_SNMP
1021 static int radius_snmp_recv(rad_listen_t *listener,
1022                             UNUSED RAD_REQUEST_FUNP *pfun,
1023                             UNUSED REQUEST **prequest)
1024 {
1025         if ((rad_snmp.smux_fd >= 0) &&
1026             (rad_snmp.smux_event == SMUX_READ)) {
1027                 smux_read();
1028         }
1029
1030         /*
1031          *  If we've got to re-connect, then do so now,
1032          *  before calling select again.
1033          */
1034         if (rad_snmp.smux_event == SMUX_CONNECT) {
1035                 smux_connect();
1036         }
1037
1038         /*
1039          *      Reset this every time, as the smux connect may have
1040          *      opened a new socket.
1041          */
1042         listener->fd = rad_snmp.smux_fd;
1043
1044         return 0;
1045 }
1046
1047
1048 static int radius_snmp_print(UNUSED rad_listen_t *this, char *buffer, size_t bufsize)
1049 {
1050         return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1051 }
1052
1053 #endif
1054
1055 #include "dhcpd.c"
1056
1057 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1058 #ifdef WITH_STATS
1059         { common_socket_parse, NULL,
1060           stats_socket_recv, auth_socket_send,
1061           socket_print, client_socket_encode, client_socket_decode },
1062 #else
1063         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1064 #endif
1065
1066 #ifdef WITH_PROXY
1067         /* proxying */
1068         { common_socket_parse, NULL,
1069           proxy_socket_recv, proxy_socket_send,
1070           socket_print, proxy_socket_encode, proxy_socket_decode },
1071 #else
1072         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1073 #endif
1074
1075         /* authentication */
1076         { common_socket_parse, NULL,
1077           auth_socket_recv, auth_socket_send,
1078           socket_print, client_socket_encode, client_socket_decode },
1079
1080 #ifdef WITH_ACCOUNTING
1081         /* accounting */
1082         { common_socket_parse, NULL,
1083           acct_socket_recv, acct_socket_send,
1084           socket_print, client_socket_encode, client_socket_decode},
1085 #else
1086         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1087 #endif
1088
1089 #ifdef WITH_DETAIL
1090         /* detail */
1091         { detail_parse, detail_free,
1092           detail_recv, detail_send,
1093           detail_print, detail_encode, detail_decode },
1094 #else
1095         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1096 #endif
1097
1098 #ifdef WITH_VMPS
1099         /* vlan query protocol */
1100         { common_socket_parse, NULL,
1101           vqp_socket_recv, vqp_socket_send,
1102           socket_print, vqp_socket_encode, vqp_socket_decode },
1103 #else
1104         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1105 #endif
1106
1107 #ifdef WITH_DHCP
1108         /* dhcp query protocol */
1109         { dhcp_socket_parse, NULL,
1110           dhcp_socket_recv, dhcp_socket_send,
1111           socket_print, dhcp_socket_encode, dhcp_socket_decode },
1112 #else
1113         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1114 #endif
1115
1116         { NULL, NULL, NULL, NULL, NULL, NULL, NULL}     /* RAD_LISTEN_SNMP */
1117 };
1118
1119
1120
1121 /*
1122  *      Binds a listener to a socket.
1123  */
1124 static int listen_bind(rad_listen_t *this)
1125 {
1126         struct sockaddr_storage salocal;
1127         socklen_t       salen;
1128         listen_socket_t *sock = this->data;
1129
1130         /*
1131          *      If the port is zero, then it means the appropriate
1132          *      thing from /etc/services.
1133          */
1134         if (sock->port == 0) {
1135                 struct servent  *svp;
1136
1137                 switch (this->type) {
1138                 case RAD_LISTEN_AUTH:
1139                         svp = getservbyname ("radius", "udp");
1140                         if (svp != NULL) {
1141                                 sock->port = ntohs(svp->s_port);
1142                         } else {
1143                                 sock->port = PW_AUTH_UDP_PORT;
1144                         }
1145                         break;
1146
1147 #ifdef WITH_ACCOUNTING
1148                 case RAD_LISTEN_ACCT:
1149                         svp = getservbyname ("radacct", "udp");
1150                         if (svp != NULL) {
1151                                 sock->port = ntohs(svp->s_port);
1152                         } else {
1153                                 sock->port = PW_ACCT_UDP_PORT;
1154                         }
1155                         break;
1156 #endif
1157
1158 #ifdef WITH_PROXY
1159                 case RAD_LISTEN_PROXY:
1160                         sock->port = 0;
1161                         break;
1162 #endif
1163
1164 #ifdef WITH_VMPS
1165                 case RAD_LISTEN_VQP:
1166                         sock->port = 1589;
1167                         break;
1168 #endif
1169
1170                 default:
1171                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1172                         return -1;
1173                 }
1174         }
1175
1176         /*
1177          *      Copy fr_socket() here, as we may need to bind to a device.
1178          */
1179         this->fd = socket(sock->ipaddr.af, SOCK_DGRAM, 0);
1180         if (this->fd < 0) {
1181                 radlog(L_ERR, "Failed opening socket: %s", strerror(errno));
1182                 return -1;
1183         }
1184                 
1185 #ifdef SO_BINDTODEVICE
1186         /*
1187          *      Bind to a device BEFORE touching IP addresses.
1188          */
1189         if (sock->interface) {
1190                 struct ifreq ifreq;
1191                 strcpy(ifreq.ifr_name, sock->interface);
1192                 
1193                 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
1194                                (char *)&ifreq, sizeof(ifreq)) < 0) {
1195                         close(this->fd);
1196                         radlog(L_ERR, "Failed opening to interface %s: %s",
1197                                sock->interface, strerror(errno));
1198                         return -1;
1199                 } /* else it worked. */
1200         }
1201 #endif
1202
1203 #ifdef WITH_UDPFROMTO
1204         /*
1205          *      Initialize udpfromto for all sockets.
1206          */
1207         if (udpfromto_init(this->fd) != 0) {
1208                 close(this->fd);
1209                 return -1;
1210         }
1211 #endif
1212         
1213         /*
1214          *      Set up sockaddr stuff.
1215          */
1216         if (!fr_ipaddr2sockaddr(&sock->ipaddr, sock->port, &salocal, &salen)) {
1217                 close(this->fd);
1218                 return -1;
1219         }
1220                 
1221 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1222         if (sock->ipaddr.af == AF_INET6) {
1223                 /*
1224                  *      Listening on '::' does NOT get you IPv4 to
1225                  *      IPv6 mapping.  You've got to listen on an IPv4
1226                  *      address, too.  This makes the rest of the server
1227                  *      design a little simpler.
1228                  */
1229 #ifdef IPV6_V6ONLY
1230                 
1231                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->ipaddr.ipaddr.ip6addr)) {
1232                         int on = 1;
1233                         
1234                         setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
1235                                    (char *)&on, sizeof(on));
1236                 }
1237 #endif /* IPV6_V6ONLY */
1238 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
1239         }
1240                 
1241         if (bind(this->fd, (struct sockaddr *) &salocal, salen) < 0) {
1242                 close(this->fd);
1243                 radlog(L_ERR, "Failed binding to socket: %s\n",
1244                        strerror(errno));
1245                 return -1;
1246         }
1247         
1248         /*
1249          *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
1250          *      kernel instead binds us to a 1.2.3.4.  If this
1251          *      happens, notice, and remember our real IP.
1252          */
1253         {
1254                 struct sockaddr_storage src;
1255                 socklen_t               sizeof_src = sizeof(src);
1256
1257                 memset(&src, 0, sizeof_src);
1258                 if (getsockname(this->fd, (struct sockaddr *) &src,
1259                                 &sizeof_src) < 0) {
1260                         radlog(L_ERR, "Failed getting socket name: %s",
1261                                strerror(errno));
1262                         return -1;
1263                 }
1264
1265                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
1266                                         &sock->ipaddr, &sock->port)) {
1267                         radlog(L_ERR, "Socket has unsupported address family");
1268                         return -1;
1269                 }
1270         }
1271
1272 #ifdef O_NONBLOCK
1273         {
1274                 int flags;
1275                 
1276                 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  {
1277                         radlog(L_ERR, "Failure getting socket flags: %s)\n",
1278                                strerror(errno));
1279                         return -1;
1280                 }
1281                 
1282                 flags |= O_NONBLOCK;
1283                 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1284                         radlog(L_ERR, "Failure setting socket flags: %s)\n",
1285                                strerror(errno));
1286                         return -1;
1287                 }
1288         }
1289 #endif
1290
1291         return 0;
1292 }
1293
1294
1295 /*
1296  *      Allocate & initialize a new listener.
1297  */
1298 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1299 {
1300         rad_listen_t *this;
1301
1302         this = rad_malloc(sizeof(*this));
1303         memset(this, 0, sizeof(*this));
1304
1305         this->type = type;
1306         this->recv = master_listen[this->type].recv;
1307         this->send = master_listen[this->type].send;
1308         this->print = master_listen[this->type].print;
1309         this->encode = master_listen[this->type].encode;
1310         this->decode = master_listen[this->type].decode;
1311
1312         switch (type) {
1313 #ifdef WITH_STATS
1314         case RAD_LISTEN_NONE:
1315 #endif
1316         case RAD_LISTEN_AUTH:
1317         case RAD_LISTEN_ACCT:
1318         case RAD_LISTEN_PROXY:
1319         case RAD_LISTEN_VQP:
1320         case RAD_LISTEN_DHCP:
1321                 this->data = rad_malloc(sizeof(listen_socket_t));
1322                 memset(this->data, 0, sizeof(listen_socket_t));
1323                 break;
1324
1325 #ifdef WITH_DETAIL
1326         case RAD_LISTEN_DETAIL:
1327                 this->data = NULL;
1328                 break;
1329 #endif
1330
1331         default:
1332                 rad_assert("Unsupported option!" == NULL);
1333                 break;
1334         }
1335
1336         return this;
1337 }
1338
1339
1340 #ifdef WITH_PROXY
1341 /*
1342  *      Externally visible function for creating a new proxy LISTENER.
1343  *
1344  *      For now, don't take ipaddr or port.
1345  *
1346  *      Not thread-safe, but all calls to it are protected by the
1347  *      proxy mutex in request_list.c
1348  */
1349 rad_listen_t *proxy_new_listener()
1350 {
1351         int last_proxy_port, port;
1352         rad_listen_t *this, *tmp, **last;
1353         listen_socket_t *sock, *old;
1354
1355         this = listen_alloc(RAD_LISTEN_PROXY);
1356
1357         /*
1358          *      Find an existing proxy socket to copy.
1359          *
1360          *      FIXME: Make it per-realm, or per-home server!
1361          */
1362         last_proxy_port = 0;
1363         old = NULL;
1364         last = &mainconfig.listen;
1365         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1366                 if (tmp->type == RAD_LISTEN_PROXY) {
1367                         sock = tmp->data;
1368                         if (sock->port > last_proxy_port) {
1369                                 last_proxy_port = sock->port + 1;
1370                         }
1371                         if (!old) old = sock;
1372                 }
1373
1374                 last = &(tmp->next);
1375         }
1376
1377         if (!old) {
1378                 listen_free(&this);
1379                 return NULL;    /* This is a serious error. */
1380         }
1381
1382         /*
1383          *      FIXME: find a new IP address to listen on?
1384          *
1385          *      This could likely be done in the "home server"
1386          *      configuration, to have per-home-server source IP's.
1387          */
1388         sock = this->data;
1389         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1390
1391         /*
1392          *      Keep going until we find an unused port.
1393          */
1394         for (port = last_proxy_port; port < 64000; port++) {
1395                 sock->port = port;
1396                 if (listen_bind(this) == 0) {
1397                         /*
1398                          *      Add the new listener to the list of
1399                          *      listeners.
1400                          */
1401                         *last = this;
1402                         return this;
1403                 }
1404         }
1405
1406         listen_free(&this);
1407         return NULL;
1408 }
1409 #endif
1410
1411 static const FR_NAME_NUMBER listen_compare[] = {
1412 #ifdef WITH_STATS
1413         { "status",     RAD_LISTEN_NONE },
1414 #endif
1415         { "auth",       RAD_LISTEN_AUTH },
1416 #ifdef WITH_ACCOUNTING
1417         { "acct",       RAD_LISTEN_ACCT },
1418 #endif
1419 #ifdef WITH_DETAIL
1420         { "detail",     RAD_LISTEN_DETAIL },
1421 #endif
1422 #ifdef WITH_PROXY
1423         { "proxy",      RAD_LISTEN_PROXY },
1424 #endif
1425 #ifdef WITH_VMPS
1426         { "vmps",       RAD_LISTEN_VQP },
1427 #endif
1428 #ifdef WITH_DHCP
1429         { "dhcp",       RAD_LISTEN_DHCP },
1430 #endif
1431         { NULL, 0 },
1432 };
1433
1434
1435 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1436 {
1437         int             type, rcode;
1438         char            *listen_type;
1439         rad_listen_t    *this;
1440
1441         listen_type = NULL;
1442         
1443         cf_log_info(cs, "listen {");
1444
1445         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1446                               &listen_type, "");
1447         if (rcode < 0) return NULL;
1448         if (rcode == 1) {
1449                 free(listen_type);
1450                 cf_log_err(cf_sectiontoitem(cs),
1451                            "No type specified in listen section");
1452                 return NULL;
1453         }
1454
1455         type = fr_str2int(listen_compare, listen_type, -1);
1456         if (type < 0) {
1457                 cf_log_err(cf_sectiontoitem(cs),
1458                            "Invalid type \"%s\" in listen section.",
1459                            listen_type);
1460                 free(listen_type);
1461                 return NULL;
1462         }
1463         free(listen_type);
1464         
1465         /*
1466          *      Allow listen sections in the default config to
1467          *      refer to a server.
1468          */
1469         if (!server) {
1470                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1471                                       &server, NULL);
1472                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1473                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1474                                               &server, NULL);
1475                 }
1476                 if (rcode < 0) return NULL;
1477         }
1478
1479         /*
1480          *      Set up cross-type data.
1481          */
1482         this = listen_alloc(type);
1483         this->server = server;
1484         this->fd = -1;
1485
1486         /*
1487          *      Call per-type parser.
1488          */
1489         if (master_listen[type].parse(cs, this) < 0) {
1490                 listen_free(&this);
1491                 return NULL;
1492         }
1493
1494         cf_log_info(cs, "}");
1495
1496         return this;
1497 }
1498
1499 /*
1500  *      Generate a list of listeners.  Takes an input list of
1501  *      listeners, too, so we don't close sockets with waiting packets.
1502  */
1503 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1504 {
1505         int             override = FALSE;
1506         int             rcode;
1507         CONF_SECTION    *cs;
1508         rad_listen_t    **last;
1509         rad_listen_t    *this;
1510         fr_ipaddr_t     server_ipaddr;
1511         int             auth_port = 0;
1512 #ifdef WITH_PROXY
1513         int             defined_proxy = 0;
1514 #endif
1515
1516         /*
1517          *      We shouldn't be called with a pre-existing list.
1518          */
1519         rad_assert(head && (*head == NULL));
1520
1521         last = head;
1522         server_ipaddr.af = AF_UNSPEC;
1523
1524         /*
1525          *      If the port is specified on the command-line,
1526          *      it over-rides the configuration file.
1527          *
1528          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1529          */
1530         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1531
1532         /*
1533          *      If the IP address was configured on the command-line,
1534          *      use that as the "bind_address"
1535          */
1536         if (mainconfig.myip.af != AF_UNSPEC) {
1537                 memcpy(&server_ipaddr, &mainconfig.myip,
1538                        sizeof(server_ipaddr));
1539                 override = TRUE;
1540                 goto bind_it;
1541         }
1542
1543         /*
1544          *      Else look for bind_address and/or listen sections.
1545          */
1546         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1547         rcode = cf_item_parse(config, "bind_address",
1548                               PW_TYPE_IPADDR,
1549                               &server_ipaddr.ipaddr.ip4addr, NULL);
1550         if (rcode < 0) return -1; /* error parsing it */
1551
1552         if (rcode == 0) { /* successfully parsed IPv4 */
1553                 listen_socket_t *sock;
1554                 server_ipaddr.af = AF_INET;
1555
1556                 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'.");
1557
1558         bind_it:
1559 #ifdef WITH_VMPS
1560                 if (strcmp(progname, "vmpsd") == 0) {
1561                         this = listen_alloc(RAD_LISTEN_VQP);
1562                         if (!auth_port) auth_port = 1589;
1563                 } else
1564 #endif
1565                         this = listen_alloc(RAD_LISTEN_AUTH);
1566
1567                 sock = this->data;
1568
1569                 sock->ipaddr = server_ipaddr;
1570                 sock->port = auth_port;
1571
1572                 sock->clients = clients_parse_section(config);
1573                 if (!sock->clients) {
1574                         cf_log_err(cf_sectiontoitem(config),
1575                                    "Failed to find any clients for this listen section");
1576                         return -1;
1577                 }
1578
1579                 if (listen_bind(this) < 0) {
1580                         listen_free(&this);
1581                         listen_free(head);
1582                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1583                         return -1;
1584                 }
1585                 auth_port = sock->port; /* may have been updated in listen_bind */
1586                 if (override) {
1587                         cs = cf_section_sub_find_name2(config, "server",
1588                                                        mainconfig.name);
1589                         if (cs) this->server = mainconfig.name;
1590                 }
1591
1592                 *last = this;
1593                 last = &(this->next);
1594
1595 #ifdef WITH_VMPS
1596                 /*
1597                  *      No acct for vmpsd
1598                  */
1599                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1600 #endif
1601
1602 #ifdef WITH_ACCOUNTING
1603                 /*
1604                  *      Open Accounting Socket.
1605                  *
1606                  *      If we haven't already gotten acct_port from
1607                  *      /etc/services, then make it auth_port + 1.
1608                  */
1609                 this = listen_alloc(RAD_LISTEN_ACCT);
1610                 sock = this->data;
1611
1612                 /*
1613                  *      Create the accounting socket.
1614                  *
1615                  *      The accounting port is always the
1616                  *      authentication port + 1
1617                  */
1618                 sock->ipaddr = server_ipaddr;
1619                 sock->port = auth_port + 1;
1620
1621                 sock->clients = clients_parse_section(config);
1622                 if (!sock->clients) {
1623                         cf_log_err(cf_sectiontoitem(config),
1624                                    "Failed to find any clients for this listen section");
1625                         return -1;
1626                 }
1627
1628                 if (listen_bind(this) < 0) {
1629                         listen_free(&this);
1630                         listen_free(head);
1631                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1632                         return -1;
1633                 }
1634
1635                 if (override) {
1636                         cs = cf_section_sub_find_name2(config, "server",
1637                                                        mainconfig.name);
1638                         if (cs) this->server = mainconfig.name;
1639                 }
1640
1641                 *last = this;
1642                 last = &(this->next);
1643 #endif
1644         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1645                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1646                        mainconfig.port);
1647                 return -1;
1648         }
1649
1650         /*
1651          *      They specified an IP on the command-line, ignore
1652          *      all listen sections except the one in '-n'.
1653          */
1654         if (mainconfig.myip.af != AF_UNSPEC) {
1655                 CONF_SECTION *subcs;
1656                 const char *name2 = cf_section_name2(cs);
1657
1658                 cs = cf_section_sub_find_name2(config, "server",
1659                                                mainconfig.name);
1660                 if (!cs) goto do_proxy;
1661
1662                 /*
1663                  *      Should really abstract this code...
1664                  */
1665                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1666                      subcs != NULL;
1667                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1668                         this = listen_parse(subcs, name2);
1669                         if (!this) {
1670                                 listen_free(head);
1671                                 return -1;
1672                         }
1673
1674 #ifdef WITH_PROXY
1675                         if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1676 #endif
1677                         
1678                         *last = this;
1679                         last = &(this->next);
1680                 } /* loop over "listen" directives in server <foo> */
1681
1682                 goto do_proxy;
1683         }
1684
1685         /*
1686          *      Walk through the "listen" sections, if they exist.
1687          */
1688         for (cs = cf_subsection_find_next(config, NULL, "listen");
1689              cs != NULL;
1690              cs = cf_subsection_find_next(config, cs, "listen")) {
1691                 this = listen_parse(cs, NULL);
1692                 if (!this) {
1693                         listen_free(head);
1694                         return -1;
1695                 }
1696
1697 #ifdef WITH_PROXY
1698                 if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1699 #endif
1700
1701                 *last = this;
1702                 last = &(this->next);
1703         }
1704
1705         /*
1706          *      Check virtual servers for "listen" sections, too.
1707          *
1708          *      FIXME: Move to virtual server init?
1709          */
1710         for (cs = cf_subsection_find_next(config, NULL, "server");
1711              cs != NULL;
1712              cs = cf_subsection_find_next(config, cs, "server")) {
1713                 CONF_SECTION *subcs;
1714                 const char *name2 = cf_section_name2(cs);
1715                 
1716                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1717                      subcs != NULL;
1718                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1719                         this = listen_parse(subcs, name2);
1720                         if (!this) {
1721                                 listen_free(head);
1722                                 return -1;
1723                         }
1724                         
1725 #ifdef WITH_PROXY
1726                         if (this->type == RAD_LISTEN_PROXY) {
1727                                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
1728                                 listen_free(head);
1729                                 return -1;
1730                         }
1731 #endif
1732
1733                         *last = this;
1734                         last = &(this->next);
1735                 } /* loop over "listen" directives in virtual servers */
1736         } /* loop over virtual servers */
1737
1738         /*
1739          *      If we're proxying requests, open the proxy FD.
1740          *      Otherwise, don't do anything.
1741          */
1742  do_proxy:
1743 #ifdef WITH_PROXY
1744         if (mainconfig.proxy_requests == TRUE) {
1745                 int             port = -1;
1746                 listen_socket_t *sock = NULL;
1747
1748                 /*
1749                  *      No sockets to receive packets, therefore
1750                  *      proxying is pointless.
1751                  */
1752                 if (!*head) return -1;
1753
1754                 if (defined_proxy) goto do_snmp;
1755
1756                 /*
1757                  *      Find the first authentication port,
1758                  *      and use it
1759                  */
1760                 for (this = *head; this != NULL; this = this->next) {
1761                         if (this->type == RAD_LISTEN_AUTH) {
1762                                 sock = this->data;
1763                                 if (server_ipaddr.af == AF_UNSPEC) {
1764                                         server_ipaddr = sock->ipaddr;
1765                                 }
1766                                 port = sock->port + 2; /* skip acct port */
1767                                 break;
1768                         }
1769                         if (this->type == RAD_LISTEN_VQP) {
1770                                 sock = this->data;
1771                                 if (server_ipaddr.af == AF_UNSPEC) {
1772                                         server_ipaddr = sock->ipaddr;
1773                                 }
1774                                 port = sock->port + 1;
1775                                 break;
1776                         }
1777                 }
1778
1779                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
1780
1781                 /*
1782                  *      Address is still unspecified, use IPv4.
1783                  */
1784                 if (server_ipaddr.af == AF_UNSPEC) {
1785                         server_ipaddr.af = AF_INET;
1786                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1787                 }
1788
1789                 this = listen_alloc(RAD_LISTEN_PROXY);
1790                 sock = this->data;
1791
1792                 /*
1793                  *      Create the first proxy socket.
1794                  */
1795                 sock->ipaddr = server_ipaddr;
1796
1797                 /*
1798                  *      Try to find a proxy port (value doesn't matter)
1799                  */
1800                 for (sock->port = port;
1801                      sock->port < 64000;
1802                      sock->port++) {
1803                         if (listen_bind(this) == 0) {
1804                                 *last = this;
1805                                 last = &(this->next); /* just in case */
1806                                 break;
1807                         }
1808                 }
1809
1810                 if (sock->port >= 64000) {
1811                         listen_free(head);
1812                         listen_free(&this);
1813                         radlog(L_ERR, "Failed to open socket for proxying");
1814                         return -1;
1815                 }
1816         }
1817
1818  do_snmp:                       /* used only in proxy code. */
1819 #endif
1820
1821 #ifdef WITH_SNMP
1822         if (radius_snmp_init(config)) {
1823                 this = rad_malloc(sizeof(*this));
1824                 memset(this, 0, sizeof(*this));
1825
1826                 this->type = RAD_LISTEN_SNMP;
1827                 this->fd = rad_snmp.smux_fd;
1828
1829                 this->recv = radius_snmp_recv;
1830                 this->print = radius_snmp_print;
1831
1832                 *last = this;
1833                 last = &(this->next);
1834         }
1835 #endif
1836
1837         return 0;
1838 }
1839
1840 /*
1841  *      Free a linked list of listeners;
1842  */
1843 void listen_free(rad_listen_t **head)
1844 {
1845         rad_listen_t *this;
1846
1847         if (!head || !*head) return;
1848
1849         this = *head;
1850         while (this) {
1851                 rad_listen_t *next = this->next;
1852
1853                 /*
1854                  *      Other code may have eaten the FD.
1855                  */
1856                 if (this->fd >= 0) close(this->fd);
1857
1858                 if (master_listen[this->type].free) {
1859                         master_listen[this->type].free(this);
1860                 }
1861                 free(this->data);
1862                 free(this);
1863
1864                 this = next;
1865         }
1866
1867         *head = NULL;
1868 }
1869
1870 #ifdef WITH_STATS
1871 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
1872                                           int port)
1873 {
1874         rad_listen_t *this;
1875
1876         for (this = mainconfig.listen; this != NULL; this = this->next) {
1877                 listen_socket_t *sock;
1878
1879                 if ((this->type != RAD_LISTEN_AUTH) &&
1880                     (this->type != RAD_LISTEN_ACCT)) continue;
1881                 
1882                 sock = this->data;
1883
1884                 if ((sock->port == port) &&
1885                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1886                         return sock->clients;
1887                 }
1888         }
1889
1890         return NULL;
1891 }
1892
1893 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
1894 {
1895         rad_listen_t *this;
1896
1897         for (this = mainconfig.listen; this != NULL; this = this->next) {
1898                 listen_socket_t *sock;
1899
1900                 if ((this->type != RAD_LISTEN_AUTH) &&
1901                     (this->type != RAD_LISTEN_ACCT)) continue;
1902                 
1903                 sock = this->data;
1904
1905                 if ((sock->port == port) &&
1906                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1907                         return this;
1908                 }
1909         }
1910
1911         return NULL;
1912 }
1913 #endif