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