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