Free memory after we're done using it, not before.
[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) return NULL;  /* This is a serious error. */
1007
1008         /*
1009          *      FIXME: find a new IP address to listen on?
1010          *
1011          *      This could likely be done in the "home server"
1012          *      configuration, to have per-home-server source IP's.
1013          */
1014         sock = this->data;
1015         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1016
1017         /*
1018          *      Keep going until we find an unused port.
1019          */
1020         for (port = last_proxy_port; port < 64000; port++) {
1021                 sock->port = port;
1022                 if (listen_bind(this) == 0) {
1023                         /*
1024                          *      Add the new listener to the list of
1025                          *      listeners.
1026                          */
1027                         *last = this;
1028                         return this;
1029                 }
1030         }
1031
1032         return NULL;
1033 }
1034
1035
1036 static const FR_NAME_NUMBER listen_compare[] = {
1037         { "auth",       RAD_LISTEN_AUTH },
1038         { "acct",       RAD_LISTEN_ACCT },
1039         { "detail",     RAD_LISTEN_DETAIL },
1040 #ifdef WITH_VMPS
1041         { "vmps",       RAD_LISTEN_VQP },
1042 #endif
1043         { NULL, 0 },
1044 };
1045
1046
1047 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1048 {
1049         int             type, rcode;
1050         char            *listen_type;
1051         rad_listen_t    *this;
1052
1053         listen_type = NULL;
1054         
1055         DEBUG2("listen {");
1056
1057         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1058                               &listen_type, "");
1059         if (rcode < 0) return NULL;
1060         if (rcode == 1) {
1061                 free(listen_type);
1062                 cf_log_err(cf_sectiontoitem(cs),
1063                            "No type specified in listen section");
1064                 return NULL;
1065         }
1066
1067         type = fr_str2int(listen_compare, listen_type,
1068                             RAD_LISTEN_NONE);
1069         if (type == RAD_LISTEN_NONE) {
1070                 cf_log_err(cf_sectiontoitem(cs),
1071                            "Invalid type \"%s\" in listen section.",
1072                            listen_type);
1073                 free(listen_type);
1074                 return NULL;
1075         }
1076         free(listen_type);
1077         
1078         /*
1079          *      Allow listen sections in the default config to
1080          *      refer to a server.
1081          */
1082         if (!server) {
1083                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
1084                                       &server, NULL);
1085                 if (rcode == 1) { /* compatiblity with 2.0-pre */
1086                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1087                                               &server, NULL);
1088                 }
1089                 if (rcode < 0) return NULL;
1090         }
1091
1092         /*
1093          *      Set up cross-type data.
1094          */
1095         this = listen_alloc(type);
1096         this->server = server;
1097         this->fd = -1;
1098
1099         /*
1100          *      Call per-type parser.
1101          */
1102         if (master_listen[type].parse(cs, this) < 0) {
1103                 listen_free(&this);
1104                 return NULL;
1105         }
1106
1107         DEBUG2("}");
1108
1109         return this;
1110 }
1111
1112 /*
1113  *      Generate a list of listeners.  Takes an input list of
1114  *      listeners, too, so we don't close sockets with waiting packets.
1115  */
1116 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1117 {
1118         int             rcode;
1119         CONF_SECTION    *cs;
1120         rad_listen_t    **last;
1121         rad_listen_t    *this;
1122         fr_ipaddr_t     server_ipaddr;
1123         int             auth_port = 0;
1124
1125         /*
1126          *      We shouldn't be called with a pre-existing list.
1127          */
1128         rad_assert(head && (*head == NULL));
1129
1130         last = head;
1131         server_ipaddr.af = AF_UNSPEC;
1132
1133         /*
1134          *      If the port is specified on the command-line,
1135          *      it over-rides the configuration file.
1136          *
1137          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1138          */
1139         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1140
1141         /*
1142          *      If the IP address was configured on the command-line,
1143          *      use that as the "bind_address"
1144          */
1145         if (mainconfig.myip.af != AF_UNSPEC) {
1146                 memcpy(&server_ipaddr, &mainconfig.myip,
1147                        sizeof(server_ipaddr));
1148                 goto bind_it;
1149         }
1150
1151         /*
1152          *      Else look for bind_address and/or listen sections.
1153          */
1154         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1155         rcode = cf_item_parse(config, "bind_address",
1156                               PW_TYPE_IPADDR,
1157                               &server_ipaddr.ipaddr.ip4addr, NULL);
1158         if (rcode < 0) return -1; /* error parsing it */
1159
1160         if (rcode == 0) { /* successfully parsed IPv4 */
1161                 listen_socket_t *sock;
1162                 server_ipaddr.af = AF_INET;
1163
1164                 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'.");
1165
1166         bind_it:
1167 #ifdef WITH_VMPS
1168                 if (strcmp(progname, "vmpsd") == 0) {
1169                         this = listen_alloc(RAD_LISTEN_VQP);
1170                         if (!auth_port) auth_port = 1589;
1171                 } else
1172 #endif
1173                         this = listen_alloc(RAD_LISTEN_AUTH);
1174
1175                 sock = this->data;
1176
1177                 sock->ipaddr = server_ipaddr;
1178                 sock->port = auth_port;
1179
1180                 if (listen_bind(this) < 0) {
1181                         listen_free(&this);
1182                         listen_free(head);
1183                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1184                         return -1;
1185                 }
1186                 auth_port = sock->port; /* may have been updated in listen_bind */
1187                 *last = this;
1188                 last = &(this->next);
1189
1190 #ifdef WITH_VMPS
1191                 /*
1192                  *      No acct for vmpsd
1193                  */
1194                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1195 #endif
1196
1197                 /*
1198                  *      Open Accounting Socket.
1199                  *
1200                  *      If we haven't already gotten acct_port from
1201                  *      /etc/services, then make it auth_port + 1.
1202                  */
1203                 this = listen_alloc(RAD_LISTEN_ACCT);
1204                 sock = this->data;
1205
1206                 /*
1207                  *      Create the accounting socket.
1208                  *
1209                  *      The accounting port is always the
1210                  *      authentication port + 1
1211                  */
1212                 sock->ipaddr = server_ipaddr;
1213                 sock->port = auth_port + 1;
1214
1215                 if (listen_bind(this) < 0) {
1216                         listen_free(&this);
1217                         listen_free(head);
1218                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1219                         return -1;
1220                 }
1221
1222                 *last = this;
1223                 last = &(this->next);
1224
1225         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1226                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1227                        mainconfig.port);
1228                 return -1;
1229         }
1230
1231         /*
1232          *      They specified an IP on the command-line, ignore
1233          *      all listen sections.
1234          */
1235         if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1236
1237         /*
1238          *      Walk through the "listen" sections, if they exist.
1239          */
1240         for (cs = cf_subsection_find_next(config, NULL, "listen");
1241              cs != NULL;
1242              cs = cf_subsection_find_next(config, cs, "listen")) {
1243                 this = listen_parse(cs, NULL);
1244                 if (!this) {
1245                         listen_free(head);
1246                         return -1;
1247                 }
1248
1249                 *last = this;
1250                 last = &(this->next);
1251         }
1252
1253         /*
1254          *      Check virtual servers for "listen" sections, too.
1255          *
1256          *      FIXME: Move to virtual server init?
1257          */
1258         for (cs = cf_subsection_find_next(config, NULL, "server");
1259              cs != NULL;
1260              cs = cf_subsection_find_next(config, cs, "server")) {
1261                 CONF_SECTION *subcs;
1262                 const char *name2 = cf_section_name2(cs);
1263                 
1264                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1265                      subcs != NULL;
1266                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1267                         this = listen_parse(subcs, name2);
1268                         if (!this) {
1269                                 listen_free(head);
1270                                 return -1;
1271                         }
1272                         
1273                         *last = this;
1274                         last = &(this->next);
1275                 } /* loop over "listen" directives in virtual servers */
1276         } /* loop over virtual servers */
1277
1278         /*
1279          *      If we're proxying requests, open the proxy FD.
1280          *      Otherwise, don't do anything.
1281          */
1282  do_proxy:
1283         if (mainconfig.proxy_requests == TRUE) {
1284                 int             port = -1;
1285                 listen_socket_t *sock = NULL;
1286
1287                 /*
1288                  *      No sockets to receive packets, therefore
1289                  *      proxying is pointless.
1290                  */
1291                 if (!*head) return -1;
1292
1293                 /*
1294                  *      If we previously had proxy sockets, copy them
1295                  *      to the new config.
1296                  */
1297                 if (mainconfig.listen != NULL) {
1298                         rad_listen_t *old, *next, **tail;
1299
1300                         tail = &mainconfig.listen;
1301                         for (old = mainconfig.listen;
1302                              old != NULL;
1303                              old = next) {
1304                                 next = old->next;
1305
1306                                 if (old->type != RAD_LISTEN_PROXY) {
1307                                         tail = &((*tail)->next);
1308                                         continue;
1309                                 }
1310
1311                                 *last = old;
1312                                 *tail = next;
1313                                 old->next = NULL;
1314                                 last = &(old->next);
1315                         }
1316
1317                         goto do_snmp;
1318                 }
1319
1320                 /*
1321                  *      Find the first authentication port,
1322                  *      and use it
1323                  */
1324                 for (this = *head; this != NULL; this = this->next) {
1325                         if (this->type == RAD_LISTEN_AUTH) {
1326                                 sock = this->data;
1327                                 if (server_ipaddr.af == AF_UNSPEC) {
1328                                         server_ipaddr = sock->ipaddr;
1329                                 }
1330                                 port = sock->port + 2; /* skip acct port */
1331                                 break;
1332                         }
1333                         if (this->type == RAD_LISTEN_VQP) {
1334                                 sock = this->data;
1335                                 if (server_ipaddr.af == AF_UNSPEC) {
1336                                         server_ipaddr = sock->ipaddr;
1337                                 }
1338                                 port = sock->port + 1;
1339                                 break;
1340                         }
1341                 }
1342
1343                 if (port < 0) port = 1024 + (fr_rand() & 0x1ff);
1344
1345                 /*
1346                  *      Address is still unspecified, use IPv4.
1347                  */
1348                 if (server_ipaddr.af == AF_UNSPEC) {
1349                         server_ipaddr.af = AF_INET;
1350                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1351                 }
1352
1353                 this = listen_alloc(RAD_LISTEN_PROXY);
1354                 sock = this->data;
1355
1356                 /*
1357                  *      Create the first proxy socket.
1358                  */
1359                 sock->ipaddr = server_ipaddr;
1360
1361                 /*
1362                  *      Try to find a proxy port (value doesn't matter)
1363                  */
1364                 for (sock->port = port;
1365                      sock->port < 64000;
1366                      sock->port++) {
1367                         if (listen_bind(this) == 0) {
1368                                 *last = this;
1369                                 last = &(this->next); /* just in case */
1370                                 break;
1371                         }
1372                 }
1373
1374                 if (sock->port >= 64000) {
1375                         listen_free(head);
1376                         listen_free(&this);
1377                         radlog(L_ERR, "Failed to open socket for proxying");
1378                         return -1;
1379                 }
1380         }
1381
1382  do_snmp:
1383 #ifdef WITH_SNMP
1384         if (radius_snmp_init(config)) {
1385                 /*
1386                  *      Forget about the old one.
1387                  */
1388                 for (this = mainconfig.listen;
1389                      this != NULL;
1390                      this = this->next) {
1391                         if (this->type != RAD_LISTEN_SNMP) continue;
1392                         this->fd = -1;
1393                 }
1394
1395                 this = rad_malloc(sizeof(*this));
1396                 memset(this, 0, sizeof(*this));
1397
1398                 this->type = RAD_LISTEN_SNMP;
1399                 this->fd = rad_snmp.smux_fd;
1400
1401                 this->recv = radius_snmp_recv;
1402                 this->print = radius_snmp_print;
1403
1404                 *last = this;
1405                 last = &(this->next);
1406         }
1407 #endif
1408
1409         return 0;
1410 }
1411
1412 /*
1413  *      Free a linked list of listeners;
1414  */
1415 void listen_free(rad_listen_t **head)
1416 {
1417         rad_listen_t *this;
1418
1419         if (!head || !*head) return;
1420
1421         this = *head;
1422         while (this) {
1423                 rad_listen_t *next = this->next;
1424
1425                 /*
1426                  *      Other code may have eaten the FD.
1427                  */
1428                 if (this->fd >= 0) close(this->fd);
1429
1430                 if (master_listen[this->type].free) {
1431                         master_listen[this->type].free(this);
1432                 }
1433                 free(this->data);
1434                 free(this);
1435
1436                 this = next;
1437         }
1438
1439         *head = NULL;
1440 }