2 * listen.c Handle socket stuff
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.
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.
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
20 * Copyright 2005,2006 The FreeRADIUS server project
21 * Copyright 2005 Alan DeKok <aland@ox.org>
24 #include <freeradius-devel/ident.h>
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>
33 #include <freeradius-devel/vmps.h>
35 #include <sys/resource.h>
41 #ifdef HAVE_SYS_STAT_H
47 #define USEC (1000000)
50 * We'll use this below.
52 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
53 typedef void (*rad_listen_free_t)(rad_listen_t *);
55 typedef struct rad_listen_master_t {
56 rad_listen_parse_t parse;
57 rad_listen_free_t free;
58 rad_listen_recv_t recv;
59 rad_listen_send_t send;
60 rad_listen_print_t print;
61 rad_listen_encode_t encode;
62 rad_listen_decode_t decode;
63 } rad_listen_master_t;
65 typedef struct listen_socket_t {
71 RADCLIENT_LIST *clients;
74 typedef struct listen_detail_t {
80 lrad_ipaddr_t client_ip;
81 int load_factor; /* 1..100 */
87 struct timeval last_packet;
92 * Find a per-socket client.
94 RADCLIENT *client_listener_find(const rad_listen_t *listener,
95 const lrad_ipaddr_t *ipaddr)
97 const RADCLIENT_LIST *clients;
99 rad_assert(listener != NULL);
100 rad_assert(ipaddr != NULL);
102 rad_assert((listener->type == RAD_LISTEN_AUTH) ||
103 (listener->type == RAD_LISTEN_ACCT) ||
104 (listener->type == RAD_LISTEN_VQP));
106 clients = ((listen_socket_t *)listener->data)->clients;
107 if (!clients) clients = mainconfig.clients;
109 rad_assert(clients != NULL);
111 return client_find(clients, ipaddr);
114 static int listen_bind(rad_listen_t *this);
117 * Process and reply to a server-status request.
118 * Like rad_authenticate and rad_accounting this should
119 * live in it's own file but it's so small we don't bother.
121 static int rad_status_server(REQUEST *request)
123 int rcode = RLM_MODULE_OK;
126 switch (request->listener->type) {
127 case RAD_LISTEN_AUTH:
128 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
130 rcode = module_authorize(dval->value, request);
132 rcode = RLM_MODULE_OK;
137 case RLM_MODULE_UPDATED:
138 request->reply->code = PW_AUTHENTICATION_ACK;
141 case RLM_MODULE_FAIL:
142 case RLM_MODULE_HANDLED:
143 request->reply->code = 0; /* don't reply */
147 case RLM_MODULE_REJECT:
148 request->reply->code = PW_AUTHENTICATION_REJECT;
153 case RAD_LISTEN_ACCT:
154 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
156 rcode = module_accounting(dval->value, request);
158 rcode = RLM_MODULE_OK;
163 case RLM_MODULE_UPDATED:
164 request->reply->code = PW_ACCOUNTING_RESPONSE;
168 request->reply->code = 0; /* don't reply */
181 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
184 listen_socket_t *sock = this->data;
188 if ((sock->ipaddr.af == AF_INET) &&
189 (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
192 ip_ntoh(&sock->ipaddr, ip_buf, sizeof(ip_buf));
195 switch (this->type) {
196 case RAD_LISTEN_AUTH:
197 name = "authentication";
200 case RAD_LISTEN_ACCT:
204 case RAD_LISTEN_PROXY:
220 return snprintf(buffer, bufsize, "%s address %s port %d",
221 name, ip_buf, sock->port);
224 return snprintf(buffer, bufsize, "%s address %s port %d as server %s",
225 name, ip_buf, sock->port, this->server);
230 * Parse an authentication or accounting socket.
232 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
236 lrad_ipaddr_t ipaddr;
237 listen_socket_t *sock = this->data;
238 const char *section_name = NULL;
239 CONF_SECTION *client_cs;
244 ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
245 rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
246 &ipaddr.ipaddr.ip4addr, NULL);
247 if (rcode < 0) return -1;
249 if (rcode == 0) { /* successfully parsed IPv4 */
252 } else { /* maybe IPv6? */
253 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
254 &ipaddr.ipaddr.ip6addr, NULL);
255 if (rcode < 0) return -1;
258 cf_log_err(cf_sectiontoitem(cs),
259 "No address specified in listen section");
262 ipaddr.af = AF_INET6;
265 rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
267 if (rcode < 0) return -1;
269 sock->ipaddr = ipaddr;
270 sock->port = listen_port;
273 * And bind it to the port.
275 if (listen_bind(this) < 0) {
277 cf_log_err(cf_sectiontoitem(cs),
278 "Error binding to port for %s port %d",
279 ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
285 * If we can bind to interfaces, do so,
288 if (cf_pair_find(cs, "interface")) {
289 #ifndef SO_BINDTODEVICE
290 cf_log_err(cf_sectiontoitem(cs),
291 "System does not support binding to interfaces. Delete this line from the configuration file.");
295 CONF_PAIR *cp = cf_pair_find(cs, "interface");
298 rad_assert(cp != NULL);
299 value = cf_pair_value(cp);
301 cf_log_err(cf_sectiontoitem(cs),
302 "No interface name given");
306 strcpy(ifreq.ifr_name, value);
308 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
309 (char *)&ifreq, sizeof(ifreq)) < 0) {
310 cf_log_err(cf_sectiontoitem(cs),
311 "Failed binding to interface %s: %s",
312 value, strerror(errno));
314 } /* else it worked. */
319 * If we have a server, prefer to use clients defined
320 * in that server, and ignore any "clients = "
321 * directive, UNLESS there are no clients in the server.
324 client_cs = cf_section_sub_find_name2(mainconfig.config,
329 * Found a "server foo" section, but there are no
330 * clients in it. Don't use this section.
333 (cf_section_sub_find(client_cs, "client") == NULL)) {
338 * No clients, look for the name of a section that holds
342 rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
343 §ion_name, NULL);
344 if (rcode < 0) return -1; /* bad string */
347 * Explicit list given: use it.
349 client_cs = cf_section_find(section_name);
352 cf_log_err(cf_sectiontoitem(cs),
353 "Failed to find clients %s {...}",
357 } /* else there was no "clients = " entry. */
361 * Still nothing. Make it global.
363 if (!client_cs) client_cs = mainconfig.config;
365 sock->clients = clients_parse_section(client_cs);
366 if (!sock->clients) {
374 * Send an authentication response packet
376 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
378 rad_assert(request->listener == listener);
379 rad_assert(listener->send == auth_socket_send);
381 return rad_send(request->reply, request->packet,
382 request->client->secret);
387 * Send an accounting response packet (or not)
389 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
391 rad_assert(request->listener == listener);
392 rad_assert(listener->send == acct_socket_send);
395 * Accounting reject's are silently dropped.
397 * We do it here to avoid polluting the rest of the
398 * code with this knowledge
400 if (request->reply->code == 0) return 0;
402 return rad_send(request->reply, request->packet,
403 request->client->secret);
408 * Send a packet to a home server.
410 * FIXME: have different code for proxy auth & acct!
412 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
414 listen_socket_t *sock = listener->data;
416 rad_assert(request->proxy_listener == listener);
417 rad_assert(listener->send == proxy_socket_send);
419 request->proxy->src_ipaddr = sock->ipaddr;
420 request->proxy->src_port = sock->port;
422 return rad_send(request->proxy, request->packet,
423 request->home_server->secret);
428 * Check if an incoming request is "ok"
430 * It takes packets, not requests. It sees if the packet looks
431 * OK. If so, it does a number of sanity checks on it.
433 static int auth_socket_recv(rad_listen_t *listener,
434 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
438 RADIUS_PACKET *packet;
439 RAD_REQUEST_FUNP fun = NULL;
442 lrad_ipaddr_t src_ipaddr;
444 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
445 if (rcode < 0) return 0;
447 RAD_SNMP_TYPE_INC(listener, total_requests);
449 if (rcode < 20) { /* AUTH_HDR_LEN */
450 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
454 if ((client = client_listener_find(listener,
455 &src_ipaddr)) == NULL) {
456 rad_recv_discard(listener->fd);
457 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
460 * This is debugging rather than logging, so that
461 * DoS attacks don't affect us.
463 DEBUG("Ignoring request from unknown client %s port %d",
464 inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
465 buffer, sizeof(buffer)), src_port);
470 * Some sanity checks, based on the packet code.
473 case PW_AUTHENTICATION_REQUEST:
474 RAD_SNMP_CLIENT_INC(listener, client, requests);
475 fun = rad_authenticate;
478 case PW_STATUS_SERVER:
479 if (!mainconfig.status_server) {
480 rad_recv_discard(listener->fd);
481 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
482 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
483 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
486 fun = rad_status_server;
490 rad_recv_discard(listener->fd);
491 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
492 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
494 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
495 code, client->shortname, src_port);
498 } /* switch over packet types */
501 * Now that we've sanity checked everything, receive the
504 packet = rad_recv(listener->fd);
506 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
507 radlog(L_ERR, "%s", librad_errstr);
511 if (!received_request(listener, packet, prequest, client)) {
512 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
513 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
524 * Receive packets from an accounting socket
526 static int acct_socket_recv(rad_listen_t *listener,
527 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
531 RADIUS_PACKET *packet;
532 RAD_REQUEST_FUNP fun = NULL;
535 lrad_ipaddr_t src_ipaddr;
537 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
538 if (rcode < 0) return 0;
540 RAD_SNMP_TYPE_INC(listener, total_requests);
542 if (rcode < 20) { /* AUTH_HDR_LEN */
543 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
547 if ((client = client_listener_find(listener,
548 &src_ipaddr)) == NULL) {
549 rad_recv_discard(listener->fd);
550 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
553 * This is debugging rather than logging, so that
554 * DoS attacks don't affect us.
556 DEBUG("Ignoring request from unknown client %s port %d",
557 inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
558 buffer, sizeof(buffer)), src_port);
563 * Some sanity checks, based on the packet code.
566 case PW_ACCOUNTING_REQUEST:
567 RAD_SNMP_CLIENT_INC(listener, client, requests);
568 fun = rad_accounting;
571 case PW_STATUS_SERVER:
572 if (!mainconfig.status_server) {
573 rad_recv_discard(listener->fd);
574 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
575 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
577 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
580 fun = rad_status_server;
584 rad_recv_discard(listener->fd);
585 RAD_SNMP_TYPE_INC(listener, total_unknown_types);
586 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
588 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
589 code, client->shortname, src_port);
591 } /* switch over packet types */
594 * Now that we've sanity checked everything, receive the
597 packet = rad_recv(listener->fd);
599 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
600 radlog(L_ERR, "%s", librad_errstr);
605 * There can be no duplicate accounting packets.
607 if (!received_request(listener, packet, prequest, client)) {
608 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
609 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
620 * Recieve packets from a proxy socket.
622 static int proxy_socket_recv(rad_listen_t *listener,
623 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
626 RADIUS_PACKET *packet;
627 RAD_REQUEST_FUNP fun = NULL;
630 packet = rad_recv(listener->fd);
632 radlog(L_ERR, "%s", librad_errstr);
637 * FIXME: Client MIB updates?
639 switch(packet->code) {
640 case PW_AUTHENTICATION_ACK:
641 case PW_ACCESS_CHALLENGE:
642 case PW_AUTHENTICATION_REJECT:
643 fun = rad_authenticate;
646 case PW_ACCOUNTING_RESPONSE:
647 fun = rad_accounting;
652 * FIXME: Update MIB for packet types?
654 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
655 "from home server %s port %d - ID %d : IGNORED",
657 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
658 packet->src_port, packet->id);
663 request = received_proxy_response(packet);
668 rad_assert(fun != NULL);
676 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
678 if (!request->reply->code) return 0;
680 rad_encode(request->reply, request->packet,
681 request->client->secret);
682 rad_sign(request->reply, request->packet,
683 request->client->secret);
689 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
691 if (rad_verify(request->packet, NULL,
692 request->client->secret) < 0) {
696 return rad_decode(request->packet, NULL,
697 request->client->secret);
700 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
702 rad_encode(request->proxy, NULL, request->home_server->secret);
703 rad_sign(request->proxy, NULL, request->home_server->secret);
709 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
711 if (rad_verify(request->proxy_reply, request->proxy,
712 request->home_server->secret) < 0) {
716 return rad_decode(request->proxy_reply, request->proxy,
717 request->home_server->secret);
721 #define STATE_UNOPENED (0)
722 #define STATE_UNLOCKED (1)
723 #define STATE_HEADER (2)
724 #define STATE_READING (3)
725 #define STATE_QUEUED (4)
726 #define STATE_RUNNING (5)
727 #define STATE_NO_REPLY (6)
728 #define STATE_REPLIED (7)
731 * If we're limiting outstanding packets, then mark the response
734 static int detail_send(rad_listen_t *listener, REQUEST *request)
738 listen_detail_t *data = listener->data;
740 rad_assert(request->listener == listener);
741 rad_assert(listener->send == detail_send);
744 * This request timed out. Remember that, and tell the
745 * caller it's OK to read more "detail" file stuff.
747 if (request->reply->code == 0) {
748 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
749 data->state = STATE_NO_REPLY;
754 * We call gettimeofday a lot. But here it should be OK,
755 * because there's nothing else to do.
757 gettimeofday(&now, NULL);
760 * If we haven't sent a packet in the last second, reset
764 if (timercmp(&data->last_packet, &now, <)) {
765 data->has_rtt = FALSE;
770 * Only one detail packet may be outstanding at a time,
771 * so it's safe to update some entries in the detail
774 * We keep smoothed round trip time (SRTT), but not round
775 * trip timeout (RTO). We use SRTT to calculate a rough
778 rtt = now.tv_sec - request->received.tv_sec;
781 rtt -= request->received.tv_usec;
784 * If we're proxying, the RTT is our processing time,
785 * plus the network delay there and back, plus the time
786 * on the other end to process the packet. Ideally, we
787 * should remove the network delays from the RTT, but we
788 * don't know what they are.
790 * So, to be safe, we over-estimate the total cost of
791 * processing the packet.
793 if (!data->has_rtt) {
794 data->has_rtt = TRUE;
796 data->rttvar = rtt / 2;
799 data->rttvar -= data->rttvar >> 2;
800 data->rttvar += (data->srtt - rtt);
801 data->srtt -= data->srtt >> 3;
802 data->srtt += rtt >> 3;
806 * Calculate the time we wait before sending the next
809 * rtt / (rtt + delay) = load_factor / 100
811 data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
814 * FIXME: Push this delay to the event handler!
816 DEBUG2("RTT %d\tdelay %d", data->srtt, data->delay_time);
818 usleep(data->delay_time);
819 data->last_packet = now;
820 data->state = STATE_REPLIED;
827 * Open the detail file..
829 * FIXME: create it, if it's not already there, so that the main
830 * server select() will wake us up if there's anything to read.
832 static int detail_open(rad_listen_t *this)
836 listen_detail_t *data = this->data;
838 rad_assert(data->state == STATE_UNOPENED);
839 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
842 * Open detail.work first, so we don't lose
843 * accounting packets. It's probably better to
844 * duplicate them than to lose them.
846 * Note that we're not writing to the file, but
847 * we've got to open it for writing in order to
848 * establish the lock, to prevent rlm_detail from
851 this->fd = open(buffer, O_RDWR);
854 * Try reading the detail file. If it
855 * doesn't exist, we can't do anything.
857 * Doing the stat will tell us if the file
858 * exists, even if we don't have permissions
861 if (stat(data->filename, &st) < 0) {
866 * Open it BEFORE we rename it, just to
869 this->fd = open(data->filename, O_RDWR);
871 radlog(L_ERR, "Failed to open %s: %s",
872 data->filename, strerror(errno));
877 * Rename detail to detail.work
879 if (rename(data->filename, buffer) < 0) {
884 } /* else detail.work existed, and we opened it */
886 rad_assert(data->vps == NULL);
888 rad_assert(data->fp == NULL);
889 data->fp = fdopen(this->fd, "r");
891 radlog(L_ERR, "Failed to re-open %s: %s",
892 data->filename, strerror(errno));
896 data->state = STATE_UNLOCKED;
898 data->client_ip.af = AF_UNSPEC;
905 * FIXME: this should be dynamically allocated.
907 static const RADCLIENT detail_client = {
926 * FIXME: add a configuration "exit when done" so that the detail
927 * file reader can be used as a one-off tool to update stuff.
929 * The time sequence for reading from the detail file is:
931 * t_0 signalled that the server is idle, and we
932 * can read from the detail file.
934 * t_rtt the packet has been processed successfully,
935 * wait for t_delay to enforce load factor.
937 * t_rtt + t_delay wait for signal that the server is idle.
940 static int detail_recv(rad_listen_t *listener,
941 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
943 char key[256], value[1024];
944 VALUE_PAIR *vp, **tail;
945 RADIUS_PACKET *packet;
947 listen_detail_t *data = listener->data;
949 switch (data->state) {
951 rad_assert(listener->fd < 0);
954 * FIXME: If the file doesn't exist, then
955 * return "sleep for 1s", to avoid busy
958 if (!detail_open(listener)) return 0;
960 rad_assert(data->state == STATE_UNLOCKED);
961 rad_assert(listener->fd >= 0);
966 * Try to lock fd. If we can't, return.
967 * If we can, continue. This means that
968 * the server doesn't block while waiting
969 * for the lock to open...
973 * Note that we do NOT block waiting for
974 * the lock. We've re-named the file
975 * above, so we've already guaranteed
976 * that any *new* detail writer will not
977 * be opening this file. The only
978 * purpose of the lock is to catch a race
979 * condition where the execution
980 * "ping-pongs" between radiusd &
983 if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
987 * Look for the header
989 data->state = STATE_HEADER;
997 * End of file. Delete it, and re-set
1000 if (feof(data->fp)) {
1002 snprintf(buffer, sizeof(buffer),
1003 "%s.work", data->filename);
1005 fclose(data->fp); /* closes listener->fd */
1008 data->state = STATE_UNOPENED;
1009 rad_assert(data->vps == NULL);
1014 * Else go read something.
1019 * Read more value-pair's, unless we're
1020 * at EOF. In that case, queue whatever
1024 if (!feof(data->fp)) break;
1025 data->state = STATE_QUEUED;
1033 * We still have an outstanding packet.
1034 * Don't read any more.
1040 * If there's no reply, keep
1041 * retransmitting the current packet
1044 case STATE_NO_REPLY:
1045 data->state = STATE_QUEUED;
1049 * We have a reply. Clean up the old
1050 * request, and go read another one.
1053 pairfree(&data->vps);
1054 data->state = STATE_HEADER;
1059 while (*tail) tail = &(*tail)->next;
1062 * Read a header, OR a value-pair.
1064 while (fgets(buffer, sizeof(buffer), data->fp)) {
1066 * Badly formatted file: delete it.
1068 * FIXME: Maybe flag an error?
1070 if (!strchr(buffer, '\n')) {
1071 pairfree(&data->vps);
1076 * We're reading VP's, and got a blank line.
1079 if ((data->state == STATE_READING) &&
1080 (buffer[0] == '\n')) {
1081 data->state = STATE_QUEUED;
1086 * Look for date/time header, and read VP's if
1087 * found. If not, keep reading lines until we
1090 if (data->state == STATE_HEADER) {
1093 if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
1094 data->state = STATE_READING;
1100 * We have a full "attribute = value" line.
1101 * If it doesn't look reasonable, skip it.
1103 * FIXME: print an error for badly formatted attributes?
1105 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
1110 * Skip non-protocol attributes.
1112 if (!strcasecmp(key, "Request-Authenticator")) continue;
1115 * Set the original client IP address, based on
1116 * what's in the detail file.
1118 * Hmm... we don't set the server IP address.
1121 if (!strcasecmp(key, "Client-IP-Address")) {
1122 data->client_ip.af = AF_INET;
1123 ip_hton(value, AF_INET, &data->client_ip);
1128 * The original time at which we received the
1129 * packet. We need this to properly calculate
1132 if (!strcasecmp(key, "Timestamp")) {
1133 data->timestamp = atoi(value);
1140 * FIXME: do we want to check for non-protocol
1141 * attributes like radsqlrelay does?
1144 if ((userparse(buffer, &vp) > 0) &&
1152 * Some kind of error.
1154 * FIXME: Leave the file in-place, and warn the
1157 if (ferror(data->fp)) goto cleanup;
1160 * Process the packet.
1163 rad_assert(data->state == STATE_QUEUED);
1166 * We're done reading the file, but we didn't read
1167 * anything. Clean up, and don't return anything.
1170 data->state = STATE_HEADER;
1175 * Allocate the packet. If we fail, it's a serious
1178 packet = rad_alloc(1);
1180 data->state = STATE_NO_REPLY; /* try again later */
1181 return 0; /* maybe memory will magically free up... */
1184 memset(packet, 0, sizeof(*packet));
1185 packet->sockfd = -1;
1186 packet->src_ipaddr.af = AF_INET;
1187 packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1188 packet->code = PW_ACCOUNTING_REQUEST;
1189 packet->timestamp = time(NULL);
1192 * Remember where it came from, so that we don't
1193 * proxy it to the place it came from...
1195 if (data->client_ip.af != AF_UNSPEC) {
1196 packet->src_ipaddr = data->client_ip;
1199 vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
1201 packet->src_ipaddr.af = AF_INET;
1202 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1204 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
1206 packet->src_ipaddr.af = AF_INET6;
1207 memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
1208 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1212 vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
1214 packet->dst_ipaddr.af = AF_INET;
1215 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1217 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
1219 packet->dst_ipaddr.af = AF_INET6;
1220 memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
1221 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1226 * We've got to give SOME value for Id & ports, so that
1227 * the packets can be added to the request queue.
1228 * However, we don't want to keep track of used/unused
1229 * id's and ports, as that's a lot of work. This hack
1230 * ensures that (if we have real random numbers), that
1231 * there will be a collision on every 2^(16+15+15+24 - 1)
1232 * packets, on average. That means we can read 2^37
1233 * packets before having a collision, which means it's
1234 * effectively impossible.
1236 packet->id = lrad_rand() & 0xffff;
1237 packet->src_port = 1024 + (lrad_rand() & 0x7fff);
1238 packet->dst_port = 1024 + (lrad_rand() & 0x7fff);
1240 packet->dst_ipaddr.af = AF_INET;
1241 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (lrad_rand() & 0xffffff));
1244 * If everything's OK, this is a waste of memory.
1245 * Otherwise, it lets us re-send the original packet
1246 * contents, unmolested.
1248 packet->vps = paircopy(data->vps);
1251 * Look for Acct-Delay-Time, and update
1252 * based on Acct-Delay-Time += (time(NULL) - timestamp)
1254 vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
1256 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1257 rad_assert(vp != NULL);
1258 pairadd(&packet->vps, vp);
1260 if (data->timestamp != 0) {
1261 vp->vp_integer += time(NULL) - data->timestamp;
1264 *pfun = rad_accounting;
1267 printf("detail_recv: Read packet from %s\n", data->filename);
1268 for (vp = packet->vps; vp; vp = vp->next) {
1270 vp_print(stdout, vp);
1276 * FIXME: many of these checks may not be necessary when
1277 * reading from the detail file.
1279 * Try again later...
1281 if (!received_request(listener, packet, prequest, &detail_client)) {
1283 data->state = STATE_NO_REPLY; /* try again later */
1287 data->state = STATE_RUNNING;
1294 * Free detail-specific stuff.
1296 static void detail_free(rad_listen_t *this)
1298 listen_detail_t *data = this->data;
1300 free(data->filename);
1301 pairfree(&data->vps);
1303 if (data->fp != NULL) fclose(data->fp);
1307 static int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
1309 if (!this->server) {
1310 return snprintf(buffer, bufsize, "%s",
1311 ((listen_detail_t *)(this->data))->filename);
1314 return snprintf(buffer, bufsize, "detail file %s as server %s",
1315 ((listen_detail_t *)(this->data))->filename,
1319 static int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1322 * We never encode responses "sent to" the detail file.
1327 static int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1330 * We never decode responses read from the detail file.
1336 static const CONF_PARSER detail_config[] = {
1337 { "filename", PW_TYPE_STRING_PTR,
1338 offsetof(listen_detail_t, filename), NULL, NULL },
1339 { "load_factor", PW_TYPE_INTEGER,
1340 offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
1342 { NULL, -1, 0, NULL, NULL } /* end the list */
1347 * Parse a detail section.
1349 static int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
1352 listen_detail_t *data;
1356 rcode = cf_section_parse(cs, data, detail_config);
1358 cf_log_err(cf_sectiontoitem(cs), "Failed parsing listen section");
1362 if (!data->filename) {
1363 cf_log_err(cf_sectiontoitem(cs), "No detail file specified in listen section");
1367 if ((data->load_factor < 1) || (data->load_factor > 100)) {
1368 cf_log_err(cf_sectiontoitem(cs), "Load factor must be between 1 and 100");
1374 data->state = STATE_UNOPENED;
1382 static int radius_snmp_recv(rad_listen_t *listener,
1383 UNUSED RAD_REQUEST_FUNP *pfun,
1384 UNUSED REQUEST **prequest)
1386 if (!mainconfig.do_snmp) return 0;
1388 if ((rad_snmp.smux_fd >= 0) &&
1389 (rad_snmp.smux_event == SMUX_READ)) {
1394 * If we've got to re-connect, then do so now,
1395 * before calling select again.
1397 if (rad_snmp.smux_event == SMUX_CONNECT) {
1402 * Reset this every time, as the smux connect may have
1403 * opened a new socket.
1405 listener->fd = rad_snmp.smux_fd;
1411 static int radius_snmp_print(UNUSED rad_listen_t *this, char *buffer, size_t bufsize)
1413 return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1418 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1419 { NULL, NULL, NULL, NULL, NULL, NULL, NULL}, /* RAD_LISTEN_NONE */
1423 proxy_socket_recv, proxy_socket_send,
1424 socket_print, proxy_socket_encode, proxy_socket_decode },
1426 /* authentication */
1427 { common_socket_parse, NULL,
1428 auth_socket_recv, auth_socket_send,
1429 socket_print, client_socket_encode, client_socket_decode },
1432 { common_socket_parse, NULL,
1433 acct_socket_recv, acct_socket_send,
1434 socket_print, client_socket_encode, client_socket_decode},
1437 { detail_parse, detail_free,
1438 detail_recv, detail_send,
1439 detail_print, detail_encode, detail_decode },
1442 /* vlan query protocol */
1443 { common_socket_parse, NULL,
1444 vqp_socket_recv, vqp_socket_send,
1445 socket_print, vqp_socket_encode, vqp_socket_decode },
1447 { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1450 { NULL, NULL, NULL, NULL, NULL, NULL, NULL} /* RAD_LISTEN_SNMP */
1456 * Binds a listener to a socket.
1458 static int listen_bind(rad_listen_t *this)
1460 rad_listen_t **last;
1461 listen_socket_t *sock = this->data;
1464 * If the port is zero, then it means the appropriate
1465 * thing from /etc/services.
1467 if (sock->port == 0) {
1468 struct servent *svp;
1470 switch (this->type) {
1471 case RAD_LISTEN_AUTH:
1472 svp = getservbyname ("radius", "udp");
1474 sock->port = ntohs(svp->s_port);
1476 sock->port = PW_AUTH_UDP_PORT;
1480 case RAD_LISTEN_ACCT:
1481 svp = getservbyname ("radacct", "udp");
1483 sock->port = ntohs(svp->s_port);
1485 sock->port = PW_ACCT_UDP_PORT;
1490 case RAD_LISTEN_VQP:
1496 radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1502 * Find it in the old list, AFTER updating the port. If
1503 * it's there, use that, rather than creating a new
1504 * socket. This allows HUP's to re-use the old sockets,
1505 * which means that packets waiting in the socket queue
1508 for (last = &mainconfig.listen;
1510 last = &((*last)->next)) {
1511 listen_socket_t *other;
1513 if (this->type != (*last)->type) continue;
1515 if ((this->type == RAD_LISTEN_DETAIL) ||
1516 (this->type == RAD_LISTEN_SNMP)) continue;
1518 other = (listen_socket_t *)((*last)->data);
1520 if ((sock->port == other->port) &&
1521 (sock->ipaddr.af == other->ipaddr.af) &&
1522 (lrad_ipaddr_cmp(&sock->ipaddr, &other->ipaddr) == 0)) {
1523 this->fd = (*last)->fd;
1529 this->fd = lrad_socket(&sock->ipaddr, sock->port);
1531 radlog(L_ERR, "ERROR: Failed to open socket: %s",
1538 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0) {
1539 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1543 flags |= O_NONBLOCK;
1544 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1545 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1556 * Allocate & initialize a new listener.
1558 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1562 this = rad_malloc(sizeof(*this));
1563 memset(this, 0, sizeof(*this));
1566 this->recv = master_listen[this->type].recv;
1567 this->send = master_listen[this->type].send;
1568 this->print = master_listen[this->type].print;
1569 this->encode = master_listen[this->type].encode;
1570 this->decode = master_listen[this->type].decode;
1573 case RAD_LISTEN_AUTH:
1574 case RAD_LISTEN_ACCT:
1575 case RAD_LISTEN_PROXY:
1576 case RAD_LISTEN_VQP:
1577 this->data = rad_malloc(sizeof(listen_socket_t));
1578 memset(this->data, 0, sizeof(listen_socket_t));
1581 case RAD_LISTEN_DETAIL:
1582 this->data = rad_malloc(sizeof(listen_detail_t));
1583 memset(this->data, 0, sizeof(listen_detail_t));
1586 rad_assert("Unsupported option!" == NULL);
1595 * Externally visible function for creating a new proxy LISTENER.
1597 * For now, don't take ipaddr or port.
1599 * Not thread-safe, but all calls to it are protected by the
1600 * proxy mutex in request_list.c
1602 rad_listen_t *proxy_new_listener()
1604 int last_proxy_port, port;
1605 rad_listen_t *this, *tmp, **last;
1606 listen_socket_t *sock, *old;
1608 this = listen_alloc(RAD_LISTEN_PROXY);
1611 * Find an existing proxy socket to copy.
1613 * FIXME: Make it per-realm, or per-home server!
1615 last_proxy_port = 0;
1617 last = &mainconfig.listen;
1618 for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1619 if (tmp->type == RAD_LISTEN_PROXY) {
1621 if (sock->port > last_proxy_port) {
1622 last_proxy_port = sock->port + 1;
1624 if (!old) old = sock;
1627 last = &(tmp->next);
1630 if (!old) return NULL; /* This is a serious error. */
1633 * FIXME: find a new IP address to listen on?
1635 * This could likely be done in the "home server"
1636 * configuration, to have per-home-server source IP's.
1639 memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1642 * Keep going until we find an unused port.
1644 for (port = last_proxy_port; port < 64000; port++) {
1646 if (listen_bind(this) == 0) {
1648 * Add the new listener to the list of
1660 static const LRAD_NAME_NUMBER listen_compare[] = {
1661 { "auth", RAD_LISTEN_AUTH },
1662 { "acct", RAD_LISTEN_ACCT },
1663 { "detail", RAD_LISTEN_DETAIL },
1665 { "vmps", RAD_LISTEN_VQP },
1671 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
1679 DEBUG2(" listen {");
1681 rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1683 if (rcode < 0) return NULL;
1686 cf_log_err(cf_sectiontoitem(cs),
1687 "No type specified in listen section");
1691 type = lrad_str2int(listen_compare, listen_type,
1694 if (type == RAD_LISTEN_NONE) {
1695 cf_log_err(cf_sectiontoitem(cs),
1696 "Invalid type \"%s\" in listen section.",
1702 * Allow listen sections in the default config to
1703 * refer to a server.
1706 rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1708 if (rcode < 0) return NULL;
1712 * Set up cross-type data.
1714 this = listen_alloc(type);
1715 this->server = server;
1719 * Call per-type parser.
1721 if (master_listen[type].parse(cs, this) < 0) {
1732 * Generate a list of listeners. Takes an input list of
1733 * listeners, too, so we don't close sockets with waiting packets.
1735 int listen_init(CONF_SECTION *config, rad_listen_t **head)
1739 rad_listen_t **last;
1741 lrad_ipaddr_t server_ipaddr;
1745 * We shouldn't be called with a pre-existing list.
1747 rad_assert(head && (*head == NULL));
1750 server_ipaddr.af = AF_UNSPEC;
1753 * If the port is specified on the command-line,
1754 * it over-rides the configuration file.
1756 * FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1758 if (mainconfig.port >= 0) auth_port = mainconfig.port;
1761 * If the IP address was configured on the command-line,
1762 * use that as the "bind_address"
1764 if (mainconfig.myip.af != AF_UNSPEC) {
1765 memcpy(&server_ipaddr, &mainconfig.myip,
1766 sizeof(server_ipaddr));
1771 * Else look for bind_address and/or listen sections.
1773 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1774 rcode = cf_item_parse(config, "bind_address",
1776 &server_ipaddr.ipaddr.ip4addr, NULL);
1777 if (rcode < 0) return -1; /* error parsing it */
1779 if (rcode == 0) { /* successfully parsed IPv4 */
1780 listen_socket_t *sock;
1781 server_ipaddr.af = AF_INET;
1783 radlog(L_INFO, "WARNING: The directive 'bind_adress' is deprecated, and will be removed in future versions of FreeRADIUS. Please edit the configuration files to use the directive 'listen'.");
1787 if (strcmp(progname, "vmpsd") == 0) {
1788 this = listen_alloc(RAD_LISTEN_VQP);
1789 if (!auth_port) auth_port = 1589;
1792 this = listen_alloc(RAD_LISTEN_AUTH);
1796 sock->ipaddr = server_ipaddr;
1797 sock->port = auth_port;
1799 if (listen_bind(this) < 0) {
1802 radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1805 auth_port = sock->port; /* may have been updated in listen_bind */
1807 last = &(this->next);
1813 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1817 * Open Accounting Socket.
1819 * If we haven't already gotten acct_port from
1820 * /etc/services, then make it auth_port + 1.
1822 this = listen_alloc(RAD_LISTEN_ACCT);
1826 * Create the accounting socket.
1828 * The accounting port is always the
1829 * authentication port + 1
1831 sock->ipaddr = server_ipaddr;
1832 sock->port = auth_port + 1;
1834 if (listen_bind(this) < 0) {
1837 radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1842 last = &(this->next);
1844 } else if (mainconfig.port > 0) { /* no bind address, but a port */
1845 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1851 * They specified an IP on the command-line, ignore
1852 * all listen sections.
1854 if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1857 * Walk through the "listen" sections, if they exist.
1859 for (cs = cf_subsection_find_next(config, NULL, "listen");
1861 cs = cf_subsection_find_next(config, cs, "listen")) {
1862 this = listen_parse(cs, NULL);
1869 last = &(this->next);
1873 * Check virtual servers for "listen" sections, too.
1875 * FIXME: Move to virtual server init?
1877 for (cs = cf_subsection_find_next(config, NULL, "server");
1879 cs = cf_subsection_find_next(config, cs, "server")) {
1880 CONF_SECTION *subcs;
1881 const char *name2 = cf_section_name2(cs);
1883 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
1885 subcs = cf_subsection_find_next(cs, subcs, "listen")) {
1886 this = listen_parse(subcs, name2);
1893 last = &(this->next);
1894 } /* loop over "listen" directives in virtual servers */
1895 } /* loop over virtual servers */
1898 * If we're proxying requests, open the proxy FD.
1899 * Otherwise, don't do anything.
1902 if (mainconfig.proxy_requests == TRUE) {
1904 listen_socket_t *sock = NULL;
1907 * No sockets to receive packets, therefore
1908 * proxying is pointless.
1910 if (!*head) return -1;
1913 * If we previously had proxy sockets, copy them
1914 * to the new config.
1916 if (mainconfig.listen != NULL) {
1917 rad_listen_t *old, *next, **tail;
1919 tail = &mainconfig.listen;
1920 for (old = mainconfig.listen;
1925 if (old->type != RAD_LISTEN_PROXY) {
1926 tail = &((*tail)->next);
1933 last = &(old->next);
1940 * Find the first authentication port,
1943 for (this = *head; this != NULL; this = this->next) {
1944 if (this->type == RAD_LISTEN_AUTH) {
1946 if (server_ipaddr.af == AF_UNSPEC) {
1947 server_ipaddr = sock->ipaddr;
1949 port = sock->port + 2; /* skip acct port */
1952 if (this->type == RAD_LISTEN_VQP) {
1954 if (server_ipaddr.af == AF_UNSPEC) {
1955 server_ipaddr = sock->ipaddr;
1957 port = sock->port + 1;
1962 if (port < 0) port = 1024 + (lrad_rand() & 0x1ff);
1965 * Address is still unspecified, use IPv4.
1967 if (server_ipaddr.af == AF_UNSPEC) {
1968 server_ipaddr.af = AF_INET;
1969 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1972 this = listen_alloc(RAD_LISTEN_PROXY);
1976 * Create the first proxy socket.
1978 sock->ipaddr = server_ipaddr;
1981 * Try to find a proxy port (value doesn't matter)
1983 for (sock->port = port;
1986 if (listen_bind(this) == 0) {
1988 last = &(this->next); /* just in case */
1993 if (sock->port >= 64000) {
1996 radlog(L_ERR, "Failed to open socket for proxying");
2003 if (mainconfig.do_snmp) {
2007 * Forget about the old one.
2009 for (this = mainconfig.listen;
2011 this = this->next) {
2012 if (this->type != RAD_LISTEN_SNMP) continue;
2016 this = rad_malloc(sizeof(*this));
2017 memset(this, 0, sizeof(*this));
2019 this->type = RAD_LISTEN_SNMP;
2020 this->fd = rad_snmp.smux_fd;
2022 this->recv = radius_snmp_recv;
2023 this->print = radius_snmp_print;
2026 last = &(this->next);
2034 * Free a linked list of listeners;
2036 void listen_free(rad_listen_t **head)
2040 if (!head || !*head) return;
2044 rad_listen_t *next = this->next;
2047 * Other code may have eaten the FD.
2049 if (this->fd >= 0) close(this->fd);
2051 if (master_listen[this->type].free) {
2052 master_listen[this->type].free(this);