Allow all ports to be used. Closes #559
[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         struct sockaddr_storage salocal;
1095         socklen_t       salen;
1096         listen_socket_t *sock = this->data;
1097
1098         /*
1099          *      If the port is zero, then it means the appropriate
1100          *      thing from /etc/services.
1101          */
1102         if (sock->port == 0) {
1103                 struct servent  *svp;
1104
1105                 switch (this->type) {
1106                 case RAD_LISTEN_AUTH:
1107                         svp = getservbyname ("radius", "udp");
1108                         if (svp != NULL) {
1109                                 sock->port = ntohs(svp->s_port);
1110                         } else {
1111                                 sock->port = PW_AUTH_UDP_PORT;
1112                         }
1113                         break;
1114
1115 #ifdef WITH_ACCOUNTING
1116                 case RAD_LISTEN_ACCT:
1117                         svp = getservbyname ("radacct", "udp");
1118                         if (svp != NULL) {
1119                                 sock->port = ntohs(svp->s_port);
1120                         } else {
1121                                 sock->port = PW_ACCT_UDP_PORT;
1122                         }
1123                         break;
1124 #endif
1125
1126 #ifdef WITH_PROXY
1127                 case RAD_LISTEN_PROXY:
1128                         sock->port = 0;
1129                         break;
1130 #endif
1131
1132 #ifdef WITH_VMPS
1133                 case RAD_LISTEN_VQP:
1134                         sock->port = 1589;
1135                         break;
1136 #endif
1137
1138                 default:
1139                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1140                         return -1;
1141                 }
1142         }
1143
1144         /*
1145          *      Copy fr_socket() here, as we may need to bind to a device.
1146          */
1147         this->fd = socket(sock->ipaddr.af, SOCK_DGRAM, 0);
1148         if (this->fd < 0) {
1149                 radlog(L_ERR, "Failed opening socket: %s", strerror(errno));
1150                 return -1;
1151         }
1152                 
1153 #ifdef SO_BINDTODEVICE
1154         /*
1155          *      Bind to a device BEFORE touching IP addresses.
1156          */
1157         if (sock->interface) {
1158                 struct ifreq ifreq;
1159                 strcpy(ifreq.ifr_name, sock->interface);
1160                 
1161                 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
1162                                (char *)&ifreq, sizeof(ifreq)) < 0) {
1163                         close(this->fd);
1164                         radlog(L_ERR, "Failed opening to interface %s: %s",
1165                                sock->interface, strerror(errno));
1166                         return -1;
1167                 } /* else it worked. */
1168         }
1169 #endif
1170
1171 #ifdef WITH_UDPFROMTO
1172         /*
1173          *      Initialize udpfromto for all sockets.
1174          */
1175         if (udpfromto_init(this->fd) != 0) {
1176                 close(this->fd);
1177                 return -1;
1178         }
1179 #endif
1180         
1181         /*
1182          *      Set up sockaddr stuff.
1183          */
1184         if (!fr_ipaddr2sockaddr(&sock->ipaddr, sock->port, &salocal, &salen)) {
1185                 close(this->fd);
1186                 return -1;
1187         }
1188                 
1189 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1190         if (sock->ipaddr.af == AF_INET6) {
1191                 /*
1192                  *      Listening on '::' does NOT get you IPv4 to
1193                  *      IPv6 mapping.  You've got to listen on an IPv4
1194                  *      address, too.  This makes the rest of the server
1195                  *      design a little simpler.
1196                  */
1197 #ifdef IPV6_V6ONLY
1198                 
1199                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->ipaddr.ipaddr.ip6addr)) {
1200                         int on = 1;
1201                         
1202                         setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
1203                                    (char *)&on, sizeof(on));
1204                 }
1205 #endif /* IPV6_V6ONLY */
1206         }
1207 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
1208                 
1209         if (bind(this->fd, (struct sockaddr *) &salocal, salen) < 0) {
1210                 close(this->fd);
1211                 radlog(L_ERR, "Failed binding to socket: %s\n",
1212                        strerror(errno));
1213                 return -1;
1214         }
1215         
1216         /*
1217          *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
1218          *      kernel instead binds us to a 1.2.3.4.  If this
1219          *      happens, notice, and remember our real IP.
1220          */
1221         {
1222                 struct sockaddr_storage src;
1223                 socklen_t               sizeof_src = sizeof(src);
1224
1225                 memset(&src, 0, sizeof_src);
1226                 if (getsockname(this->fd, (struct sockaddr *) &src,
1227                                 &sizeof_src) < 0) {
1228                         radlog(L_ERR, "Failed getting socket name: %s",
1229                                strerror(errno));
1230                         return -1;
1231                 }
1232
1233                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
1234                                         &sock->ipaddr, &sock->port)) {
1235                         radlog(L_ERR, "Socket has unsupported address family");
1236                         return -1;
1237                 }
1238         }
1239
1240 #ifdef O_NONBLOCK
1241         {
1242                 int flags;
1243                 
1244                 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  {
1245                         radlog(L_ERR, "Failure getting socket flags: %s)\n",
1246                                strerror(errno));
1247                         return -1;
1248                 }
1249                 
1250                 flags |= O_NONBLOCK;
1251                 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1252                         radlog(L_ERR, "Failure setting socket flags: %s)\n",
1253                                strerror(errno));
1254                         return -1;
1255                 }
1256         }
1257 #endif
1258
1259         return 0;
1260 }
1261
1262
1263 /*
1264  *      Allocate & initialize a new listener.
1265  */
1266 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1267 {
1268         rad_listen_t *this;
1269
1270         this = rad_malloc(sizeof(*this));
1271         memset(this, 0, sizeof(*this));
1272
1273         this->type = type;
1274         this->recv = master_listen[this->type].recv;
1275         this->send = master_listen[this->type].send;
1276         this->print = master_listen[this->type].print;
1277         this->encode = master_listen[this->type].encode;
1278         this->decode = master_listen[this->type].decode;
1279
1280         switch (type) {
1281 #ifdef WITH_STATS
1282         case RAD_LISTEN_NONE:
1283 #endif
1284         case RAD_LISTEN_AUTH:
1285 #ifdef WITH_ACCOUNTING
1286         case RAD_LISTEN_ACCT:
1287 #endif
1288 #ifdef WITH_PROXY
1289         case RAD_LISTEN_PROXY:
1290 #endif
1291 #ifdef WITH_VMPS
1292         case RAD_LISTEN_VQP:
1293 #endif
1294 #ifdef WITH_DHCP
1295         case RAD_LISTEN_DHCP:
1296 #endif
1297                 this->data = rad_malloc(sizeof(listen_socket_t));
1298                 memset(this->data, 0, sizeof(listen_socket_t));
1299                 break;
1300
1301 #ifdef WITH_DETAIL
1302         case RAD_LISTEN_DETAIL:
1303                 this->data = NULL;
1304                 break;
1305 #endif
1306
1307 #ifdef WITH_COMMAND_SOCKET
1308         case RAD_LISTEN_COMMAND:
1309                 this->data = rad_malloc(sizeof(fr_command_socket_t));
1310                 memset(this->data, 0, sizeof(fr_command_socket_t));
1311                 break;
1312 #endif
1313
1314         default:
1315                 rad_assert("Unsupported option!" == NULL);
1316                 break;
1317         }
1318
1319         return this;
1320 }
1321
1322
1323 #ifdef WITH_PROXY
1324 /*
1325  *      Externally visible function for creating a new proxy LISTENER.
1326  *
1327  *      For now, don't take ipaddr or port.
1328  *
1329  *      Not thread-safe, but all calls to it are protected by the
1330  *      proxy mutex in request_list.c
1331  */
1332 rad_listen_t *proxy_new_listener()
1333 {
1334         int last_proxy_port, port;
1335         rad_listen_t *this, *tmp, **last;
1336         listen_socket_t *sock, *old;
1337
1338         this = listen_alloc(RAD_LISTEN_PROXY);
1339
1340         /*
1341          *      Find an existing proxy socket to copy.
1342          *
1343          *      FIXME: Make it per-realm, or per-home server!
1344          */
1345         last_proxy_port = 0;
1346         old = NULL;
1347         last = &mainconfig.listen;
1348         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1349                 if (tmp->type == RAD_LISTEN_PROXY) {
1350                         sock = tmp->data;
1351                         if (sock->port > last_proxy_port) {
1352                                 last_proxy_port = sock->port + 1;
1353                         }
1354                         if (!old) old = sock;
1355                 }
1356
1357                 last = &(tmp->next);
1358         }
1359
1360         if (!old) {
1361                 listen_free(&this);
1362                 return NULL;    /* This is a serious error. */
1363         }
1364
1365         /*
1366          *      FIXME: find a new IP address to listen on?
1367          *
1368          *      This could likely be done in the "home server"
1369          *      configuration, to have per-home-server source IP's.
1370          */
1371         sock = this->data;
1372         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1373
1374         /*
1375          *      Keep going until we find an unused port.
1376          */
1377         for (port = last_proxy_port; port < 64000; port++) {
1378                 sock->port = port;
1379                 if (listen_bind(this) == 0) {
1380                         /*
1381                          *      Add the new listener to the list of
1382                          *      listeners.
1383                          */
1384                         *last = this;
1385                         return this;
1386                 }
1387         }
1388
1389         listen_free(&this);
1390         return NULL;
1391 }
1392 #endif
1393
1394 static const FR_NAME_NUMBER listen_compare[] = {
1395 #ifdef WITH_STATS
1396         { "status",     RAD_LISTEN_NONE },
1397 #endif
1398         { "auth",       RAD_LISTEN_AUTH },
1399 #ifdef WITH_ACCOUNTING
1400         { "acct",       RAD_LISTEN_ACCT },
1401 #endif
1402 #ifdef WITH_DETAIL
1403         { "detail",     RAD_LISTEN_DETAIL },
1404 #endif
1405 #ifdef WITH_PROXY
1406         { "proxy",      RAD_LISTEN_PROXY },
1407 #endif
1408 #ifdef WITH_VMPS
1409         { "vmps",       RAD_LISTEN_VQP },
1410 #endif
1411 #ifdef WITH_DHCP
1412         { "dhcp",       RAD_LISTEN_DHCP },
1413 #endif
1414 #ifdef WITH_COMMAND_SOCKET
1415         { "control",    RAD_LISTEN_COMMAND },
1416 #endif
1417         { NULL, 0 },
1418 };
1419
1420
1421 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1422 {
1423         int             type, rcode;
1424         char            *listen_type;
1425         rad_listen_t    *this;
1426
1427         listen_type = NULL;
1428         
1429         cf_log_info(cs, "listen {");
1430
1431         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1432                               &listen_type, "");
1433         if (rcode < 0) return NULL;
1434         if (rcode == 1) {
1435                 free(listen_type);
1436                 cf_log_err(cf_sectiontoitem(cs),
1437                            "No type specified in listen section");
1438                 return NULL;
1439         }
1440
1441         type = fr_str2int(listen_compare, listen_type, -1);
1442         if (type < 0) {
1443                 cf_log_err(cf_sectiontoitem(cs),
1444                            "Invalid type \"%s\" in listen section.",
1445                            listen_type);
1446                 free(listen_type);
1447                 return NULL;
1448         }
1449         free(listen_type);
1450         
1451         /*
1452          *      Allow listen sections in the default config to
1453          *      refer to a server.
1454          */
1455         if (!server) {
1456                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1457                                       &server, NULL);
1458                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1459                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1460                                               &server, NULL);
1461                 }
1462                 if (rcode < 0) return NULL;
1463         }
1464
1465         /*
1466          *      Set up cross-type data.
1467          */
1468         this = listen_alloc(type);
1469         this->server = server;
1470         this->fd = -1;
1471
1472         /*
1473          *      Call per-type parser.
1474          */
1475         if (master_listen[type].parse(cs, this) < 0) {
1476                 listen_free(&this);
1477                 return NULL;
1478         }
1479
1480         cf_log_info(cs, "}");
1481
1482         return this;
1483 }
1484
1485 /*
1486  *      Generate a list of listeners.  Takes an input list of
1487  *      listeners, too, so we don't close sockets with waiting packets.
1488  */
1489 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1490 {
1491         int             override = FALSE;
1492         int             rcode;
1493         CONF_SECTION    *cs = NULL;
1494         rad_listen_t    **last;
1495         rad_listen_t    *this;
1496         fr_ipaddr_t     server_ipaddr;
1497         int             auth_port = 0;
1498 #ifdef WITH_PROXY
1499         int             defined_proxy = 0;
1500 #endif
1501
1502         /*
1503          *      We shouldn't be called with a pre-existing list.
1504          */
1505         rad_assert(head && (*head == NULL));
1506
1507         last = head;
1508         server_ipaddr.af = AF_UNSPEC;
1509
1510         /*
1511          *      If the port is specified on the command-line,
1512          *      it over-rides the configuration file.
1513          *
1514          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1515          */
1516         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1517
1518         /*
1519          *      If the IP address was configured on the command-line,
1520          *      use that as the "bind_address"
1521          */
1522         if (mainconfig.myip.af != AF_UNSPEC) {
1523                 memcpy(&server_ipaddr, &mainconfig.myip,
1524                        sizeof(server_ipaddr));
1525                 override = TRUE;
1526                 goto bind_it;
1527         }
1528
1529         /*
1530          *      Else look for bind_address and/or listen sections.
1531          */
1532         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1533         rcode = cf_item_parse(config, "bind_address",
1534                               PW_TYPE_IPADDR,
1535                               &server_ipaddr.ipaddr.ip4addr, NULL);
1536         if (rcode < 0) return -1; /* error parsing it */
1537
1538         if (rcode == 0) { /* successfully parsed IPv4 */
1539                 listen_socket_t *sock;
1540                 server_ipaddr.af = AF_INET;
1541
1542                 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'.");
1543
1544         bind_it:
1545 #ifdef WITH_VMPS
1546                 if (strcmp(progname, "vmpsd") == 0) {
1547                         this = listen_alloc(RAD_LISTEN_VQP);
1548                         if (!auth_port) auth_port = 1589;
1549                 } else
1550 #endif
1551                         this = listen_alloc(RAD_LISTEN_AUTH);
1552
1553                 sock = this->data;
1554
1555                 sock->ipaddr = server_ipaddr;
1556                 sock->port = auth_port;
1557
1558                 sock->clients = clients_parse_section(config);
1559                 if (!sock->clients) {
1560                         cf_log_err(cf_sectiontoitem(config),
1561                                    "Failed to find any clients for this listen section");
1562                         listen_free(&this);
1563                         return -1;
1564                 }
1565
1566                 if (listen_bind(this) < 0) {
1567                         listen_free(head);
1568                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1569                         listen_free(&this);
1570                         return -1;
1571                 }
1572                 auth_port = sock->port; /* may have been updated in listen_bind */
1573                 if (override) {
1574                         cs = cf_section_sub_find_name2(config, "server",
1575                                                        mainconfig.name);
1576                         if (cs) this->server = mainconfig.name;
1577                 }
1578
1579                 *last = this;
1580                 last = &(this->next);
1581
1582 #ifdef WITH_VMPS
1583                 /*
1584                  *      No acct for vmpsd
1585                  */
1586                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1587 #endif
1588
1589 #ifdef WITH_ACCOUNTING
1590                 /*
1591                  *      Open Accounting Socket.
1592                  *
1593                  *      If we haven't already gotten acct_port from
1594                  *      /etc/services, then make it auth_port + 1.
1595                  */
1596                 this = listen_alloc(RAD_LISTEN_ACCT);
1597                 sock = this->data;
1598
1599                 /*
1600                  *      Create the accounting socket.
1601                  *
1602                  *      The accounting port is always the
1603                  *      authentication port + 1
1604                  */
1605                 sock->ipaddr = server_ipaddr;
1606                 sock->port = auth_port + 1;
1607
1608                 sock->clients = clients_parse_section(config);
1609                 if (!sock->clients) {
1610                         cf_log_err(cf_sectiontoitem(config),
1611                                    "Failed to find any clients for this listen section");
1612                         return -1;
1613                 }
1614
1615                 if (listen_bind(this) < 0) {
1616                         listen_free(&this);
1617                         listen_free(head);
1618                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1619                         return -1;
1620                 }
1621
1622                 if (override) {
1623                         cs = cf_section_sub_find_name2(config, "server",
1624                                                        mainconfig.name);
1625                         if (cs) this->server = mainconfig.name;
1626                 }
1627
1628                 *last = this;
1629                 last = &(this->next);
1630 #endif
1631         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1632                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1633                        mainconfig.port);
1634                 return -1;
1635         }
1636
1637         /*
1638          *      They specified an IP on the command-line, ignore
1639          *      all listen sections except the one in '-n'.
1640          */
1641         if (mainconfig.myip.af != AF_UNSPEC) {
1642                 CONF_SECTION *subcs;
1643                 const char *name2 = cf_section_name2(cs);
1644
1645                 cs = cf_section_sub_find_name2(config, "server",
1646                                                mainconfig.name);
1647                 if (!cs) goto do_proxy;
1648
1649                 /*
1650                  *      Should really abstract this code...
1651                  */
1652                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1653                      subcs != NULL;
1654                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1655                         this = listen_parse(subcs, name2);
1656                         if (!this) {
1657                                 listen_free(head);
1658                                 return -1;
1659                         }
1660
1661 #ifdef WITH_PROXY
1662                         if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1663 #endif
1664                         
1665                         *last = this;
1666                         last = &(this->next);
1667                 } /* loop over "listen" directives in server <foo> */
1668
1669                 goto do_proxy;
1670         }
1671
1672         /*
1673          *      Walk through the "listen" sections, if they exist.
1674          */
1675         for (cs = cf_subsection_find_next(config, NULL, "listen");
1676              cs != NULL;
1677              cs = cf_subsection_find_next(config, cs, "listen")) {
1678                 this = listen_parse(cs, NULL);
1679                 if (!this) {
1680                         listen_free(head);
1681                         return -1;
1682                 }
1683
1684 #ifdef WITH_PROXY
1685                 if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1686 #endif
1687
1688                 *last = this;
1689                 last = &(this->next);
1690         }
1691
1692         /*
1693          *      Check virtual servers for "listen" sections, too.
1694          *
1695          *      FIXME: Move to virtual server init?
1696          */
1697         for (cs = cf_subsection_find_next(config, NULL, "server");
1698              cs != NULL;
1699              cs = cf_subsection_find_next(config, cs, "server")) {
1700                 CONF_SECTION *subcs;
1701                 const char *name2 = cf_section_name2(cs);
1702                 
1703                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1704                      subcs != NULL;
1705                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1706                         this = listen_parse(subcs, name2);
1707                         if (!this) {
1708                                 listen_free(head);
1709                                 return -1;
1710                         }
1711                         
1712 #ifdef WITH_PROXY
1713                         if (this->type == RAD_LISTEN_PROXY) {
1714                                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
1715                                 listen_free(head);
1716                                 return -1;
1717                         }
1718 #endif
1719
1720                         *last = this;
1721                         last = &(this->next);
1722                 } /* loop over "listen" directives in virtual servers */
1723         } /* loop over virtual servers */
1724
1725         /*
1726          *      If we're proxying requests, open the proxy FD.
1727          *      Otherwise, don't do anything.
1728          */
1729  do_proxy:
1730 #ifdef WITH_PROXY
1731         if (mainconfig.proxy_requests == TRUE) {
1732                 int             port = -1;
1733                 listen_socket_t *sock = NULL;
1734
1735                 /*
1736                  *      No sockets to receive packets, therefore
1737                  *      proxying is pointless.
1738                  */
1739                 if (!*head) return -1;
1740
1741                 if (defined_proxy) goto done;
1742
1743                 /*
1744                  *      Find the first authentication port,
1745                  *      and use it
1746                  */
1747                 for (this = *head; this != NULL; this = this->next) {
1748                         if (this->type == RAD_LISTEN_AUTH) {
1749                                 sock = this->data;
1750                                 if (server_ipaddr.af == AF_UNSPEC) {
1751                                         server_ipaddr = sock->ipaddr;
1752                                 }
1753                                 port = sock->port + 2; /* skip acct port */
1754                                 break;
1755                         }
1756                         if (this->type == RAD_LISTEN_VQP) {
1757                                 sock = this->data;
1758                                 if (server_ipaddr.af == AF_UNSPEC) {
1759                                         server_ipaddr = sock->ipaddr;
1760                                 }
1761                                 port = sock->port + 1;
1762                                 break;
1763                         }
1764                 }
1765
1766                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
1767
1768                 /*
1769                  *      Address is still unspecified, use IPv4.
1770                  */
1771                 if (server_ipaddr.af == AF_UNSPEC) {
1772                         server_ipaddr.af = AF_INET;
1773                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1774                 }
1775
1776                 this = listen_alloc(RAD_LISTEN_PROXY);
1777                 sock = this->data;
1778
1779                 /*
1780                  *      Create the first proxy socket.
1781                  */
1782                 sock->ipaddr = server_ipaddr;
1783
1784                 /*
1785                  *      Try to find a proxy port (value doesn't matter)
1786                  */
1787                 for (sock->port = port;
1788                      sock->port < 64000;
1789                      sock->port++) {
1790                         if (listen_bind(this) == 0) {
1791                                 *last = this;
1792                                 last = &(this->next); /* just in case */
1793                                 break;
1794                         }
1795                 }
1796
1797                 if (sock->port >= 64000) {
1798                         listen_free(head);
1799                         listen_free(&this);
1800                         radlog(L_ERR, "Failed to open socket for proxying");
1801                         return -1;
1802                 }
1803         }
1804
1805  done:                  /* used only in proxy code. */
1806 #endif
1807
1808         return 0;
1809 }
1810
1811 /*
1812  *      Free a linked list of listeners;
1813  */
1814 void listen_free(rad_listen_t **head)
1815 {
1816         rad_listen_t *this;
1817
1818         if (!head || !*head) return;
1819
1820         this = *head;
1821         while (this) {
1822                 rad_listen_t *next = this->next;
1823
1824                 /*
1825                  *      Other code may have eaten the FD.
1826                  */
1827                 if (this->fd >= 0) close(this->fd);
1828
1829                 if (master_listen[this->type].free) {
1830                         master_listen[this->type].free(this);
1831                 }
1832                 free(this->data);
1833                 free(this);
1834
1835                 this = next;
1836         }
1837
1838         *head = NULL;
1839 }
1840
1841 #ifdef WITH_STATS
1842 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
1843                                           int port)
1844 {
1845         rad_listen_t *this;
1846
1847         for (this = mainconfig.listen; this != NULL; this = this->next) {
1848                 listen_socket_t *sock;
1849
1850                 if ((this->type != RAD_LISTEN_AUTH) &&
1851                     (this->type != RAD_LISTEN_ACCT)) continue;
1852                 
1853                 sock = this->data;
1854
1855                 if ((sock->port == port) &&
1856                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1857                         return sock->clients;
1858                 }
1859         }
1860
1861         return NULL;
1862 }
1863
1864 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
1865 {
1866         rad_listen_t *this;
1867
1868         for (this = mainconfig.listen; this != NULL; this = this->next) {
1869                 listen_socket_t *sock;
1870
1871                 if ((this->type != RAD_LISTEN_AUTH) &&
1872                     (this->type != RAD_LISTEN_ACCT)) continue;
1873                 
1874                 sock = this->data;
1875
1876                 if ((sock->port == port) &&
1877                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1878                         return this;
1879                 }
1880         }
1881
1882         return NULL;
1883 }
1884 #endif