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