Correct documentation, and allow client lists without the
[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/radius_snmp.h>
29 #include <freeradius-devel/modules.h>
30 #include <freeradius-devel/rad_assert.h>
31 #include <freeradius-devel/vqp.h>
32
33 #include <freeradius-devel/vmps.h>
34 #include <freeradius-devel/detail.h>
35
36 #ifdef HAVE_SYS_RESOURCE_H
37 #include <sys/resource.h>
38 #endif
39
40 #ifdef HAVE_NET_IF_H
41 #include <net/if.h>
42 #endif
43
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47
48
49 /*
50  *      We'll use this below.
51  */
52 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
53 typedef void (*rad_listen_free_t)(rad_listen_t *);
54
55 typedef struct rad_listen_master_t {
56         rad_listen_parse_t      parse;
57         rad_listen_free_t       free;
58         rad_listen_recv_t       recv;
59         rad_listen_send_t       send;
60         rad_listen_print_t      print;
61         rad_listen_encode_t     encode;
62         rad_listen_decode_t     decode;
63 } rad_listen_master_t;
64
65 typedef struct listen_socket_t {
66         /*
67          *      For normal sockets.
68          */
69         fr_ipaddr_t     ipaddr;
70         int             port;
71         RADCLIENT_LIST  *clients;
72 } listen_socket_t;
73
74 /*
75  *      Find a per-socket client.
76  */
77 RADCLIENT *client_listener_find(const rad_listen_t *listener,
78                                        const fr_ipaddr_t *ipaddr)
79 {
80         const RADCLIENT_LIST *clients;
81
82         rad_assert(listener != NULL);
83         rad_assert(ipaddr != NULL);
84
85         rad_assert((listener->type == RAD_LISTEN_AUTH) ||
86                    (listener->type == RAD_LISTEN_ACCT) ||
87                    (listener->type == RAD_LISTEN_VQP));
88
89         clients = ((listen_socket_t *)listener->data)->clients;
90
91         /*
92          *      This HAS to have been initialized previously.
93          */
94         rad_assert(clients != NULL);
95
96         return client_find(clients, ipaddr);
97 }
98
99 static int listen_bind(rad_listen_t *this);
100
101
102 /*
103  *      Process and reply to a server-status request.
104  *      Like rad_authenticate and rad_accounting this should
105  *      live in it's own file but it's so small we don't bother.
106  */
107 static int rad_status_server(REQUEST *request)
108 {
109         int rcode = RLM_MODULE_OK;
110         DICT_VALUE *dval;
111
112         switch (request->listener->type) {
113         case RAD_LISTEN_AUTH:
114                 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
115                 if (dval) {
116                         rcode = module_authorize(dval->value, request);
117                 } else {
118                         rcode = RLM_MODULE_OK;
119                 }
120
121                 switch (rcode) {
122                 case RLM_MODULE_OK:
123                 case RLM_MODULE_UPDATED:
124                         request->reply->code = PW_AUTHENTICATION_ACK;
125                         break;
126
127                 case RLM_MODULE_FAIL:
128                 case RLM_MODULE_HANDLED:
129                         request->reply->code = 0; /* don't reply */
130                         break;
131
132                 default:
133                 case RLM_MODULE_REJECT:
134                         request->reply->code = PW_AUTHENTICATION_REJECT;
135                         break;
136                 }
137                 break;
138
139         case RAD_LISTEN_ACCT:
140                 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
141                 if (dval) {
142                         rcode = module_accounting(dval->value, request);
143                 } else {
144                         rcode = RLM_MODULE_OK;
145                 }
146
147                 switch (rcode) {
148                 case RLM_MODULE_OK:
149                 case RLM_MODULE_UPDATED:
150                         request->reply->code = PW_ACCOUNTING_RESPONSE;
151                         break;
152
153                 default:
154                         request->reply->code = 0; /* don't reply */
155                         break;
156                 }
157                 break;
158
159         default:
160                 return 0;
161         }
162
163         return 0;
164 }
165
166
167 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
168 {
169         listen_socket_t *sock = this->data;
170         const char *name;
171         char ip_buf[256];
172
173         if ((sock->ipaddr.af == AF_INET) &&
174             (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
175                 strcpy(ip_buf, "*");
176         } else {
177                 ip_ntoh(&sock->ipaddr, ip_buf, sizeof(ip_buf));
178         }
179
180         switch (this->type) {
181         case RAD_LISTEN_AUTH:
182                 name = "authentication";
183                 break;
184
185         case RAD_LISTEN_ACCT:
186                 name = "accounting";
187                 break;
188
189         case RAD_LISTEN_PROXY:
190                 name = "proxy";
191                 break;
192
193 #ifdef WITH_VMPS
194         case RAD_LISTEN_VQP:
195                 name = "vmps";
196                 break;
197 #endif
198
199         default:
200                 name = "??";
201                 break;
202         }
203
204         if (!this->server) {
205                 return snprintf(buffer, bufsize, "%s address %s port %d",
206                                 name, ip_buf, sock->port);
207         }
208
209         return snprintf(buffer, bufsize, "%s address %s port %d as server %s",
210                         name, ip_buf, sock->port, this->server);
211 }
212
213
214 /*
215  *      Parse an authentication or accounting socket.
216  */
217 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
218 {
219         int             rcode;
220         int             listen_port;
221         fr_ipaddr_t     ipaddr;
222         listen_socket_t *sock = this->data;
223         char            *section_name = NULL;
224         CONF_SECTION    *client_cs, *parentcs;
225
226         /*
227          *      Try IPv4 first
228          */
229         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
230         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
231                               &ipaddr.ipaddr.ip4addr, NULL);
232         if (rcode < 0) return -1;
233
234         if (rcode == 0) { /* successfully parsed IPv4 */
235                 ipaddr.af = AF_INET;
236
237         } else {        /* maybe IPv6? */
238                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
239                                       &ipaddr.ipaddr.ip6addr, NULL);
240                 if (rcode < 0) return -1;
241
242                 if (rcode == 1) {
243                         cf_log_err(cf_sectiontoitem(cs),
244                                    "No address specified in listen section");
245                         return -1;
246                 }
247                 ipaddr.af = AF_INET6;
248         }
249
250         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
251                               &listen_port, "0");
252         if (rcode < 0) return -1;
253
254         if ((listen_port < 0) || (listen_port > 65500)) {
255                         cf_log_err(cf_sectiontoitem(cs),
256                                    "Invalid value for \"port\"");
257                         return -1;
258         }
259
260         sock->ipaddr = ipaddr;
261         sock->port = listen_port;
262
263         /*
264          *      And bind it to the port.
265          */
266         if (listen_bind(this) < 0) {
267                 char buffer[128];
268                 cf_log_err(cf_sectiontoitem(cs),
269                            "Error binding to port for %s port %d",
270                            ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
271                            sock->port);
272                 return -1;
273         }
274
275         /*
276          *      If we can bind to interfaces, do so,
277          *      else don't.
278          */
279         if (cf_pair_find(cs, "interface")) {
280 #ifndef SO_BINDTODEVICE
281                 cf_log_err(cf_sectiontoitem(cs),
282                            "System does not support binding to interfaces.  Delete this line from the configuration file.");
283                 return -1;
284 #else
285                 const char *value;
286                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
287                 struct ifreq ifreq;
288
289                 rad_assert(cp != NULL);
290                 value = cf_pair_value(cp);
291                 if (!value) {
292                         cf_log_err(cf_sectiontoitem(cs),
293                                    "No interface name given");
294                         return -1;
295                 }
296
297                 strcpy(ifreq.ifr_name, value);
298
299                 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
300                                (char *)&ifreq, sizeof(ifreq)) < 0) {
301                         cf_log_err(cf_sectiontoitem(cs),
302                                    "Failed binding to interface %s: %s",
303                                    value, strerror(errno));
304                         return -1;
305                 } /* else it worked. */
306 #endif
307         }
308
309         /*
310          *      Proxy sockets don't have clients.
311          */
312         if (this->type == RAD_LISTEN_PROXY) return 0;
313         
314         /*
315          *      The more specific configurations are preferred to more
316          *      generic ones.
317          */
318         client_cs = NULL;
319         parentcs = cf_top_section(cs);
320         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
321                               &section_name, NULL);
322         if (rcode < 0) return -1; /* bad string */
323         if (rcode == 0) {
324                 /*
325                  *      Explicit list given: use it.
326                  */
327                 client_cs = cf_section_sub_find_name2(parentcs,
328                                                       "clients",
329                                                       section_name);
330                 if (!client_cs) {
331                         client_cs = cf_section_find(section_name);
332                 }
333                 if (!client_cs) {
334                         cf_log_err(cf_sectiontoitem(cs),
335                                    "Failed to find clients %s {...}",
336                                    section_name);
337                         free(section_name);
338                         return -1;
339                 }
340                 free(section_name);
341         } /* else there was no "clients = " entry. */
342
343         if (!client_cs) {
344                 CONF_SECTION *server_cs;
345
346                 server_cs = cf_section_sub_find_name2(parentcs,
347                                                       "server",
348                                                       this->server);
349                 /*
350                  *      Found a "server foo" section.  If there are clients
351                  *      in it, use them.
352                  */
353                 if (server_cs &&
354                     (cf_section_sub_find(server_cs, "client") != NULL)) {
355                         client_cs = server_cs;
356                 }
357         }
358
359         /*
360          *      Still nothing.  Look for global clients.
361          */
362         if (!client_cs) client_cs = parentcs;
363
364         sock->clients = clients_parse_section(client_cs);
365         if (!sock->clients) {
366                 cf_log_err(cf_sectiontoitem(cs),
367                            "Failed to find any clients for this listen section");
368                 return -1;
369         }
370
371         return 0;
372 }
373
374 /*
375  *      Send an authentication response packet
376  */
377 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
378 {
379         rad_assert(request->listener == listener);
380         rad_assert(listener->send == auth_socket_send);
381
382         return rad_send(request->reply, request->packet,
383                         request->client->secret);
384 }
385
386
387 /*
388  *      Send an accounting response packet (or not)
389  */
390 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
391 {
392         rad_assert(request->listener == listener);
393         rad_assert(listener->send == acct_socket_send);
394
395         /*
396          *      Accounting reject's are silently dropped.
397          *
398          *      We do it here to avoid polluting the rest of the
399          *      code with this knowledge
400          */
401         if (request->reply->code == 0) return 0;
402
403         return rad_send(request->reply, request->packet,
404                         request->client->secret);
405 }
406
407
408 /*
409  *      Send a packet to a home server.
410  *
411  *      FIXME: have different code for proxy auth & acct!
412  */
413 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
414 {
415         listen_socket_t *sock = listener->data;
416
417         rad_assert(request->proxy_listener == listener);
418         rad_assert(listener->send == proxy_socket_send);
419
420         request->proxy->src_ipaddr = sock->ipaddr;
421         request->proxy->src_port = sock->port;
422
423         return rad_send(request->proxy, request->packet,
424                         request->home_server->secret);
425 }
426
427
428 /*
429  *      Check if an incoming request is "ok"
430  *
431  *      It takes packets, not requests.  It sees if the packet looks
432  *      OK.  If so, it does a number of sanity checks on it.
433   */
434 static int auth_socket_recv(rad_listen_t *listener,
435                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
436 {
437         ssize_t         rcode;
438         int             code, src_port;
439         RADIUS_PACKET   *packet;
440         RAD_REQUEST_FUNP fun = NULL;
441         char            buffer[128];
442         RADCLIENT       *client;
443         fr_ipaddr_t     src_ipaddr;
444
445         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
446         if (rcode < 0) return 0;
447
448         RAD_SNMP_TYPE_INC(listener, total_requests);
449
450         if (rcode < 20) {       /* AUTH_HDR_LEN */
451                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
452                 return 0;
453         }
454
455         if ((client = client_listener_find(listener,
456                                            &src_ipaddr)) == NULL) {
457                 rad_recv_discard(listener->fd);
458                 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
459
460                 if (debug_flag > 0) {
461                         char name[1024];
462
463                         listener->print(listener, name, sizeof(name));
464
465                         /*
466                          *      This is debugging rather than logging, so that
467                          *      DoS attacks don't affect us.
468                          */
469                         DEBUG("Ignoring request to %s from unknown client %s port %d",
470                               name,
471                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
472                                         buffer, sizeof(buffer)), src_port);
473                 }
474
475                 return 0;
476         }
477
478         /*
479          *      Some sanity checks, based on the packet code.
480          */
481         switch(code) {
482         case PW_AUTHENTICATION_REQUEST:
483                 RAD_SNMP_CLIENT_INC(listener, client, requests);
484                 fun = rad_authenticate;
485                 break;
486
487         case PW_STATUS_SERVER:
488                 if (!mainconfig.status_server) {
489                         rad_recv_discard(listener->fd);
490                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
491                         RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
492                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
493                         return 0;
494                 }
495                 fun = rad_status_server;
496                 break;
497
498         default:
499                 rad_recv_discard(listener->fd);
500                 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
501                 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
502
503                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
504                       code, client->shortname, src_port);
505                 return 0;
506                 break;
507         } /* switch over packet types */
508
509         /*
510          *      Now that we've sanity checked everything, receive the
511          *      packet.
512          */
513         packet = rad_recv(listener->fd, client->message_authenticator);
514         if (!packet) {
515                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
516                 DEBUG("%s", librad_errstr);
517                 return 0;
518         }
519
520         if (!received_request(listener, packet, prequest, client)) {
521                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
522                 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
523                 rad_free(&packet);
524                 return 0;
525         }
526
527         *pfun = fun;
528         return 1;
529 }
530
531
532 /*
533  *      Receive packets from an accounting socket
534  */
535 static int acct_socket_recv(rad_listen_t *listener,
536                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
537 {
538         ssize_t         rcode;
539         int             code, src_port;
540         RADIUS_PACKET   *packet;
541         RAD_REQUEST_FUNP fun = NULL;
542         char            buffer[128];
543         RADCLIENT       *client;
544         fr_ipaddr_t     src_ipaddr;
545
546         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
547         if (rcode < 0) return 0;
548
549         RAD_SNMP_TYPE_INC(listener, total_requests);
550
551         if (rcode < 20) {       /* AUTH_HDR_LEN */
552                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
553                 return 0;
554         }
555
556         if ((client = client_listener_find(listener,
557                                            &src_ipaddr)) == NULL) {
558                 rad_recv_discard(listener->fd);
559                 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
560
561                 /*
562                  *      This is debugging rather than logging, so that
563                  *      DoS attacks don't affect us.
564                  */
565                 if (debug_flag > 0) {
566                         char name[1024];
567
568                         listener->print(listener, name, sizeof(name));
569
570                         DEBUG("Ignoring request to %s from unknown client %s port %d",
571                               name,
572                               inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
573                                         buffer, sizeof(buffer)), src_port);
574                 }
575
576                 return 0;
577         }
578
579         /*
580          *      Some sanity checks, based on the packet code.
581          */
582         switch(code) {
583         case PW_ACCOUNTING_REQUEST:
584                 RAD_SNMP_CLIENT_INC(listener, client, requests);
585                 fun = rad_accounting;
586                 break;
587
588         case PW_STATUS_SERVER:
589                 if (!mainconfig.status_server) {
590                         rad_recv_discard(listener->fd);
591                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
592                         RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
593
594                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
595                         return 0;
596                 }
597                 fun = rad_status_server;
598                 break;
599
600         default:
601                 rad_recv_discard(listener->fd);
602                 RAD_SNMP_TYPE_INC(listener, total_unknown_types);
603                 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
604
605                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
606                       code, client->shortname, src_port);
607                 return 0;
608         } /* switch over packet types */
609
610         /*
611          *      Now that we've sanity checked everything, receive the
612          *      packet.
613          */
614         packet = rad_recv(listener->fd, 0);
615         if (!packet) {
616                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
617                 radlog(L_ERR, "%s", librad_errstr);
618                 return 0;
619         }
620
621         /*
622          *      There can be no duplicate accounting packets.
623          */
624         if (!received_request(listener, packet, prequest, client)) {
625                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
626                 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
627                 rad_free(&packet);
628                 return 0;
629         }
630
631         *pfun = fun;
632         return 1;
633 }
634
635
636 /*
637  *      Recieve packets from a proxy socket.
638  */
639 static int proxy_socket_recv(rad_listen_t *listener,
640                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
641 {
642         REQUEST         *request;
643         RADIUS_PACKET   *packet;
644         RAD_REQUEST_FUNP fun = NULL;
645         char            buffer[128];
646
647         packet = rad_recv(listener->fd, 0);
648         if (!packet) {
649                 radlog(L_ERR, "%s", librad_errstr);
650                 return 0;
651         }
652
653         /*
654          *      FIXME: Client MIB updates?
655          */
656         switch(packet->code) {
657         case PW_AUTHENTICATION_ACK:
658         case PW_ACCESS_CHALLENGE:
659         case PW_AUTHENTICATION_REJECT:
660                 fun = rad_authenticate;
661                 break;
662
663         case PW_ACCOUNTING_RESPONSE:
664                 fun = rad_accounting;
665                 break;
666
667         default:
668                 /*
669                  *      FIXME: Update MIB for packet types?
670                  */
671                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
672                        "from home server %s port %d - ID %d : IGNORED",
673                        packet->code,
674                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
675                        packet->src_port, packet->id);
676                 rad_free(&packet);
677                 return 0;
678         }
679
680         request = received_proxy_response(packet);
681         if (!request) {
682                 return 0;
683         }
684
685         rad_assert(fun != NULL);
686         *pfun = fun;
687         *prequest = request;
688
689         return 1;
690 }
691
692
693 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
694 {
695         if (!request->reply->code) return 0;
696
697         rad_encode(request->reply, request->packet,
698                    request->client->secret);
699         rad_sign(request->reply, request->packet,
700                  request->client->secret);
701
702         return 0;
703 }
704
705
706 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
707 {
708         if (rad_verify(request->packet, NULL,
709                        request->client->secret) < 0) {
710                 return -1;
711         }
712
713         return rad_decode(request->packet, NULL,
714                           request->client->secret);
715 }
716
717 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
718 {
719         rad_encode(request->proxy, NULL, request->home_server->secret);
720         rad_sign(request->proxy, NULL, request->home_server->secret);
721
722         return 0;
723 }
724
725
726 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
727 {
728         if (rad_verify(request->proxy_reply, request->proxy,
729                        request->home_server->secret) < 0) {
730                 return -1;
731         }
732
733         return rad_decode(request->proxy_reply, request->proxy,
734                            request->home_server->secret);
735 }
736
737
738 #ifdef WITH_SNMP
739 static int radius_snmp_recv(rad_listen_t *listener,
740                             UNUSED RAD_REQUEST_FUNP *pfun,
741                             UNUSED REQUEST **prequest)
742 {
743         if ((rad_snmp.smux_fd >= 0) &&
744             (rad_snmp.smux_event == SMUX_READ)) {
745                 smux_read();
746         }
747
748         /*
749          *  If we've got to re-connect, then do so now,
750          *  before calling select again.
751          */
752         if (rad_snmp.smux_event == SMUX_CONNECT) {
753                 smux_connect();
754         }
755
756         /*
757          *      Reset this every time, as the smux connect may have
758          *      opened a new socket.
759          */
760         listener->fd = rad_snmp.smux_fd;
761
762         return 0;
763 }
764
765
766 static int radius_snmp_print(UNUSED rad_listen_t *this, char *buffer, size_t bufsize)
767 {
768         return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
769 }
770
771 #endif
772
773 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
774         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
775
776         /* proxying */
777         { common_socket_parse, NULL,
778           proxy_socket_recv, proxy_socket_send,
779           socket_print, proxy_socket_encode, proxy_socket_decode },
780
781         /* authentication */
782         { common_socket_parse, NULL,
783           auth_socket_recv, auth_socket_send,
784           socket_print, client_socket_encode, client_socket_decode },
785
786         /* accounting */
787         { common_socket_parse, NULL,
788           acct_socket_recv, acct_socket_send,
789           socket_print, client_socket_encode, client_socket_decode},
790
791         /* detail */
792         { detail_parse, detail_free,
793           detail_recv, detail_send,
794           detail_print, detail_encode, detail_decode },
795
796 #ifdef WITH_VMPS
797         /* vlan query protocol */
798         { common_socket_parse, NULL,
799           vqp_socket_recv, vqp_socket_send,
800           socket_print, vqp_socket_encode, vqp_socket_decode },
801 #else
802         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
803 #endif
804
805         { NULL, NULL, NULL, NULL, NULL, NULL, NULL}     /* RAD_LISTEN_SNMP */
806 };
807
808
809
810 /*
811  *      Binds a listener to a socket.
812  */
813 static int listen_bind(rad_listen_t *this)
814 {
815         listen_socket_t *sock = this->data;
816
817         /*
818          *      If the port is zero, then it means the appropriate
819          *      thing from /etc/services.
820          */
821         if (sock->port == 0) {
822                 struct servent  *svp;
823
824                 switch (this->type) {
825                 case RAD_LISTEN_AUTH:
826                         svp = getservbyname ("radius", "udp");
827                         if (svp != NULL) {
828                                 sock->port = ntohs(svp->s_port);
829                         } else {
830                                 sock->port = PW_AUTH_UDP_PORT;
831                         }
832                         break;
833
834                 case RAD_LISTEN_ACCT:
835                         svp = getservbyname ("radacct", "udp");
836                         if (svp != NULL) {
837                                 sock->port = ntohs(svp->s_port);
838                         } else {
839                                 sock->port = PW_ACCT_UDP_PORT;
840                         }
841                         break;
842
843                 case RAD_LISTEN_PROXY:
844                         sock->port = 0;
845                         break;
846
847 #ifdef WITH_VMPS
848                 case RAD_LISTEN_VQP:
849                         sock->port = 1589;
850                         break;
851 #endif
852
853                 default:
854                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
855                         return -1;
856                 }
857         }
858
859         this->fd = fr_socket(&sock->ipaddr, sock->port);
860         if (this->fd < 0) {
861                 radlog(L_ERR, "ERROR: Failed to open socket: %s",
862                        librad_errstr);
863                 return -1;
864         }
865
866         /*
867          *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
868          *      kernel instead binds us to a 1.2.3.4.  If this
869          *      happens, notice, and remember our real IP.
870          */
871         {
872                 struct sockaddr_storage src;
873                 socklen_t               sizeof_src = sizeof(src);
874
875                 memset(&src, 0, sizeof_src);
876                 if (getsockname(this->fd, (struct sockaddr *) &src,
877                                 &sizeof_src) < 0) {
878                         radlog(L_ERR, "Failed getting socket name: %s",
879                                strerror(errno));
880                         return -1;
881                 }
882
883                 if (src.ss_family == AF_INET) {
884                         struct sockaddr_in      *s4;
885                         
886                         s4 = (struct sockaddr_in *)&src;
887                         sock->ipaddr.ipaddr.ip4addr = s4->sin_addr;
888                         sock->port = ntohs(s4->sin_port);
889                         
890 #ifdef HAVE_STRUCT_SOCKADDR_IN6
891                 } else if (src.ss_family == AF_INET6) {
892                         struct sockaddr_in6     *s6;
893                         
894                         s6 = (struct sockaddr_in6 *)&src;
895                         sock->ipaddr.ipaddr.ip6addr = s6->sin6_addr;
896                         sock->port = ntohs(s6->sin6_port);
897 #endif
898                 } else {
899                         radlog(L_ERR, "Socket has unsupported address family");
900                         return -1;
901                 }
902         }
903
904 #ifdef O_NONBLOCK
905         {
906                 int flags;
907                 
908                 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  {
909                         radlog(L_ERR, "Failure getting socket flags: %s)\n",
910                                strerror(errno));
911                         return -1;
912                 }
913                 
914                 flags |= O_NONBLOCK;
915                 if( fcntl(this->fd, F_SETFL, flags) < 0) {
916                         radlog(L_ERR, "Failure setting socket flags: %s)\n",
917                                strerror(errno));
918                         return -1;
919                 }
920         }
921 #endif
922
923         return 0;
924 }
925
926
927 /*
928  *      Allocate & initialize a new listener.
929  */
930 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
931 {
932         rad_listen_t *this;
933
934         this = rad_malloc(sizeof(*this));
935         memset(this, 0, sizeof(*this));
936
937         this->type = type;
938         this->recv = master_listen[this->type].recv;
939         this->send = master_listen[this->type].send;
940         this->print = master_listen[this->type].print;
941         this->encode = master_listen[this->type].encode;
942         this->decode = master_listen[this->type].decode;
943
944         switch (type) {
945         case RAD_LISTEN_AUTH:
946         case RAD_LISTEN_ACCT:
947         case RAD_LISTEN_PROXY:
948         case RAD_LISTEN_VQP:
949                 this->data = rad_malloc(sizeof(listen_socket_t));
950                 memset(this->data, 0, sizeof(listen_socket_t));
951                 break;
952
953         case RAD_LISTEN_DETAIL:
954                 this->data = NULL;
955                 break;
956
957         default:
958                 rad_assert("Unsupported option!" == NULL);
959                 break;
960         }
961
962         return this;
963 }
964
965
966 /*
967  *      Externally visible function for creating a new proxy LISTENER.
968  *
969  *      For now, don't take ipaddr or port.
970  *
971  *      Not thread-safe, but all calls to it are protected by the
972  *      proxy mutex in request_list.c
973  */
974 rad_listen_t *proxy_new_listener()
975 {
976         int last_proxy_port, port;
977         rad_listen_t *this, *tmp, **last;
978         listen_socket_t *sock, *old;
979
980         this = listen_alloc(RAD_LISTEN_PROXY);
981
982         /*
983          *      Find an existing proxy socket to copy.
984          *
985          *      FIXME: Make it per-realm, or per-home server!
986          */
987         last_proxy_port = 0;
988         old = NULL;
989         last = &mainconfig.listen;
990         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
991                 if (tmp->type == RAD_LISTEN_PROXY) {
992                         sock = tmp->data;
993                         if (sock->port > last_proxy_port) {
994                                 last_proxy_port = sock->port + 1;
995                         }
996                         if (!old) old = sock;
997                 }
998
999                 last = &(tmp->next);
1000         }
1001
1002         if (!old) {
1003                 listen_free(&this);
1004                 return NULL;    /* This is a serious error. */
1005         }
1006
1007         /*
1008          *      FIXME: find a new IP address to listen on?
1009          *
1010          *      This could likely be done in the "home server"
1011          *      configuration, to have per-home-server source IP's.
1012          */
1013         sock = this->data;
1014         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1015
1016         /*
1017          *      Keep going until we find an unused port.
1018          */
1019         for (port = last_proxy_port; port < 64000; port++) {
1020                 sock->port = port;
1021                 if (listen_bind(this) == 0) {
1022                         /*
1023                          *      Add the new listener to the list of
1024                          *      listeners.
1025                          */
1026                         *last = this;
1027                         return this;
1028                 }
1029         }
1030
1031         listen_free(&this);
1032         return NULL;
1033 }
1034
1035
1036 static const FR_NAME_NUMBER listen_compare[] = {
1037         { "auth",       RAD_LISTEN_AUTH },
1038         { "acct",       RAD_LISTEN_ACCT },
1039         { "detail",     RAD_LISTEN_DETAIL },
1040         { "proxy",      RAD_LISTEN_PROXY },
1041 #ifdef WITH_VMPS
1042         { "vmps",       RAD_LISTEN_VQP },
1043 #endif
1044         { NULL, 0 },
1045 };
1046
1047
1048 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1049 {
1050         int             type, rcode;
1051         char            *listen_type;
1052         rad_listen_t    *this;
1053
1054         listen_type = NULL;
1055         
1056         cf_log_info(cs, "listen {");
1057
1058         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1059                               &listen_type, "");
1060         if (rcode < 0) return NULL;
1061         if (rcode == 1) {
1062                 free(listen_type);
1063                 cf_log_err(cf_sectiontoitem(cs),
1064                            "No type specified in listen section");
1065                 return NULL;
1066         }
1067
1068         type = fr_str2int(listen_compare, listen_type,
1069                             RAD_LISTEN_NONE);
1070         if (type == RAD_LISTEN_NONE) {
1071                 cf_log_err(cf_sectiontoitem(cs),
1072                            "Invalid type \"%s\" in listen section.",
1073                            listen_type);
1074                 free(listen_type);
1075                 return NULL;
1076         }
1077         free(listen_type);
1078         
1079         /*
1080          *      Allow listen sections in the default config to
1081          *      refer to a server.
1082          */
1083         if (!server) {
1084                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1085                                       &server, NULL);
1086                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1087                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1088                                               &server, NULL);
1089                 }
1090                 if (rcode < 0) return NULL;
1091         }
1092
1093         /*
1094          *      Set up cross-type data.
1095          */
1096         this = listen_alloc(type);
1097         this->server = server;
1098         this->fd = -1;
1099
1100         /*
1101          *      Call per-type parser.
1102          */
1103         if (master_listen[type].parse(cs, this) < 0) {
1104                 listen_free(&this);
1105                 return NULL;
1106         }
1107
1108         cf_log_info(cs, "}");
1109
1110         return this;
1111 }
1112
1113 /*
1114  *      Generate a list of listeners.  Takes an input list of
1115  *      listeners, too, so we don't close sockets with waiting packets.
1116  */
1117 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1118 {
1119         int             override = FALSE;
1120         int             rcode;
1121         CONF_SECTION    *cs;
1122         rad_listen_t    **last;
1123         rad_listen_t    *this;
1124         fr_ipaddr_t     server_ipaddr;
1125         int             auth_port = 0;
1126         int             defined_proxy = 0;
1127
1128         /*
1129          *      We shouldn't be called with a pre-existing list.
1130          */
1131         rad_assert(head && (*head == NULL));
1132
1133         last = head;
1134         server_ipaddr.af = AF_UNSPEC;
1135
1136         /*
1137          *      If the port is specified on the command-line,
1138          *      it over-rides the configuration file.
1139          *
1140          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1141          */
1142         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1143
1144         /*
1145          *      If the IP address was configured on the command-line,
1146          *      use that as the "bind_address"
1147          */
1148         if (mainconfig.myip.af != AF_UNSPEC) {
1149                 memcpy(&server_ipaddr, &mainconfig.myip,
1150                        sizeof(server_ipaddr));
1151                 override = TRUE;
1152                 goto bind_it;
1153         }
1154
1155         /*
1156          *      Else look for bind_address and/or listen sections.
1157          */
1158         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1159         rcode = cf_item_parse(config, "bind_address",
1160                               PW_TYPE_IPADDR,
1161                               &server_ipaddr.ipaddr.ip4addr, NULL);
1162         if (rcode < 0) return -1; /* error parsing it */
1163
1164         if (rcode == 0) { /* successfully parsed IPv4 */
1165                 listen_socket_t *sock;
1166                 server_ipaddr.af = AF_INET;
1167
1168                 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'.");
1169
1170         bind_it:
1171 #ifdef WITH_VMPS
1172                 if (strcmp(progname, "vmpsd") == 0) {
1173                         this = listen_alloc(RAD_LISTEN_VQP);
1174                         if (!auth_port) auth_port = 1589;
1175                 } else
1176 #endif
1177                         this = listen_alloc(RAD_LISTEN_AUTH);
1178
1179                 sock = this->data;
1180
1181                 sock->ipaddr = server_ipaddr;
1182                 sock->port = auth_port;
1183
1184                 sock->clients = clients_parse_section(config);
1185                 if (!sock->clients) {
1186                         cf_log_err(cf_sectiontoitem(config),
1187                                    "Failed to find any clients for this listen section");
1188                         return -1;
1189                 }
1190
1191                 if (listen_bind(this) < 0) {
1192                         listen_free(&this);
1193                         listen_free(head);
1194                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1195                         return -1;
1196                 }
1197                 auth_port = sock->port; /* may have been updated in listen_bind */
1198                 if (override) {
1199                         cs = cf_section_sub_find_name2(config, "server",
1200                                                        mainconfig.name);
1201                         if (cs) this->server = mainconfig.name;
1202                 }
1203
1204                 *last = this;
1205                 last = &(this->next);
1206
1207 #ifdef WITH_VMPS
1208                 /*
1209                  *      No acct for vmpsd
1210                  */
1211                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1212 #endif
1213
1214                 /*
1215                  *      Open Accounting Socket.
1216                  *
1217                  *      If we haven't already gotten acct_port from
1218                  *      /etc/services, then make it auth_port + 1.
1219                  */
1220                 this = listen_alloc(RAD_LISTEN_ACCT);
1221                 sock = this->data;
1222
1223                 /*
1224                  *      Create the accounting socket.
1225                  *
1226                  *      The accounting port is always the
1227                  *      authentication port + 1
1228                  */
1229                 sock->ipaddr = server_ipaddr;
1230                 sock->port = auth_port + 1;
1231
1232                 sock->clients = clients_parse_section(config);
1233                 if (!sock->clients) {
1234                         cf_log_err(cf_sectiontoitem(config),
1235                                    "Failed to find any clients for this listen section");
1236                         return -1;
1237                 }
1238
1239                 if (listen_bind(this) < 0) {
1240                         listen_free(&this);
1241                         listen_free(head);
1242                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1243                         return -1;
1244                 }
1245
1246                 if (override) {
1247                         cs = cf_section_sub_find_name2(config, "server",
1248                                                        mainconfig.name);
1249                         if (cs) this->server = mainconfig.name;
1250                 }
1251
1252                 *last = this;
1253                 last = &(this->next);
1254
1255         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1256                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1257                        mainconfig.port);
1258                 return -1;
1259         }
1260
1261         /*
1262          *      They specified an IP on the command-line, ignore
1263          *      all listen sections except the one in '-n'.
1264          */
1265         if (mainconfig.myip.af != AF_UNSPEC) {
1266                 CONF_SECTION *subcs;
1267                 const char *name2 = cf_section_name2(cs);
1268
1269                 cs = cf_section_sub_find_name2(config, "server",
1270                                                mainconfig.name);
1271                 if (!cs) goto do_proxy;
1272
1273                 /*
1274                  *      Should really abstract this code...
1275                  */
1276                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1277                      subcs != NULL;
1278                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1279                         this = listen_parse(subcs, name2);
1280                         if (!this) {
1281                                 listen_free(head);
1282                                 return -1;
1283                         }
1284
1285                         if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1286                         
1287                         *last = this;
1288                         last = &(this->next);
1289                 } /* loop over "listen" directives in server <foo> */
1290
1291                 goto do_proxy;
1292         }
1293
1294         /*
1295          *      Walk through the "listen" sections, if they exist.
1296          */
1297         for (cs = cf_subsection_find_next(config, NULL, "listen");
1298              cs != NULL;
1299              cs = cf_subsection_find_next(config, cs, "listen")) {
1300                 this = listen_parse(cs, NULL);
1301                 if (!this) {
1302                         listen_free(head);
1303                         return -1;
1304                 }
1305
1306                 if (this->type == RAD_LISTEN_PROXY) defined_proxy = 1;
1307
1308                 *last = this;
1309                 last = &(this->next);
1310         }
1311
1312         /*
1313          *      Check virtual servers for "listen" sections, too.
1314          *
1315          *      FIXME: Move to virtual server init?
1316          */
1317         for (cs = cf_subsection_find_next(config, NULL, "server");
1318              cs != NULL;
1319              cs = cf_subsection_find_next(config, cs, "server")) {
1320                 CONF_SECTION *subcs;
1321                 const char *name2 = cf_section_name2(cs);
1322                 
1323                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1324                      subcs != NULL;
1325                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1326                         this = listen_parse(subcs, name2);
1327                         if (!this) {
1328                                 listen_free(head);
1329                                 return -1;
1330                         }
1331                         
1332                         if (this->type == RAD_LISTEN_PROXY) {
1333                                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
1334                                 listen_free(head);
1335                                 return -1;
1336                         }
1337
1338                         *last = this;
1339                         last = &(this->next);
1340                 } /* loop over "listen" directives in virtual servers */
1341         } /* loop over virtual servers */
1342
1343         /*
1344          *      If we're proxying requests, open the proxy FD.
1345          *      Otherwise, don't do anything.
1346          */
1347  do_proxy:
1348         if (mainconfig.proxy_requests == TRUE) {
1349                 int             port = -1;
1350                 listen_socket_t *sock = NULL;
1351
1352                 /*
1353                  *      No sockets to receive packets, therefore
1354                  *      proxying is pointless.
1355                  */
1356                 if (!*head) return -1;
1357
1358                 if (defined_proxy) goto do_snmp;
1359
1360                 /*
1361                  *      Find the first authentication port,
1362                  *      and use it
1363                  */
1364                 for (this = *head; this != NULL; this = this->next) {
1365                         if (this->type == RAD_LISTEN_AUTH) {
1366                                 sock = this->data;
1367                                 if (server_ipaddr.af == AF_UNSPEC) {
1368                                         server_ipaddr = sock->ipaddr;
1369                                 }
1370                                 port = sock->port + 2; /* skip acct port */
1371                                 break;
1372                         }
1373                         if (this->type == RAD_LISTEN_VQP) {
1374                                 sock = this->data;
1375                                 if (server_ipaddr.af == AF_UNSPEC) {
1376                                         server_ipaddr = sock->ipaddr;
1377                                 }
1378                                 port = sock->port + 1;
1379                                 break;
1380                         }
1381                 }
1382
1383                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
1384
1385                 /*
1386                  *      Address is still unspecified, use IPv4.
1387                  */
1388                 if (server_ipaddr.af == AF_UNSPEC) {
1389                         server_ipaddr.af = AF_INET;
1390                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1391                 }
1392
1393                 this = listen_alloc(RAD_LISTEN_PROXY);
1394                 sock = this->data;
1395
1396                 /*
1397                  *      Create the first proxy socket.
1398                  */
1399                 sock->ipaddr = server_ipaddr;
1400
1401                 /*
1402                  *      Try to find a proxy port (value doesn't matter)
1403                  */
1404                 for (sock->port = port;
1405                      sock->port < 64000;
1406                      sock->port++) {
1407                         if (listen_bind(this) == 0) {
1408                                 *last = this;
1409                                 last = &(this->next); /* just in case */
1410                                 break;
1411                         }
1412                 }
1413
1414                 if (sock->port >= 64000) {
1415                         listen_free(head);
1416                         listen_free(&this);
1417                         radlog(L_ERR, "Failed to open socket for proxying");
1418                         return -1;
1419                 }
1420         }
1421
1422  do_snmp:
1423 #ifdef WITH_SNMP
1424         if (radius_snmp_init(config)) {
1425                 this = rad_malloc(sizeof(*this));
1426                 memset(this, 0, sizeof(*this));
1427
1428                 this->type = RAD_LISTEN_SNMP;
1429                 this->fd = rad_snmp.smux_fd;
1430
1431                 this->recv = radius_snmp_recv;
1432                 this->print = radius_snmp_print;
1433
1434                 *last = this;
1435                 last = &(this->next);
1436         }
1437 #endif
1438
1439         return 0;
1440 }
1441
1442 /*
1443  *      Free a linked list of listeners;
1444  */
1445 void listen_free(rad_listen_t **head)
1446 {
1447         rad_listen_t *this;
1448
1449         if (!head || !*head) return;
1450
1451         this = *head;
1452         while (this) {
1453                 rad_listen_t *next = this->next;
1454
1455                 /*
1456                  *      Other code may have eaten the FD.
1457                  */
1458                 if (this->fd >= 0) close(this->fd);
1459
1460                 if (master_listen[this->type].free) {
1461                         master_listen[this->type].free(this);
1462                 }
1463                 free(this->data);
1464                 free(this);
1465
1466                 this = next;
1467         }
1468
1469         *head = NULL;
1470 }