Remove broken macro.
[freeradius.git] / src / main / listen.c
1 /*
2  * listen.c     Handle socket stuff
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2005,2006  The FreeRADIUS server project
21  * Copyright 2005  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30 #include <freeradius-devel/vqp.h>
31 #include <freeradius-devel/dhcp.h>
32
33 #include <freeradius-devel/vmps.h>
34 #include <freeradius-devel/detail.h>
35
36 #ifdef HAVE_SYS_RESOURCE_H
37 #include <sys/resource.h>
38 #endif
39
40 #ifdef HAVE_NET_IF_H
41 #include <net/if.h>
42 #endif
43
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47
48
49 /*
50  *      We'll use this below.
51  */
52 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
53 typedef void (*rad_listen_free_t)(rad_listen_t *);
54
55 typedef struct rad_listen_master_t {
56         rad_listen_parse_t      parse;
57         rad_listen_free_t       free;
58         rad_listen_recv_t       recv;
59         rad_listen_send_t       send;
60         rad_listen_print_t      print;
61         rad_listen_encode_t     encode;
62         rad_listen_decode_t     decode;
63 } rad_listen_master_t;
64
65 typedef struct listen_socket_t {
66         /*
67          *      For normal sockets.
68          */
69         fr_ipaddr_t     ipaddr;
70         int             port;
71 #ifdef SO_BINDTODEVICE
72         const char              *interface;
73 #endif
74         RADCLIENT_LIST  *clients;
75 } listen_socket_t;
76
77 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type);
78
79 /*
80  *      Find a per-socket client.
81  */
82 RADCLIENT *client_listener_find(const rad_listen_t *listener,
83                                 const fr_ipaddr_t *ipaddr, int src_port)
84 {
85 #ifdef WITH_DYNAMIC_CLIENTS
86         int rcode;
87         listen_socket_t *sock;
88         REQUEST *request;
89         RADCLIENT *created;
90 #endif
91         time_t now;
92         RADCLIENT *client;
93         RADCLIENT_LIST *clients;
94
95         rad_assert(listener != NULL);
96         rad_assert(ipaddr != NULL);
97
98         clients = ((listen_socket_t *)listener->data)->clients;
99
100         /*
101          *      This HAS to have been initialized previously.
102          */
103         rad_assert(clients != NULL);
104
105         client = client_find(clients, ipaddr);
106         if (!client) {
107                 static time_t last_printed = 0;
108                 char name[256], buffer[128];
109                                         
110 #ifdef WITH_DYNAMIC_CLIENTS
111         unknown:                /* used only for dynamic clients */
112 #endif
113
114                 /*
115                  *      DoS attack quenching, but only in debug mode.
116                  *      If they're running in debug mode, show them
117                  *      every packet.
118                  */
119                 if (debug_flag == 0) {
120                         now = time(NULL);
121                         if (last_printed == now) return NULL;
122                         
123                         last_printed = now;
124                 }
125
126                 listener->print(listener, name, sizeof(name));
127
128                 radlog(L_ERR, "Ignoring request to %s from unknown client %s port %d",
129                        name, inet_ntop(ipaddr->af, &ipaddr->ipaddr,
130                                        buffer, sizeof(buffer)),
131                        src_port);
132                 return NULL;
133         }
134
135 #ifndef WITH_DYNAMIC_CLIENTS
136         return client;          /* return the found client. */
137 #else
138
139         /*
140          *      No server defined, and it's not dynamic.  Return it.
141          */
142         if (!client->client_server && !client->dynamic) return client;
143
144         now = time(NULL);
145         
146         /*
147          *      It's a dynamically generated client, check it.
148          */
149         if (client->dynamic) {
150                 /*
151                  *      Lives forever.  Return it.
152                  */
153                 if (client->lifetime == 0) return client;
154                 
155                 /*
156                  *      Rate-limit the deletion of known clients.
157                  *      This makes them last a little longer, but
158                  *      prevents the server from melting down if (say)
159                  *      10k clients all expire at once.
160                  */
161                 if (now == client->last_new_client) return client;
162
163                 /*
164                  *      It's not dead yet.  Return it.
165                  */
166                 if ((client->created + client->lifetime) > now) return client;
167                 
168                 /*
169                  *      FIXME: Don't delete it until after the last
170                  *      request using it has expired.  i.e. keep a
171                  *      "use counter" (ugh).  Why can't we use a
172                  *      language with garbage collection?
173                  *      
174                  */
175                 client_delete(clients, client);
176
177                 /*
178                  *      Go find the enclosing network again.
179                  */
180                 client = client_find(clients, ipaddr);
181
182                 /*
183                  *      WTF?
184                  */
185                 if (!client) goto unknown;
186                 if (!client->client_server) goto unknown;
187
188                 /*
189                  *      At this point, 'client' is the enclosing
190                  *      network that configures where dynamic clients
191                  *      can be defined.
192                  */
193                 rad_assert(client->dynamic == 0);
194         } else {
195                 /*
196                  *      The IP is unknown, so we've found an enclosing
197                  *      network.  Enable DoS protection.  We only
198                  *      allow one new client per second.  Known
199                  *      clients aren't subject to this restriction.
200                  */
201                 if (now == client->last_new_client) goto unknown;
202         }
203
204         client->last_new_client = now;
205
206         request = request_alloc();
207         if (!request) goto unknown;
208
209         request->listener = listener;
210         request->client = client;
211         request->packet = rad_alloc(0);
212         if (!request->packet) {
213                 request_free(&request);
214                 goto unknown;
215         }
216         request->reply = rad_alloc(0);
217         if (!request->reply) {
218                 request_free(&request);
219                 goto unknown;
220         }
221         request->packet->timestamp = request->timestamp;
222         request->number = 0;
223         request->priority = listener->type;
224         request->server = client->client_server;
225         request->root = &mainconfig;
226
227         /*
228          *      Run a fake request through the given virtual server.
229          *      Look for FreeRADIUS-Client-IP-Address
230          *               FreeRADIUS-Client-Secret
231          *              ...
232          *
233          *      and create the RADCLIENT structure from that.
234          */
235
236         sock = listener->data;
237         request->packet->sockfd = listener->fd;
238         request->packet->src_ipaddr = *ipaddr;
239         request->packet->src_port = 0; /* who cares... */
240         request->packet->dst_ipaddr = sock->ipaddr;
241         request->packet->dst_port = sock->port;
242
243         request->reply->sockfd = request->packet->sockfd;
244         request->reply->dst_ipaddr = request->packet->src_ipaddr;
245         request->reply->src_ipaddr = request->packet->dst_ipaddr;
246         request->reply->dst_port = request->packet->src_port;
247         request->reply->src_port = request->packet->dst_port;
248         request->reply->id = request->packet->id;
249         request->reply->code = 0; /* UNKNOWN code */
250
251         
252         DEBUG("server %s {", request->server);
253
254         rcode = module_authorize(0, request);
255
256         DEBUG("} # server %s", request->server);
257
258         if (rcode != RLM_MODULE_OK) {
259                 request_free(&request);
260                 goto unknown;
261         }
262
263         /*
264          *      If the client was updated by rlm_dynamic_clients,
265          *      don't create the client from attribute-value pairs.
266          */
267         if (request->client == client) {
268                 created = client_create(clients, request);
269         } else {
270                 created = request->client;
271
272                 /*
273                  *      This frees the client if it isn't valid.
274                  */
275                 if (!client_validate(clients, client, created)) goto unknown;
276         }
277         request_free(&request);
278
279         if (!created) goto unknown;
280
281         return created;
282 #endif
283 }
284
285 static int listen_bind(rad_listen_t *this);
286
287
288 /*
289  *      Process and reply to a server-status request.
290  *      Like rad_authenticate and rad_accounting this should
291  *      live in it's own file but it's so small we don't bother.
292  */
293 static int rad_status_server(REQUEST *request)
294 {
295         int rcode = RLM_MODULE_OK;
296         DICT_VALUE *dval;
297
298         switch (request->listener->type) {
299 #ifdef WITH_STATS
300         case RAD_LISTEN_NONE:
301 #endif
302         case RAD_LISTEN_AUTH:
303                 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
304                 if (dval) {
305                         rcode = module_authorize(dval->value, request);
306                 } else {
307                         rcode = RLM_MODULE_OK;
308                 }
309
310                 switch (rcode) {
311                 case RLM_MODULE_OK:
312                 case RLM_MODULE_UPDATED:
313                         request->reply->code = PW_AUTHENTICATION_ACK;
314                         break;
315
316                 case RLM_MODULE_FAIL:
317                 case RLM_MODULE_HANDLED:
318                         request->reply->code = 0; /* don't reply */
319                         break;
320
321                 default:
322                 case RLM_MODULE_REJECT:
323                         request->reply->code = PW_AUTHENTICATION_REJECT;
324                         break;
325                 }
326                 break;
327
328 #ifdef WITH_ACCOUNTING
329         case RAD_LISTEN_ACCT:
330                 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
331                 if (dval) {
332                         rcode = module_accounting(dval->value, request);
333                 } else {
334                         rcode = RLM_MODULE_OK;
335                 }
336
337                 switch (rcode) {
338                 case RLM_MODULE_OK:
339                 case RLM_MODULE_UPDATED:
340                         request->reply->code = PW_ACCOUNTING_RESPONSE;
341                         break;
342
343                 default:
344                         request->reply->code = 0; /* don't reply */
345                         break;
346                 }
347                 break;
348 #endif
349
350         default:
351                 return 0;
352         }
353
354 #ifdef WITH_STATS
355         /*
356          *      Full statistics are available only on a statistics
357          *      socket.
358          */
359         if (request->listener->type == RAD_LISTEN_NONE) {
360                 request_stats_reply(request);
361         }
362 #endif
363
364         return 0;
365 }
366
367
368 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
369 {
370         size_t len;
371         listen_socket_t *sock = this->data;
372         const char *name;
373
374         switch (this->type) {
375 #ifdef WITH_STATS
376         case RAD_LISTEN_NONE:   /* what a hack... */
377                 name = "status";
378                 break;
379 #endif
380
381         case RAD_LISTEN_AUTH:
382                 name = "authentication";
383                 break;
384
385 #ifdef WITH_ACCOUNTING
386         case RAD_LISTEN_ACCT:
387                 name = "accounting";
388                 break;
389 #endif
390
391 #ifdef WITH_PROXY
392         case RAD_LISTEN_PROXY:
393                 name = "proxy";
394                 break;
395 #endif
396
397 #ifdef WITH_VMPS
398         case RAD_LISTEN_VQP:
399                 name = "vmps";
400                 break;
401 #endif
402
403 #ifdef WITH_DHCP
404         case RAD_LISTEN_DHCP:
405                 name = "dhcp";
406                 break;
407 #endif
408
409         default:
410                 name = "??";
411                 break;
412         }
413
414 #define FORWARD len = strlen(buffer); if (len >= (bufsize + 1)) return 0;buffer += len;bufsize -= len
415 #define ADDSTRING(_x) strlcpy(buffer, _x, bufsize);FORWARD
416
417         ADDSTRING(name);
418
419 #ifdef SO_BINDTODEVICE
420         if (sock->interface) {
421                 ADDSTRING(" interface ");
422                 ADDSTRING(sock->interface);
423         }
424 #endif
425
426         ADDSTRING(" address ");
427         
428         if ((sock->ipaddr.af == AF_INET) &&
429             (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
430                 strlcpy(buffer, "*", bufsize);
431         } else {
432                 ip_ntoh(&sock->ipaddr, buffer, bufsize);
433         }
434         FORWARD;
435
436         ADDSTRING(" port ");
437         snprintf(buffer, bufsize, "%d", sock->port);
438         FORWARD;
439
440         if (this->server) {
441                 ADDSTRING(" as server ");
442                 ADDSTRING(this->server);
443         }
444
445 #undef ADDSTRING
446 #undef FORWARD
447
448         return 1;
449 }
450
451
452 /*
453  *      Parse an authentication or accounting socket.
454  */
455 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
456 {
457         int             rcode;
458         int             listen_port;
459         fr_ipaddr_t     ipaddr;
460         listen_socket_t *sock = this->data;
461         char            *section_name = NULL;
462         CONF_SECTION    *client_cs, *parentcs;
463
464         /*
465          *      Try IPv4 first
466          */
467         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
468         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
469                               &ipaddr.ipaddr.ip4addr, NULL);
470         if (rcode < 0) return -1;
471
472         if (rcode == 0) { /* successfully parsed IPv4 */
473                 ipaddr.af = AF_INET;
474
475         } else {        /* maybe IPv6? */
476                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
477                                       &ipaddr.ipaddr.ip6addr, NULL);
478                 if (rcode < 0) return -1;
479
480                 if (rcode == 1) {
481                         cf_log_err(cf_sectiontoitem(cs),
482                                    "No address specified in listen section");
483                         return -1;
484                 }
485                 ipaddr.af = AF_INET6;
486         }
487
488         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
489                               &listen_port, "0");
490         if (rcode < 0) return -1;
491
492         if ((listen_port < 0) || (listen_port > 65535)) {
493                         cf_log_err(cf_sectiontoitem(cs),
494                                    "Invalid value for \"port\"");
495                         return -1;
496         }
497
498         sock->ipaddr = ipaddr;
499         sock->port = listen_port;
500
501         /*
502          *      If we can bind to interfaces, do so,
503          *      else don't.
504          */
505         if (cf_pair_find(cs, "interface")) {
506 #ifndef SO_BINDTODEVICE
507                 cf_log_err(cf_sectiontoitem(cs),
508                            "System does not support binding to interfaces.  Delete this line from the configuration file.");
509                 return -1;
510 #else
511                 const char *value;
512                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
513
514                 rad_assert(cp != NULL);
515                 value = cf_pair_value(cp);
516                 if (!value) {
517                         cf_log_err(cf_sectiontoitem(cs),
518                                    "No interface name given");
519                         return -1;
520                 }
521                 sock->interface = value;
522 #endif
523         }
524
525         /*
526          *      And bind it to the port.
527          */
528         if (listen_bind(this) < 0) {
529                 char buffer[128];
530                 cf_log_err(cf_sectiontoitem(cs),
531                            "Error binding to port for %s port %d",
532                            ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
533                            sock->port);
534                 return -1;
535         }
536
537 #ifdef WITH_PROXY
538         /*
539          *      Proxy sockets don't have clients.
540          */
541         if (this->type == RAD_LISTEN_PROXY) return 0;
542 #endif
543         
544         /*
545          *      The more specific configurations are preferred to more
546          *      generic ones.
547          */
548         client_cs = NULL;
549         parentcs = cf_top_section(cs);
550         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
551                               &section_name, NULL);
552         if (rcode < 0) return -1; /* bad string */
553         if (rcode == 0) {
554                 /*
555                  *      Explicit list given: use it.
556                  */
557                 client_cs = cf_section_sub_find_name2(parentcs,
558                                                       "clients",
559                                                       section_name);
560                 if (!client_cs) {
561                         client_cs = cf_section_find(section_name);
562                 }
563                 if (!client_cs) {
564                         cf_log_err(cf_sectiontoitem(cs),
565                                    "Failed to find clients %s {...}",
566                                    section_name);
567                         free(section_name);
568                         return -1;
569                 }
570                 free(section_name);
571         } /* else there was no "clients = " entry. */
572
573         if (!client_cs) {
574                 CONF_SECTION *server_cs;
575
576                 server_cs = cf_section_sub_find_name2(parentcs,
577                                                       "server",
578                                                       this->server);
579                 /*
580                  *      Found a "server foo" section.  If there are clients
581                  *      in it, use them.
582                  */
583                 if (server_cs &&
584                     (cf_section_sub_find(server_cs, "client") != NULL)) {
585                         client_cs = server_cs;
586                 }
587         }
588
589         /*
590          *      Still nothing.  Look for global clients.
591          */
592         if (!client_cs) client_cs = parentcs;
593
594         sock->clients = clients_parse_section(client_cs);
595         if (!sock->clients) {
596                 cf_log_err(cf_sectiontoitem(cs),
597                            "Failed to load clients for this listen section");
598                 return -1;
599         }
600
601         return 0;
602 }
603
604 /*
605  *      Send an authentication response packet
606  */
607 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
608 {
609         rad_assert(request->listener == listener);
610         rad_assert(listener->send == auth_socket_send);
611
612         return rad_send(request->reply, request->packet,
613                         request->client->secret);
614 }
615
616
617 #ifdef WITH_ACCOUNTING
618 /*
619  *      Send an accounting response packet (or not)
620  */
621 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
622 {
623         rad_assert(request->listener == listener);
624         rad_assert(listener->send == acct_socket_send);
625
626         /*
627          *      Accounting reject's are silently dropped.
628          *
629          *      We do it here to avoid polluting the rest of the
630          *      code with this knowledge
631          */
632         if (request->reply->code == 0) return 0;
633
634         return rad_send(request->reply, request->packet,
635                         request->client->secret);
636 }
637 #endif
638
639 #ifdef WITH_PROXY
640 /*
641  *      Send a packet to a home server.
642  *
643  *      FIXME: have different code for proxy auth & acct!
644  */
645 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
646 {
647         listen_socket_t *sock = listener->data;
648
649         rad_assert(request->proxy_listener == listener);
650         rad_assert(listener->send == proxy_socket_send);
651
652         request->proxy->src_ipaddr = sock->ipaddr;
653         request->proxy->src_port = sock->port;
654
655         return rad_send(request->proxy, request->packet,
656                         request->home_server->secret);
657 }
658 #endif
659
660 #ifdef WITH_STATS
661 /*
662  *      Check if an incoming request is "ok"
663  *
664  *      It takes packets, not requests.  It sees if the packet looks
665  *      OK.  If so, it does a number of sanity checks on it.
666   */
667 static int stats_socket_recv(rad_listen_t *listener,
668                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
669 {
670         ssize_t         rcode;
671         int             code, src_port;
672         RADIUS_PACKET   *packet;
673         RADCLIENT       *client;
674         fr_ipaddr_t     src_ipaddr;
675
676         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
677         if (rcode < 0) return 0;
678
679         RAD_STATS_TYPE_INC(listener, total_requests);
680
681         if (rcode < 20) {       /* AUTH_HDR_LEN */
682                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
683                 return 0;
684         }
685
686         if ((client = client_listener_find(listener,
687                                            &src_ipaddr, src_port)) == NULL) {
688                 rad_recv_discard(listener->fd);
689                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
690                 return 0;
691         }
692
693         /*
694          *      We only understand Status-Server on this socket.
695          */
696         if (code != PW_STATUS_SERVER) {
697                 DEBUG("Ignoring packet code %d sent to Status-Server port",
698                       code);
699                 rad_recv_discard(listener->fd);
700                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
701                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
702                 return 0;
703         }
704
705         /*
706          *      Now that we've sanity checked everything, receive the
707          *      packet.
708          */
709         packet = rad_recv(listener->fd, 1); /* require message authenticator */
710         if (!packet) {
711                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
712                 DEBUG("%s", fr_strerror());
713                 return 0;
714         }
715
716         if (!received_request(listener, packet, prequest, client)) {
717                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
718                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
719                 rad_free(&packet);
720                 return 0;
721         }
722
723         *pfun = rad_status_server;
724         return 1;
725 }
726 #endif
727
728
729 /*
730  *      Check if an incoming request is "ok"
731  *
732  *      It takes packets, not requests.  It sees if the packet looks
733  *      OK.  If so, it does a number of sanity checks on it.
734   */
735 static int auth_socket_recv(rad_listen_t *listener,
736                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
737 {
738         ssize_t         rcode;
739         int             code, src_port;
740         RADIUS_PACKET   *packet;
741         RAD_REQUEST_FUNP fun = NULL;
742         RADCLIENT       *client;
743         fr_ipaddr_t     src_ipaddr;
744
745         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
746         if (rcode < 0) return 0;
747
748         RAD_STATS_TYPE_INC(listener, total_requests);
749
750         if (rcode < 20) {       /* AUTH_HDR_LEN */
751                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
752                 return 0;
753         }
754
755         if ((client = client_listener_find(listener,
756                                            &src_ipaddr, src_port)) == NULL) {
757                 rad_recv_discard(listener->fd);
758                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
759                 return 0;
760         }
761
762         /*
763          *      Some sanity checks, based on the packet code.
764          */
765         switch(code) {
766         case PW_AUTHENTICATION_REQUEST:
767                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
768                 fun = rad_authenticate;
769                 break;
770
771         case PW_STATUS_SERVER:
772                 if (!mainconfig.status_server) {
773                         rad_recv_discard(listener->fd);
774                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
775                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
776                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
777                         return 0;
778                 }
779                 fun = rad_status_server;
780                 break;
781
782         default:
783                 rad_recv_discard(listener->fd);
784                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
785                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
786
787                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
788                       code, client->shortname, src_port);
789                 return 0;
790                 break;
791         } /* switch over packet types */
792
793         /*
794          *      Now that we've sanity checked everything, receive the
795          *      packet.
796          */
797         packet = rad_recv(listener->fd, client->message_authenticator);
798         if (!packet) {
799                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
800                 DEBUG("%s", fr_strerror());
801                 return 0;
802         }
803
804         if (!received_request(listener, packet, prequest, client)) {
805                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
806                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
807                 rad_free(&packet);
808                 return 0;
809         }
810
811         *pfun = fun;
812         return 1;
813 }
814
815
816 #ifdef WITH_ACCOUNTING
817 /*
818  *      Receive packets from an accounting socket
819  */
820 static int acct_socket_recv(rad_listen_t *listener,
821                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
822 {
823         ssize_t         rcode;
824         int             code, src_port;
825         RADIUS_PACKET   *packet;
826         RAD_REQUEST_FUNP fun = NULL;
827         RADCLIENT       *client;
828         fr_ipaddr_t     src_ipaddr;
829
830         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
831         if (rcode < 0) return 0;
832
833         RAD_STATS_TYPE_INC(listener, total_requests);
834
835         if (rcode < 20) {       /* AUTH_HDR_LEN */
836                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
837                 return 0;
838         }
839
840         if ((client = client_listener_find(listener,
841                                            &src_ipaddr, src_port)) == NULL) {
842                 rad_recv_discard(listener->fd);
843                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
844                 return 0;
845         }
846
847         /*
848          *      Some sanity checks, based on the packet code.
849          */
850         switch(code) {
851         case PW_ACCOUNTING_REQUEST:
852                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
853                 fun = rad_accounting;
854                 break;
855
856         case PW_STATUS_SERVER:
857                 if (!mainconfig.status_server) {
858                         rad_recv_discard(listener->fd);
859                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
860                         RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
861
862                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
863                         return 0;
864                 }
865                 fun = rad_status_server;
866                 break;
867
868         default:
869                 rad_recv_discard(listener->fd);
870                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
871                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
872
873                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
874                       code, client->shortname, src_port);
875                 return 0;
876         } /* switch over packet types */
877
878         /*
879          *      Now that we've sanity checked everything, receive the
880          *      packet.
881          */
882         packet = rad_recv(listener->fd, 0);
883         if (!packet) {
884                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
885                 radlog(L_ERR, "%s", fr_strerror());
886                 return 0;
887         }
888
889         /*
890          *      There can be no duplicate accounting packets.
891          */
892         if (!received_request(listener, packet, prequest, client)) {
893                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
894                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
895                 rad_free(&packet);
896                 return 0;
897         }
898
899         *pfun = fun;
900         return 1;
901 }
902 #endif
903
904
905 #ifdef WITH_COA
906 /*
907  *      For now, all CoA requests are *only* originated, and not
908  *      proxied.  So all of the necessary work is done in the
909  *      post-proxy section, which is automatically handled by event.c.
910  *      As a result, we don't have to do anything here.
911  */
912 static int rad_coa_reply(REQUEST *request)
913 {
914         VALUE_PAIR *s1, *s2;
915
916         /*
917          *      Inform the user about RFC requirements.
918          */
919         s1 = pairfind(request->proxy->vps, PW_STATE);
920         if (s1) {
921                 s2 = pairfind(request->proxy_reply->vps, PW_STATE);
922
923                 if (!s2) {
924                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with State.");
925
926                 } else if ((s1->length != s2->length) ||
927                            (memcmp(s1->vp_octets, s2->vp_octets,
928                                    s1->length) != 0)) {
929                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with the same State.");
930                 }
931         }
932
933         return RLM_MODULE_OK;
934 }
935 #endif
936
937 #ifdef WITH_PROXY
938 /*
939  *      Recieve packets from a proxy socket.
940  */
941 static int proxy_socket_recv(rad_listen_t *listener,
942                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
943 {
944         REQUEST         *request;
945         RADIUS_PACKET   *packet;
946         RAD_REQUEST_FUNP fun = NULL;
947         char            buffer[128];
948
949         packet = rad_recv(listener->fd, 0);
950         if (!packet) {
951                 radlog(L_ERR, "%s", fr_strerror());
952                 return 0;
953         }
954
955         /*
956          *      FIXME: Client MIB updates?
957          */
958         switch(packet->code) {
959         case PW_AUTHENTICATION_ACK:
960         case PW_ACCESS_CHALLENGE:
961         case PW_AUTHENTICATION_REJECT:
962                 fun = rad_authenticate;
963                 break;
964
965 #ifdef WITH_ACCOUNTING
966         case PW_ACCOUNTING_RESPONSE:
967                 fun = rad_accounting;
968                 break;
969 #endif
970
971 #ifdef WITH_COA
972         case PW_DISCONNECT_ACK:
973         case PW_DISCONNECT_NAK:
974         case PW_COA_ACK:
975         case PW_COA_NAK:
976                 fun = rad_coa_reply;
977                 break;
978 #endif
979
980         default:
981                 /*
982                  *      FIXME: Update MIB for packet types?
983                  */
984                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
985                        "from home server %s port %d - ID %d : IGNORED",
986                        packet->code,
987                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
988                        packet->src_port, packet->id);
989                 rad_free(&packet);
990                 return 0;
991         }
992
993         request = received_proxy_response(packet);
994         if (!request) {
995                 rad_free(&packet);
996                 return 0;
997         }
998
999         rad_assert(fun != NULL);
1000         *pfun = fun;
1001         *prequest = request;
1002
1003         return 1;
1004 }
1005 #endif
1006
1007
1008 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1009 {
1010         if (!request->reply->code) return 0;
1011
1012         rad_encode(request->reply, request->packet,
1013                    request->client->secret);
1014         rad_sign(request->reply, request->packet,
1015                  request->client->secret);
1016
1017         return 0;
1018 }
1019
1020
1021 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1022 {
1023         if (rad_verify(request->packet, NULL,
1024                        request->client->secret) < 0) {
1025                 return -1;
1026         }
1027
1028         return rad_decode(request->packet, NULL,
1029                           request->client->secret);
1030 }
1031
1032 #ifdef WITH_PROXY
1033 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1034 {
1035         rad_encode(request->proxy, NULL, request->home_server->secret);
1036         rad_sign(request->proxy, NULL, request->home_server->secret);
1037
1038         return 0;
1039 }
1040
1041
1042 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1043 {
1044         if (rad_verify(request->proxy_reply, request->proxy,
1045                        request->home_server->secret) < 0) {
1046                 return -1;
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                         if (this->type == RAD_LISTEN_VQP) {
1799                                 sock = this->data;
1800                                 if (server_ipaddr.af == AF_UNSPEC) {
1801                                         server_ipaddr = sock->ipaddr;
1802                                 }
1803                                 port = sock->port + 1;
1804                                 break;
1805                         }
1806                 }
1807
1808                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
1809
1810                 /*
1811                  *      Address is still unspecified, use IPv4.
1812                  */
1813                 if (server_ipaddr.af == AF_UNSPEC) {
1814                         server_ipaddr.af = AF_INET;
1815                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1816                 }
1817
1818                 this = listen_alloc(RAD_LISTEN_PROXY);
1819                 sock = this->data;
1820
1821                 /*
1822                  *      Create the first proxy socket.
1823                  */
1824                 sock->ipaddr = server_ipaddr;
1825
1826                 /*
1827                  *      Try to find a proxy port (value doesn't matter)
1828                  */
1829                 for (sock->port = port;
1830                      sock->port < 64000;
1831                      sock->port++) {
1832                         if (listen_bind(this) == 0) {
1833                                 *last = this;
1834                                 last = &(this->next); /* just in case */
1835                                 break;
1836                         }
1837                 }
1838
1839                 if (sock->port >= 64000) {
1840                         listen_free(head);
1841                         listen_free(&this);
1842                         radlog(L_ERR, "Failed to open socket for proxying");
1843                         return -1;
1844                 }
1845         }
1846
1847  done:                  /* used only in proxy code. */
1848 #endif
1849
1850         return 0;
1851 }
1852
1853 /*
1854  *      Free a linked list of listeners;
1855  */
1856 void listen_free(rad_listen_t **head)
1857 {
1858         rad_listen_t *this;
1859
1860         if (!head || !*head) return;
1861
1862         this = *head;
1863         while (this) {
1864                 rad_listen_t *next = this->next;
1865
1866                 /*
1867                  *      Other code may have eaten the FD.
1868                  */
1869                 if (this->fd >= 0) close(this->fd);
1870
1871                 if (master_listen[this->type].free) {
1872                         master_listen[this->type].free(this);
1873                 }
1874                 free(this->data);
1875                 free(this);
1876
1877                 this = next;
1878         }
1879
1880         *head = NULL;
1881 }
1882
1883 #ifdef WITH_STATS
1884 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
1885                                           int port)
1886 {
1887         rad_listen_t *this;
1888
1889         for (this = mainconfig.listen; this != NULL; this = this->next) {
1890                 listen_socket_t *sock;
1891
1892                 if ((this->type != RAD_LISTEN_AUTH) &&
1893                     (this->type != RAD_LISTEN_ACCT)) continue;
1894                 
1895                 sock = this->data;
1896
1897                 if ((sock->port == port) &&
1898                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1899                         return sock->clients;
1900                 }
1901         }
1902
1903         return NULL;
1904 }
1905
1906 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
1907 {
1908         rad_listen_t *this;
1909
1910         for (this = mainconfig.listen; this != NULL; this = this->next) {
1911                 listen_socket_t *sock;
1912
1913                 if ((this->type != RAD_LISTEN_AUTH) &&
1914                     (this->type != RAD_LISTEN_ACCT)) continue;
1915                 
1916                 sock = this->data;
1917
1918                 if ((sock->port == port) &&
1919                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
1920                         return this;
1921                 }
1922         }
1923
1924         return NULL;
1925 }
1926 #endif