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