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