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