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