If the port is already used, try another.
[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         int last_proxy_port, port;
1674         rad_listen_t *this, *tmp, **last;
1675         listen_socket_t *sock, *old;
1676
1677         /*
1678          *      Find an existing proxy socket to copy.
1679          */
1680         last_proxy_port = 0;
1681         old = NULL;
1682         last = &mainconfig.listen;
1683         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1684                 /*
1685                  *      Not proxy, ignore it.
1686                  */
1687                 if (tmp->type != RAD_LISTEN_PROXY) continue;
1688
1689                 sock = tmp->data;
1690
1691                 /*
1692                  *      If we were asked to copy a specific one, do
1693                  *      so.  If we're just finding one that already
1694                  *      exists, return a pointer to it.  Otherwise,
1695                  *      create ANOTHER one with the same IP address.
1696                  */
1697                 if ((ipaddr->af != AF_UNSPEC) &&
1698                     (fr_ipaddr_cmp(&sock->ipaddr, ipaddr) != 0)) {
1699                         if (exists) return tmp;
1700                         continue;
1701                 }
1702                 
1703                 if (sock->port > last_proxy_port) {
1704                         last_proxy_port = sock->port + 1;
1705                 }
1706                 if (!old) old = sock;
1707
1708                 last = &(tmp->next);
1709         }
1710
1711         if (!old) {
1712                 /*
1713                  *      The socket MUST already exist if we're binding
1714                  *      to an address while proxying.
1715                  *
1716                  *      If we're initializing the server, it's OK for the
1717                  *      socket to NOT exist.
1718                  */
1719                 if (!exists) return NULL;
1720
1721                 this = listen_alloc(RAD_LISTEN_PROXY);
1722
1723                 sock = this->data;
1724                 sock->ipaddr = *ipaddr;
1725
1726         } else {
1727                 this = listen_alloc(RAD_LISTEN_PROXY);
1728                 
1729                 sock = this->data;
1730                 sock->ipaddr = old->ipaddr;
1731         }
1732
1733         /*
1734          *      Keep going until we find an unused port.
1735          */
1736         for (port = last_proxy_port; port < 64000; port++) {
1737                 int rcode;
1738
1739                 sock->port = port;
1740
1741                 rcode = listen_bind(this);
1742                 if (rcode < 0) {
1743                         continue;
1744                 }
1745                 
1746                 /*
1747                  *      Add the new listener to the list of
1748                  *      listeners.
1749                  */
1750                 *last = this;
1751                 return this;
1752         }
1753
1754         listen_free(&this);
1755         return NULL;
1756 }
1757 #endif
1758
1759 static const FR_NAME_NUMBER listen_compare[] = {
1760 #ifdef WITH_STATS
1761         { "status",     RAD_LISTEN_NONE },
1762 #endif
1763         { "auth",       RAD_LISTEN_AUTH },
1764 #ifdef WITH_ACCOUNTING
1765         { "acct",       RAD_LISTEN_ACCT },
1766 #endif
1767 #ifdef WITH_DETAIL
1768         { "detail",     RAD_LISTEN_DETAIL },
1769 #endif
1770 #ifdef WITH_PROXY
1771         { "proxy",      RAD_LISTEN_PROXY },
1772 #endif
1773 #ifdef WITH_VMPS
1774         { "vmps",       RAD_LISTEN_VQP },
1775 #endif
1776 #ifdef WITH_DHCP
1777         { "dhcp",       RAD_LISTEN_DHCP },
1778 #endif
1779 #ifdef WITH_COMMAND_SOCKET
1780         { "control",    RAD_LISTEN_COMMAND },
1781 #endif
1782 #ifdef WITH_COA
1783         { "coa",        RAD_LISTEN_COA },
1784 #endif
1785         { NULL, 0 },
1786 };
1787
1788
1789 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1790 {
1791         int             type, rcode;
1792         char            *listen_type;
1793         rad_listen_t    *this;
1794
1795         listen_type = NULL;
1796         
1797         cf_log_info(cs, "listen {");
1798
1799         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1800                               &listen_type, "");
1801         if (rcode < 0) return NULL;
1802         if (rcode == 1) {
1803                 free(listen_type);
1804                 cf_log_err(cf_sectiontoitem(cs),
1805                            "No type specified in listen section");
1806                 return NULL;
1807         }
1808
1809         type = fr_str2int(listen_compare, listen_type, -1);
1810         if (type < 0) {
1811                 cf_log_err(cf_sectiontoitem(cs),
1812                            "Invalid type \"%s\" in listen section.",
1813                            listen_type);
1814                 free(listen_type);
1815                 return NULL;
1816         }
1817         free(listen_type);
1818         
1819         /*
1820          *      Allow listen sections in the default config to
1821          *      refer to a server.
1822          */
1823         if (!server) {
1824                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1825                                       &server, NULL);
1826                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1827                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1828                                               &server, NULL);
1829                 }
1830                 if (rcode < 0) return NULL;
1831         }
1832
1833         /*
1834          *      Set up cross-type data.
1835          */
1836         this = listen_alloc(type);
1837         this->server = server;
1838         this->fd = -1;
1839
1840         /*
1841          *      Call per-type parser.
1842          */
1843         if (master_listen[type].parse(cs, this) < 0) {
1844                 listen_free(&this);
1845                 return NULL;
1846         }
1847
1848         cf_log_info(cs, "}");
1849
1850         return this;
1851 }
1852
1853 /*
1854  *      Generate a list of listeners.  Takes an input list of
1855  *      listeners, too, so we don't close sockets with waiting packets.
1856  */
1857 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1858 {
1859         int             override = FALSE;
1860         int             rcode;
1861         CONF_SECTION    *cs = NULL;
1862         rad_listen_t    **last;
1863         rad_listen_t    *this;
1864         fr_ipaddr_t     server_ipaddr;
1865         int             auth_port = 0;
1866 #ifdef WITH_PROXY
1867         int             defined_proxy = 0;
1868 #endif
1869
1870         /*
1871          *      We shouldn't be called with a pre-existing list.
1872          */
1873         rad_assert(head && (*head == NULL));
1874
1875         last = head;
1876         server_ipaddr.af = AF_UNSPEC;
1877
1878         /*
1879          *      If the port is specified on the command-line,
1880          *      it over-rides the configuration file.
1881          *
1882          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1883          */
1884         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1885
1886         /*
1887          *      If the IP address was configured on the command-line,
1888          *      use that as the "bind_address"
1889          */
1890         if (mainconfig.myip.af != AF_UNSPEC) {
1891                 memcpy(&server_ipaddr, &mainconfig.myip,
1892                        sizeof(server_ipaddr));
1893                 override = TRUE;
1894                 goto bind_it;
1895         }
1896
1897         /*
1898          *      Else look for bind_address and/or listen sections.
1899          */
1900         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1901         rcode = cf_item_parse(config, "bind_address",
1902                               PW_TYPE_IPADDR,
1903                               &server_ipaddr.ipaddr.ip4addr, NULL);
1904         if (rcode < 0) return -1; /* error parsing it */
1905
1906         if (rcode == 0) { /* successfully parsed IPv4 */
1907                 listen_socket_t *sock;
1908                 server_ipaddr.af = AF_INET;
1909
1910                 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'.");
1911
1912         bind_it:
1913 #ifdef WITH_VMPS
1914                 if (strcmp(progname, "vmpsd") == 0) {
1915                         this = listen_alloc(RAD_LISTEN_VQP);
1916                         if (!auth_port) auth_port = 1589;
1917                 } else
1918 #endif
1919                         this = listen_alloc(RAD_LISTEN_AUTH);
1920
1921                 sock = this->data;
1922
1923                 sock->ipaddr = server_ipaddr;
1924                 sock->port = auth_port;
1925
1926                 sock->clients = clients_parse_section(config);
1927                 if (!sock->clients) {
1928                         cf_log_err(cf_sectiontoitem(config),
1929                                    "Failed to find any clients for this listen section");
1930                         listen_free(&this);
1931                         return -1;
1932                 }
1933
1934                 if (listen_bind(this) < 0) {
1935                         listen_free(head);
1936                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1937                         listen_free(&this);
1938                         return -1;
1939                 }
1940                 auth_port = sock->port; /* may have been updated in listen_bind */
1941                 if (override) {
1942                         cs = cf_section_sub_find_name2(config, "server",
1943                                                        mainconfig.name);
1944                         if (cs) this->server = mainconfig.name;
1945                 }
1946
1947                 *last = this;
1948                 last = &(this->next);
1949
1950 #ifdef WITH_VMPS
1951                 /*
1952                  *      No acct for vmpsd
1953                  */
1954                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1955 #endif
1956
1957 #ifdef WITH_ACCOUNTING
1958                 /*
1959                  *      Open Accounting Socket.
1960                  *
1961                  *      If we haven't already gotten acct_port from
1962                  *      /etc/services, then make it auth_port + 1.
1963                  */
1964                 this = listen_alloc(RAD_LISTEN_ACCT);
1965                 sock = this->data;
1966
1967                 /*
1968                  *      Create the accounting socket.
1969                  *
1970                  *      The accounting port is always the
1971                  *      authentication port + 1
1972                  */
1973                 sock->ipaddr = server_ipaddr;
1974                 sock->port = auth_port + 1;
1975
1976                 sock->clients = clients_parse_section(config);
1977                 if (!sock->clients) {
1978                         cf_log_err(cf_sectiontoitem(config),
1979                                    "Failed to find any clients for this listen section");
1980                         return -1;
1981                 }
1982
1983                 if (listen_bind(this) < 0) {
1984                         listen_free(&this);
1985                         listen_free(head);
1986                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1987                         return -1;
1988                 }
1989
1990                 if (override) {
1991                         cs = cf_section_sub_find_name2(config, "server",
1992                                                        mainconfig.name);
1993                         if (cs) this->server = mainconfig.name;
1994                 }
1995
1996                 *last = this;
1997                 last = &(this->next);
1998 #endif
1999         } else if (mainconfig.port > 0) { /* no bind address, but a port */
2000                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
2001                        mainconfig.port);
2002                 return -1;
2003         }
2004
2005         /*
2006          *      They specified an IP on the command-line, ignore
2007          *      all listen sections except the one in '-n'.
2008          */
2009         if (mainconfig.myip.af != AF_UNSPEC) {
2010                 CONF_SECTION *subcs;
2011                 const char *name2 = cf_section_name2(cs);
2012
2013                 cs = cf_section_sub_find_name2(config, "server",
2014                                                mainconfig.name);
2015                 if (!cs) goto do_proxy;
2016
2017                 /*
2018                  *      Should really abstract this code...
2019                  */
2020                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2021                      subcs != NULL;
2022                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2023                         this = listen_parse(subcs, name2);
2024                         if (!this) {
2025                                 listen_free(head);
2026                                 return -1;
2027                         }
2028
2029 #ifdef WITH_PROXY
2030                         if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
2031 #endif
2032                         
2033                         *last = this;
2034                         last = &(this->next);
2035                 } /* loop over "listen" directives in server <foo> */
2036
2037                 goto do_proxy;
2038         }
2039
2040         /*
2041          *      Walk through the "listen" sections, if they exist.
2042          */
2043         for (cs = cf_subsection_find_next(config, NULL, "listen");
2044              cs != NULL;
2045              cs = cf_subsection_find_next(config, cs, "listen")) {
2046                 this = listen_parse(cs, NULL);
2047                 if (!this) {
2048                         listen_free(head);
2049                         return -1;
2050                 }
2051
2052 #ifdef WITH_PROXY
2053                 if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
2054 #endif
2055
2056                 *last = this;
2057                 last = &(this->next);
2058         }
2059
2060         /*
2061          *      Check virtual servers for "listen" sections, too.
2062          *
2063          *      FIXME: Move to virtual server init?
2064          */
2065         for (cs = cf_subsection_find_next(config, NULL, "server");
2066              cs != NULL;
2067              cs = cf_subsection_find_next(config, cs, "server")) {
2068                 CONF_SECTION *subcs;
2069                 const char *name2 = cf_section_name2(cs);
2070                 
2071                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2072                      subcs != NULL;
2073                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2074                         this = listen_parse(subcs, name2);
2075                         if (!this) {
2076                                 listen_free(head);
2077                                 return -1;
2078                         }
2079                         
2080 #ifdef WITH_PROXY
2081                         if (this->type == RAD_LISTEN_PROXY) {
2082                                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
2083                                 listen_free(head);
2084                                 return -1;
2085                         }
2086 #endif
2087
2088                         *last = this;
2089                         last = &(this->next);
2090                 } /* loop over "listen" directives in virtual servers */
2091         } /* loop over virtual servers */
2092
2093         /*
2094          *      If we're proxying requests, open the proxy FD.
2095          *      Otherwise, don't do anything.
2096          */
2097  do_proxy:
2098 #ifdef WITH_PROXY
2099         if (mainconfig.proxy_requests == TRUE) {
2100                 int             port = -1;
2101                 listen_socket_t *sock = NULL;
2102
2103                 /*
2104                  *      No sockets to receive packets, therefore
2105                  *      proxying is pointless.
2106                  */
2107                 if (!*head) return -1;
2108
2109                 if (defined_proxy) goto check_home_servers;
2110
2111                 /*
2112                  *      Find the first authentication port,
2113                  *      and use it
2114                  */
2115                 for (this = *head; this != NULL; this = this->next) {
2116                         if (this->type == RAD_LISTEN_AUTH) {
2117                                 sock = this->data;
2118                                 if (server_ipaddr.af == AF_UNSPEC) {
2119                                         server_ipaddr = sock->ipaddr;
2120                                 }
2121                                 port = sock->port + 2; /* skip acct port */
2122                                 break;
2123                         }
2124 #ifdef WITH_VMPS
2125                         if (this->type == RAD_LISTEN_VQP) {
2126                                 sock = this->data;
2127                                 if (server_ipaddr.af == AF_UNSPEC) {
2128                                         server_ipaddr = sock->ipaddr;
2129                                 }
2130                                 port = sock->port + 1;
2131                                 break;
2132                         }
2133 #endif
2134                 }
2135
2136                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
2137
2138                 /*
2139                  *      Address is still unspecified, use IPv4.
2140                  */
2141                 if (server_ipaddr.af == AF_UNSPEC) {
2142                         server_ipaddr.af = AF_INET;
2143                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
2144                 }
2145
2146                 this = listen_alloc(RAD_LISTEN_PROXY);
2147                 sock = this->data;
2148
2149                 /*
2150                  *      Create the first proxy socket.
2151                  */
2152                 sock->ipaddr = server_ipaddr;
2153
2154                 /*
2155                  *      Try to find a proxy port (value doesn't matter)
2156                  */
2157                 for (sock->port = port;
2158                      sock->port < 64000;
2159                      sock->port++) {
2160                         if (listen_bind(this) == 0) {
2161                                 *last = this;
2162                                 last = &(this->next); /* just in case */
2163                                 break;
2164                         }
2165                 }
2166
2167                 if (sock->port >= 64000) {
2168                         listen_free(head);
2169                         listen_free(&this);
2170                         radlog(L_ERR, "Failed to open socket for proxying");
2171                         return -1;
2172                 }
2173                 
2174                 /*
2175                  *      Create *additional* proxy listeners, based
2176                  *      on their src_ipaddr.
2177                  */
2178         check_home_servers:
2179                 if (home_server_create_listeners(*head) != 0) return -1;
2180         }
2181 #endif
2182
2183         return 0;
2184 }
2185
2186 /*
2187  *      Free a linked list of listeners;
2188  */
2189 void listen_free(rad_listen_t **head)
2190 {
2191         rad_listen_t *this;
2192
2193         if (!head || !*head) return;
2194
2195         this = *head;
2196         while (this) {
2197                 rad_listen_t *next = this->next;
2198
2199                 /*
2200                  *      Other code may have eaten the FD.
2201                  */
2202                 if (this->fd >= 0) close(this->fd);
2203
2204                 if (master_listen[this->type].free) {
2205                         master_listen[this->type].free(this);
2206                 }
2207                 free(this->data);
2208                 free(this);
2209
2210                 this = next;
2211         }
2212
2213         *head = NULL;
2214 }
2215
2216 #ifdef WITH_STATS
2217 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
2218                                           int port)
2219 {
2220         rad_listen_t *this;
2221
2222         for (this = mainconfig.listen; this != NULL; this = this->next) {
2223                 listen_socket_t *sock;
2224
2225                 if ((this->type != RAD_LISTEN_AUTH) &&
2226                     (this->type != RAD_LISTEN_ACCT)) continue;
2227                 
2228                 sock = this->data;
2229
2230                 if ((sock->port == port) &&
2231                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
2232                         return sock->clients;
2233                 }
2234         }
2235
2236         return NULL;
2237 }
2238 #endif
2239
2240 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
2241 {
2242         rad_listen_t *this;
2243
2244         for (this = mainconfig.listen; this != NULL; this = this->next) {
2245                 listen_socket_t *sock;
2246
2247                 /*
2248                  *      FIXME: For TCP, ignore the *secondary*
2249                  *      listeners associated with the main socket.
2250                  */
2251                 if ((this->type != RAD_LISTEN_AUTH) &&
2252                     (this->type != RAD_LISTEN_ACCT)) continue;
2253                 
2254                 sock = this->data;
2255
2256                 if ((sock->port == port) &&
2257                     (fr_ipaddr_cmp(ipaddr, &sock->ipaddr) == 0)) {
2258                         return this;
2259                 }
2260
2261                 if ((sock->port == port) &&
2262                     ((sock->ipaddr.af == AF_INET) &&
2263                      (sock->ipaddr.ipaddr.ip4addr.s_addr == INADDR_ANY))) {
2264                         return this;
2265                 }
2266
2267 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2268                 if ((sock->port == port) &&
2269                     (sock->ipaddr.af == AF_INET6) &&
2270                     (IN6_IS_ADDR_UNSPECIFIED(&sock->ipaddr.ipaddr.ip6addr))) {
2271                         return this;
2272                 }
2273 #endif
2274         }
2275
2276         return NULL;
2277 }