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, const 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 REQUEST *request; /* can only be one at a time! */
80 int load_factor; /* 1..100 */
86 struct timeval last_packet;
91 * Find a per-socket client.
93 static RADCLIENT *client_listener_find(const rad_listen_t *listener,
94 const lrad_ipaddr_t *ipaddr)
96 const RADCLIENT_LIST *clients;
98 rad_assert(listener != NULL);
99 rad_assert(ipaddr != NULL);
101 rad_assert((listener->type == RAD_LISTEN_AUTH) ||
102 (listener->type == RAD_LISTEN_ACCT) ||
103 (listener->type == RAD_LISTEN_VQP));
105 clients = ((listen_socket_t *)listener->data)->clients;
106 if (!clients) clients = mainconfig.clients;
108 rad_assert(clients != NULL);
110 return client_find(clients, ipaddr);
113 static int listen_bind(rad_listen_t *this);
116 * Process and reply to a server-status request.
117 * Like rad_authenticate and rad_accounting this should
118 * live in it's own file but it's so small we don't bother.
120 static int rad_status_server(REQUEST *request)
122 int rcode = RLM_MODULE_OK;
125 switch (request->listener->type) {
126 case RAD_LISTEN_AUTH:
127 dval = dict_valbyname(PW_AUTZ_TYPE, "Status-Server");
129 rcode = module_authorize(dval->value, request);
131 rcode = RLM_MODULE_OK;
136 case RLM_MODULE_UPDATED:
137 request->reply->code = PW_AUTHENTICATION_ACK;
140 case RLM_MODULE_FAIL:
141 case RLM_MODULE_HANDLED:
142 request->reply->code = 0; /* don't reply */
146 case RLM_MODULE_REJECT:
147 request->reply->code = PW_AUTHENTICATION_REJECT;
152 case RAD_LISTEN_ACCT:
153 dval = dict_valbyname(PW_ACCT_TYPE, "Status-Server");
155 rcode = module_accounting(dval->value, request);
157 rcode = RLM_MODULE_OK;
162 case RLM_MODULE_UPDATED:
163 request->reply->code = PW_ACCOUNTING_RESPONSE;
167 request->reply->code = 0; /* don't reply */
180 static int socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
183 listen_socket_t *sock = this->data;
185 if ((sock->ipaddr.af == AF_INET) &&
186 (sock->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
189 ip_ntoh(&sock->ipaddr, buffer, bufsize);
192 len = strlen(buffer);
194 return len + snprintf(buffer + len, bufsize - len, " port %d",
200 * Parse an authentication or accounting socket.
202 static int common_socket_parse(const char *filename, int lineno,
203 const CONF_SECTION *cs, rad_listen_t *this)
207 lrad_ipaddr_t ipaddr;
208 listen_socket_t *sock = this->data;
209 const char *section_name = NULL;
210 CONF_SECTION *client_cs;
215 ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
216 rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
217 &ipaddr.ipaddr.ip4addr, NULL);
218 if (rcode < 0) return -1;
220 if (rcode == 0) { /* successfully parsed IPv4 */
223 } else { /* maybe IPv6? */
224 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
225 &ipaddr.ipaddr.ip6addr, NULL);
226 if (rcode < 0) return -1;
229 radlog(L_ERR, "%s[%d]: No address specified in listen section",
233 ipaddr.af = AF_INET6;
236 rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
238 if (rcode < 0) return -1;
240 sock->ipaddr = ipaddr;
241 sock->port = listen_port;
244 * And bind it to the port.
246 if (listen_bind(this) < 0) {
248 radlog(L_CONS|L_ERR, "%s[%d]: Error binding to port for %s port %d",
249 filename, cf_section_lineno(cs),
250 ip_ntoh(&sock->ipaddr, buffer, sizeof(buffer)),
256 * If we can bind to interfaces, do so,
259 if (cf_pair_find(cs, "interface")) {
260 #ifndef SO_BINDTODEVICE
261 radlog(L_CONS|L_ERR, "%s[%d]: System does not support binding to interfaces, delete this line from the configuration file.",
262 filename, cf_section_lineno(cs));
266 const CONF_PAIR *cp = cf_pair_find(cs, "interface");
269 rad_assert(cp != NULL);
270 value = cf_pair_value(cp);
271 rad_assert(value != NULL);
273 strcpy(ifreq.ifr_name, value);
275 if (setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
276 (char *)&ifreq, sizeof(ifreq)) < 0) {
277 radlog(L_CONS|L_ERR, "%s[%d]: Failed binding to interface %s: %s",
278 filename, cf_section_lineno(cs),
279 value, strerror(errno));
281 } /* else it worked. */
286 * Look for the name of a section that holds a list
289 rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
290 §ion_name, NULL);
291 if (rcode < 0) return -1; /* bad string */
292 if (rcode > 0) return 0; /* non-existent is OK. */
294 client_cs = cf_section_find(section_name);
297 radlog(L_CONS|L_ERR, "%s[%d]: Failed to find client section %s",
298 filename, cf_section_lineno(cs), section_name);
302 sock->clients = clients_parse_section(filename, client_cs);
303 if (!sock->clients) {
311 * Send an authentication response packet
313 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
315 rad_assert(request->listener == listener);
316 rad_assert(listener->send == auth_socket_send);
318 return rad_send(request->reply, request->packet,
319 request->client->secret);
324 * Send an accounting response packet (or not)
326 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
328 rad_assert(request->listener == listener);
329 rad_assert(listener->send == acct_socket_send);
332 * Accounting reject's are silently dropped.
334 * We do it here to avoid polluting the rest of the
335 * code with this knowledge
337 if (request->reply->code == 0) return 0;
339 return rad_send(request->reply, request->packet,
340 request->client->secret);
345 * Send a packet to a home server.
347 * FIXME: have different code for proxy auth & acct!
349 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
351 listen_socket_t *sock = listener->data;
353 rad_assert(request->proxy_listener == listener);
354 rad_assert(listener->send == proxy_socket_send);
356 request->proxy->src_ipaddr = sock->ipaddr;
357 request->proxy->src_port = sock->port;
359 return rad_send(request->proxy, request->packet,
360 request->home_server->secret);
365 * Check if an incoming request is "ok"
367 * It takes packets, not requests. It sees if the packet looks
368 * OK. If so, it does a number of sanity checks on it.
370 static int auth_socket_recv(rad_listen_t *listener,
371 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
375 RADIUS_PACKET *packet;
376 RAD_REQUEST_FUNP fun = NULL;
379 lrad_ipaddr_t src_ipaddr;
381 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
382 if (rcode < 0) return 0;
384 RAD_SNMP_TYPE_INC(listener, total_requests);
386 if (rcode < 20) { /* AUTH_HDR_LEN */
387 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
391 if ((client = client_listener_find(listener,
392 &src_ipaddr)) == NULL) {
393 rad_recv_discard(listener->fd);
394 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
397 * This is debugging rather than logging, so that
398 * DoS attacks don't affect us.
400 DEBUG("Ignoring request from unknown client %s port %d",
401 inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
402 buffer, sizeof(buffer)), src_port);
407 * Some sanity checks, based on the packet code.
410 case PW_AUTHENTICATION_REQUEST:
411 RAD_SNMP_CLIENT_INC(listener, client, requests);
412 fun = rad_authenticate;
415 case PW_STATUS_SERVER:
416 if (!mainconfig.status_server) {
417 rad_recv_discard(listener->fd);
418 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
419 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
420 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
423 fun = rad_status_server;
427 rad_recv_discard(listener->fd);
428 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
429 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
431 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
432 code, client->shortname, src_port);
435 } /* switch over packet types */
438 * Now that we've sanity checked everything, receive the
441 packet = rad_recv(listener->fd);
443 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
444 radlog(L_ERR, "%s", librad_errstr);
448 if (!received_request(listener, packet, prequest, client)) {
449 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
450 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
461 * Receive packets from an accounting socket
463 static int acct_socket_recv(rad_listen_t *listener,
464 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
468 RADIUS_PACKET *packet;
469 RAD_REQUEST_FUNP fun = NULL;
472 lrad_ipaddr_t src_ipaddr;
474 rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
475 if (rcode < 0) return 0;
477 RAD_SNMP_TYPE_INC(listener, total_requests);
479 if (rcode < 20) { /* AUTH_HDR_LEN */
480 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
484 if ((client = client_listener_find(listener,
485 &src_ipaddr)) == NULL) {
486 rad_recv_discard(listener->fd);
487 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
490 * This is debugging rather than logging, so that
491 * DoS attacks don't affect us.
493 DEBUG("Ignoring request from unknown client %s port %d",
494 inet_ntop(src_ipaddr.af, &src_ipaddr.ipaddr,
495 buffer, sizeof(buffer)), src_port);
500 * Some sanity checks, based on the packet code.
503 case PW_ACCOUNTING_REQUEST:
504 RAD_SNMP_CLIENT_INC(listener, client, requests);
505 fun = rad_accounting;
508 case PW_STATUS_SERVER:
509 if (!mainconfig.status_server) {
510 rad_recv_discard(listener->fd);
511 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
512 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
514 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
517 fun = rad_status_server;
521 rad_recv_discard(listener->fd);
522 RAD_SNMP_TYPE_INC(listener, total_unknown_types);
523 RAD_SNMP_CLIENT_INC(listener, client, unknown_types);
525 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
526 code, client->shortname, src_port);
528 } /* switch over packet types */
531 * Now that we've sanity checked everything, receive the
534 packet = rad_recv(listener->fd);
536 RAD_SNMP_TYPE_INC(listener, total_malformed_requests);
537 radlog(L_ERR, "%s", librad_errstr);
542 * There can be no duplicate accounting packets.
544 if (!received_request(listener, packet, prequest, client)) {
545 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
546 RAD_SNMP_CLIENT_INC(listener, client, packets_dropped);
557 * Recieve packets from a proxy socket.
559 static int proxy_socket_recv(rad_listen_t *listener,
560 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
563 RADIUS_PACKET *packet;
564 RAD_REQUEST_FUNP fun = NULL;
567 packet = rad_recv(listener->fd);
569 radlog(L_ERR, "%s", librad_errstr);
574 * FIXME: Client MIB updates?
576 switch(packet->code) {
577 case PW_AUTHENTICATION_ACK:
578 case PW_ACCESS_CHALLENGE:
579 case PW_AUTHENTICATION_REJECT:
580 fun = rad_authenticate;
583 case PW_ACCOUNTING_RESPONSE:
584 fun = rad_accounting;
589 * FIXME: Update MIB for packet types?
591 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
592 "from home server %s port %d - ID %d : IGNORED",
594 ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
595 packet->src_port, packet->id);
600 request = received_proxy_response(packet);
605 rad_assert(fun != NULL);
613 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
615 if (!request->reply->code) return 0;
617 rad_encode(request->reply, request->packet,
618 request->client->secret);
619 rad_sign(request->reply, request->packet,
620 request->client->secret);
626 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
628 if (rad_verify(request->packet, NULL,
629 request->client->secret) < 0) {
633 return rad_decode(request->packet, NULL,
634 request->client->secret);
637 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
639 rad_encode(request->proxy, NULL, request->home_server->secret);
640 rad_sign(request->proxy, NULL, request->home_server->secret);
646 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
648 if (rad_verify(request->proxy_reply, request->proxy,
649 request->home_server->secret) < 0) {
653 return rad_decode(request->proxy_reply, request->proxy,
654 request->home_server->secret);
658 #define STATE_UNOPENED (0)
659 #define STATE_UNLOCKED (1)
660 #define STATE_HEADER (2)
661 #define STATE_READING (3)
662 #define STATE_DONE (4)
663 #define STATE_WAITING (5)
666 * If we're limiting outstanding packets, then mark the response
669 static int detail_send(rad_listen_t *listener, REQUEST *request)
673 listen_detail_t *data = listener->data;
675 rad_assert(request->listener == listener);
676 rad_assert(listener->send == detail_send);
679 * This request timed out. We should probably re-send it
682 if (request->reply->code == 0) {
684 * FIXME: do something sane!
689 * We call gettimeofday a lot. But here it should be OK,
690 * because there's nothing else to do.
692 gettimeofday(&now, NULL);
695 * If we haven't sent a packet in the last second, reset
699 if (timercmp(&data->last_packet, &now, <)) {
700 data->has_rtt = FALSE;
705 * Only one detail packet may be outstanding at a time,
706 * so it's safe to update some entries in the detail
709 * We keep smoothed round trip time (SRTT), but not round
710 * trip timeout (RTO). We use SRTT to calculate a rough
713 rtt = now.tv_sec - request->received.tv_sec;
716 rtt -= request->received.tv_usec;
719 * If we're proxying, the RTT is our processing time,
720 * plus the network delay there and back, plus the time
721 * on the other end to process the packet. Ideally, we
722 * should remove the network delays from the RTT, but we
723 * don't know what they are.
725 * So, to be safe, we over-estimate the total cost of
726 * processing the packet.
728 if (!data->has_rtt) {
729 data->has_rtt = TRUE;
731 data->rttvar = rtt / 2;
734 data->rttvar -= data->rttvar >> 2;
735 data->rttvar += (data->srtt - rtt);
736 data->srtt -= data->srtt >> 3;
737 data->srtt += rtt >> 3;
741 * Calculate the time we wait before sending the next
744 * rtt / (rtt + delay) = load_factor / 100
746 data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
749 * FIXME: Push this delay to the event handler!
751 DEBUG2("RTT %d\tdelay %d", data->srtt, data->delay_time);
753 usleep(data->delay_time);
755 data->last_packet = now;
758 * FIXME: Cache the LAST offset in the file where we
759 * successfully read a packet, and got a response. Then
760 * when we re-open the file (say after a restart), we
761 * start reading from that offset, rather than from the
762 * beginning of the file again.
764 * OR, put the offset into a comment in the first line of
767 data->request = NULL;
770 * Code in threads.c will take care performing self
771 * signalling that we can read from the detail file.
773 * Even though this request is now done, there may be
774 * auth/acct requests pending that mean we shouldn't read
783 * Open the detail file..
785 * FIXME: create it, if it's not already there, so that the main
786 * server select() will wake us up if there's anything to read.
788 static int detail_open(rad_listen_t *this)
792 listen_detail_t *data = this->data;
794 rad_assert(data->state == STATE_UNOPENED);
795 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
798 * Open detail.work first, so we don't lose
799 * accounting packets. It's probably better to
800 * duplicate them than to lose them.
802 * Note that we're not writing to the file, but
803 * we've got to open it for writing in order to
804 * establish the lock, to prevent rlm_detail from
807 this->fd = open(buffer, O_RDWR);
810 * Try reading the detail file. If it
811 * doesn't exist, we can't do anything.
813 * Doing the stat will tell us if the file
814 * exists, even if we don't have permissions
817 if (stat(data->filename, &st) < 0) {
822 * Open it BEFORE we rename it, just to
825 this->fd = open(data->filename, O_RDWR);
827 radlog(L_ERR, "Failed to open %s: %s",
828 data->filename, strerror(errno));
833 * Rename detail to detail.work
835 if (rename(data->filename, buffer) < 0) {
840 } /* else detail.work existed, and we opened it */
842 rad_assert(data->vps == NULL);
844 rad_assert(data->fp == NULL);
845 data->fp = fdopen(this->fd, "r");
847 radlog(L_ERR, "Failed to re-open %s: %s",
848 data->filename, strerror(errno));
852 data->state = STATE_UNLOCKED;
854 data->client_ip.af = AF_UNSPEC;
861 * FIXME: this should be dynamically allocated.
863 static const RADCLIENT detail_client = {
882 * FIXME: add a configuration "exit when done" so that the detail
883 * file reader can be used as a one-off tool to update stuff.
885 * The time sequence for reading from the detail file is:
887 * t_0 signalled that the server is idle, and we
888 * can read from the detail file.
890 * t_rtt the packet has been processed successfully,
891 * wait for t_delay to enforce load factor.
893 * t_rtt + t_delay wait for signal that the server is idle.
896 static int detail_recv(rad_listen_t *listener,
897 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
899 char key[256], value[1024];
900 VALUE_PAIR *vp, **tail;
901 RADIUS_PACKET *packet;
903 listen_detail_t *data = listener->data;
904 REQUEST *old_request;
906 if (data->state == STATE_UNOPENED) {
907 rad_assert(listener->fd < 0);
910 * FIXME: If the file doesn't exist, then return
911 * "sleep for 1s", to avoid busy looping.
913 if (!detail_open(listener)) return 0;
915 rad_assert(listener->fd >= 0);
918 * Try to lock fd. If we can't, return. If we can,
919 * continue. This means that the server doesn't block
920 * while waiting for the lock to open...
922 if (data->state == STATE_UNLOCKED) {
924 * Note that we do NOT block waiting for the
925 * lock. We've re-named the file above, so we've
926 * already guaranteed that any *new* detail
927 * writer will not be opening this file. The
928 * only purpose of the lock is to catch a race
929 * condition where the execution "ping-pongs"
930 * between radiusd & radrelay.
932 if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
936 * Look for the header
938 data->state = STATE_HEADER;
943 * Catch an out of memory condition which will most likely
946 if (data->state == STATE_DONE) goto alloc_packet;
949 * We still have an outstanding packet. Don't read any
952 old_request = data->request; /* threading issues */
953 if (old_request && old_request->reply->code == 0) {
955 * FIXME: return "don't do anything until the
956 * request is done, AND we receive another signal
957 * saying it's OK to read the detail file.
963 * We read the last packet, and returned it for
964 * processing. We later come back here to shut
965 * everything down, and unlink the file.
967 if (feof(data->fp)) {
968 if (data->state == STATE_READING) {
969 data->state = STATE_DONE;
974 * If there's a pending request, don't delete the
978 data->state = STATE_WAITING;
983 rad_assert(data->vps == NULL);
985 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
987 fclose(data->fp); /* closes listener->fd */
990 data->state = STATE_UNOPENED;
993 * Try to open "detail" again. If we're on a
994 * busy RADIUS server, odds are that it will
997 detail_open(listener);
1004 * Fill the buffer...
1006 while (fgets(buffer, sizeof(buffer), data->fp)) {
1010 if (!strchr(buffer, '\n')) {
1011 pairfree(&data->vps);
1016 * We've read a header, possibly packet contents,
1017 * and are now at the end of the packet.
1019 if ((data->state == STATE_READING) &&
1020 (buffer[0] == '\n')) {
1021 data->state = STATE_DONE;
1026 * Look for date/time header, and read VP's if
1027 * found. If not, keep reading lines until we
1030 if (data->state == STATE_HEADER) {
1033 if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
1034 data->state = STATE_READING;
1040 * We have a full "attribute = value" line.
1041 * If it doesn't look reasonable, skip it.
1043 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
1048 * Skip non-protocol attributes.
1050 if (!strcasecmp(key, "Request-Authenticator")) continue;
1053 * Set the original client IP address, based on
1054 * what's in the detail file.
1056 * Hmm... we don't set the server IP address.
1059 if (!strcasecmp(key, "Client-IP-Address")) {
1060 data->client_ip.af = AF_INET;
1061 ip_hton(value, AF_INET, &data->client_ip);
1066 * The original time at which we received the
1067 * packet. We need this to properly calculate
1070 if (!strcasecmp(key, "Timestamp")) {
1071 data->timestamp = atoi(value);
1078 * FIXME: do we want to check for non-protocol
1079 * attributes like radsqlrelay does?
1082 if ((userparse(buffer, &vp) > 0) &&
1090 * We got to EOF, If we're in STATE_HEADER, it's OK.
1091 * Otherwise it's a problem. In any case, nuke the file
1092 * and start over from scratch,
1094 if (feof(data->fp)) {
1098 if (data->state == STATE_READING) goto alloc_packet;
1099 pairfree(&data->vps);
1104 * If we're not done, then there's a problem. The checks
1107 rad_assert(data->state == STATE_DONE);
1110 * The packet we read was empty, re-set the state to look
1111 * for a header, and don't return anything.
1114 data->state = STATE_HEADER;
1119 * Allocate the packet. If we fail, it's a serious
1123 rad_assert(data->request == NULL);
1125 packet = rad_alloc(1);
1127 return 0; /* maybe memory will magically free up... */
1130 memset(packet, 0, sizeof(*packet));
1131 packet->sockfd = -1;
1132 packet->src_ipaddr.af = AF_INET;
1133 packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1134 packet->code = PW_ACCOUNTING_REQUEST;
1135 packet->timestamp = time(NULL);
1138 * Remember where it came from, so that we don't
1139 * proxy it to the place it came from...
1141 if (data->client_ip.af != AF_UNSPEC) {
1142 packet->src_ipaddr = data->client_ip;
1145 vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
1147 packet->src_ipaddr.af = AF_INET;
1148 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1150 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
1152 packet->src_ipaddr.af = AF_INET6;
1153 memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
1154 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1158 vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
1160 packet->dst_ipaddr.af = AF_INET;
1161 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1163 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
1165 packet->dst_ipaddr.af = AF_INET6;
1166 memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
1167 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
1172 * We've got to give SOME value for Id & ports, so that
1173 * the packets can be added to the request queue.
1174 * However, we don't want to keep track of used/unused
1175 * id's and ports, as that's a lot of work. This hack
1176 * ensures that (if we have real random numbers), that
1177 * there will be a collision on every 2^(16+15+15+24 - 1)
1178 * packets, on average. That means we can read 2^37
1179 * packets before having a collision, which means it's
1180 * effectively impossible.
1182 packet->id = lrad_rand() & 0xffff;
1183 packet->src_port = 1024 + (lrad_rand() & 0x7fff);
1184 packet->dst_port = 1024 + (lrad_rand() & 0x7fff);
1186 packet->dst_ipaddr.af = AF_INET;
1187 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (lrad_rand() & 0xffffff));
1189 packet->vps = data->vps;
1195 data->state = STATE_HEADER;
1198 * Look for Acct-Delay-Time, and update
1199 * based on Acct-Delay-Time += (time(NULL) - timestamp)
1201 vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
1203 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1204 rad_assert(vp != NULL);
1205 pairadd(&packet->vps, vp);
1207 if (data->timestamp != 0) {
1208 vp->vp_integer += time(NULL) - data->timestamp;
1211 *pfun = rad_accounting;
1214 printf("detail_recv: Read packet from %s\n", data->filename);
1215 for (vp = packet->vps; vp; vp = vp->next) {
1217 vp_print(stdout, vp);
1223 * FIXME: many of these checks may not be necessary when
1224 * reading from the detail file.
1226 if (!received_request(listener, packet, prequest, &detail_client)) {
1236 * Free detail-specific stuff.
1238 static void detail_free(rad_listen_t *this)
1240 listen_detail_t *data = this->data;
1242 free(data->filename);
1243 pairfree(&data->vps);
1245 if (data->fp != NULL) fclose(data->fp);
1249 static int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
1251 return snprintf(buffer, bufsize, "%s",
1252 ((listen_detail_t *)(this->data))->filename);
1255 static int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1258 * We never encode responses "sent to" the detail file.
1263 static int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
1266 * We never decode responses read from the detail file.
1272 static const CONF_PARSER detail_config[] = {
1273 { "filename", PW_TYPE_STRING_PTR,
1274 offsetof(listen_detail_t, filename), NULL, NULL },
1275 { "load_factor", PW_TYPE_INTEGER,
1276 offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
1278 { NULL, -1, 0, NULL, NULL } /* end the list */
1283 * Parse a detail section.
1285 static int detail_parse(const char *filename, int lineno,
1286 const CONF_SECTION *cs, rad_listen_t *this)
1289 listen_detail_t *data;
1293 rcode = cf_section_parse(cs, data, detail_config);
1295 radlog(L_ERR, "%s[%d]: Failed parsing listen section",
1300 if (!data->filename) {
1301 radlog(L_ERR, "%s[%d]: No detail file specified in listen section",
1306 if ((data->load_factor < 1) || (data->load_factor > 100)) {
1307 radlog(L_ERR, "%s[%d]: Load factor must be between 1 and 100",
1314 data->state = STATE_UNOPENED;
1322 static int radius_snmp_recv(rad_listen_t *listener,
1323 UNUSED RAD_REQUEST_FUNP *pfun,
1324 UNUSED REQUEST **prequest)
1326 if (!mainconfig.do_snmp) return 0;
1328 if ((rad_snmp.smux_fd >= 0) &&
1329 (rad_snmp.smux_event == SMUX_READ)) {
1334 * If we've got to re-connect, then do so now,
1335 * before calling select again.
1337 if (rad_snmp.smux_event == SMUX_CONNECT) {
1342 * Reset this every time, as the smux connect may have
1343 * opened a new socket.
1345 listener->fd = rad_snmp.smux_fd;
1351 static int radius_snmp_print(rad_listen_t *this, char *buffer, size_t bufsize)
1353 return snprintf(buffer, bufsize, "SMUX with OID .1.3.6.1.4.1.11344.1.1.1");
1359 * Check if an incoming request is "ok"
1361 * It takes packets, not requests. It sees if the packet looks
1362 * OK. If so, it does a number of sanity checks on it.
1364 static int vqp_socket_recv(rad_listen_t *listener,
1365 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1367 RADIUS_PACKET *packet;
1368 RAD_REQUEST_FUNP fun = NULL;
1372 packet = vqp_recv(listener->fd);
1374 radlog(L_ERR, "%s", librad_errstr);
1378 if ((client = client_listener_find(listener,
1379 &packet->src_ipaddr)) == NULL) {
1380 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1382 radlog(L_ERR, "Ignoring request from unknown client %s port %d",
1383 inet_ntop(packet->src_ipaddr.af,
1384 &packet->src_ipaddr.ipaddr,
1385 buffer, sizeof(buffer)),
1396 if (!received_request(listener, packet, prequest, client)) {
1408 * Send an authentication response packet
1410 static int vqp_socket_send(rad_listen_t *listener, REQUEST *request)
1412 rad_assert(request->listener == listener);
1413 rad_assert(listener->send == vqp_socket_send);
1415 if (vqp_encode(request->reply, request->packet) < 0) {
1416 DEBUG2("Failed encoding packet: %s\n", librad_errstr);
1420 return vqp_send(request->reply);
1424 static int vqp_socket_encode(rad_listen_t *listener, REQUEST *request)
1426 return vqp_encode(request->reply, request->packet);
1430 static int vqp_socket_decode(rad_listen_t *listener, REQUEST *request)
1432 return vqp_decode(request->packet);
1436 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1437 { NULL, NULL, NULL, NULL, NULL, NULL, NULL}, /* RAD_LISTEN_NONE */
1441 proxy_socket_recv, proxy_socket_send,
1442 socket_print, proxy_socket_encode, proxy_socket_decode },
1444 /* authentication */
1445 { common_socket_parse, NULL,
1446 auth_socket_recv, auth_socket_send,
1447 socket_print, client_socket_encode, client_socket_decode },
1450 { common_socket_parse, NULL,
1451 acct_socket_recv, acct_socket_send,
1452 socket_print, client_socket_encode, client_socket_decode},
1455 { detail_parse, detail_free,
1456 detail_recv, detail_send,
1457 detail_print, detail_encode, detail_decode },
1459 /* vlan query protocol */
1460 { common_socket_parse, NULL,
1461 vqp_socket_recv, vqp_socket_send,
1462 socket_print, vqp_socket_encode, vqp_socket_decode },
1464 { NULL, NULL, NULL, NULL, NULL, NULL, NULL} /* RAD_LISTEN_SNMP */
1470 * Binds a listener to a socket.
1472 static int listen_bind(rad_listen_t *this)
1474 rad_listen_t **last;
1475 listen_socket_t *sock = this->data;
1478 * If the port is zero, then it means the appropriate
1479 * thing from /etc/services.
1481 if (sock->port == 0) {
1482 struct servent *svp;
1484 switch (this->type) {
1485 case RAD_LISTEN_AUTH:
1486 svp = getservbyname ("radius", "udp");
1488 sock->port = ntohs(svp->s_port);
1490 sock->port = PW_AUTH_UDP_PORT;
1494 case RAD_LISTEN_ACCT:
1495 svp = getservbyname ("radacct", "udp");
1497 sock->port = ntohs(svp->s_port);
1499 sock->port = PW_ACCT_UDP_PORT;
1504 radlog(L_ERR|L_CONS, "ERROR: Non-fatal internal sanity check failed in bind.");
1510 * Find it in the old list, AFTER updating the port. If
1511 * it's there, use that, rather than creating a new
1512 * socket. This allows HUP's to re-use the old sockets,
1513 * which means that packets waiting in the socket queue
1516 for (last = &mainconfig.listen;
1518 last = &((*last)->next)) {
1519 listen_socket_t *other;
1521 if (this->type != (*last)->type) continue;
1523 if ((this->type == RAD_LISTEN_DETAIL) ||
1524 (this->type == RAD_LISTEN_SNMP)) continue;
1526 other = (listen_socket_t *)((*last)->data);
1528 if ((sock->port == other->port) &&
1529 (sock->ipaddr.af == other->ipaddr.af) &&
1530 (lrad_ipaddr_cmp(&sock->ipaddr, &other->ipaddr) == 0)) {
1531 this->fd = (*last)->fd;
1537 this->fd = lrad_socket(&sock->ipaddr, sock->port);
1539 radlog(L_ERR|L_CONS, "ERROR: Failed to open socket: %s",
1546 if ((flags = fcntl(this->fd, F_GETFL, NULL)) < 0) {
1547 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1551 flags |= O_NONBLOCK;
1552 if( fcntl(this->fd, F_SETFL, flags) < 0) {
1553 radlog(L_ERR, "Failure in fcntl: %s)\n", strerror(errno));
1564 * Allocate & initialize a new listener.
1566 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
1570 this = rad_malloc(sizeof(*this));
1571 memset(this, 0, sizeof(*this));
1574 this->recv = master_listen[this->type].recv;
1575 this->send = master_listen[this->type].send;
1576 this->print = master_listen[this->type].print;
1577 this->encode = master_listen[this->type].encode;
1578 this->decode = master_listen[this->type].decode;
1581 case RAD_LISTEN_AUTH:
1582 case RAD_LISTEN_ACCT:
1583 case RAD_LISTEN_PROXY:
1584 case RAD_LISTEN_VQP:
1585 this->data = rad_malloc(sizeof(listen_socket_t));
1586 memset(this->data, 0, sizeof(listen_socket_t));
1589 case RAD_LISTEN_DETAIL:
1590 this->data = rad_malloc(sizeof(listen_detail_t));
1591 memset(this->data, 0, sizeof(listen_detail_t));
1594 rad_assert("Unsupported option!" == NULL);
1603 * Externally visible function for creating a new proxy LISTENER.
1605 * For now, don't take ipaddr or port.
1607 * Not thread-safe, but all calls to it are protected by the
1608 * proxy mutex in request_list.c
1610 rad_listen_t *proxy_new_listener()
1612 int last_proxy_port, port;
1613 rad_listen_t *this, *tmp, **last;
1614 listen_socket_t *sock, *old;
1616 this = listen_alloc(RAD_LISTEN_PROXY);
1619 * Find an existing proxy socket to copy.
1621 * FIXME: Make it per-realm, or per-home server!
1623 last_proxy_port = 0;
1625 last = &mainconfig.listen;
1626 for (tmp = mainconfig.listen; tmp != NULL; tmp = tmp->next) {
1627 if (tmp->type == RAD_LISTEN_PROXY) {
1629 if (sock->port > last_proxy_port) {
1630 last_proxy_port = sock->port + 1;
1632 if (!old) old = sock;
1635 last = &(tmp->next);
1638 if (!old) return NULL; /* This is a serious error. */
1641 * FIXME: find a new IP address to listen on?
1643 * This could likely be done in the "home server"
1644 * configuration, to have per-home-server source IP's.
1647 memcpy(&sock->ipaddr, &old->ipaddr, sizeof(sock->ipaddr));
1650 * Keep going until we find an unused port.
1652 for (port = last_proxy_port; port < 64000; port++) {
1654 if (listen_bind(this) == 0) {
1656 * Add the new listener to the list of
1668 static const LRAD_NAME_NUMBER listen_compare[] = {
1669 { "auth", RAD_LISTEN_AUTH },
1670 { "acct", RAD_LISTEN_ACCT },
1671 { "detail", RAD_LISTEN_DETAIL },
1672 { "vmps", RAD_LISTEN_VQP },
1678 * Generate a list of listeners. Takes an input list of
1679 * listeners, too, so we don't close sockets with waiting packets.
1681 int listen_init(const char *filename, rad_listen_t **head)
1685 rad_listen_t **last;
1687 lrad_ipaddr_t server_ipaddr;
1691 * We shouldn't be called with a pre-existing list.
1693 rad_assert(head && (*head == NULL));
1696 server_ipaddr.af = AF_UNSPEC;
1699 * If the port is specified on the command-line,
1700 * it over-rides the configuration file.
1702 * FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
1704 if (mainconfig.port >= 0) auth_port = mainconfig.port;
1707 * If the IP address was configured on the command-line,
1708 * use that as the "bind_address"
1710 if (mainconfig.myip.af != AF_UNSPEC) {
1711 memcpy(&server_ipaddr, &mainconfig.myip,
1712 sizeof(server_ipaddr));
1717 * Else look for bind_address and/or listen sections.
1719 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
1720 rcode = cf_item_parse(mainconfig.config, "bind_address",
1722 &server_ipaddr.ipaddr.ip4addr, NULL);
1723 if (rcode < 0) return -1; /* error parsing it */
1725 if (rcode == 0) { /* successfully parsed IPv4 */
1726 listen_socket_t *sock;
1727 server_ipaddr.af = AF_INET;
1729 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'.");
1732 if (strcmp(progname, "vmpsd") != 0) {
1733 this = listen_alloc(RAD_LISTEN_AUTH);
1735 this = listen_alloc(RAD_LISTEN_VQP);
1736 if (!auth_port) auth_port = 1589;
1740 sock->ipaddr = server_ipaddr;
1741 sock->port = auth_port;
1743 if (listen_bind(this) < 0) {
1746 radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->port);
1749 auth_port = sock->port; /* may have been updated in listen_bind */
1751 last = &(this->next);
1756 if (strcmp(progname, "vmpsd") == 0) goto do_proxy;
1759 * Open Accounting Socket.
1761 * If we haven't already gotten acct_port from
1762 * /etc/services, then make it auth_port + 1.
1764 this = listen_alloc(RAD_LISTEN_ACCT);
1768 * Create the accounting socket.
1770 * The accounting port is always the
1771 * authentication port + 1
1773 sock->ipaddr = server_ipaddr;
1774 sock->port = auth_port + 1;
1776 if (listen_bind(this) < 0) {
1779 radlog(L_CONS|L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->port);
1784 last = &(this->next);
1786 } else if (mainconfig.port > 0) { /* no bind address, but a port */
1787 radlog(L_CONS|L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
1793 * They specified an IP on the command-line, ignore
1794 * all listen sections.
1796 if (mainconfig.myip.af != AF_UNSPEC) goto do_proxy;
1799 * Walk through the "listen" sections, if they exist.
1801 for (cs = cf_subsection_find_next(mainconfig.config, NULL, "listen");
1803 cs = cf_subsection_find_next(mainconfig.config, cs, "listen")) {
1805 char *listen_type, *identity;
1806 int lineno = cf_section_lineno(cs);
1808 listen_type = identity = NULL;
1810 DEBUG2(" listen {");
1812 rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
1814 if (rcode < 0) return -1;
1818 radlog(L_ERR, "%s[%d]: No type specified in listen section",
1824 * See if there's an identity.
1826 rcode = cf_item_parse(cs, "identity", PW_TYPE_STRING_PTR,
1834 type = lrad_str2int(listen_compare, listen_type,
1837 if (type == RAD_LISTEN_NONE) {
1839 radlog(L_CONS|L_ERR, "%s[%d]: Invalid type in listen section.",
1845 * Set up cross-type data.
1847 this = listen_alloc(type);
1848 this->identity = identity;
1852 * Call per-type parser.
1854 if (master_listen[type].parse(filename, lineno,
1864 last = &(this->next);
1868 * If we're proxying requests, open the proxy FD.
1869 * Otherwise, don't do anything.
1872 if (mainconfig.proxy_requests == TRUE) {
1874 listen_socket_t *sock = NULL;
1877 * No sockets to receive packets, therefore
1878 * proxying is pointless.
1880 if (!*head) return -1;
1883 * If we previously had proxy sockets, copy them
1884 * to the new config.
1886 if (mainconfig.listen != NULL) {
1887 rad_listen_t *old, *next, **tail;
1889 tail = &mainconfig.listen;
1890 for (old = mainconfig.listen;
1895 if (old->type != RAD_LISTEN_PROXY) {
1896 tail = &((*tail)->next);
1903 last = &(old->next);
1910 * Find the first authentication port,
1913 for (this = *head; this != NULL; this = this->next) {
1914 if (this->type == RAD_LISTEN_AUTH) {
1916 if (server_ipaddr.af == AF_UNSPEC) {
1917 server_ipaddr = sock->ipaddr;
1919 port = sock->port + 2; /* skip acct port */
1922 if (this->type == RAD_LISTEN_VQP) {
1924 if (server_ipaddr.af == AF_UNSPEC) {
1925 server_ipaddr = sock->ipaddr;
1927 port = sock->port + 1;
1932 if (port < 0) port = 1024 + (lrad_rand() & 0x1ff);
1935 * Address is still unspecified, use IPv4.
1937 if (server_ipaddr.af == AF_UNSPEC) {
1938 server_ipaddr.af = AF_INET;
1939 server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
1942 this = listen_alloc(RAD_LISTEN_PROXY);
1946 * Create the first proxy socket.
1948 sock->ipaddr = server_ipaddr;
1951 * Try to find a proxy port (value doesn't matter)
1953 for (sock->port = port;
1956 if (listen_bind(this) == 0) {
1958 last = &(this->next); /* just in case */
1963 if (sock->port >= 64000) {
1966 radlog(L_ERR|L_CONS, "Failed to open socket for proxying");
1973 if (mainconfig.do_snmp) {
1977 * Forget about the old one.
1979 for (this = mainconfig.listen;
1981 this = this->next) {
1982 if (this->type != RAD_LISTEN_SNMP) continue;
1986 this = rad_malloc(sizeof(*this));
1987 memset(this, 0, sizeof(*this));
1989 this->type = RAD_LISTEN_SNMP;
1990 this->fd = rad_snmp.smux_fd;
1992 this->recv = radius_snmp_recv;
1993 this->print = radius_snmp_print;
1996 last = &(this->next);
2005 * Free a linked list of listeners;
2007 void listen_free(rad_listen_t **head)
2011 if (!head || !*head) return;
2015 rad_listen_t *next = this->next;
2017 free(this->identity);
2020 * Other code may have eaten the FD.
2022 if (this->fd >= 0) close(this->fd);
2024 if (master_listen[this->type].free) {
2025 master_listen[this->type].free(this);