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