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 <sys/resource.h>
39 #ifdef HAVE_SYS_STAT_H
45 #define USEC (1000000)
48 * We'll use this below.
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 *);
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;
63 typedef struct listen_socket_t {
69 RADCLIENT_LIST *clients;
72 typedef struct listen_detail_t {
78 lrad_ipaddr_t client_ip;
79 int load_factor; /* 1..100 */
85 struct timeval last_packet;
90 * Find a per-socket client.
92 static RADCLIENT *client_listener_find(const rad_listen_t *listener,
93 const lrad_ipaddr_t *ipaddr)
95 const RADCLIENT_LIST *clients;
97 rad_assert(listener != NULL);
98 rad_assert(ipaddr != NULL);
100 rad_assert((listener->type == RAD_LISTEN_AUTH) ||
101 (listener->type == RAD_LISTEN_ACCT) ||
102 (listener->type == RAD_LISTEN_VQP));
104 clients = ((listen_socket_t *)listener->data)->clients;
105 if (!clients) clients = mainconfig.clients;
107 rad_assert(clients != NULL);
109 return client_find(clients, ipaddr);
112 static int listen_bind(rad_listen_t *this);
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.
119 static int rad_status_server(REQUEST *request)
121 int rcode = RLM_MODULE_OK;
124 switch (request->listener->type) {
125 case RAD_LISTEN_AUTH:
126 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
128 rcode = module_authorize(dval->value, request);
130 rcode = RLM_MODULE_OK;
135 case RLM_MODULE_UPDATED:
136 request->reply->code = PW_AUTHENTICATION_ACK;
139 case RLM_MODULE_FAIL:
140 case RLM_MODULE_HANDLED:
141 request->reply->code = 0; /* don't reply */
145 case RLM_MODULE_REJECT:
146 request->reply->code = PW_AUTHENTICATION_REJECT;
151 case RAD_LISTEN_ACCT:
152 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
154 rcode = module_accounting(dval->value, request);
156 rcode = RLM_MODULE_OK;
161 case RLM_MODULE_UPDATED:
162 request->reply->code = PW_ACCOUNTING_RESPONSE;
166 request->reply->code = 0; /* don't reply */
179 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
182 listen_socket_t *sock = this->data;
184 if ((sock->ipaddr.af == AF_INET) &&
185 (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
188 ip_ntoh(&sock->ipaddr, buffer, bufsize);
191 len = strlen(buffer);
194 return len + snprintf(buffer + len, bufsize - len, " port %d",
198 return len + snprintf(buffer + len, bufsize - len, " port %d as server %s",
199 sock->port, this->server);
204 * Parse an authentication or accounting socket.
206 static int common_socket_parse(const char *filename, int lineno,
207 CONF_SECTION *cs, rad_listen_t *this)
211 lrad_ipaddr_t ipaddr;
212 listen_socket_t *sock = this->data;
213 const char *section_name = NULL;
214 CONF_SECTION *client_cs;
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;
224 if (rcode == 0) { /* successfully parsed IPv4 */
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;
233 radlog(L_ERR, "%s[%d]: No address specified in listen section",
237 ipaddr.af = AF_INET6;
240 rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
242 if (rcode < 0) return -1;
244 sock->ipaddr = ipaddr;
245 sock->port = listen_port;
248 * And bind it to the port.
250 if (listen_bind(this) < 0) {
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)),
260 * If we can bind to interfaces, do so,
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));
270 CONF_PAIR *cp = cf_pair_find(cs, "interface");
273 rad_assert(cp != NULL);
274 value = cf_pair_value(cp);
275 rad_assert(value != NULL);
277 strcpy(ifreq.ifr_name, value);
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));
285 } /* else it worked. */
290 * Look for the name of a section that holds a list
293 rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
294 §ion_name, NULL);
295 if (rcode < 0) return -1; /* bad string */
298 * Explicit list given: use it.
300 client_cs = cf_section_find(section_name);
303 radlog(L_CONS|L_ERR, "%s[%d]: Failed to find client section %s",
304 filename, cf_section_lineno(cs), section_name);
308 } else if (this->server) {
310 * Else base it off of the server.
312 client_cs = cf_section_sub_find_name2(mainconfig.config,
316 (cf_section_sub_find(client_cs, "client") == NULL)) {
317 client_cs = mainconfig.config;
321 client_cs = mainconfig.config;
324 sock->clients = clients_parse_section(filename, client_cs);
325 if (!sock->clients) {
333 * Send an authentication response packet
335 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
337 rad_assert(request->listener == listener);
338 rad_assert(listener->send == auth_socket_send);
340 return rad_send(request->reply, request->packet,
341 request->client->secret);
346 * Send an accounting response packet (or not)
348 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
350 rad_assert(request->listener == listener);
351 rad_assert(listener->send == acct_socket_send);
354 * Accounting reject's are silently dropped.
356 * We do it here to avoid polluting the rest of the
357 * code with this knowledge
359 if (request->reply->code == 0) return 0;
361 return rad_send(request->reply, request->packet,
362 request->client->secret);
367 * Send a packet to a home server.
369 * FIXME: have different code for proxy auth & acct!
371 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
373 listen_socket_t *sock = listener->data;
375 rad_assert(request->proxy_listener == listener);
376 rad_assert(listener->send == proxy_socket_send);
378 request->proxy->src_ipaddr = sock->ipaddr;
379 request->proxy->src_port = sock->port;
381 return rad_send(request->proxy, request->packet,
382 request->home_server->secret);
387 * Check if an incoming request is "ok"
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.
392 static int auth_socket_recv(rad_listen_t *listener,
393 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
397 RADIUS_PACKET *packet;
398 RAD_REQUEST_FUNP fun = NULL;
401 lrad_ipaddr_t src_ipaddr;
403 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
404 if (rcode < 0) return 0;
406 RAD_SNMP_TYPE_INC(listener, total_requests);
408 if (rcode < 20) { /* AUTH_HDR_LEN */
409 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
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);
419 * This is debugging rather than logging, so that
420 * DoS attacks don't affect us.
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);
429 * Some sanity checks, based on the packet code.
432 case PW_AUTHENTICATION_REQUEST:
433 RAD_SNMP_CLIENT_INC(listener, client, requests);
434 fun = rad_authenticate;
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");
445 fun = rad_status_server;
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);
453 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
454 code, client->shortname, src_port);
457 } /* switch over packet types */
460 * Now that we've sanity checked everything, receive the
463 packet = rad_recv(listener->fd);
465 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
466 radlog(L_ERR, "%s", librad_errstr);
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);
483 * Receive packets from an accounting socket
485 static int acct_socket_recv(rad_listen_t *listener,
486 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
490 RADIUS_PACKET *packet;
491 RAD_REQUEST_FUNP fun = NULL;
494 lrad_ipaddr_t src_ipaddr;
496 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
497 if (rcode < 0) return 0;
499 RAD_SNMP_TYPE_INC(listener, total_requests);
501 if (rcode < 20) { /* AUTH_HDR_LEN */
502 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
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);
512 * This is debugging rather than logging, so that
513 * DoS attacks don't affect us.
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);
522 * Some sanity checks, based on the packet code.
525 case PW_ACCOUNTING_REQUEST:
526 RAD_SNMP_CLIENT_INC(listener, client, requests);
527 fun = rad_accounting;
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);
536 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
539 fun = rad_status_server;
543 rad_recv_discard(listener->fd);
544 RAD_SNMP_TYPE_INC(listener, total_unknown_types);
545 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
547 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
548 code, client->shortname, src_port);
550 } /* switch over packet types */
553 * Now that we've sanity checked everything, receive the
556 packet = rad_recv(listener->fd);
558 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
559 radlog(L_ERR, "%s", librad_errstr);
564 * There can be no duplicate accounting packets.
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);
579 * Recieve packets from a proxy socket.
581 static int proxy_socket_recv(rad_listen_t *listener,
582 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
585 RADIUS_PACKET *packet;
586 RAD_REQUEST_FUNP fun = NULL;
589 packet = rad_recv(listener->fd);
591 radlog(L_ERR, "%s", librad_errstr);
596 * FIXME: Client MIB updates?
598 switch(packet->code) {
599 case PW_AUTHENTICATION_ACK:
600 case PW_ACCESS_CHALLENGE:
601 case PW_AUTHENTICATION_REJECT:
602 fun = rad_authenticate;
605 case PW_ACCOUNTING_RESPONSE:
606 fun = rad_accounting;
611 * FIXME: Update MIB for packet types?
613 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
614 "from home server %s port %d - ID %d : IGNORED",
616 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
617 packet->src_port, packet->id);
622 request = received_proxy_response(packet);
627 rad_assert(fun != NULL);
635 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
637 if (!request->reply->code) return 0;
639 rad_encode(request->reply, request->packet,
640 request->client->secret);
641 rad_sign(request->reply, request->packet,
642 request->client->secret);
648 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
650 if (rad_verify(request->packet, NULL,
651 request->client->secret) < 0) {
655 return rad_decode(request->packet, NULL,
656 request->client->secret);
659 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
661 rad_encode(request->proxy, NULL, request->home_server->secret);
662 rad_sign(request->proxy, NULL, request->home_server->secret);
668 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
670 if (rad_verify(request->proxy_reply, request->proxy,
671 request->home_server->secret) < 0) {
675 return rad_decode(request->proxy_reply, request->proxy,
676 request->home_server->secret);
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)
690 * If we're limiting outstanding packets, then mark the response
693 static int detail_send(rad_listen_t *listener, REQUEST *request)
697 listen_detail_t *data = listener->data;
699 rad_assert(request->listener == listener);
700 rad_assert(listener->send == detail_send);
703 * This request timed out. Remember that, and tell the
704 * caller it's OK to read more "detail" file stuff.
706 if (request->reply->code == 0) {
707 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
708 data->state = STATE_NO_REPLY;
713 * We call gettimeofday a lot. But here it should be OK,
714 * because there's nothing else to do.
716 gettimeofday(&now, NULL);
719 * If we haven't sent a packet in the last second, reset
723 if (timercmp(&data->last_packet, &now, <)) {
724 data->has_rtt = FALSE;
729 * Only one detail packet may be outstanding at a time,
730 * so it's safe to update some entries in the detail
733 * We keep smoothed round trip time (SRTT), but not round
734 * trip timeout (RTO). We use SRTT to calculate a rough
737 rtt = now.tv_sec - request->received.tv_sec;
740 rtt -= request->received.tv_usec;
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.
749 * So, to be safe, we over-estimate the total cost of
750 * processing the packet.
752 if (!data->has_rtt) {
753 data->has_rtt = TRUE;
755 data->rttvar = rtt / 2;
758 data->rttvar -= data->rttvar >> 2;
759 data->rttvar += (data->srtt - rtt);
760 data->srtt -= data->srtt >> 3;
761 data->srtt += rtt >> 3;
765 * Calculate the time we wait before sending the next
768 * rtt / (rtt + delay) = load_factor / 100
770 data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
773 * FIXME: Push this delay to the event handler!
775 DEBUG2("RTT %d\tdelay %d", data->srtt, data->delay_time);
777 usleep(data->delay_time);
778 data->last_packet = now;
779 data->state = STATE_REPLIED;
786 * Open the detail file..
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.
791 static int detail_open(rad_listen_t *this)
795 listen_detail_t *data = this->data;
797 rad_assert(data->state == STATE_UNOPENED);
798 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
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.
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
810 this->fd = open(buffer, O_RDWR);
813 * Try reading the detail file. If it
814 * doesn't exist, we can't do anything.
816 * Doing the stat will tell us if the file
817 * exists, even if we don't have permissions
820 if (stat(data->filename, &st) < 0) {
825 * Open it BEFORE we rename it, just to
828 this->fd = open(data->filename, O_RDWR);
830 radlog(L_ERR, "Failed to open %s: %s",
831 data->filename, strerror(errno));
836 * Rename detail to detail.work
838 if (rename(data->filename, buffer) < 0) {
843 } /* else detail.work existed, and we opened it */
845 rad_assert(data->vps == NULL);
847 rad_assert(data->fp == NULL);
848 data->fp = fdopen(this->fd, "r");
850 radlog(L_ERR, "Failed to re-open %s: %s",
851 data->filename, strerror(errno));
855 data->state = STATE_UNLOCKED;
857 data->client_ip.af = AF_UNSPEC;
864 * FIXME: this should be dynamically allocated.
866 static const RADCLIENT detail_client = {
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.
888 * The time sequence for reading from the detail file is:
890 * t_0 signalled that the server is idle, and we
891 * can read from the detail file.
893 * t_rtt the packet has been processed successfully,
894 * wait for t_delay to enforce load factor.
896 * t_rtt + t_delay wait for signal that the server is idle.
899 static int detail_recv(rad_listen_t *listener,
900 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
902 char key[256], value[1024];
903 VALUE_PAIR *vp, **tail;
904 RADIUS_PACKET *packet;
906 listen_detail_t *data = listener->data;
908 switch (data->state) {
910 rad_assert(listener->fd < 0);
913 * FIXME: If the file doesn't exist, then
914 * return "sleep for 1s", to avoid busy
917 if (!detail_open(listener)) return 0;
919 rad_assert(data->state == STATE_UNLOCKED);
920 rad_assert(listener->fd >= 0);
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...
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 &
942 if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
946 * Look for the header
948 data->state = STATE_HEADER;
956 * End of file. Delete it, and re-set
959 if (feof(data->fp)) {
961 snprintf(buffer, sizeof(buffer),
962 "%s.work", data->filename);
964 fclose(data->fp); /* closes listener->fd */
967 data->state = STATE_UNOPENED;
968 rad_assert(data->vps == NULL);
973 * Else go read something.
978 * Read more value-pair's, unless we're
979 * at EOF. In that case, queue whatever
983 if (!feof(data->fp)) break;
984 data->state = STATE_QUEUED;
992 * We still have an outstanding packet.
993 * Don't read any more.
999 * If there's no reply, keep
1000 * retransmitting the current packet
1003 case STATE_NO_REPLY:
1004 data->state = STATE_QUEUED;
1008 * We have a reply. Clean up the old
1009 * request, and go read another one.
1012 pairfree(&data->vps);
1013 data->state = STATE_HEADER;
1018 while (*tail) tail = &(*tail)->next;
1021 * Read a header, OR a value-pair.
1023 while (fgets(buffer, sizeof(buffer), data->fp)) {
1025 * Badly formatted file: delete it.
1027 * FIXME: Maybe flag an error?
1029 if (!strchr(buffer, '\n')) {
1030 pairfree(&data->vps);
1035 * We're reading VP's, and got a blank line.
1038 if ((data->state == STATE_READING) &&
1039 (buffer[0] == '\n')) {
1040 data->state = STATE_QUEUED;
1045 * Look for date/time header, and read VP's if
1046 * found. If not, keep reading lines until we
1049 if (data->state == STATE_HEADER) {
1052 if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
1053 data->state = STATE_READING;
1059 * We have a full "attribute = value" line.
1060 * If it doesn't look reasonable, skip it.
1062 * FIXME: print an error for badly formatted attributes?
1064 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
1069 * Skip non-protocol attributes.
1071 if (!strcasecmp(key, "Request-Authenticator")) continue;
1074 * Set the original client IP address, based on
1075 * what's in the detail file.
1077 * Hmm... we don't set the server IP address.
1080 if (!strcasecmp(key, "Client-IP-Address")) {
1081 data->client_ip.af = AF_INET;
1082 ip_hton(value, AF_INET, &data->client_ip);
1087 * The original time at which we received the
1088 * packet. We need this to properly calculate
1091 if (!strcasecmp(key, "Timestamp")) {
1092 data->timestamp = atoi(value);
1099 * FIXME: do we want to check for non-protocol
1100 * attributes like radsqlrelay does?
1103 if ((userparse(buffer, &vp) > 0) &&
1111 * Some kind of error.
1113 * FIXME: Leave the file in-place, and warn the
1116 if (ferror(data->fp)) goto cleanup;
1119 * Process the packet.
1122 rad_assert(data->state == STATE_QUEUED);
1125 * We're done reading the file, but we didn't read
1126 * anything. Clean up, and don't return anything.
1129 data->state = STATE_HEADER;
1134 * Allocate the packet. If we fail, it's a serious
1137 packet = rad_alloc(1);
1139 data->state = STATE_NO_REPLY; /* try again later */
1140 return 0; /* maybe memory will magically free up... */
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);
1151 * Remember where it came from, so that we don't
1152 * proxy it to the place it came from...
1154 if (data->client_ip.af != AF_UNSPEC) {
1155 packet->src_ipaddr = data->client_ip;
1158 vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
1160 packet->src_ipaddr.af = AF_INET;
1161 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1163 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
1165 packet->src_ipaddr.af = AF_INET6;
1166 memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
1167 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1171 vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
1173 packet->dst_ipaddr.af = AF_INET;
1174 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1176 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
1178 packet->dst_ipaddr.af = AF_INET6;
1179 memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
1180 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
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.
1195 packet->id = lrad_rand() & 0xffff;
1196 packet->src_port = 1024 + (lrad_rand() & 0x7fff);
1197 packet->dst_port = 1024 + (lrad_rand() & 0x7fff);
1199 packet->dst_ipaddr.af = AF_INET;
1200 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (lrad_rand() & 0xffffff));
1203 * If everything's OK, this is a waste of memory.
1204 * Otherwise, it lets us re-send the original packet
1205 * contents, unmolested.
1207 packet->vps = paircopy(data->vps);
1210 * Look for Acct-Delay-Time, and update
1211 * based on Acct-Delay-Time += (time(NULL) - timestamp)
1213 vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
1215 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1216 rad_assert(vp != NULL);
1217 pairadd(&packet->vps, vp);
1219 if (data->timestamp != 0) {
1220 vp->vp_integer += time(NULL) - data->timestamp;
1223 *pfun = rad_accounting;
1226 printf("detail_recv: Read packet from %s\n", data->filename);
1227 for (vp = packet->vps; vp; vp = vp->next) {
1229 vp_print(stdout, vp);
1235 * FIXME: many of these checks may not be necessary when
1236 * reading from the detail file.
1238 * Try again later...
1240 if (!received_request(listener, packet, prequest, &detail_client)) {
1242 data->state = STATE_NO_REPLY; /* try again later */
1246 data->state = STATE_RUNNING;
1253 * Free detail-specific stuff.
1255 static void detail_free(rad_listen_t *this)
1257 listen_detail_t *data = this->data;
1259 free(data->filename);
1260 pairfree(&data->vps);
1262 if (data->fp != NULL) fclose(data->fp);
1266 static int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
1268 if (!this->server) {
1269 return snprintf(buffer, bufsize, "%s",
1270 ((listen_detail_t *)(this->data))->filename);
1273 return snprintf(buffer, bufsize, "%s as server %s",
1274 ((listen_detail_t *)(this->data))->filename,
1278 static int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1281 * We never encode responses "sent to" the detail file.
1286 static int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1289 * We never decode responses read from the detail file.
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)},
1301 { NULL, -1, 0, NULL, NULL } /* end the list */
1306 * Parse a detail section.
1308 static int detail_parse(const char *filename, int lineno,
1309 CONF_SECTION *cs, rad_listen_t *this)
1312 listen_detail_t *data;
1316 rcode = cf_section_parse(cs, data, detail_config);
1318 radlog(L_ERR, "%s[%d]: Failed parsing listen section",
1323 if (!data->filename) {
1324 radlog(L_ERR, "%s[%d]: No detail file specified in listen section",
1329 if ((data->load_factor < 1) || (data->load_factor > 100)) {
1330 radlog(L_ERR, "%s[%d]: Load factor must be between 1 and 100",
1337 data->state = STATE_UNOPENED;
1345 static int radius_snmp_recv(rad_listen_t *listener,
1346 UNUSED RAD_REQUEST_FUNP *pfun,
1347 UNUSED REQUEST **prequest)
1349 if (!mainconfig.do_snmp) return 0;
1351 if ((rad_snmp.smux_fd >= 0) &&
1352 (rad_snmp.smux_event == SMUX_READ)) {
1357 * If we've got to re-connect, then do so now,
1358 * before calling select again.
1360 if (rad_snmp.smux_event == SMUX_CONNECT) {
1365 * Reset this every time, as the smux connect may have
1366 * opened a new socket.
1368 listener->fd = rad_snmp.smux_fd;
1374 static int radius_snmp_print(UNUSED rad_listen_t *this, char *buffer, size_t bufsize)
1376 return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1383 * Check if an incoming request is "ok"
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.
1388 static int vqp_socket_recv(rad_listen_t *listener,
1389 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1391 RADIUS_PACKET *packet;
1392 RAD_REQUEST_FUNP fun = NULL;
1396 packet = vqp_recv(listener->fd);
1398 radlog(L_ERR, "%s", librad_errstr);
1402 if ((client = client_listener_find(listener,
1403 &packet->src_ipaddr)) == NULL) {
1404 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
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)),
1420 if (!received_request(listener, packet, prequest, client)) {
1432 * Send an authentication response packet
1434 static int vqp_socket_send(rad_listen_t *listener, REQUEST *request)
1436 rad_assert(request->listener == listener);
1437 rad_assert(listener->send == vqp_socket_send);
1439 if (vqp_encode(request->reply, request->packet) < 0) {
1440 DEBUG2("Failed encoding packet: %s\n", librad_errstr);
1444 return vqp_send(request->reply);
1448 static int vqp_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1450 return vqp_encode(request->reply, request->packet);
1454 static int vqp_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1456 return vqp_decode(request->packet);
1458 #endif /* WITH_VMPS */
1461 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1462 { NULL, NULL, NULL, NULL, NULL, NULL, NULL}, /* RAD_LISTEN_NONE */
1466 proxy_socket_recv, proxy_socket_send,
1467 socket_print, proxy_socket_encode, proxy_socket_decode },
1469 /* authentication */
1470 { common_socket_parse, NULL,
1471 auth_socket_recv, auth_socket_send,
1472 socket_print, client_socket_encode, client_socket_decode },
1475 { common_socket_parse, NULL,
1476 acct_socket_recv, acct_socket_send,
1477 socket_print, client_socket_encode, client_socket_decode},
1480 { detail_parse, detail_free,
1481 detail_recv, detail_send,
1482 detail_print, detail_encode, detail_decode },
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 },
1490 { NULL, NULL, NULL, NULL, NULL, NULL, NULL},
1493 { NULL, NULL, NULL, NULL, NULL, NULL, NULL} /* RAD_LISTEN_SNMP */
1499 * Binds a listener to a socket.
1501 static int listen_bind(rad_listen_t *this)
1503 rad_listen_t **last;
1504 listen_socket_t *sock = this->data;
1507 * If the port is zero, then it means the appropriate
1508 * thing from /etc/services.
1510 if (sock->port == 0) {
1511 struct servent *svp;
1513 switch (this->type) {
1514 case RAD_LISTEN_AUTH:
1515 svp = getservbyname ("radius", "udp");
1517 sock->port = ntohs(svp->s_port);
1519 sock->port = PW_AUTH_UDP_PORT;
1523 case RAD_LISTEN_ACCT:
1524 svp = getservbyname ("radacct", "udp");
1526 sock->port = ntohs(svp->s_port);
1528 sock->port = PW_ACCT_UDP_PORT;
1533 radlog(L_ERR|L_CONS, "ERROR: Non-fatal internal sanity check failed in bind.");
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
1545 for (last = &mainconfig.listen;
1547 last = &((*last)->next)) {
1548 listen_socket_t *other;
1550 if (this->type != (*last)->type) continue;
1552 if ((this->type == RAD_LISTEN_DETAIL) ||
1553 (this->type == RAD_LISTEN_SNMP)) continue;
1555 other = (listen_socket_t *)((*last)->data);
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;
1566 this->fd = lrad_socket(&sock->ipaddr, sock->port);
1568 radlog(L_ERR|L_CONS, "ERROR: Failed to open socket: %s",
1575 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0) {
1576 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1580 flags |= O_NONBLOCK;
1581 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1582 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1593 * Allocate & initialize a new listener.
1595 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1599 this = rad_malloc(sizeof(*this));
1600 memset(this, 0, sizeof(*this));
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;
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));
1618 case RAD_LISTEN_DETAIL:
1619 this->data = rad_malloc(sizeof(listen_detail_t));
1620 memset(this->data, 0, sizeof(listen_detail_t));
1623 rad_assert("Unsupported option!" == NULL);
1632 * Externally visible function for creating a new proxy LISTENER.
1634 * For now, don't take ipaddr or port.
1636 * Not thread-safe, but all calls to it are protected by the
1637 * proxy mutex in request_list.c
1639 rad_listen_t *proxy_new_listener()
1641 int last_proxy_port, port;
1642 rad_listen_t *this, *tmp, **last;
1643 listen_socket_t *sock, *old;
1645 this = listen_alloc(RAD_LISTEN_PROXY);
1648 * Find an existing proxy socket to copy.
1650 * FIXME: Make it per-realm, or per-home server!
1652 last_proxy_port = 0;
1654 last = &mainconfig.listen;
1655 for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1656 if (tmp->type == RAD_LISTEN_PROXY) {
1658 if (sock->port > last_proxy_port) {
1659 last_proxy_port = sock->port + 1;
1661 if (!old) old = sock;
1664 last = &(tmp->next);
1667 if (!old) return NULL; /* This is a serious error. */
1670 * FIXME: find a new IP address to listen on?
1672 * This could likely be done in the "home server"
1673 * configuration, to have per-home-server source IP's.
1676 memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1679 * Keep going until we find an unused port.
1681 for (port = last_proxy_port; port < 64000; port++) {
1683 if (listen_bind(this) == 0) {
1685 * Add the new listener to the list of
1697 static const LRAD_NAME_NUMBER listen_compare[] = {
1698 { "auth", RAD_LISTEN_AUTH },
1699 { "acct", RAD_LISTEN_ACCT },
1700 { "detail", RAD_LISTEN_DETAIL },
1702 { "vmps", RAD_LISTEN_VQP },
1709 * Generate a list of listeners. Takes an input list of
1710 * listeners, too, so we don't close sockets with waiting packets.
1712 int listen_init(const char *filename, rad_listen_t **head)
1716 rad_listen_t **last;
1718 lrad_ipaddr_t server_ipaddr;
1722 * We shouldn't be called with a pre-existing list.
1724 rad_assert(head && (*head == NULL));
1727 server_ipaddr.af = AF_UNSPEC;
1730 * If the port is specified on the command-line,
1731 * it over-rides the configuration file.
1733 * FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1735 if (mainconfig.port >= 0) auth_port = mainconfig.port;
1738 * If the IP address was configured on the command-line,
1739 * use that as the "bind_address"
1741 if (mainconfig.myip.af != AF_UNSPEC) {
1742 memcpy(&server_ipaddr, &mainconfig.myip,
1743 sizeof(server_ipaddr));
1748 * Else look for bind_address and/or listen sections.
1750 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1751 rcode = cf_item_parse(mainconfig.config, "bind_address",
1753 &server_ipaddr.ipaddr.ip4addr, NULL);
1754 if (rcode < 0) return -1; /* error parsing it */
1756 if (rcode == 0) { /* successfully parsed IPv4 */
1757 listen_socket_t *sock;
1758 server_ipaddr.af = AF_INET;
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'.");
1764 if (strcmp(progname, "vmpsd") == 0) {
1765 this = listen_alloc(RAD_LISTEN_VQP);
1766 if (!auth_port) auth_port = 1589;
1769 this = listen_alloc(RAD_LISTEN_AUTH);
1773 sock->ipaddr = server_ipaddr;
1774 sock->port = auth_port;
1776 if (listen_bind(this) < 0) {
1779 radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1782 auth_port = sock->port; /* may have been updated in listen_bind */
1784 last = &(this->next);
1790 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1794 * Open Accounting Socket.
1796 * If we haven't already gotten acct_port from
1797 * /etc/services, then make it auth_port + 1.
1799 this = listen_alloc(RAD_LISTEN_ACCT);
1803 * Create the accounting socket.
1805 * The accounting port is always the
1806 * authentication port + 1
1808 sock->ipaddr = server_ipaddr;
1809 sock->port = auth_port + 1;
1811 if (listen_bind(this) < 0) {
1814 radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1819 last = &(this->next);
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",
1828 * They specified an IP on the command-line, ignore
1829 * all listen sections.
1831 if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1834 * Walk through the "listen" sections, if they exist.
1836 for (cs = cf_subsection_find_next(mainconfig.config, NULL, "listen");
1838 cs = cf_subsection_find_next(mainconfig.config, cs, "listen")) {
1840 char *listen_type, *server;
1841 int lineno = cf_section_lineno(cs);
1843 listen_type = server = NULL;
1845 DEBUG2(" listen {");
1847 rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1849 if (rcode < 0) return -1;
1853 radlog(L_ERR, "%s[%d]: No type specified in listen section",
1859 * See if there's a server configuration.
1861 * FIXME: Also allow "listen" sections in
1862 * "server" sections.
1864 rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
1872 type = lrad_str2int(listen_compare, listen_type,
1875 if (type == RAD_LISTEN_NONE) {
1877 radlog(L_CONS|L_ERR, "%s[%d]: Invalid type in listen section.",
1883 * Set up cross-type data.
1885 this = listen_alloc(type);
1886 this->server = server;
1890 * Call per-type parser.
1892 if (master_listen[type].parse(filename, lineno,
1902 last = &(this->next);
1906 * If we're proxying requests, open the proxy FD.
1907 * Otherwise, don't do anything.
1910 if (mainconfig.proxy_requests == TRUE) {
1912 listen_socket_t *sock = NULL;
1915 * No sockets to receive packets, therefore
1916 * proxying is pointless.
1918 if (!*head) return -1;
1921 * If we previously had proxy sockets, copy them
1922 * to the new config.
1924 if (mainconfig.listen != NULL) {
1925 rad_listen_t *old, *next, **tail;
1927 tail = &mainconfig.listen;
1928 for (old = mainconfig.listen;
1933 if (old->type != RAD_LISTEN_PROXY) {
1934 tail = &((*tail)->next);
1941 last = &(old->next);
1948 * Find the first authentication port,
1951 for (this = *head; this != NULL; this = this->next) {
1952 if (this->type == RAD_LISTEN_AUTH) {
1954 if (server_ipaddr.af == AF_UNSPEC) {
1955 server_ipaddr = sock->ipaddr;
1957 port = sock->port + 2; /* skip acct port */
1960 if (this->type == RAD_LISTEN_VQP) {
1962 if (server_ipaddr.af == AF_UNSPEC) {
1963 server_ipaddr = sock->ipaddr;
1965 port = sock->port + 1;
1970 if (port < 0) port = 1024 + (lrad_rand() & 0x1ff);
1973 * Address is still unspecified, use IPv4.
1975 if (server_ipaddr.af == AF_UNSPEC) {
1976 server_ipaddr.af = AF_INET;
1977 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1980 this = listen_alloc(RAD_LISTEN_PROXY);
1984 * Create the first proxy socket.
1986 sock->ipaddr = server_ipaddr;
1989 * Try to find a proxy port (value doesn't matter)
1991 for (sock->port = port;
1994 if (listen_bind(this) == 0) {
1996 last = &(this->next); /* just in case */
2001 if (sock->port >= 64000) {
2004 radlog(L_ERR|L_CONS, "Failed to open socket for proxying");
2011 if (mainconfig.do_snmp) {
2015 * Forget about the old one.
2017 for (this = mainconfig.listen;
2019 this = this->next) {
2020 if (this->type != RAD_LISTEN_SNMP) continue;
2024 this = rad_malloc(sizeof(*this));
2025 memset(this, 0, sizeof(*this));
2027 this->type = RAD_LISTEN_SNMP;
2028 this->fd = rad_snmp.smux_fd;
2030 this->recv = radius_snmp_recv;
2031 this->print = radius_snmp_print;
2034 last = &(this->next);
2042 * Free a linked list of listeners;
2044 void listen_free(rad_listen_t **head)
2048 if (!head || !*head) return;
2052 rad_listen_t *next = this->next;
2057 * Other code may have eaten the FD.
2059 if (this->fd >= 0) close(this->fd);
2061 if (master_listen[this->type].free) {
2062 master_listen[this->type].free(this);