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