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