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