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