2 * detail.c Process the detail file
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 2007 The FreeRADIUS server project
21 * Copyright 2007 Alan DeKok <aland@deployingradius.com>
24 #include <freeradius-devel/ident.h>
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/detail.h>
30 #include <freeradius-devel/rad_assert.h>
32 #ifdef HAVE_SYS_STAT_H
44 #define USEC (1000000)
46 typedef struct listen_detail_t {
47 int delay_time; /* should be first entry */
54 fr_ipaddr_t client_ip;
55 int load_factor; /* 1..100 */
62 struct timeval last_packet;
63 RADCLIENT detail_client;
67 #define STATE_UNOPENED (0)
68 #define STATE_UNLOCKED (1)
69 #define STATE_HEADER (2)
70 #define STATE_READING (3)
71 #define STATE_QUEUED (4)
72 #define STATE_RUNNING (5)
73 #define STATE_NO_REPLY (6)
74 #define STATE_REPLIED (7)
77 * If we're limiting outstanding packets, then mark the response
80 int detail_send(rad_listen_t *listener, REQUEST *request)
84 listen_detail_t *data = listener->data;
86 rad_assert(request->listener == listener);
87 rad_assert(listener->send == detail_send);
90 * This request timed out. Remember that, and tell the
91 * caller it's OK to read more "detail" file stuff.
93 if (request->reply->code == 0) {
94 data->delay_time = USEC;
96 data->state = STATE_NO_REPLY;
97 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
102 * We call gettimeofday a lot. But here it should be OK,
103 * because there's nothing else to do.
105 gettimeofday(&now, NULL);
108 * If we haven't sent a packet in the last second, reset
112 if (timercmp(&data->last_packet, &now, <)) {
113 data->has_rtt = FALSE;
118 * Only one detail packet may be outstanding at a time,
119 * so it's safe to update some entries in the detail
122 * We keep smoothed round trip time (SRTT), but not round
123 * trip timeout (RTO). We use SRTT to calculate a rough
126 rtt = now.tv_sec - request->received.tv_sec;
129 rtt -= request->received.tv_usec;
132 * If we're proxying, the RTT is our processing time,
133 * plus the network delay there and back, plus the time
134 * on the other end to process the packet. Ideally, we
135 * should remove the network delays from the RTT, but we
136 * don't know what they are.
138 * So, to be safe, we over-estimate the total cost of
139 * processing the packet.
141 if (!data->has_rtt) {
142 data->has_rtt = TRUE;
144 data->rttvar = rtt / 2;
147 data->rttvar -= data->rttvar >> 2;
148 data->rttvar += (data->srtt - rtt);
149 data->srtt -= data->srtt >> 3;
150 data->srtt += rtt >> 3;
154 * Calculate the time we wait before sending the next
157 * rtt / (rtt + delay) = load_factor / 100
159 data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
160 if (data->delay_time == 0) data->delay_time = USEC / 10;
163 * Cap delay at 4 packets/s. If the end system can't
164 * handle this, then it's very broken.
166 if (data->delay_time > (USEC / 4)) data->delay_time= USEC / 4;
169 DEBUG2("RTT %d\tdelay %d", data->srtt, data->delay_time);
172 data->last_packet = now;
174 data->state = STATE_REPLIED;
175 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
180 int detail_delay(rad_listen_t *listener)
182 listen_detail_t *data = listener->data;
184 if (!data->signal) return 0;
188 return data->delay_time;
193 * Open the detail file, if we can.
195 * FIXME: create it, if it's not already there, so that the main
196 * server select() will wake us up if there's anything to read.
198 static int detail_open(rad_listen_t *this)
201 listen_detail_t *data = this->data;
202 char *filename = data->filename;
204 rad_assert(data->state == STATE_UNOPENED);
205 data->delay_time = USEC;
208 * Open detail.work first, so we don't lose
209 * accounting packets. It's probably better to
210 * duplicate them than to lose them.
212 * Note that we're not writing to the file, but
213 * we've got to open it for writing in order to
214 * establish the lock, to prevent rlm_detail from
217 * This also means that if we're doing globbing,
218 * this file will be read && processed before the
219 * file globbing is done.
221 this->fd = open(data->filename_work, O_RDWR);
223 DEBUG2("Polling for detail file %s", filename);
226 * Try reading the detail file. If it
227 * doesn't exist, we can't do anything.
229 * Doing the stat will tell us if the file
230 * exists, even if we don't have permissions
233 if (stat(filename, &st) < 0) {
239 memset(&files, 0, sizeof(files));
240 if (glob(filename, 0, NULL, &files) != 0) {
246 for (i = 0; i < files.gl_pathc; i++) {
247 if (stat(files.gl_pathv[i], &st) < 0) continue;
250 (st.st_ctime < chtime)) {
251 chtime = st.st_ctime;
261 filename = strdup(files.gl_pathv[found]);
269 * Open it BEFORE we rename it, just to
272 this->fd = open(filename, O_RDWR);
274 radlog(L_ERR, "Failed to open %s: %s",
275 filename, strerror(errno));
276 if (filename != data->filename) free(filename);
281 * Rename detail to detail.work
283 DEBUG("detail_recv: Renaming %s -> %s", filename, data->filename_work);
284 if (rename(filename, data->filename_work) < 0) {
285 if (filename != data->filename) free(filename);
290 if (filename != data->filename) free(filename);
291 } /* else detail.work existed, and we opened it */
293 rad_assert(data->vps == NULL);
294 rad_assert(data->fp == NULL);
296 data->state = STATE_UNLOCKED;
298 data->client_ip.af = AF_UNSPEC;
306 * FIXME: add a configuration "exit when done" so that the detail
307 * file reader can be used as a one-off tool to update stuff.
309 * The time sequence for reading from the detail file is:
311 * t_0 signalled that the server is idle, and we
312 * can read from the detail file.
314 * t_rtt the packet has been processed successfully,
315 * wait for t_delay to enforce load factor.
317 * t_rtt + t_delay wait for signal that the server is idle.
320 int detail_recv(rad_listen_t *listener,
321 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
323 char key[256], value[1024];
324 VALUE_PAIR *vp, **tail;
325 RADIUS_PACKET *packet;
327 listen_detail_t *data = listener->data;
329 switch (data->state) {
332 rad_assert(listener->fd < 0);
334 if (!detail_open(listener)) return 0;
336 rad_assert(data->state == STATE_UNLOCKED);
337 rad_assert(listener->fd >= 0);
342 * Try to lock fd. If we can't, return.
343 * If we can, continue. This means that
344 * the server doesn't block while waiting
345 * for the lock to open...
349 * Note that we do NOT block waiting for
350 * the lock. We've re-named the file
351 * above, so we've already guaranteed
352 * that any *new* detail writer will not
353 * be opening this file. The only
354 * purpose of the lock is to catch a race
355 * condition where the execution
356 * "ping-pongs" between radiusd &
359 if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
361 * Close the FD. The main loop
362 * will wake up in a second and
367 data->state = STATE_UNOPENED;
371 data->fp = fdopen(listener->fd, "r");
373 radlog(L_ERR, "FATAL: Failed to re-open detail file %s: %s",
374 data->filename, strerror(errno));
379 * Look for the header
381 data->state = STATE_HEADER;
389 data->state = STATE_UNOPENED;
396 fstat(listener->fd, &buf);
397 if (((off_t) ftell(data->fp)) == buf.st_size) {
403 * End of file. Delete it, and re-set
406 if (feof(data->fp)) {
408 unlink(data->filename_work);
409 if (data->fp) fclose(data->fp);
412 data->state = STATE_UNOPENED;
413 rad_assert(data->vps == NULL);
418 * Else go read something.
423 * Read more value-pair's, unless we're
424 * at EOF. In that case, queue whatever
428 if (data->fp && !feof(data->fp)) break;
429 data->state = STATE_QUEUED;
437 * We still have an outstanding packet.
438 * Don't read any more.
444 * If there's no reply, keep
445 * retransmitting the current packet
449 data->state = STATE_QUEUED;
453 * We have a reply. Clean up the old
454 * request, and go read another one.
457 pairfree(&data->vps);
458 data->state = STATE_HEADER;
463 while (*tail) tail = &(*tail)->next;
466 * Read a header, OR a value-pair.
468 while (fgets(buffer, sizeof(buffer), data->fp)) {
470 * Badly formatted file: delete it.
472 * FIXME: Maybe flag an error?
474 if (!strchr(buffer, '\n')) {
475 pairfree(&data->vps);
480 * We're reading VP's, and got a blank line.
483 if ((data->state == STATE_READING) &&
484 (buffer[0] == '\n')) {
485 data->state = STATE_QUEUED;
490 * Look for date/time header, and read VP's if
491 * found. If not, keep reading lines until we
494 if (data->state == STATE_HEADER) {
497 if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
498 data->state = STATE_READING;
504 * We have a full "attribute = value" line.
505 * If it doesn't look reasonable, skip it.
507 * FIXME: print an error for badly formatted attributes?
509 if (sscanf(buffer, "%255s = %1023s", key, value) != 2) {
514 * Skip non-protocol attributes.
516 if (!strcasecmp(key, "Request-Authenticator")) continue;
519 * Set the original client IP address, based on
520 * what's in the detail file.
522 * Hmm... we don't set the server IP address.
525 if (!strcasecmp(key, "Client-IP-Address")) {
526 data->client_ip.af = AF_INET;
527 ip_hton(value, AF_INET, &data->client_ip);
532 * The original time at which we received the
533 * packet. We need this to properly calculate
536 if (!strcasecmp(key, "Timestamp")) {
537 data->timestamp = atoi(value);
539 vp = paircreate(PW_PACKET_ORIGINAL_TIMESTAMP,
542 vp->vp_date = (uint32_t) data->timestamp;
552 * FIXME: do we want to check for non-protocol
553 * attributes like radsqlrelay does?
556 if ((userparse(buffer, &vp) > 0) &&
564 * Some kind of error.
566 * FIXME: Leave the file in-place, and warn the
569 if (ferror(data->fp)) goto cleanup;
572 * Process the packet.
575 rad_assert(data->state == STATE_QUEUED);
578 * We're done reading the file, but we didn't read
579 * anything. Clean up, and don't return anything.
582 data->state = STATE_HEADER;
583 if (feof(data->fp)) goto cleanup;
588 * Allocate the packet. If we fail, it's a serious
591 packet = rad_alloc(1);
593 radlog(L_ERR, "FATAL: Failed allocating memory for detail");
597 memset(packet, 0, sizeof(*packet));
599 packet->src_ipaddr.af = AF_INET;
600 packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
601 packet->code = PW_ACCOUNTING_REQUEST;
602 packet->timestamp = time(NULL);
605 * Remember where it came from, so that we don't
606 * proxy it to the place it came from...
608 if (data->client_ip.af != AF_UNSPEC) {
609 packet->src_ipaddr = data->client_ip;
612 vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
614 packet->src_ipaddr.af = AF_INET;
615 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
617 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
619 packet->src_ipaddr.af = AF_INET6;
620 memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
621 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
625 vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
627 packet->dst_ipaddr.af = AF_INET;
628 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
630 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
632 packet->dst_ipaddr.af = AF_INET6;
633 memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
634 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
639 * We've got to give SOME value for Id & ports, so that
640 * the packets can be added to the request queue.
641 * However, we don't want to keep track of used/unused
642 * id's and ports, as that's a lot of work. This hack
643 * ensures that (if we have real random numbers), that
644 * there will be a collision on every 2^(16+15+15+24 - 1)
645 * packets, on average. That means we can read 2^37
646 * packets before having a collision, which means it's
647 * effectively impossible.
649 packet->id = fr_rand() & 0xffff;
650 packet->src_port = 1024 + (fr_rand() & 0x7fff);
651 packet->dst_port = 1024 + (fr_rand() & 0x7fff);
653 packet->dst_ipaddr.af = AF_INET;
654 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (fr_rand() & 0xffffff));
657 * If everything's OK, this is a waste of memory.
658 * Otherwise, it lets us re-send the original packet
659 * contents, unmolested.
661 packet->vps = paircopy(data->vps);
664 * Look for Acct-Delay-Time, and update
665 * based on Acct-Delay-Time += (time(NULL) - timestamp)
667 vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
669 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
670 rad_assert(vp != NULL);
671 pairadd(&packet->vps, vp);
673 if (data->timestamp != 0) {
674 vp->vp_integer += time(NULL) - data->timestamp;
677 *pfun = rad_accounting;
680 fr_printf_log("detail_recv: Read packet from %s\n", data->filename_work);
681 for (vp = packet->vps; vp; vp = vp->next) {
687 * FIXME: many of these checks may not be necessary when
688 * reading from the detail file.
692 if (!received_request(listener, packet, prequest,
693 &data->detail_client)) {
695 data->state = STATE_NO_REPLY; /* try again later */
699 data->state = STATE_RUNNING;
706 * Free detail-specific stuff.
708 void detail_free(rad_listen_t *this)
710 listen_detail_t *data = this->data;
712 free(data->filename);
713 pairfree(&data->vps);
715 if (data->fp != NULL) fclose(data->fp);
719 int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
722 return snprintf(buffer, bufsize, "%s",
723 ((listen_detail_t *)(this->data))->filename);
726 return snprintf(buffer, bufsize, "detail file %s as server %s",
727 ((listen_detail_t *)(this->data))->filename,
731 int detail_encode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
734 * We never encode responses "sent to" the detail file.
739 int detail_decode(UNUSED rad_listen_t *this, UNUSED REQUEST *request)
742 * We never decode responses read from the detail file.
748 static const CONF_PARSER detail_config[] = {
749 { "filename", PW_TYPE_STRING_PTR,
750 offsetof(listen_detail_t, filename), NULL, NULL },
751 { "load_factor", PW_TYPE_INTEGER,
752 offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
753 { "poll_interval", PW_TYPE_INTEGER,
754 offsetof(listen_detail_t, poll_interval), NULL, Stringify(1)},
756 { NULL, -1, 0, NULL, NULL } /* end the list */
761 * Parse a detail section.
763 int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
766 listen_detail_t *data;
771 this->data = rad_malloc(sizeof(*data));
772 memset(this->data, 0, sizeof(*data));
776 data->delay_time = USEC;
778 rcode = cf_section_parse(cs, data, detail_config);
780 cf_log_err(cf_sectiontoitem(cs), "Failed parsing listen section");
784 if (!data->filename) {
785 cf_log_err(cf_sectiontoitem(cs), "No detail file specified in listen section");
789 if ((data->load_factor < 1) || (data->load_factor > 100)) {
790 cf_log_err(cf_sectiontoitem(cs), "Load factor must be between 1 and 100");
794 if ((data->poll_interval < 1) || (data->poll_interval > 3600)) {
795 cf_log_err(cf_sectiontoitem(cs), "poll_interval must be between 1 and 3600");
800 * If the filename is a glob, use "detail.work" as the
803 if ((strchr(data->filename, '*') != NULL) ||
804 (strchr(data->filename, '[') != NULL)) {
808 radlog(L_INFO, "WARNING: Detail file \"%s\" appears to use file globbing, but it is not supported on this system.", data->filename);
810 strlcpy(buffer, data->filename, sizeof(buffer));
811 p = strrchr(buffer, FR_DIR_SEP);
817 strlcat(buffer, "detail.work",
818 sizeof(buffer) - strlen(buffer));
821 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
824 free(data->filename_work);
825 data->filename_work = strdup(buffer); /* FIXME: leaked */
829 data->state = STATE_UNOPENED;
832 * Initialize the fake client.
834 client = &data->detail_client;
835 memset(client, 0, sizeof(*client));
836 client->ipaddr.af = AF_INET;
837 client->ipaddr.ipaddr.ip4addr.s_addr = INADDR_NONE;
839 client->longname = client->shortname = data->filename;
840 client->secret = client->shortname;
841 client->nastype = strdup("none");
846 int detail_poll_interval(rad_listen_t *listener)
848 listen_detail_t *data = listener->data;
850 return data->poll_interval;