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