Re-parent the SNMP MIBs to use our own OID, rather than gnome's
[freeradius.git] / src / main / listen.c
1 /*
2  * listen.c     Handle socket stuff
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2005,2006  The FreeRADIUS server project
21  * Copyright 2005  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/radius_snmp.h>
29 #include <freeradius-devel/modules.h>
30 #include <freeradius-devel/rad_assert.h>
31
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          *      We read the last packet, and returned it for
848          *      processing.  We later come back here to shut
849          *      everything down, and unlink the file.
850          */
851         if (feof(data->fp)) {
852                 if (data->state == STATE_READING) {
853                         data->state = STATE_DONE;
854                         goto alloc_packet;
855                 }
856
857                 /*
858                  *      Don't unlink the file until we've received
859                  *      all of the responses.
860                  */
861                 if (data->max_outstanding > 0) {
862                         int i;
863
864                         for (i = 0; i < data->max_outstanding; i++) {
865                                 /*
866                                  *      FIXME: close the file?
867                                  */
868                                 if (data->outstanding[i]) {
869                                         data->state = STATE_WAITING;
870                                         return 0;
871                                 }
872                         }
873                 }
874
875         cleanup:
876                 rad_assert(data->vps == NULL);
877
878                 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
879                 unlink(buffer);
880                 fclose(data->fp); /* closes listener->fd */
881                 data->fp = NULL;
882                 listener->fd = -1;
883                 data->state = STATE_UNOPENED;
884
885                 /*
886                  *      Try to open "detail" again.  If we're on a
887                  *      busy RADIUS server, odds are that it will
888                  *      now exist.
889                  */
890                 detail_open(listener);
891                 return 0;
892         }
893
894         tail = &data->vps;
895
896         /*
897          *      Fill the buffer...
898          */
899         while (fgets(buffer, sizeof(buffer), data->fp)) {
900                 /*
901                  *      No CR, die.
902                  */
903                 if (!strchr(buffer, '\n')) {
904                         pairfree(&data->vps);
905                         goto cleanup;
906                 }
907
908                 /*
909                  *      We've read a header, possibly packet contents,
910                  *      and are now at the end of the packet.
911                  */
912                 if ((data->state == STATE_READING) &&
913                     (buffer[0] == '\n')) {
914                         data->state = STATE_DONE;
915                         break;
916                 }
917
918                 /*
919                  *      Look for date/time header, and read VP's if
920                  *      found.  If not, keep reading lines until we
921                  *      find one.
922                  */
923                 if (data->state == STATE_HEADER) {
924                         int y;
925                         
926                         if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
927                                 data->state = STATE_READING;
928                         }
929                         continue;
930                 }
931
932                 /*
933                  *      We have a full "attribute = value" line.
934                  *      If it doesn't look reasonable, skip it.
935                  */
936                 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
937                         continue;
938                 }
939
940                 /*
941                  *      Skip non-protocol attributes.
942                  */
943                 if (!strcasecmp(key, "Request-Authenticator")) continue;
944
945                 /*
946                  *      Set the original client IP address, based on
947                  *      what's in the detail file.
948                  *
949                  *      Hmm... we don't set the server IP address.
950                  *      or port.  Oh well.
951                  */
952                 if (!strcasecmp(key, "Client-IP-Address")) {
953                         data->client_ip.af = AF_INET;
954                         ip_hton(value, AF_INET, &data->client_ip);
955                         continue;
956                 }
957
958                 /*
959                  *      The original time at which we received the
960                  *      packet.  We need this to properly calculate
961                  *      Acct-Delay-Time.
962                  */
963                 if (!strcasecmp(key, "Timestamp")) {
964                         data->timestamp = atoi(value);
965                         continue;
966                 }
967
968                 /*
969                  *      Read one VP.
970                  *
971                  *      FIXME: do we want to check for non-protocol
972                  *      attributes like radsqlrelay does?
973                  */
974                 vp = NULL;
975                 if ((userparse(buffer, &vp) > 0) &&
976                     (vp != NULL)) {
977                         *tail = vp;
978                         tail = &(vp->next);
979                 }               
980         }
981
982         /*
983          *      We got to EOF,  If we're in STATE_HEADER, it's OK.
984          *      Otherwise it's a problem.  In any case, nuke the file
985          *      and start over from scratch,
986          */
987         if (feof(data->fp)) {
988                 /*
989                  *      Send the packet.
990                  */
991                 if (data->state == STATE_READING) goto alloc_packet;
992                 pairfree(&data->vps);
993                 goto cleanup;
994         }
995
996         /*
997          *      If we're not done, then there's a problem.  The checks
998          *      above for EOF
999          */
1000         rad_assert(data->state == STATE_DONE);
1001
1002         /*
1003          *      The packet we read was empty, re-set the state to look
1004          *      for a header, and don't return anything.
1005          */
1006         if (!data->vps) {
1007                 data->state = STATE_HEADER;
1008                 return 0;
1009         }
1010
1011         /*
1012          *      Allocate the packet.  If we fail, it's a serious
1013          *      problem.
1014          */
1015  alloc_packet:
1016         /*
1017          *      If we keep track of the outstanding requests, do so
1018          *      here.  Note that to minimize potential work, we do
1019          *      so only once the file is opened & locked.
1020          */
1021         if (data->max_outstanding) {
1022                 int i;
1023
1024                 for (i = 0; i < data->max_outstanding; i++) {
1025                         if (!data->outstanding[i]) {
1026                                 free_slot = i;
1027                                 break;
1028                         }
1029                 }
1030
1031                 /*
1032                  *      All of the slots are full.  Put the LF back,
1033                  *      so select will say that data is ready, and set
1034                  *      the state back to reading.  Then, return so
1035                  *      that we don't overload the server.
1036                  */
1037                 if (free_slot < 0) {
1038                         ungetc('\n', data->fp);
1039                         data->state = STATE_READING;
1040                         return 0;
1041                 }
1042         }
1043
1044         packet = rad_alloc(1);
1045         if (!packet) {
1046                 return 0;       /* maybe memory will magically free up... */
1047         }
1048
1049         memset(packet, 0, sizeof(*packet));
1050         packet->sockfd = -1;
1051         packet->src_ipaddr.af = AF_INET;
1052         packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1053         packet->code = PW_ACCOUNTING_REQUEST;
1054         packet->timestamp = time(NULL);
1055
1056         /*
1057          *      Remember where it came from, so that we don't
1058          *      proxy it to the place it came from...
1059          */
1060         if (data->client_ip.af != AF_UNSPEC) {
1061                 packet->src_ipaddr = data->client_ip;
1062         }
1063
1064         vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
1065         if (vp) {
1066                 packet->src_ipaddr.af = AF_INET;
1067                 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1068         } else {
1069                 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
1070                 if (vp) {
1071                         packet->src_ipaddr.af = AF_INET6;
1072                         memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
1073                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1074                 }
1075         }
1076
1077         vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
1078         if (vp) {
1079                 packet->dst_ipaddr.af = AF_INET;
1080                 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1081         } else {
1082                 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
1083                 if (vp) {
1084                         packet->dst_ipaddr.af = AF_INET6;
1085                         memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
1086                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1087                 }
1088         }
1089
1090         /*
1091          *      We've got to give SOME value for Id & ports, so that
1092          *      the packets can be added to the request queue.
1093          *      However, we don't want to keep track of used/unused
1094          *      id's and ports, as that's a lot of work.  This hack
1095          *      ensures that (if we have real random numbers), that
1096          *      there will be a collision on every 2^(16+15+15+24 - 1)
1097          *      packets, on average.  That means we can read 2^37
1098          *      packets before having a collision, which means it's
1099          *      effectively impossible.
1100          */
1101         packet->id = lrad_rand() & 0xffff;
1102         packet->src_port = 1024 + (lrad_rand() & 0x7fff);
1103         packet->dst_port = 1024 + (lrad_rand() & 0x7fff);
1104
1105         packet->dst_ipaddr.af = AF_INET;
1106         packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (lrad_rand() & 0xffffff));
1107
1108         packet->vps = data->vps;
1109
1110         /*
1111          *      Re-set the state.
1112          */
1113         data->vps = NULL;
1114         data->state = STATE_HEADER;
1115
1116         /*
1117          *      Look for Acct-Delay-Time, and update
1118          *      based on Acct-Delay-Time += (time(NULL) - timestamp)
1119          */
1120         vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
1121         if (!vp) {
1122                 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1123                 rad_assert(vp != NULL);
1124                 pairadd(&packet->vps, vp);
1125         }
1126         if (data->timestamp != 0) {
1127                 vp->vp_integer += time(NULL) - data->timestamp;
1128         }
1129
1130         /*
1131          *      Keep track of free slots, as a hack, in an otherwise
1132          *      unused 'int'
1133          */
1134         (*prequest)->simul_max = free_slot;
1135         data->outstanding[free_slot] = 1;
1136
1137         *pfun = rad_accounting;
1138
1139         if (debug_flag) {
1140                 printf("detail_recv: Read packet from %s\n", data->filename);
1141                 for (vp = packet->vps; vp; vp = vp->next) {
1142                         putchar('\t');
1143                         vp_print(stdout, vp);
1144                         putchar('\n');
1145                 }
1146         }
1147
1148         /*
1149          *      FIXME: many of these checks may not be necessary when
1150          *      reading from the detail file.
1151          */
1152         if (!received_request(listener, packet, prequest, &detail_client)) {
1153                 rad_free(&packet);
1154                 return 0;
1155         }
1156
1157         return 1;
1158 }
1159
1160
1161 /*
1162  *      Free detail-specific stuff.
1163  */
1164 static void detail_free(rad_listen_t *this)
1165 {
1166         listen_detail_t *data = this->data;
1167
1168         free(data->filename);
1169         pairfree(&data->vps);
1170         free(data->outstanding);
1171
1172         if (data->fp != NULL) fclose(data->fp);
1173 }
1174
1175
1176 static int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
1177 {
1178         return snprintf(buffer, bufsize, "%s",
1179                         ((listen_detail_t *)(this->data))->filename);
1180 }
1181
1182 static int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1183 {
1184         /*
1185          *      We never encode responses "sent to" the detail file.
1186          */
1187         return 0;
1188 }
1189
1190 static int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1191 {
1192         /*
1193          *      We never decode responses read from the detail file.
1194          */
1195         return 0;
1196 }
1197
1198
1199 static const CONF_PARSER detail_config[] = {
1200         { "filename",   PW_TYPE_STRING_PTR,
1201           offsetof(listen_detail_t, filename), NULL,  NULL },
1202         { "max_outstanding",  PW_TYPE_INTEGER,
1203            offsetof(listen_detail_t, max_outstanding), NULL, "100" },
1204
1205         { NULL, -1, 0, NULL, NULL }             /* end the list */
1206 };
1207
1208
1209 /*
1210  *      Parse a detail section.
1211  */
1212 static int detail_parse(const char *filename, int lineno,
1213                         const CONF_SECTION *cs, rad_listen_t *this)
1214 {
1215         int             rcode;
1216         listen_detail_t *data;
1217
1218         data = this->data;
1219
1220         rcode = cf_section_parse(cs, data, detail_config);
1221         if (rcode < 0) {
1222                 radlog(L_ERR, "%s[%d]: Failed parsing listen section",
1223                        filename, lineno);
1224                 return -1;
1225         }
1226
1227         if (!data->filename) {
1228                 radlog(L_ERR, "%s[%d]: No detail file specified in listen section",
1229                        filename, lineno);
1230                 return -1;
1231         }
1232         
1233         data->vps = NULL;
1234         data->fp = NULL;
1235         data->state = STATE_UNOPENED;
1236
1237         if (data->max_outstanding > 32768) data->max_outstanding = 32768;
1238
1239         if (data->max_outstanding > 0) {
1240                 data->outstanding = rad_malloc(sizeof(int) * data->max_outstanding);
1241         }
1242         
1243         detail_open(this);
1244
1245         return 0;
1246 }
1247
1248
1249 #ifdef WITH_SNMP
1250 static int radius_snmp_recv(rad_listen_t *listener,
1251                             UNUSED RAD_REQUEST_FUNP *pfun,
1252                             UNUSED REQUEST **prequest)
1253 {
1254         if (!mainconfig.do_snmp) return 0;
1255
1256         if ((rad_snmp.smux_fd >= 0) &&
1257             (rad_snmp.smux_event == SMUX_READ)) {
1258                 smux_read();
1259         }
1260         
1261         /*
1262          *  If we've got to re-connect, then do so now,
1263          *  before calling select again.
1264          */
1265         if (rad_snmp.smux_event == SMUX_CONNECT) {
1266                 smux_connect();
1267         }
1268
1269         /*
1270          *      Reset this every time, as the smux connect may have
1271          *      opened a new socket.
1272          */
1273         listener->fd = rad_snmp.smux_fd;
1274
1275         return 0;
1276 }
1277
1278
1279 static int radius_snmp_print(rad_listen_t *this, char *buffer, size_t bufsize)
1280 {
1281         return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1282 }
1283
1284 #endif
1285
1286 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1287         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1288
1289         /* proxying */
1290         { NULL, NULL,
1291           proxy_socket_recv, proxy_socket_send,
1292           socket_print, proxy_socket_encode, proxy_socket_decode },
1293
1294         /* authentication */
1295         { common_socket_parse, NULL,
1296           auth_socket_recv, auth_socket_send,
1297           socket_print, client_socket_encode, client_socket_decode },
1298
1299         /* accounting */
1300         { common_socket_parse, NULL,
1301           acct_socket_recv, acct_socket_send,
1302           socket_print, client_socket_encode, client_socket_decode},
1303
1304         /* detail */
1305         { detail_parse, detail_free,
1306           detail_recv, detail_send,
1307           detail_print, detail_encode, detail_decode },
1308
1309         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_SNMP */
1310 };
1311
1312
1313
1314 /*
1315  *      Binds a listener to a socket.
1316  */
1317 static int listen_bind(rad_listen_t *this)
1318 {
1319         rad_listen_t    **last;
1320         listen_socket_t *sock = this->data;
1321
1322         /*
1323          *      If the port is zero, then it means the appropriate
1324          *      thing from /etc/services.
1325          */
1326         if (sock->port == 0) {
1327                 struct servent  *svp;
1328
1329                 switch (this->type) {
1330                 case RAD_LISTEN_AUTH:
1331                         svp = getservbyname ("radius", "udp");
1332                         if (svp != NULL) {
1333                                 sock->port = ntohs(svp->s_port);
1334                         } else {
1335                                 sock->port = PW_AUTH_UDP_PORT;
1336                         }
1337                         break;
1338
1339                 case RAD_LISTEN_ACCT:
1340                         svp = getservbyname ("radacct", "udp");
1341                         if (svp != NULL) {
1342                                 sock->port = ntohs(svp->s_port);
1343                         } else {
1344                                 sock->port = PW_ACCT_UDP_PORT;
1345                         }
1346                         break;
1347
1348                 default:
1349                         radlog(L_ERR|L_CONS, "ERROR: Non-fatal internal sanity check failed in bind.");
1350                         return -1;
1351                 }
1352         }
1353
1354         /*
1355          *      Find it in the old list, AFTER updating the port.  If
1356          *      it's there, use that, rather than creating a new
1357          *      socket.  This allows HUP's to re-use the old sockets,
1358          *      which means that packets waiting in the socket queue
1359          *      don't get lost.
1360          */
1361         for (last = &mainconfig.listen;
1362              *last != NULL;
1363              last = &((*last)->next)) {
1364                 listen_socket_t *other;
1365
1366                 if (this->type != (*last)->type) continue;
1367
1368                 if ((this->type == RAD_LISTEN_DETAIL) ||
1369                     (this->type == RAD_LISTEN_SNMP)) continue;
1370
1371                 other = (listen_socket_t *)((*last)->data);
1372
1373                 if ((sock->port == other->port) &&
1374                     (sock->ipaddr.af == other->ipaddr.af) &&
1375                     (lrad_ipaddr_cmp(&sock->ipaddr, &other->ipaddr) == 0)) {
1376                         this->fd = (*last)->fd;
1377                         (*last)->fd = -1;
1378                         return 0;
1379                 }
1380         }
1381
1382         this->fd = lrad_socket(&sock->ipaddr, sock->port);
1383         if (this->fd < 0) {
1384                 radlog(L_ERR|L_CONS, "ERROR: Failed to open socket: %s",
1385                        librad_errstr);
1386                 return -1;
1387         }
1388
1389 #if 0
1390 #ifdef O_NONBLOCK
1391         if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0)  { 
1392                 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno)); 
1393                 return -1;
1394         }
1395
1396         flags |= O_NONBLOCK; 
1397         if( fcntl(this->fd, F_SETFL, flags) < 0) { 
1398                 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno)); 
1399                 return -1;
1400         }
1401 #endif
1402 #endif
1403
1404         return 0;
1405 }
1406
1407
1408 /*
1409  *      Allocate & initialize a new listener.
1410  */
1411 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1412 {
1413         rad_listen_t *this;
1414
1415         this = rad_malloc(sizeof(*this));
1416         memset(this, 0, sizeof(*this));
1417
1418         this->type = type;
1419         this->recv = master_listen[this->type].recv;
1420         this->send = master_listen[this->type].send;
1421         this->print = master_listen[this->type].print;
1422         this->encode = master_listen[this->type].encode;
1423         this->decode = master_listen[this->type].decode;
1424
1425         switch (type) {
1426         case RAD_LISTEN_AUTH:
1427         case RAD_LISTEN_ACCT:
1428         case RAD_LISTEN_PROXY:
1429                 this->data = rad_malloc(sizeof(listen_socket_t));
1430                 memset(this->data, 0, sizeof(listen_socket_t));
1431                 break;
1432
1433         case RAD_LISTEN_DETAIL:
1434                 this->data = rad_malloc(sizeof(listen_detail_t));
1435                 memset(this->data, 0, sizeof(listen_detail_t));
1436                 
1437         default:
1438                 break;
1439         }
1440
1441         return this;
1442 }
1443
1444
1445 /*
1446  *      Externally visible function for creating a new proxy LISTENER.
1447  *
1448  *      For now, don't take ipaddr or port.
1449  *
1450  *      Not thread-safe, but all calls to it are protected by the
1451  *      proxy mutex in request_list.c
1452  */
1453 rad_listen_t *proxy_new_listener()
1454 {
1455         int last_proxy_port, port;
1456         rad_listen_t *this, *tmp, **last;
1457         listen_socket_t *sock, *old;
1458
1459         this = listen_alloc(RAD_LISTEN_PROXY);
1460
1461         /*
1462          *      Find an existing proxy socket to copy.
1463          *
1464          *      FIXME: Make it per-realm, or per-home server!
1465          */
1466         last_proxy_port = 0;
1467         old = NULL;
1468         last = &mainconfig.listen;
1469         for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1470                 if (tmp->type == RAD_LISTEN_PROXY) {
1471                         sock = tmp->data;
1472                         if (sock->port > last_proxy_port) {
1473                                 last_proxy_port = sock->port + 1;
1474                         }
1475                         if (!old) old = sock;
1476                 }
1477
1478                 last = &(tmp->next);
1479         }
1480
1481         if (!old) return NULL;  /* This is a serious error. */
1482
1483         /*
1484          *      FIXME: find a new IP address to listen on?
1485          */
1486         sock = this->data;
1487         memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1488
1489         /*
1490          *      Keep going until we find an unused port.
1491          */
1492         for (port = last_proxy_port; port < 64000; port++) {
1493                 sock->port = port;
1494                 if (listen_bind(this) == 0) {
1495                         /*
1496                          *      Add the new listener to the list of
1497                          *      listeners.
1498                          */
1499                         *last = this;
1500                         return this;
1501                 }
1502         }
1503
1504         return NULL;
1505 }
1506
1507
1508 static const LRAD_NAME_NUMBER listen_compare[] = {
1509         { "auth",       RAD_LISTEN_AUTH },
1510         { "acct",       RAD_LISTEN_ACCT },
1511         { "detail",     RAD_LISTEN_DETAIL },
1512         { NULL, 0 },
1513 };
1514
1515
1516 /*
1517  *      Generate a list of listeners.  Takes an input list of
1518  *      listeners, too, so we don't close sockets with waiting packets.
1519  */
1520 int listen_init(const char *filename, rad_listen_t **head)
1521 {
1522         int             rcode;
1523         CONF_SECTION    *cs;
1524         rad_listen_t    **last;
1525         rad_listen_t    *this;
1526         lrad_ipaddr_t   server_ipaddr;
1527         int             auth_port = 0;
1528
1529         /*
1530          *      We shouldn't be called with a pre-existing list.
1531          */
1532         rad_assert(head && (*head == NULL));
1533         
1534         if (start_time != 0) start_time = time(NULL);
1535
1536         last = head;
1537         server_ipaddr.af = AF_UNSPEC;
1538
1539         /*
1540          *      If the port is specified on the command-line,
1541          *      it over-rides the configuration file.
1542          */
1543         if (mainconfig.port >= 0) {
1544                 auth_port = mainconfig.port;
1545         } else {
1546                 rcode = cf_item_parse(mainconfig.config, "port",
1547                                       PW_TYPE_INTEGER, &auth_port,
1548                                       Stringify(PW_AUTH_UDP_PORT));
1549                 if (rcode < 0) return -1; /* error parsing it */
1550
1551                 if (rcode == 0)
1552                         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'.");
1553         }
1554
1555         /*
1556          *      If the IP address was configured on the command-line,
1557          *      use that as the "bind_address"
1558          */
1559         if (mainconfig.myip.af != AF_UNSPEC) {
1560                 memcpy(&server_ipaddr, &mainconfig.myip,
1561                        sizeof(server_ipaddr));
1562                 goto bind_it;
1563         }
1564
1565         /*
1566          *      Else look for bind_address and/or listen sections.
1567          */
1568         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1569         rcode = cf_item_parse(mainconfig.config, "bind_address",
1570                               PW_TYPE_IPADDR,
1571                               &server_ipaddr.ipaddr.ip4addr, NULL);
1572         if (rcode < 0) return -1; /* error parsing it */
1573         
1574         if (rcode == 0) { /* successfully parsed IPv4 */
1575                 listen_socket_t *sock;
1576                 server_ipaddr.af = AF_INET;
1577
1578                 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'.");
1579
1580         bind_it:
1581                 this = listen_alloc(RAD_LISTEN_AUTH);
1582                 sock = this->data;
1583
1584                 sock->ipaddr = server_ipaddr;
1585                 sock->port = auth_port;
1586                 
1587                 if (listen_bind(this) < 0) {
1588                         listen_free(&this);
1589                         listen_free(head);
1590                         radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1591                         return -1;
1592                 }
1593                 auth_port = sock->port; /* may have been updated in listen_bind */
1594                 *last = this;
1595                 last = &(this->next);
1596                 
1597                 /*
1598                  *      Open Accounting Socket.
1599                  *
1600                  *      If we haven't already gotten acct_port from
1601                  *      /etc/services, then make it auth_port + 1.
1602                  */
1603                 this = listen_alloc(RAD_LISTEN_ACCT);
1604                 sock = this->data;
1605                 
1606                 /*
1607                  *      Create the accounting socket.
1608                  *
1609                  *      The accounting port is always the
1610                  *      authentication port + 1
1611                  */
1612                 sock->ipaddr = server_ipaddr;
1613                 sock->port = auth_port + 1;
1614                 
1615                 if (listen_bind(this) < 0) {
1616                         listen_free(&this);
1617                         listen_free(head);
1618                         radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1619                         return -1;
1620                 }
1621
1622                 *last = this;
1623                 last = &(this->next);
1624
1625         } else if (mainconfig.port > 0) { /* no bind address, but a port */
1626                 radlog(L_CONS|L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1627                        mainconfig.port);
1628                 return -1;
1629         }
1630
1631         /*
1632          *      They specified an IP on the command-line, ignore
1633          *      all listen sections.
1634          */
1635         if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1636
1637         /*
1638          *      Walk through the "listen" sections, if they exist.
1639          */
1640         for (cs = cf_subsection_find_next(mainconfig.config, NULL, "listen");
1641              cs != NULL;
1642              cs = cf_subsection_find_next(mainconfig.config, cs, "listen")) {
1643                 int             type;
1644                 char            *listen_type, *identity;
1645                 int             lineno = cf_section_lineno(cs);
1646
1647                 listen_type = identity = NULL;
1648                 
1649                 DEBUG2(" listen {");
1650
1651                 rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1652                                       &listen_type, "");
1653                 if (rcode < 0) return -1;
1654                 if (rcode == 1) {
1655                         listen_free(head);
1656                         free(listen_type);
1657                         radlog(L_ERR, "%s[%d]: No type specified in listen section",
1658                                filename, lineno);
1659                         return -1;
1660                 }
1661
1662                 /*
1663                  *      See if there's an identity.
1664                  */
1665                 rcode = cf_item_parse(cs, "identity", PW_TYPE_STRING_PTR,
1666                                       &identity, NULL);
1667                 if (rcode < 0) {
1668                         listen_free(head);
1669                         free(identity);
1670                         return -1;
1671                 }
1672
1673                 type = lrad_str2int(listen_compare, listen_type,
1674                                     RAD_LISTEN_NONE);
1675                 free(listen_type);
1676                 if (type == RAD_LISTEN_NONE) {
1677                         listen_free(head);
1678                         radlog(L_CONS|L_ERR, "%s[%d]: Invalid type in listen section.",
1679                                filename, lineno);
1680                         return -1;
1681                 }
1682
1683                 /*
1684                  *      Set up cross-type data.
1685                  */
1686                 this = listen_alloc(type);
1687                 this->identity = identity;
1688                 this->fd = -1;
1689                 
1690                 /*
1691                  *      Call per-type parser.
1692                  */
1693                 if (master_listen[type].parse(filename, lineno,
1694                                               cs, this) < 0) {
1695                         listen_free(&this);
1696                         listen_free(head);
1697                         return -1;
1698                 }
1699
1700                 DEBUG2(" }");
1701
1702                 *last = this;
1703                 last = &(this->next);   
1704         }
1705
1706         /*
1707          *      If we're proxying requests, open the proxy FD.
1708          *      Otherwise, don't do anything.
1709          */
1710  do_proxy:
1711         if (mainconfig.proxy_requests == TRUE) {
1712                 int             port = -1;
1713                 listen_socket_t *sock = NULL;
1714
1715                 /*
1716                  *      No sockets to receive packets, therefore
1717                  *      proxying is pointless.
1718                  */
1719                 if (!*head) return -1;
1720
1721                 /*
1722                  *      If we previously had proxy sockets, copy them
1723                  *      to the new config.
1724                  */
1725                 if (mainconfig.listen != NULL) {
1726                         rad_listen_t *old, *next, **tail;
1727
1728                         tail = &mainconfig.listen;
1729                         for (old = mainconfig.listen;
1730                              old != NULL;
1731                              old = next) {
1732                                 next = old->next;
1733
1734                                 if (old->type != RAD_LISTEN_PROXY) {
1735                                         tail = &((*tail)->next);
1736                                         continue;
1737                                 }
1738
1739                                 *last = old;
1740                                 *tail = next;
1741                                 old->next = NULL;
1742                                 last = &(old->next);
1743                         }
1744
1745                         goto do_snmp;
1746                 }
1747
1748                 /*
1749                  *      Find the first authentication port,
1750                  *      and use it
1751                  */
1752                 for (this = *head; this != NULL; this = this->next) {
1753                         if (this->type == RAD_LISTEN_AUTH) {
1754                                 sock = this->data;
1755                                 if (server_ipaddr.af == AF_UNSPEC) {
1756                                         server_ipaddr = sock->ipaddr;
1757                                 }
1758                                 port = sock->port + 2; /* skip acct port */
1759                                 break;
1760                         }
1761                 }
1762
1763                 if (port < 0) port = 1024 + (lrad_rand() & 0x1ff);
1764
1765                 /*
1766                  *      Address is still unspecified, use IPv4.
1767                  */
1768                 if (server_ipaddr.af == AF_UNSPEC) {
1769                         server_ipaddr.af = AF_INET;
1770                         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1771                 }
1772
1773                 this = listen_alloc(RAD_LISTEN_PROXY);
1774                 sock = this->data;
1775
1776                 /*
1777                  *      Create the first proxy socket.
1778                  */
1779                 sock->ipaddr = server_ipaddr;
1780
1781                 /*
1782                  *      Try to find a proxy port (value doesn't matter)
1783                  */
1784                 for (sock->port = port;
1785                      sock->port < 64000;
1786                      sock->port++) {
1787                         if (listen_bind(this) == 0) {
1788                                 *last = this;
1789                                 last = &(this->next); /* just in case */
1790                                 break;
1791                         }
1792                 }
1793
1794                 if (sock->port >= 64000) {
1795                         listen_free(head);
1796                         listen_free(&this);
1797                         radlog(L_ERR|L_CONS, "Failed to open socket for proxying");
1798                         return -1;
1799                 }
1800         }
1801         
1802  do_snmp:
1803 #ifdef WITH_SNMP
1804         if (mainconfig.do_snmp) {
1805                 radius_snmp_init();
1806
1807                 /*
1808                  *      Forget about the old one.
1809                  */
1810                 for (this = mainconfig.listen;
1811                      this != NULL;
1812                      this = this->next) {
1813                         if (this->type != RAD_LISTEN_SNMP) continue;
1814                         this->fd = -1;
1815                 }
1816
1817                 this = rad_malloc(sizeof(*this));
1818                 memset(this, 0, sizeof(*this));
1819                 
1820                 this->type = RAD_LISTEN_SNMP;
1821                 this->fd = rad_snmp.smux_fd;
1822                 
1823                 this->recv = radius_snmp_recv;
1824                 this->print = radius_snmp_print;
1825
1826                 *last = this;
1827                 last = &(this->next);
1828         }
1829 #endif
1830
1831         /*
1832          *      Sanity check the configuration.
1833          */
1834         rcode = 0;
1835         if (mainconfig.listen != NULL) for (this = *head;
1836                                             this != NULL;
1837                                             this = this->next) {
1838                 if (((this->type == RAD_LISTEN_ACCT) &&
1839                      (rcode == RAD_LISTEN_DETAIL)) ||
1840                     ((this->type == RAD_LISTEN_DETAIL) &&
1841                      (rcode == RAD_LISTEN_ACCT))) {
1842                         rad_assert(0 == 1); /* FIXME: configuration error */
1843                 }
1844
1845                 if (rcode != 0) continue;
1846
1847                 if ((this->type == RAD_LISTEN_ACCT) ||
1848                     (this->type == RAD_LISTEN_DETAIL)) {
1849                         rcode = this->type;
1850                 }
1851         }
1852
1853  done:
1854         return 0;
1855 }
1856
1857 /*
1858  *      Free a linked list of listeners;
1859  */
1860 void listen_free(rad_listen_t **head)
1861 {
1862         rad_listen_t *this;
1863
1864         if (!head || !*head) return;
1865
1866         this = *head;
1867         while (this) {
1868                 rad_listen_t *next = this->next;
1869                 
1870                 free(this->identity);
1871
1872                 /*
1873                  *      Other code may have eaten the FD.
1874                  */
1875                 if (this->fd >= 0) close(this->fd);
1876
1877                 if (master_listen[this->type].free) {
1878                         master_listen[this->type].free(this);
1879                 }
1880                 free(this->data);
1881                 free(this);
1882                 
1883                 this = next;
1884         }
1885
1886         *head = NULL;
1887 }