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