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