e2f4f45847483b4b6de08aebbde47910ba97cb41
[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
35 #include <sys/resource.h>
36
37 #ifdef HAVE_NET_IF_H
38 #include <net/if.h>
39 #endif
40
41 #ifdef HAVE_SYS_STAT_H
42 #include <sys/stat.h>
43 #endif
44
45 #include <fcntl.h>
46
47 #define USEC (1000000)
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         lrad_ipaddr_t   ipaddr;
70         int             port;
71         RADCLIENT_LIST  *clients;
72 } listen_socket_t;
73
74 typedef struct listen_detail_t {
75         const char      *filename;
76         VALUE_PAIR      *vps;
77         FILE            *fp;
78         int             state;
79         time_t          timestamp;
80         lrad_ipaddr_t   client_ip;
81         int             load_factor; /* 1..100 */
82
83         int             has_rtt;
84         int             srtt;
85         int             rttvar;
86         int             delay_time;
87         struct timeval  last_packet;
88 } listen_detail_t;
89
90
91 /*
92  *      Find a per-socket client.
93  */
94 RADCLIENT *client_listener_find(const rad_listen_t *listener,
95                                        const lrad_ipaddr_t *ipaddr)
96 {
97         const RADCLIENT_LIST *clients;
98
99         rad_assert(listener != NULL);
100         rad_assert(ipaddr != NULL);
101
102         rad_assert((listener->type == RAD_LISTEN_AUTH) ||
103                    (listener->type == RAD_LISTEN_ACCT) ||
104                    (listener->type == RAD_LISTEN_VQP));
105
106         clients = ((listen_socket_t *)listener->data)->clients;
107         if (!clients) clients = mainconfig.clients;
108
109         rad_assert(clients != NULL);
110
111         return client_find(clients, ipaddr);
112 }
113
114 static int listen_bind(rad_listen_t *this);
115
116 /*
117  *      Process and reply to a server-status request.
118  *      Like rad_authenticate and rad_accounting this should
119  *      live in it's own file but it's so small we don't bother.
120  */
121 static int rad_status_server(REQUEST *request)
122 {
123         int rcode = RLM_MODULE_OK;
124         DICT_VALUE *dval;
125
126         switch (request->listener->type) {
127         case RAD_LISTEN_AUTH:
128                 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
129                 if (dval) {
130                         rcode = module_authorize(dval->value, request);
131                 } else {
132                         rcode = RLM_MODULE_OK;
133                 }
134
135                 switch (rcode) {
136                 case RLM_MODULE_OK:
137                 case RLM_MODULE_UPDATED:
138                         request->reply->code = PW_AUTHENTICATION_ACK;
139                         break;
140
141                 case RLM_MODULE_FAIL:
142                 case RLM_MODULE_HANDLED:
143                         request->reply->code = 0; /* don't reply */
144                         break;
145
146                 default:
147                 case RLM_MODULE_REJECT:
148                         request->reply->code = PW_AUTHENTICATION_REJECT;
149                         break;
150                 }
151                 break;
152
153         case RAD_LISTEN_ACCT:
154                 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
155                 if (dval) {
156                         rcode = module_accounting(dval->value, request);
157                 } else {
158                         rcode = RLM_MODULE_OK;
159                 }
160
161                 switch (rcode) {
162                 case RLM_MODULE_OK:
163                 case RLM_MODULE_UPDATED:
164                         request->reply->code = PW_ACCOUNTING_RESPONSE;
165                         break;
166
167                 default:
168                         request->reply->code = 0; /* don't reply */
169                         break;
170                 }
171                 break;
172
173         default:
174                 return 0;
175         }
176
177         return 0;
178 }
179
180
181 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
182 {
183         size_t len;
184         listen_socket_t *sock = this->data;
185         const char *name;
186         char ip_buf[256];
187
188         if ((sock->ipaddr.af == AF_INET) &&
189             (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
190                 strcpy(ip_buf, "*");
191         } else {
192                 ip_ntoh(&sock->ipaddr, ip_buf, sizeof(ip_buf));
193         }
194
195         switch (this->type) {
196         case RAD_LISTEN_AUTH:
197                 name = "authentication";
198                 break;
199
200         case RAD_LISTEN_ACCT:
201                 name = "accounting";
202                 break;
203
204         case RAD_LISTEN_PROXY:
205                 name = "proxy";
206                 break;
207
208 #ifdef WITH_VMPS
209         case RAD_LISTEN_VQP:
210                 name = "vmps";
211                 break;
212 #endif
213
214         default:
215                 name = "??";
216                 break;
217         }
218
219         if (!this->server) {
220                 return snprintf(buffer, bufsize, "%s address %s port %d",
221                                 name, ip_buf, sock->port);
222         }
223
224         return snprintf(buffer, bufsize, "%s address %s port %d as server %s",
225                         name, ip_buf, sock->port, this->server);
226 }
227
228
229 /*
230  *      Parse an authentication or accounting socket.
231  */
232 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
233 {
234         int             rcode;
235         int             listen_port;
236         lrad_ipaddr_t   ipaddr;
237         listen_socket_t *sock = this->data;
238         const char      *section_name = NULL;
239         CONF_SECTION    *client_cs;
240
241         /*
242          *      Try IPv4 first
243          */
244         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
245         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
246                               &ipaddr.ipaddr.ip4addr, NULL);
247         if (rcode < 0) return -1;
248
249         if (rcode == 0) { /* successfully parsed IPv4 */
250                 ipaddr.af = AF_INET;
251
252         } else {        /* maybe IPv6? */
253                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
254                                       &ipaddr.ipaddr.ip6addr, NULL);
255                 if (rcode < 0) return -1;
256
257                 if (rcode == 1) {
258                         cf_log_err(cf_sectiontoitem(cs),
259                                    "No address specified in listen section");
260                         return -1;
261                 }
262                 ipaddr.af = AF_INET6;
263         }
264
265         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
266                               &listen_port, "0");
267         if (rcode < 0) return -1;
268
269         sock->ipaddr = ipaddr;
270         sock->port = listen_port;
271
272         /*
273          *      And bind it to the port.
274          */
275         if (listen_bind(this) < 0) {
276                 char buffer[128];
277                 cf_log_err(cf_sectiontoitem(cs),
278                            "Error binding to port for %s port %d",
279                            ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
280                            sock->port);
281                 return -1;
282         }
283
284         /*
285          *      If we can bind to interfaces, do so,
286          *      else don't.
287          */
288         if (cf_pair_find(cs, "interface")) {
289 #ifndef SO_BINDTODEVICE
290                 cf_log_err(cf_sectiontoitem(cs),
291                            "System does not support binding to interfaces.  Delete this line from the configuration file.");
292                 return -1;
293 #else
294                 const char *value;
295                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
296                 struct ifreq ifreq;
297
298                 rad_assert(cp != NULL);
299                 value = cf_pair_value(cp);
300                 if (!value) {
301                         cf_log_err(cf_sectiontoitem(cs),
302                                    "No interface name given");
303                         return -1;
304                 }
305
306                 strcpy(ifreq.ifr_name, value);
307
308                 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
309                                (char *)&ifreq, sizeof(ifreq)) < 0) {
310                         cf_log_err(cf_sectiontoitem(cs),
311                                    "Failed binding to interface %s: %s",
312                                    value, strerror(errno));
313                         return -1;
314                 } /* else it worked. */
315 #endif
316         }
317         
318         /*
319          *      If we have a server, prefer to use clients defined
320          *      in that server, and ignore any "clients = "
321          *      directive, UNLESS there are no clients in the server.
322          */
323         client_cs = NULL;
324         client_cs = cf_section_sub_find_name2(mainconfig.config,
325                                               "server",
326                                               this->server);
327         
328         /*
329          *      Found a "server foo" section, but there are no
330          *      clients in it.  Don't use this section.
331          */
332         if (client_cs &&
333             (cf_section_sub_find(client_cs, "client") == NULL)) {
334                 client_cs = NULL;
335         }
336
337         /*
338          *      No clients, look for the name of a section that holds
339          *      a list of clients.
340          */
341         if (!client_cs) {
342                 rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
343                                       &section_name, NULL);
344                 if (rcode < 0) return -1; /* bad string */
345                 if (rcode == 0) {
346                         /*
347                          *      Explicit list given: use it.
348                          */
349                         client_cs = cf_section_find(section_name);
350                         free(section_name);
351                         if (!client_cs) {
352                                 cf_log_err(cf_sectiontoitem(cs),
353                                            "Failed to find clients %s {...}",
354                                            section_name);
355                                 return -1;
356                         }
357                 } /* else there was no "clients = " entry. */
358         }
359
360         /*
361          *      Still nothing.  Make it global.
362          */
363         if (!client_cs) client_cs = mainconfig.config;
364
365         sock->clients = clients_parse_section(client_cs);
366         if (!sock->clients) {
367                 return -1;
368         }
369
370         return 0;
371 }
372
373 /*
374  *      Send an authentication response packet
375  */
376 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
377 {
378         rad_assert(request->listener == listener);
379         rad_assert(listener->send == auth_socket_send);
380
381         return rad_send(request->reply, request->packet,
382                         request->client->secret);
383 }
384
385
386 /*
387  *      Send an accounting response packet (or not)
388  */
389 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
390 {
391         rad_assert(request->listener == listener);
392         rad_assert(listener->send == acct_socket_send);
393
394         /*
395          *      Accounting reject's are silently dropped.
396          *
397          *      We do it here to avoid polluting the rest of the
398          *      code with this knowledge
399          */
400         if (request->reply->code == 0) return 0;
401
402         return rad_send(request->reply, request->packet,
403                         request->client->secret);
404 }
405
406
407 /*
408  *      Send a packet to a home server.
409  *
410  *      FIXME: have different code for proxy auth & acct!
411  */
412 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
413 {
414         listen_socket_t *sock = listener->data;
415
416         rad_assert(request->proxy_listener == listener);
417         rad_assert(listener->send == proxy_socket_send);
418
419         request->proxy->src_ipaddr = sock->ipaddr;
420         request->proxy->src_port = sock->port;
421
422         return rad_send(request->proxy, request->packet,
423                         request->home_server->secret);
424 }
425
426
427 /*
428  *      Check if an incoming request is "ok"
429  *
430  *      It takes packets, not requests.  It sees if the packet looks
431  *      OK.  If so, it does a number of sanity checks on it.
432   */
433 static int auth_socket_recv(rad_listen_t *listener,
434                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
435 {
436         ssize_t         rcode;
437         int             code, src_port;
438         RADIUS_PACKET   *packet;
439         RAD_REQUEST_FUNP fun = NULL;
440         char            buffer[128];
441         RADCLIENT       *client;
442         lrad_ipaddr_t   src_ipaddr;
443
444         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
445         if (rcode < 0) return 0;
446
447         RAD_SNMP_TYPE_INC(listener, total_requests);
448
449         if (rcode < 20) {       /* AUTH_HDR_LEN */
450                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
451                 return 0;
452         }
453
454         if ((client = client_listener_find(listener,
455                                            &src_ipaddr)) == NULL) {
456                 rad_recv_discard(listener->fd);
457                 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
458
459                 /*
460                  *      This is debugging rather than logging, so that
461                  *      DoS attacks don't affect us.
462                  */
463                 DEBUG("Ignoring request from unknown client %s port %d",
464                       inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
465                                 buffer, sizeof(buffer)), src_port);
466                 return 0;
467         }
468
469         /*
470          *      Some sanity checks, based on the packet code.
471          */
472         switch(code) {
473         case PW_AUTHENTICATION_REQUEST:
474                 RAD_SNMP_CLIENT_INC(listener, client, requests);
475                 fun = rad_authenticate;
476                 break;
477
478         case PW_STATUS_SERVER:
479                 if (!mainconfig.status_server) {
480                         rad_recv_discard(listener->fd);
481                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
482                         RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
483                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
484                         return 0;
485                 }
486                 fun = rad_status_server;
487                 break;
488
489         default:
490                 rad_recv_discard(listener->fd);
491                 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
492                 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
493
494                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
495                       code, client->shortname, src_port);
496                 return 0;
497                 break;
498         } /* switch over packet types */
499
500         /*
501          *      Now that we've sanity checked everything, receive the
502          *      packet.
503          */
504         packet = rad_recv(listener->fd);
505         if (!packet) {
506                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
507                 radlog(L_ERR, "%s", librad_errstr);
508                 return 0;
509         }
510
511         if (!received_request(listener, packet, prequest, client)) {
512                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
513                 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
514                 rad_free(&packet);
515                 return 0;
516         }
517
518         *pfun = fun;
519         return 1;
520 }
521
522
523 /*
524  *      Receive packets from an accounting socket
525  */
526 static int acct_socket_recv(rad_listen_t *listener,
527                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
528 {
529         ssize_t         rcode;
530         int             code, src_port;
531         RADIUS_PACKET   *packet;
532         RAD_REQUEST_FUNP fun = NULL;
533         char            buffer[128];
534         RADCLIENT       *client;
535         lrad_ipaddr_t   src_ipaddr;
536
537         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
538         if (rcode < 0) return 0;
539
540         RAD_SNMP_TYPE_INC(listener, total_requests);
541
542         if (rcode < 20) {       /* AUTH_HDR_LEN */
543                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
544                 return 0;
545         }
546
547         if ((client = client_listener_find(listener,
548                                            &src_ipaddr)) == NULL) {
549                 rad_recv_discard(listener->fd);
550                 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
551
552                 /*
553                  *      This is debugging rather than logging, so that
554                  *      DoS attacks don't affect us.
555                  */
556                 DEBUG("Ignoring request from unknown client %s port %d",
557                       inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
558                                 buffer, sizeof(buffer)), src_port);
559                 return 0;
560         }
561
562         /*
563          *      Some sanity checks, based on the packet code.
564          */
565         switch(code) {
566         case PW_ACCOUNTING_REQUEST:
567                 RAD_SNMP_CLIENT_INC(listener, client, requests);
568                 fun = rad_accounting;
569                 break;
570
571         case PW_STATUS_SERVER:
572                 if (!mainconfig.status_server) {
573                         rad_recv_discard(listener->fd);
574                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
575                         RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
576
577                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
578                         return 0;
579                 }
580                 fun = rad_status_server;
581                 break;
582
583         default:
584                 rad_recv_discard(listener->fd);
585                 RAD_SNMP_TYPE_INC(listener, total_unknown_types);
586                 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
587
588                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
589                       code, client->shortname, src_port);
590                 return 0;
591         } /* switch over packet types */
592
593         /*
594          *      Now that we've sanity checked everything, receive the
595          *      packet.
596          */
597         packet = rad_recv(listener->fd);
598         if (!packet) {
599                 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
600                 radlog(L_ERR, "%s", librad_errstr);
601                 return 0;
602         }
603
604         /*
605          *      There can be no duplicate accounting packets.
606          */
607         if (!received_request(listener, packet, prequest, client)) {
608                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
609                 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
610                 rad_free(&packet);
611                 return 0;
612         }
613
614         *pfun = fun;
615         return 1;
616 }
617
618
619 /*
620  *      Recieve packets from a proxy socket.
621  */
622 static int proxy_socket_recv(rad_listen_t *listener,
623                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
624 {
625         REQUEST         *request;
626         RADIUS_PACKET   *packet;
627         RAD_REQUEST_FUNP fun = NULL;
628         char            buffer[128];
629
630         packet = rad_recv(listener->fd);
631         if (!packet) {
632                 radlog(L_ERR, "%s", librad_errstr);
633                 return 0;
634         }
635
636         /*
637          *      FIXME: Client MIB updates?
638          */
639         switch(packet->code) {
640         case PW_AUTHENTICATION_ACK:
641         case PW_ACCESS_CHALLENGE:
642         case PW_AUTHENTICATION_REJECT:
643                 fun = rad_authenticate;
644                 break;
645
646         case PW_ACCOUNTING_RESPONSE:
647                 fun = rad_accounting;
648                 break;
649
650         default:
651                 /*
652                  *      FIXME: Update MIB for packet types?
653                  */
654                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
655                        "from home server %s port %d - ID %d : IGNORED",
656                        packet->code,
657                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
658                        packet->src_port, packet->id);
659                 rad_free(&packet);
660                 return 0;
661         }
662
663         request = received_proxy_response(packet);
664         if (!request) {
665                 return 0;
666         }
667
668         rad_assert(fun != NULL);
669         *pfun = fun;
670         *prequest = request;
671
672         return 1;
673 }
674
675
676 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
677 {
678         if (!request->reply->code) return 0;
679
680         rad_encode(request->reply, request->packet,
681                    request->client->secret);
682         rad_sign(request->reply, request->packet,
683                  request->client->secret);
684
685         return 0;
686 }
687
688
689 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
690 {
691         if (rad_verify(request->packet, NULL,
692                        request->client->secret) < 0) {
693                 return -1;
694         }
695
696         return rad_decode(request->packet, NULL,
697                           request->client->secret);
698 }
699
700 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
701 {
702         rad_encode(request->proxy, NULL, request->home_server->secret);
703         rad_sign(request->proxy, NULL, request->home_server->secret);
704
705         return 0;
706 }
707
708
709 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
710 {
711         if (rad_verify(request->proxy_reply, request->proxy,
712                        request->home_server->secret) < 0) {
713                 return -1;
714         }
715
716         return rad_decode(request->proxy_reply, request->proxy,
717                            request->home_server->secret);
718 }
719
720
721 #define STATE_UNOPENED  (0)
722 #define STATE_UNLOCKED  (1)
723 #define STATE_HEADER    (2)
724 #define STATE_READING   (3)
725 #define STATE_QUEUED    (4)
726 #define STATE_RUNNING   (5)
727 #define STATE_NO_REPLY  (6)
728 #define STATE_REPLIED   (7)
729
730 /*
731  *      If we're limiting outstanding packets, then mark the response
732  *      as being sent.
733  */
734 static int detail_send(rad_listen_t *listener, REQUEST *request)
735 {
736         int rtt;
737         struct timeval now;
738         listen_detail_t *data = listener->data;
739
740         rad_assert(request->listener == listener);
741         rad_assert(listener->send == detail_send);
742
743         /*
744          *      This request timed out.  Remember that, and tell the
745          *      caller it's OK to read more "detail" file stuff.
746          */
747         if (request->reply->code == 0) {
748                 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
749                 data->state = STATE_NO_REPLY;
750                 return 0;
751         }
752
753         /*
754          *      We call gettimeofday a lot.  But here it should be OK,
755          *      because there's nothing else to do.
756          */
757         gettimeofday(&now, NULL);
758
759         /*
760          *      If we haven't sent a packet in the last second, reset
761          *      the RTT.
762          */
763         now.tv_sec -= 1;
764         if (timercmp(&data->last_packet, &now, <)) {
765                 data->has_rtt = FALSE;
766         }
767         now.tv_sec += 1;
768
769         /*
770          *      Only one detail packet may be outstanding at a time,
771          *      so it's safe to update some entries in the detail
772          *      structure.
773          *
774          *      We keep smoothed round trip time (SRTT), but not round
775          *      trip timeout (RTO).  We use SRTT to calculate a rough
776          *      load factor.
777          */
778         rtt = now.tv_sec - request->received.tv_sec;
779         rtt *= USEC;
780         rtt += now.tv_usec;
781         rtt -= request->received.tv_usec;
782
783         /*
784          *      If we're proxying, the RTT is our processing time,
785          *      plus the network delay there and back, plus the time
786          *      on the other end to process the packet.  Ideally, we
787          *      should remove the network delays from the RTT, but we
788          *      don't know what they are.
789          *
790          *      So, to be safe, we over-estimate the total cost of
791          *      processing the packet.
792          */
793         if (!data->has_rtt) {
794                 data->has_rtt = TRUE;
795                 data->srtt = rtt;
796                 data->rttvar = rtt / 2;
797
798         } else {
799                 data->rttvar -= data->rttvar >> 2;
800                 data->rttvar += (data->srtt - rtt);
801                 data->srtt -= data->srtt >> 3;
802                 data->srtt += rtt >> 3;
803         }
804
805         /*
806          *      Calculate the time we wait before sending the next
807          *      packet.
808          *
809          *      rtt / (rtt + delay) = load_factor / 100
810          */
811         data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
812
813         /*
814          *      FIXME: Push this delay to the event handler!
815          */
816         DEBUG2("RTT %d\tdelay %d", data->srtt, data->delay_time);
817
818         usleep(data->delay_time);
819         data->last_packet = now;
820         data->state = STATE_REPLIED;
821
822         return 0;
823 }
824
825
826 /*
827  *      Open the detail file..
828  *
829  *      FIXME: create it, if it's not already there, so that the main
830  *      server select() will wake us up if there's anything to read.
831  */
832 static int detail_open(rad_listen_t *this)
833 {
834         struct stat st;
835         char buffer[2048];
836         listen_detail_t *data = this->data;
837
838         rad_assert(data->state == STATE_UNOPENED);
839         snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
840
841         /*
842          *      Open detail.work first, so we don't lose
843          *      accounting packets.  It's probably better to
844          *      duplicate them than to lose them.
845          *
846          *      Note that we're not writing to the file, but
847          *      we've got to open it for writing in order to
848          *      establish the lock, to prevent rlm_detail from
849          *      writing to it.
850          */
851         this->fd = open(buffer, O_RDWR);
852         if (this->fd < 0) {
853                 /*
854                  *      Try reading the detail file.  If it
855                  *      doesn't exist, we can't do anything.
856                  *
857                  *      Doing the stat will tell us if the file
858                  *      exists, even if we don't have permissions
859                  *      to read it.
860                  */
861                 if (stat(data->filename, &st) < 0) {
862                         return 0;
863                 }
864
865                 /*
866                  *      Open it BEFORE we rename it, just to
867                  *      be safe...
868                  */
869                 this->fd = open(data->filename, O_RDWR);
870                 if (this->fd < 0) {
871                         radlog(L_ERR, "Failed to open %s: %s",
872                                data->filename, strerror(errno));
873                         return 0;
874                 }
875
876                 /*
877                  *      Rename detail to detail.work
878                  */
879                 if (rename(data->filename, buffer) < 0) {
880                         close(this->fd);
881                         this->fd = -1;
882                         return 0;
883                 }
884         } /* else detail.work existed, and we opened it */
885
886         rad_assert(data->vps == NULL);
887
888         rad_assert(data->fp == NULL);
889         data->fp = fdopen(this->fd, "r");
890         if (!data->fp) {
891                 radlog(L_ERR, "Failed to re-open %s: %s",
892                        data->filename, strerror(errno));
893                 return 0;
894         }
895
896         data->state = STATE_UNLOCKED;
897
898         data->client_ip.af = AF_UNSPEC;
899         data->timestamp = 0;
900
901         return 1;
902 }
903
904 /*
905  *      FIXME: this should be dynamically allocated.
906  */
907 static const RADCLIENT detail_client = {
908         {               /* ipaddr */
909                 AF_INET,
910                 {{ INADDR_NONE }}
911         },
912         32,
913         "<detail-file>",
914         "secret",
915         "UNKNOWN-CLIENT",
916         "other",
917         "",
918         "",
919         -1
920 #ifdef WITH_SNMP
921         , NULL, NULL
922 #endif
923 };
924
925 /*
926  *      FIXME: add a configuration "exit when done" so that the detail
927  *      file reader can be used as a one-off tool to update stuff.
928  *
929  *      The time sequence for reading from the detail file is:
930  *
931  *      t_0             signalled that the server is idle, and we
932  *                      can read from the detail file.
933  *
934  *      t_rtt           the packet has been processed successfully,
935  *                      wait for t_delay to enforce load factor.
936  *                      
937  *      t_rtt + t_delay wait for signal that the server is idle.
938  *      
939  */
940 static int detail_recv(rad_listen_t *listener,
941                        RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
942 {
943         char            key[256], value[1024];
944         VALUE_PAIR      *vp, **tail;
945         RADIUS_PACKET   *packet;
946         char            buffer[2048];
947         listen_detail_t *data = listener->data;
948
949         switch (data->state) {
950                 case STATE_UNOPENED:
951                         rad_assert(listener->fd < 0);
952                         
953                         /*
954                          *      FIXME: If the file doesn't exist, then
955                          *      return "sleep for 1s", to avoid busy
956                          *      looping.
957                          */
958                         if (!detail_open(listener)) return 0;
959
960                         rad_assert(data->state == STATE_UNLOCKED);
961                         rad_assert(listener->fd >= 0);
962
963                         /* FALL-THROUGH */
964
965                         /*
966                          *      Try to lock fd.  If we can't, return.
967                          *      If we can, continue.  This means that
968                          *      the server doesn't block while waiting
969                          *      for the lock to open...
970                          */
971                 case STATE_UNLOCKED:
972                         /*
973                          *      Note that we do NOT block waiting for
974                          *      the lock.  We've re-named the file
975                          *      above, so we've already guaranteed
976                          *      that any *new* detail writer will not
977                          *      be opening this file.  The only
978                          *      purpose of the lock is to catch a race
979                          *      condition where the execution
980                          *      "ping-pongs" between radiusd &
981                          *      radrelay.
982                          */
983                         if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
984                                 return 0;
985                         }
986                         /*
987                          *      Look for the header
988                          */
989                         data->state = STATE_HEADER;
990                         data->vps = NULL;
991
992                         /* FALL-THROUGH */
993
994                 case STATE_HEADER:
995                 do_header:
996                         /*
997                          *      End of file.  Delete it, and re-set
998                          *      everything.
999                          */
1000                         if (feof(data->fp)) {
1001                         cleanup:
1002                                 snprintf(buffer, sizeof(buffer),
1003                                          "%s.work", data->filename);
1004                                 unlink(buffer);
1005                                 fclose(data->fp); /* closes listener->fd */
1006                                 data->fp = NULL;
1007                                 listener->fd = -1;
1008                                 data->state = STATE_UNOPENED;
1009                                 rad_assert(data->vps == NULL);
1010                                 return 0;
1011                         }
1012
1013                         /*
1014                          *      Else go read something.
1015                          */
1016                         break;
1017
1018                         /*
1019                          *      Read more value-pair's, unless we're
1020                          *      at EOF.  In that case, queue whatever
1021                          *      we have.
1022                          */
1023                 case STATE_READING:
1024                         if (!feof(data->fp)) break;
1025                         data->state = STATE_QUEUED;
1026
1027                         /* FALL-THROUGH */
1028
1029                 case STATE_QUEUED:
1030                         goto alloc_packet;
1031
1032                         /*
1033                          *      We still have an outstanding packet.
1034                          *      Don't read any more.
1035                          */
1036                 case STATE_RUNNING:
1037                         return 0;
1038
1039                         /*
1040                          *      If there's no reply, keep
1041                          *      retransmitting the current packet
1042                          *      forever.
1043                          */
1044                 case STATE_NO_REPLY:
1045                         data->state = STATE_QUEUED;
1046                         goto alloc_packet;
1047                                 
1048                         /*
1049                          *      We have a reply.  Clean up the old
1050                          *      request, and go read another one.
1051                          */
1052                 case STATE_REPLIED:
1053                         pairfree(&data->vps);
1054                         data->state = STATE_HEADER;
1055                         goto do_header;
1056         }
1057         
1058         tail = &data->vps;
1059         while (*tail) tail = &(*tail)->next;
1060
1061         /*
1062          *      Read a header, OR a value-pair.
1063          */
1064         while (fgets(buffer, sizeof(buffer), data->fp)) {
1065                 /*
1066                  *      Badly formatted file: delete it.
1067                  *
1068                  *      FIXME: Maybe flag an error?
1069                  */
1070                 if (!strchr(buffer, '\n')) {
1071                         pairfree(&data->vps);
1072                         goto cleanup;
1073                 }
1074
1075                 /*
1076                  *      We're reading VP's, and got a blank line.
1077                  *      Queue the packet.
1078                  */
1079                 if ((data->state == STATE_READING) &&
1080                     (buffer[0] == '\n')) {
1081                         data->state = STATE_QUEUED;
1082                         break;
1083                 }
1084
1085                 /*
1086                  *      Look for date/time header, and read VP's if
1087                  *      found.  If not, keep reading lines until we
1088                  *      find one.
1089                  */
1090                 if (data->state == STATE_HEADER) {
1091                         int y;
1092
1093                         if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
1094                                 data->state = STATE_READING;
1095                         }
1096                         continue;
1097                 }
1098
1099                 /*
1100                  *      We have a full "attribute = value" line.
1101                  *      If it doesn't look reasonable, skip it.
1102                  *
1103                  *      FIXME: print an error for badly formatted attributes?
1104                  */
1105                 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
1106                         continue;
1107                 }
1108
1109                 /*
1110                  *      Skip non-protocol attributes.
1111                  */
1112                 if (!strcasecmp(key, "Request-Authenticator")) continue;
1113
1114                 /*
1115                  *      Set the original client IP address, based on
1116                  *      what's in the detail file.
1117                  *
1118                  *      Hmm... we don't set the server IP address.
1119                  *      or port.  Oh well.
1120                  */
1121                 if (!strcasecmp(key, "Client-IP-Address")) {
1122                         data->client_ip.af = AF_INET;
1123                         ip_hton(value, AF_INET, &data->client_ip);
1124                         continue;
1125                 }
1126
1127                 /*
1128                  *      The original time at which we received the
1129                  *      packet.  We need this to properly calculate
1130                  *      Acct-Delay-Time.
1131                  */
1132                 if (!strcasecmp(key, "Timestamp")) {
1133                         data->timestamp = atoi(value);
1134                         continue;
1135                 }
1136
1137                 /*
1138                  *      Read one VP.
1139                  *
1140                  *      FIXME: do we want to check for non-protocol
1141                  *      attributes like radsqlrelay does?
1142                  */
1143                 vp = NULL;
1144                 if ((userparse(buffer, &vp) > 0) &&
1145                     (vp != NULL)) {
1146                         *tail = vp;
1147                         tail = &(vp->next);
1148                 }
1149         }
1150
1151         /*
1152          *      Some kind of error.
1153          *
1154          *      FIXME: Leave the file in-place, and warn the
1155          *      administrator?
1156          */
1157         if (ferror(data->fp)) goto cleanup;
1158
1159         /*
1160          *      Process the packet.
1161          */
1162  alloc_packet:
1163         rad_assert(data->state == STATE_QUEUED);
1164
1165         /*
1166          *      We're done reading the file, but we didn't read
1167          *      anything.  Clean up, and don't return anything.
1168          */
1169         if (!data->vps) {
1170                 data->state = STATE_HEADER;
1171                 return 0;
1172         }
1173
1174         /*
1175          *      Allocate the packet.  If we fail, it's a serious
1176          *      problem.
1177          */
1178         packet = rad_alloc(1);
1179         if (!packet) {
1180                 data->state = STATE_NO_REPLY;   /* try again later */
1181                 return 0;       /* maybe memory will magically free up... */
1182         }
1183
1184         memset(packet, 0, sizeof(*packet));
1185         packet->sockfd = -1;
1186         packet->src_ipaddr.af = AF_INET;
1187         packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1188         packet->code = PW_ACCOUNTING_REQUEST;
1189         packet->timestamp = time(NULL);
1190
1191         /*
1192          *      Remember where it came from, so that we don't
1193          *      proxy it to the place it came from...
1194          */
1195         if (data->client_ip.af != AF_UNSPEC) {
1196                 packet->src_ipaddr = data->client_ip;
1197         }
1198
1199         vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
1200         if (vp) {
1201                 packet->src_ipaddr.af = AF_INET;
1202                 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1203         } else {
1204                 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
1205                 if (vp) {
1206                         packet->src_ipaddr.af = AF_INET6;
1207                         memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
1208                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1209                 }
1210         }
1211
1212         vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
1213         if (vp) {
1214                 packet->dst_ipaddr.af = AF_INET;
1215                 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1216         } else {
1217                 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
1218                 if (vp) {
1219                         packet->dst_ipaddr.af = AF_INET6;
1220                         memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
1221                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1222                 }
1223         }
1224
1225         /*
1226          *      We've got to give SOME value for Id & ports, so that
1227          *      the packets can be added to the request queue.
1228          *      However, we don't want to keep track of used/unused
1229          *      id's and ports, as that's a lot of work.  This hack
1230          *      ensures that (if we have real random numbers), that
1231          *      there will be a collision on every 2^(16+15+15+24 - 1)
1232          *      packets, on average.  That means we can read 2^37
1233          *      packets before having a collision, which means it's
1234          *      effectively impossible.
1235          */
1236         packet->id = lrad_rand() & 0xffff;
1237         packet->src_port = 1024 + (lrad_rand() & 0x7fff);
1238         packet->dst_port = 1024 + (lrad_rand() & 0x7fff);
1239
1240         packet->dst_ipaddr.af = AF_INET;
1241         packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (lrad_rand() & 0xffffff));
1242
1243         /*
1244          *      If everything's OK, this is a waste of memory.
1245          *      Otherwise, it lets us re-send the original packet
1246          *      contents, unmolested.
1247          */
1248         packet->vps = paircopy(data->vps);
1249
1250         /*
1251          *      Look for Acct-Delay-Time, and update
1252          *      based on Acct-Delay-Time += (time(NULL) - timestamp)
1253          */
1254         vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
1255         if (!vp) {
1256                 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1257                 rad_assert(vp != NULL);
1258                 pairadd(&packet->vps, vp);
1259         }
1260         if (data->timestamp != 0) {
1261                 vp->vp_integer += time(NULL) - data->timestamp;
1262         }
1263
1264         *pfun = rad_accounting;
1265
1266         if (debug_flag) {
1267                 printf("detail_recv: Read packet from %s\n", data->filename);
1268                 for (vp = packet->vps; vp; vp = vp->next) {
1269                         putchar('\t');
1270                         vp_print(stdout, vp);
1271                         putchar('\n');
1272                 }
1273         }
1274
1275         /*
1276          *      FIXME: many of these checks may not be necessary when
1277          *      reading from the detail file.
1278          *
1279          *      Try again later...
1280          */
1281         if (!received_request(listener, packet, prequest, &detail_client)) {
1282                 rad_free(&packet);
1283                 data->state = STATE_NO_REPLY;   /* try again later */
1284                 return 0;
1285         }
1286
1287         data->state = STATE_RUNNING;
1288
1289         return 1;
1290 }
1291
1292
1293 /*
1294  *      Free detail-specific stuff.
1295  */
1296 static void detail_free(rad_listen_t *this)
1297 {
1298         listen_detail_t *data = this->data;
1299
1300         free(data->filename);
1301         pairfree(&data->vps);
1302
1303         if (data->fp != NULL) fclose(data->fp);
1304 }
1305
1306
1307 static int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
1308 {
1309         if (!this->server) {
1310                 return snprintf(buffer, bufsize, "%s",
1311                                 ((listen_detail_t *)(this->data))->filename);
1312         }
1313
1314         return snprintf(buffer, bufsize, "detail file %s as server %s",
1315                         ((listen_detail_t *)(this->data))->filename,
1316                         this->server);
1317 }
1318
1319 static int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1320 {
1321         /*
1322          *      We never encode responses "sent to" the detail file.
1323          */
1324         return 0;
1325 }
1326
1327 static int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1328 {
1329         /*
1330          *      We never decode responses read from the detail file.
1331          */
1332         return 0;
1333 }
1334
1335
1336 static const CONF_PARSER detail_config[] = {
1337         { "filename",   PW_TYPE_STRING_PTR,
1338           offsetof(listen_detail_t, filename), NULL,  NULL },
1339         { "load_factor",   PW_TYPE_INTEGER,
1340           offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
1341
1342         { NULL, -1, 0, NULL, NULL }             /* end the list */
1343 };
1344
1345
1346 /*
1347  *      Parse a detail section.
1348  */
1349 static int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
1350 {
1351         int             rcode;
1352         listen_detail_t *data;
1353
1354         data = this->data;
1355
1356         rcode = cf_section_parse(cs, data, detail_config);
1357         if (rcode < 0) {
1358                 cf_log_err(cf_sectiontoitem(cs), "Failed parsing listen section");
1359                 return -1;
1360         }
1361
1362         if (!data->filename) {
1363                 cf_log_err(cf_sectiontoitem(cs), "No detail file specified in listen section");
1364                 return -1;
1365         }
1366
1367         if ((data->load_factor < 1) || (data->load_factor > 100)) {
1368                 cf_log_err(cf_sectiontoitem(cs), "Load factor must be between 1 and 100");
1369                 return -1;
1370         }
1371
1372         data->vps = NULL;
1373         data->fp = NULL;
1374         data->state = STATE_UNOPENED;
1375         detail_open(this);
1376
1377         return 0;
1378 }
1379
1380
1381 #ifdef WITH_SNMP
1382 static int radius_snmp_recv(rad_listen_t *listener,
1383                             UNUSED RAD_REQUEST_FUNP *pfun,
1384                             UNUSED REQUEST **prequest)
1385 {
1386         if (!mainconfig.do_snmp) return 0;
1387
1388         if ((rad_snmp.smux_fd >= 0) &&
1389             (rad_snmp.smux_event == SMUX_READ)) {
1390                 smux_read();
1391         }
1392
1393         /*
1394          *  If we've got to re-connect, then do so now,
1395          *  before calling select again.
1396          */
1397         if (rad_snmp.smux_event == SMUX_CONNECT) {
1398                 smux_connect();
1399         }
1400
1401         /*
1402          *      Reset this every time, as the smux connect may have
1403          *      opened a new socket.
1404          */
1405         listener->fd = rad_snmp.smux_fd;
1406
1407         return 0;
1408 }
1409
1410
1411 static int radius_snmp_print(UNUSED rad_listen_t *this, char *buffer, size_t bufsize)
1412 {
1413         return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1414 }
1415
1416 #endif
1417
1418 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1419         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1420
1421         /* proxying */
1422         { NULL, NULL,
1423           proxy_socket_recv, proxy_socket_send,
1424           socket_print, proxy_socket_encode, proxy_socket_decode },
1425
1426         /* authentication */
1427         { common_socket_parse, NULL,
1428           auth_socket_recv, auth_socket_send,
1429           socket_print, client_socket_encode, client_socket_decode },
1430
1431         /* accounting */
1432         { common_socket_parse, NULL,
1433           acct_socket_recv, acct_socket_send,
1434           socket_print, client_socket_encode, client_socket_decode},
1435
1436         /* detail */
1437         { detail_parse, detail_free,
1438           detail_recv, detail_send,
1439           detail_print, detail_encode, detail_decode },
1440
1441 #ifdef WITH_VMPS
1442         /* vlan query protocol */
1443         { common_socket_parse, NULL,
1444           vqp_socket_recv, vqp_socket_send,
1445           socket_print, vqp_socket_encode, vqp_socket_decode },
1446 #else
1447         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1448 #endif
1449
1450         { NULL, NULL, NULL, NULL, NULL, NULL, NULL}     /* RAD_LISTEN_SNMP */
1451 };
1452
1453
1454
1455 /*
1456  *      Binds a listener to a socket.
1457  */
1458 static int listen_bind(rad_listen_t *this)
1459 {
1460         rad_listen_t    **last;
1461         listen_socket_t *sock = this->data;
1462
1463         /*
1464          *      If the port is zero, then it means the appropriate
1465          *      thing from /etc/services.
1466          */
1467         if (sock->port == 0) {
1468                 struct servent  *svp;
1469
1470                 switch (this->type) {
1471                 case RAD_LISTEN_AUTH:
1472                         svp = getservbyname ("radius", "udp");
1473                         if (svp != NULL) {
1474                                 sock->port = ntohs(svp->s_port);
1475                         } else {
1476                                 sock->port = PW_AUTH_UDP_PORT;
1477                         }
1478                         break;
1479
1480                 case RAD_LISTEN_ACCT:
1481                         svp = getservbyname ("radacct", "udp");
1482                         if (svp != NULL) {
1483                                 sock->port = ntohs(svp->s_port);
1484                         } else {
1485                                 sock->port = PW_ACCT_UDP_PORT;
1486                         }
1487                         break;
1488
1489 #ifdef WITH_VMPS
1490                 case RAD_LISTEN_VQP:
1491                         sock->port = 1589;
1492                         break;
1493 #endif
1494
1495                 default:
1496                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1497                         return -1;
1498                 }
1499         }
1500
1501         /*
1502          *      Find it in the old list, AFTER updating the port.  If
1503          *      it's there, use that, rather than creating a new
1504          *      socket.  This allows HUP's to re-use the old sockets,
1505          *      which means that packets waiting in the socket queue
1506          *      don't get lost.
1507          */
1508         for (last = &mainconfig.listen;
1509              *last != NULL;
1510              last = &((*last)->next)) {
1511                 listen_socket_t *other;
1512
1513                 if (this->type != (*last)->type) continue;
1514
1515                 if ((this->type == RAD_LISTEN_DETAIL) ||
1516                     (this->type == RAD_LISTEN_SNMP)) continue;
1517
1518                 other = (listen_socket_t *)((*last)->data);
1519
1520                 if ((sock->port == other->port) &&
1521                     (sock->ipaddr.af == other->ipaddr.af) &&
1522                     (lrad_ipaddr_cmp(&sock->ipaddr, &other->ipaddr) == 0)) {
1523                         this->fd = (*last)->fd;
1524                         (*last)->fd = -1;
1525                         return 0;
1526                 }
1527         }
1528
1529         this->fd = lrad_socket(&sock->ipaddr, sock->port);
1530         if (this->fd < 0) {
1531                 radlog(L_ERR, "ERROR: Failed to open socket: %s",
1532                        librad_errstr);
1533                 return -1;
1534         }
1535
1536 #if 0
1537 #ifdef O_NONBLOCK
1538         if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  {
1539                 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1540                 return -1;
1541         }
1542
1543         flags |= O_NONBLOCK;
1544         if( fcntl(this->fd, F_SETFL, flags) < 0) {
1545                 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1546                 return -1;
1547         }
1548 #endif
1549 #endif
1550
1551         return 0;
1552 }
1553
1554
1555 /*
1556  *      Allocate & initialize a new listener.
1557  */
1558 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1559 {
1560         rad_listen_t *this;
1561
1562         this = rad_malloc(sizeof(*this));
1563         memset(this, 0, sizeof(*this));
1564
1565         this->type = type;
1566         this->recv = master_listen[this->type].recv;
1567         this->send = master_listen[this->type].send;
1568         this->print = master_listen[this->type].print;
1569         this->encode = master_listen[this->type].encode;
1570         this->decode = master_listen[this->type].decode;
1571
1572         switch (type) {
1573         case RAD_LISTEN_AUTH:
1574         case RAD_LISTEN_ACCT:
1575         case RAD_LISTEN_PROXY:
1576         case RAD_LISTEN_VQP:
1577                 this->data = rad_malloc(sizeof(listen_socket_t));
1578                 memset(this->data, 0, sizeof(listen_socket_t));
1579                 break;
1580
1581         case RAD_LISTEN_DETAIL:
1582                 this->data = rad_malloc(sizeof(listen_detail_t));
1583                 memset(this->data, 0, sizeof(listen_detail_t));
1584
1585         default:
1586                 rad_assert("Unsupported option!" == NULL);
1587                 break;
1588         }
1589
1590         return this;
1591 }
1592
1593
1594 /*
1595  *      Externally visible function for creating a new proxy LISTENER.
1596  *
1597  *      For now, don't take ipaddr or port.
1598  *
1599  *      Not thread-safe, but all calls to it are protected by the
1600  *      proxy mutex in request_list.c
1601  */
1602 rad_listen_t *proxy_new_listener()
1603 {
1604         int last_proxy_port, port;
1605         rad_listen_t *this, *tmp, **last;
1606         listen_socket_t *sock, *old;
1607
1608         this = listen_alloc(RAD_LISTEN_PROXY);
1609
1610         /*
1611          *      Find an existing proxy socket to copy.
1612          *
1613          *      FIXME: Make it per-realm, or per-home server!
1614          */
1615         last_proxy_port = 0;
1616         old = NULL;
1617         last = &mainconfig.listen;
1618         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1619                 if (tmp->type == RAD_LISTEN_PROXY) {
1620                         sock = tmp->data;
1621                         if (sock->port > last_proxy_port) {
1622                                 last_proxy_port = sock->port + 1;
1623                         }
1624                         if (!old) old = sock;
1625                 }
1626
1627                 last = &(tmp->next);
1628         }
1629
1630         if (!old) return NULL;  /* This is a serious error. */
1631
1632         /*
1633          *      FIXME: find a new IP address to listen on?
1634          *
1635          *      This could likely be done in the "home server"
1636          *      configuration, to have per-home-server source IP's.
1637          */
1638         sock = this->data;
1639         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1640
1641         /*
1642          *      Keep going until we find an unused port.
1643          */
1644         for (port = last_proxy_port; port < 64000; port++) {
1645                 sock->port = port;
1646                 if (listen_bind(this) == 0) {
1647                         /*
1648                          *      Add the new listener to the list of
1649                          *      listeners.
1650                          */
1651                         *last = this;
1652                         return this;
1653                 }
1654         }
1655
1656         return NULL;
1657 }
1658
1659
1660 static const LRAD_NAME_NUMBER listen_compare[] = {
1661         { "auth",       RAD_LISTEN_AUTH },
1662         { "acct",       RAD_LISTEN_ACCT },
1663         { "detail",     RAD_LISTEN_DETAIL },
1664 #ifdef WITH_VMPS
1665         { "vmps",       RAD_LISTEN_VQP },
1666 #endif
1667         { NULL, 0 },
1668 };
1669
1670
1671 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1672 {
1673         int             type, rcode;
1674         char            *listen_type;
1675         rad_listen_t    *this;
1676
1677         listen_type = NULL;
1678         
1679         DEBUG2(" listen {");
1680
1681         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1682                               &listen_type, "");
1683         if (rcode < 0) return NULL;
1684         if (rcode == 1) {
1685                 free(listen_type);
1686                 cf_log_err(cf_sectiontoitem(cs),
1687                            "No type specified in listen section");
1688                 return NULL;
1689         }
1690
1691         type = lrad_str2int(listen_compare, listen_type,
1692                             RAD_LISTEN_NONE);
1693         free(listen_type);
1694         if (type == RAD_LISTEN_NONE) {
1695                 cf_log_err(cf_sectiontoitem(cs),
1696                            "Invalid type \"%s\" in listen section.",
1697                            listen_type);
1698                 return NULL;
1699         }
1700         
1701         /*
1702          *      Allow listen sections in the default config to
1703          *      refer to a server.
1704          */
1705         if (!server) {
1706                 rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1707                                       &server, NULL);
1708                 if (rcode < 0) return NULL;
1709         }
1710
1711         /*
1712          *      Set up cross-type data.
1713          */
1714         this = listen_alloc(type);
1715         this->server = server;
1716         this->fd = -1;
1717
1718         /*
1719          *      Call per-type parser.
1720          */
1721         if (master_listen[type].parse(cs, this) < 0) {
1722                 listen_free(&this);
1723                 return NULL;
1724         }
1725
1726         DEBUG2(" }");
1727
1728         return this;
1729 }
1730
1731 /*
1732  *      Generate a list of listeners.  Takes an input list of
1733  *      listeners, too, so we don't close sockets with waiting packets.
1734  */
1735 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1736 {
1737         int             rcode;
1738         CONF_SECTION    *cs;
1739         rad_listen_t    **last;
1740         rad_listen_t    *this;
1741         lrad_ipaddr_t   server_ipaddr;
1742         int             auth_port = 0;
1743
1744         /*
1745          *      We shouldn't be called with a pre-existing list.
1746          */
1747         rad_assert(head && (*head == NULL));
1748
1749         last = head;
1750         server_ipaddr.af = AF_UNSPEC;
1751
1752         /*
1753          *      If the port is specified on the command-line,
1754          *      it over-rides the configuration file.
1755          *
1756          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1757          */
1758         if (mainconfig.port >= 0) auth_port = mainconfig.port;
1759
1760         /*
1761          *      If the IP address was configured on the command-line,
1762          *      use that as the "bind_address"
1763          */
1764         if (mainconfig.myip.af != AF_UNSPEC) {
1765                 memcpy(&server_ipaddr, &mainconfig.myip,
1766                        sizeof(server_ipaddr));
1767                 goto bind_it;
1768         }
1769
1770         /*
1771          *      Else look for bind_address and/or listen sections.
1772          */
1773         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1774         rcode = cf_item_parse(config, "bind_address",
1775                               PW_TYPE_IPADDR,
1776                               &server_ipaddr.ipaddr.ip4addr, NULL);
1777         if (rcode < 0) return -1; /* error parsing it */
1778
1779         if (rcode == 0) { /* successfully parsed IPv4 */
1780                 listen_socket_t *sock;
1781                 server_ipaddr.af = AF_INET;
1782
1783                 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'.");
1784
1785         bind_it:
1786 #ifdef WITH_VMPS
1787                 if (strcmp(progname, "vmpsd") == 0) {
1788                         this = listen_alloc(RAD_LISTEN_VQP);
1789                         if (!auth_port) auth_port = 1589;
1790                 } else
1791 #endif
1792                         this = listen_alloc(RAD_LISTEN_AUTH);
1793
1794                 sock = this->data;
1795
1796                 sock->ipaddr = server_ipaddr;
1797                 sock->port = auth_port;
1798
1799                 if (listen_bind(this) < 0) {
1800                         listen_free(&this);
1801                         listen_free(head);
1802                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1803                         return -1;
1804                 }
1805                 auth_port = sock->port; /* may have been updated in listen_bind */
1806                 *last = this;
1807                 last = &(this->next);
1808
1809 #ifdef WITH_VMPS
1810                 /*
1811                  *      No acct for vmpsd
1812                  */
1813                 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1814 #endif
1815
1816                 /*
1817                  *      Open Accounting Socket.
1818                  *
1819                  *      If we haven't already gotten acct_port from
1820                  *      /etc/services, then make it auth_port + 1.
1821                  */
1822                 this = listen_alloc(RAD_LISTEN_ACCT);
1823                 sock = this->data;
1824
1825                 /*
1826                  *      Create the accounting socket.
1827                  *
1828                  *      The accounting port is always the
1829                  *      authentication port + 1
1830                  */
1831                 sock->ipaddr = server_ipaddr;
1832                 sock->port = auth_port + 1;
1833
1834                 if (listen_bind(this) < 0) {
1835                         listen_free(&this);
1836                         listen_free(head);
1837                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1838                         return -1;
1839                 }
1840
1841                 *last = this;
1842                 last = &(this->next);
1843
1844         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1845                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1846                        mainconfig.port);
1847                 return -1;
1848         }
1849
1850         /*
1851          *      They specified an IP on the command-line, ignore
1852          *      all listen sections.
1853          */
1854         if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1855
1856         /*
1857          *      Walk through the "listen" sections, if they exist.
1858          */
1859         for (cs = cf_subsection_find_next(config, NULL, "listen");
1860              cs != NULL;
1861              cs = cf_subsection_find_next(config, cs, "listen")) {
1862                 this = listen_parse(cs, NULL);
1863                 if (!this) {
1864                         listen_free(head);
1865                         return -1;
1866                 }
1867
1868                 *last = this;
1869                 last = &(this->next);
1870         }
1871
1872         /*
1873          *      Check virtual servers for "listen" sections, too.
1874          *
1875          *      FIXME: Move to virtual server init?
1876          */
1877         for (cs = cf_subsection_find_next(config, NULL, "server");
1878              cs != NULL;
1879              cs = cf_subsection_find_next(config, cs, "server")) {
1880                 CONF_SECTION *subcs;
1881                 const char *name2 = cf_section_name2(cs);
1882                 
1883                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1884                      subcs != NULL;
1885                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1886                         this = listen_parse(subcs, name2);
1887                         if (!this) {
1888                                 listen_free(head);
1889                                 return -1;
1890                         }
1891                         
1892                         *last = this;
1893                         last = &(this->next);
1894                 } /* loop over "listen" directives in virtual servers */
1895         } /* loop over virtual servers */
1896
1897         /*
1898          *      If we're proxying requests, open the proxy FD.
1899          *      Otherwise, don't do anything.
1900          */
1901  do_proxy:
1902         if (mainconfig.proxy_requests == TRUE) {
1903                 int             port = -1;
1904                 listen_socket_t *sock = NULL;
1905
1906                 /*
1907                  *      No sockets to receive packets, therefore
1908                  *      proxying is pointless.
1909                  */
1910                 if (!*head) return -1;
1911
1912                 /*
1913                  *      If we previously had proxy sockets, copy them
1914                  *      to the new config.
1915                  */
1916                 if (mainconfig.listen != NULL) {
1917                         rad_listen_t *old, *next, **tail;
1918
1919                         tail = &mainconfig.listen;
1920                         for (old = mainconfig.listen;
1921                              old != NULL;
1922                              old = next) {
1923                                 next = old->next;
1924
1925                                 if (old->type != RAD_LISTEN_PROXY) {
1926                                         tail = &((*tail)->next);
1927                                         continue;
1928                                 }
1929
1930                                 *last = old;
1931                                 *tail = next;
1932                                 old->next = NULL;
1933                                 last = &(old->next);
1934                         }
1935
1936                         goto do_snmp;
1937                 }
1938
1939                 /*
1940                  *      Find the first authentication port,
1941                  *      and use it
1942                  */
1943                 for (this = *head; this != NULL; this = this->next) {
1944                         if (this->type == RAD_LISTEN_AUTH) {
1945                                 sock = this->data;
1946                                 if (server_ipaddr.af == AF_UNSPEC) {
1947                                         server_ipaddr = sock->ipaddr;
1948                                 }
1949                                 port = sock->port + 2; /* skip acct port */
1950                                 break;
1951                         }
1952                         if (this->type == RAD_LISTEN_VQP) {
1953                                 sock = this->data;
1954                                 if (server_ipaddr.af == AF_UNSPEC) {
1955                                         server_ipaddr = sock->ipaddr;
1956                                 }
1957                                 port = sock->port + 1;
1958                                 break;
1959                         }
1960                 }
1961
1962                 if (port < 0) port = 1024 + (lrad_rand() & 0x1ff);
1963
1964                 /*
1965                  *      Address is still unspecified, use IPv4.
1966                  */
1967                 if (server_ipaddr.af == AF_UNSPEC) {
1968                         server_ipaddr.af = AF_INET;
1969                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1970                 }
1971
1972                 this = listen_alloc(RAD_LISTEN_PROXY);
1973                 sock = this->data;
1974
1975                 /*
1976                  *      Create the first proxy socket.
1977                  */
1978                 sock->ipaddr = server_ipaddr;
1979
1980                 /*
1981                  *      Try to find a proxy port (value doesn't matter)
1982                  */
1983                 for (sock->port = port;
1984                      sock->port < 64000;
1985                      sock->port++) {
1986                         if (listen_bind(this) == 0) {
1987                                 *last = this;
1988                                 last = &(this->next); /* just in case */
1989                                 break;
1990                         }
1991                 }
1992
1993                 if (sock->port >= 64000) {
1994                         listen_free(head);
1995                         listen_free(&this);
1996                         radlog(L_ERR, "Failed to open socket for proxying");
1997                         return -1;
1998                 }
1999         }
2000
2001  do_snmp:
2002 #ifdef WITH_SNMP
2003         if (mainconfig.do_snmp) {
2004                 radius_snmp_init();
2005
2006                 /*
2007                  *      Forget about the old one.
2008                  */
2009                 for (this = mainconfig.listen;
2010                      this != NULL;
2011                      this = this->next) {
2012                         if (this->type != RAD_LISTEN_SNMP) continue;
2013                         this->fd = -1;
2014                 }
2015
2016                 this = rad_malloc(sizeof(*this));
2017                 memset(this, 0, sizeof(*this));
2018
2019                 this->type = RAD_LISTEN_SNMP;
2020                 this->fd = rad_snmp.smux_fd;
2021
2022                 this->recv = radius_snmp_recv;
2023                 this->print = radius_snmp_print;
2024
2025                 *last = this;
2026                 last = &(this->next);
2027         }
2028 #endif
2029
2030         return 0;
2031 }
2032
2033 /*
2034  *      Free a linked list of listeners;
2035  */
2036 void listen_free(rad_listen_t **head)
2037 {
2038         rad_listen_t *this;
2039
2040         if (!head || !*head) return;
2041
2042         this = *head;
2043         while (this) {
2044                 rad_listen_t *next = this->next;
2045
2046                 /*
2047                  *      Other code may have eaten the FD.
2048                  */
2049                 if (this->fd >= 0) close(this->fd);
2050
2051                 if (master_listen[this->type].free) {
2052                         master_listen[this->type].free(this);
2053                 }
2054                 free(this->data);
2055                 free(this);
2056
2057                 this = next;
2058         }
2059
2060         *head = NULL;
2061 }