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