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