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