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 enum detail_state_t {
57 static FR_NAME_NUMBER state_names[] = {
58 { "unopened", STATE_UNOPENED },
59 { "unlocked", STATE_UNLOCKED },
60 { "header", STATE_HEADER },
61 { "reading", STATE_READING },
62 { "queued", STATE_QUEUED },
63 { "running", STATE_RUNNING },
64 { "no-reply", STATE_NO_REPLY },
65 { "replied", STATE_REPLIED },
70 typedef struct listen_detail_t {
71 fr_event_t *ev; /* has to be first entry (ugh) */
79 fr_ipaddr_t client_ip;
80 int load_factor; /* 1..100 */
88 struct timeval last_packet;
89 RADCLIENT detail_client;
94 * If we're limiting outstanding packets, then mark the response
97 int detail_send(rad_listen_t *listener, REQUEST *request)
101 listen_detail_t *data = listener->data;
103 rad_assert(request->listener == listener);
104 rad_assert(listener->send == detail_send);
107 * This request timed out. Remember that, and tell the
108 * caller it's OK to read more "detail" file stuff.
110 if (request->reply->code == 0) {
111 data->delay_time = data->retry_interval * USEC;
113 data->state = STATE_NO_REPLY;
115 RDEBUG("Detail - No response configured for request %d. Will retry in %d seconds",
116 request->number, data->retry_interval);
118 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
123 * We call gettimeofday a lot. But it should be OK,
124 * because there's nothing else to do.
126 gettimeofday(&now, NULL);
129 * If we haven't sent a packet in the last second, reset
133 if (timercmp(&data->last_packet, &now, <)) {
134 data->has_rtt = FALSE;
139 * Only one detail packet may be outstanding at a time,
140 * so it's safe to update some entries in the detail
143 * We keep smoothed round trip time (SRTT), but not round
144 * trip timeout (RTO). We use SRTT to calculate a rough
147 rtt = now.tv_sec - request->received.tv_sec;
150 rtt -= request->received.tv_usec;
153 * If we're proxying, the RTT is our processing time,
154 * plus the network delay there and back, plus the time
155 * on the other end to process the packet. Ideally, we
156 * should remove the network delays from the RTT, but we
157 * don't know what they are.
159 * So, to be safe, we over-estimate the total cost of
160 * processing the packet.
162 if (!data->has_rtt) {
163 data->has_rtt = TRUE;
165 data->rttvar = rtt / 2;
168 data->rttvar -= data->rttvar >> 2;
169 data->rttvar += (data->srtt - rtt);
170 data->srtt -= data->srtt >> 3;
171 data->srtt += rtt >> 3;
175 * Calculate the time we wait before sending the next
178 * rtt / (rtt + delay) = load_factor / 100
180 data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
183 * Cap delay at 4 packets/s. If the end system can't
184 * handle this, then it's very broken.
186 if (data->delay_time > (USEC / 4)) data->delay_time= USEC / 4;
188 RDEBUG3("Received response for request %d. Will read the next packet in %d seconds",
189 request->number, data->delay_time / USEC);
191 data->last_packet = now;
193 data->state = STATE_REPLIED;
194 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
201 * Open the detail file, if we can.
203 * FIXME: create it, if it's not already there, so that the main
204 * server select() will wake us up if there's anything to read.
206 static int detail_open(rad_listen_t *this)
209 listen_detail_t *data = this->data;
210 char *filename = data->filename;
212 rad_assert(data->state == STATE_UNOPENED);
213 data->delay_time = USEC;
216 * Open detail.work first, so we don't lose
217 * accounting packets. It's probably better to
218 * duplicate them than to lose them.
220 * Note that we're not writing to the file, but
221 * we've got to open it for writing in order to
222 * establish the lock, to prevent rlm_detail from
225 * This also means that if we're doing globbing,
226 * this file will be read && processed before the
227 * file globbing is done.
229 this->fd = open(data->filename_work, O_RDWR);
231 DEBUG2("Polling for detail file %s", filename);
234 * Try reading the detail file. If it
235 * doesn't exist, we can't do anything.
237 * Doing the stat will tell us if the file
238 * exists, even if we don't have permissions
241 if (stat(filename, &st) < 0) {
248 memset(&files, 0, sizeof(files));
249 if (glob(filename, 0, NULL, &files) != 0) {
255 for (i = 0; i < files.gl_pathc; i++) {
256 if (stat(files.gl_pathv[i], &st) < 0) continue;
259 (st.st_ctime < chtime)) {
260 chtime = st.st_ctime;
270 filename = strdup(files.gl_pathv[found]);
278 * Open it BEFORE we rename it, just to
281 this->fd = open(filename, O_RDWR);
283 radlog(L_ERR, "Detail - Failed to open %s: %s",
284 filename, strerror(errno));
285 if (filename != data->filename) free(filename);
290 * Rename detail to detail.work
292 DEBUG("Detail - Renaming %s -> %s", filename, data->filename_work);
293 if (rename(filename, data->filename_work) < 0) {
294 if (filename != data->filename) free(filename);
299 if (filename != data->filename) free(filename);
300 } /* else detail.work existed, and we opened it */
302 rad_assert(data->vps == NULL);
303 rad_assert(data->fp == NULL);
305 data->state = STATE_UNLOCKED;
307 data->client_ip.af = AF_UNSPEC;
315 * FIXME: add a configuration "exit when done" so that the detail
316 * file reader can be used as a one-off tool to update stuff.
318 * The time sequence for reading from the detail file is:
320 * t_0 signalled that the server is idle, and we
321 * can read from the detail file.
323 * t_rtt the packet has been processed successfully,
324 * wait for t_delay to enforce load factor.
326 * t_rtt + t_delay wait for signal that the server is idle.
329 int detail_recv(rad_listen_t *listener,
330 RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
332 char key[256], op[8], value[1024];
333 VALUE_PAIR *vp, **tail;
334 RADIUS_PACKET *packet;
336 listen_detail_t *data = listener->data;
339 * We may be in the main thread. It needs to update the
340 * timers before we try to read from the file again.
342 if (data->signal) return 0;
344 switch (data->state) {
347 rad_assert(listener->fd < 0);
349 if (!detail_open(listener)) return 0;
351 rad_assert(data->state == STATE_UNLOCKED);
352 rad_assert(listener->fd >= 0);
357 * Try to lock fd. If we can't, return.
358 * If we can, continue. This means that
359 * the server doesn't block while waiting
360 * for the lock to open...
364 * Note that we do NOT block waiting for
365 * the lock. We've re-named the file
366 * above, so we've already guaranteed
367 * that any *new* detail writer will not
368 * be opening this file. The only
369 * purpose of the lock is to catch a race
370 * condition where the execution
371 * "ping-pongs" between radiusd &
374 if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
376 * Close the FD. The main loop
377 * will wake up in a second and
382 data->state = STATE_UNOPENED;
386 data->fp = fdopen(listener->fd, "r");
388 radlog(L_ERR, "FATAL: Failed to re-open detail file %s: %s",
389 data->filename, strerror(errno));
394 * Look for the header
396 data->state = STATE_HEADER;
397 data->delay_time = USEC;
405 data->state = STATE_UNOPENED;
412 fstat(listener->fd, &buf);
413 if (((off_t) ftell(data->fp)) == buf.st_size) {
419 * End of file. Delete it, and re-set
422 if (feof(data->fp)) {
424 DEBUG("Detail - unlinking %s",
425 data->filename_work);
426 unlink(data->filename_work);
427 if (data->fp) fclose(data->fp);
430 data->state = STATE_UNOPENED;
431 rad_assert(data->vps == NULL);
436 * Else go read something.
441 * Read more value-pair's, unless we're
442 * at EOF. In that case, queue whatever
446 if (data->fp && !feof(data->fp)) break;
447 data->state = STATE_QUEUED;
455 * We still have an outstanding packet.
456 * Don't read any more.
462 * If there's no reply, keep
463 * retransmitting the current packet
467 data->state = STATE_QUEUED;
471 * We have a reply. Clean up the old
472 * request, and go read another one.
475 pairfree(&data->vps);
476 data->state = STATE_HEADER;
481 while (*tail) tail = &(*tail)->next;
484 * Read a header, OR a value-pair.
486 while (fgets(buffer, sizeof(buffer), data->fp)) {
488 * Badly formatted file: delete it.
490 * FIXME: Maybe flag an error?
492 if (!strchr(buffer, '\n')) {
493 pairfree(&data->vps);
498 * We're reading VP's, and got a blank line.
501 if ((data->state == STATE_READING) &&
502 (buffer[0] == '\n')) {
503 data->state = STATE_QUEUED;
508 * Look for date/time header, and read VP's if
509 * found. If not, keep reading lines until we
512 if (data->state == STATE_HEADER) {
515 if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
516 data->state = STATE_READING;
522 * We have a full "attribute = value" line.
523 * If it doesn't look reasonable, skip it.
525 * FIXME: print an error for badly formatted attributes?
527 if (sscanf(buffer, "%255s %8s %1023s", key, op, value) != 3) {
528 DEBUG2("WARNING: Skipping badly formatted line %s",
534 * Should be =, :=, +=, ...
536 if (!strchr(op, '=')) continue;
539 * Skip non-protocol attributes.
541 if (!strcasecmp(key, "Request-Authenticator")) continue;
544 * Set the original client IP address, based on
545 * what's in the detail file.
547 * Hmm... we don't set the server IP address.
550 if (!strcasecmp(key, "Client-IP-Address")) {
551 data->client_ip.af = AF_INET;
552 ip_hton(value, AF_INET, &data->client_ip);
557 * The original time at which we received the
558 * packet. We need this to properly calculate
561 if (!strcasecmp(key, "Timestamp")) {
562 data->timestamp = atoi(value);
564 vp = paircreate(PW_PACKET_ORIGINAL_TIMESTAMP,
567 vp->vp_date = (uint32_t) data->timestamp;
577 * FIXME: do we want to check for non-protocol
578 * attributes like radsqlrelay does?
581 if ((userparse(buffer, &vp) > 0) &&
589 * Some kind of error.
591 * FIXME: Leave the file in-place, and warn the
594 if (ferror(data->fp)) goto cleanup;
597 * Process the packet.
600 rad_assert(data->state == STATE_QUEUED);
603 * We're done reading the file, but we didn't read
604 * anything. Clean up, and don't return anything.
607 data->state = STATE_HEADER;
608 if (feof(data->fp)) goto cleanup;
613 * Allocate the packet. If we fail, it's a serious
616 packet = rad_alloc(1);
618 radlog(L_ERR, "FATAL: Failed allocating memory for detail");
622 memset(packet, 0, sizeof(*packet));
624 packet->src_ipaddr.af = AF_INET;
625 packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
626 packet->code = PW_ACCOUNTING_REQUEST;
627 packet->timestamp = time(NULL);
630 * Remember where it came from, so that we don't
631 * proxy it to the place it came from...
633 if (data->client_ip.af != AF_UNSPEC) {
634 packet->src_ipaddr = data->client_ip;
637 vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS);
639 packet->src_ipaddr.af = AF_INET;
640 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
642 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS);
644 packet->src_ipaddr.af = AF_INET6;
645 memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
646 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
650 vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS);
652 packet->dst_ipaddr.af = AF_INET;
653 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
655 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS);
657 packet->dst_ipaddr.af = AF_INET6;
658 memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
659 &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
664 * We've got to give SOME value for Id & ports, so that
665 * the packets can be added to the request queue.
666 * However, we don't want to keep track of used/unused
667 * id's and ports, as that's a lot of work. This hack
668 * ensures that (if we have real random numbers), that
669 * there will be a collision on every 2^(16+15+15+24 - 1)
670 * packets, on average. That means we can read 2^37
671 * packets before having a collision, which means it's
672 * effectively impossible.
674 packet->id = fr_rand() & 0xffff;
675 packet->src_port = 1024 + (fr_rand() & 0x7fff);
676 packet->dst_port = 1024 + (fr_rand() & 0x7fff);
678 packet->dst_ipaddr.af = AF_INET;
679 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | (fr_rand() & 0xffffff));
682 * If everything's OK, this is a waste of memory.
683 * Otherwise, it lets us re-send the original packet
684 * contents, unmolested.
686 packet->vps = paircopy(data->vps);
689 * Look for Acct-Delay-Time, and update
690 * based on Acct-Delay-Time += (time(NULL) - timestamp)
692 vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME);
694 vp = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
695 rad_assert(vp != NULL);
696 pairadd(&packet->vps, vp);
698 if (data->timestamp != 0) {
699 vp->vp_integer += time(NULL) - data->timestamp;
702 *pfun = rad_accounting;
705 fr_printf_log("detail_recv: Read packet from %s\n", data->filename_work);
706 for (vp = packet->vps; vp; vp = vp->next) {
712 * FIXME: many of these checks may not be necessary when
713 * reading from the detail file.
717 if (!received_request(listener, packet, prequest,
718 &data->detail_client)) {
720 data->state = STATE_NO_REPLY; /* try again later */
724 data->state = STATE_RUNNING;
731 * Free detail-specific stuff.
733 void detail_free(rad_listen_t *this)
735 listen_detail_t *data = this->data;
737 free(data->filename);
738 pairfree(&data->vps);
740 if (data->fp != NULL) fclose(data->fp);
744 int detail_print(rad_listen_t *this, char *buffer, size_t bufsize)
747 return snprintf(buffer, bufsize, "%s",
748 ((listen_detail_t *)(this->data))->filename);
751 return snprintf(buffer, bufsize, "detail file %s as server %s",
752 ((listen_detail_t *)(this->data))->filename,
757 * Overloaded to return delay times.
759 int detail_encode(rad_listen_t *this, UNUSED REQUEST *request)
761 listen_detail_t *data = this->data;
764 * We haven't sent a packet... delay things a bit.
767 int delay = (data->poll_interval - 1) * USEC;
770 * Add +/- 0.25s of jitter
772 delay += (USEC * 3) / 4;
773 delay += fr_rand() % (USEC / 2);
775 DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
777 fr_int2str(state_names, data->state, "?"), data->signal,
778 (delay / USEC), delay % USEC);
785 DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
786 data->filename, fr_int2str(state_names, data->state, "?"),
788 data->delay_time / USEC,
789 data->delay_time % USEC);
791 return data->delay_time;
796 * Overloaded to return "should we fix delay times"
798 int detail_decode(rad_listen_t *this, UNUSED REQUEST *request)
800 listen_detail_t *data = this->data;
806 static const CONF_PARSER detail_config[] = {
807 { "filename", PW_TYPE_STRING_PTR,
808 offsetof(listen_detail_t, filename), NULL, NULL },
809 { "load_factor", PW_TYPE_INTEGER,
810 offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
811 { "poll_interval", PW_TYPE_INTEGER,
812 offsetof(listen_detail_t, poll_interval), NULL, Stringify(1)},
813 { "retry_interval", PW_TYPE_INTEGER,
814 offsetof(listen_detail_t, retry_interval), NULL, Stringify(30)},
816 { NULL, -1, 0, NULL, NULL } /* end the list */
821 * Parse a detail section.
823 int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
826 listen_detail_t *data;
831 this->data = rad_malloc(sizeof(*data));
832 memset(this->data, 0, sizeof(*data));
837 rcode = cf_section_parse(cs, data, detail_config);
839 cf_log_err(cf_sectiontoitem(cs), "Failed parsing listen section");
843 if (!data->filename) {
844 cf_log_err(cf_sectiontoitem(cs), "No detail file specified in listen section");
848 if ((data->load_factor < 1) || (data->load_factor > 100)) {
849 cf_log_err(cf_sectiontoitem(cs), "Load factor must be between 1 and 100");
853 if ((data->poll_interval < 1) || (data->poll_interval > 20)) {
854 cf_log_err(cf_sectiontoitem(cs), "poll_interval must be between 1 and 20");
859 * If the filename is a glob, use "detail.work" as the
862 if ((strchr(data->filename, '*') != NULL) ||
863 (strchr(data->filename, '[') != NULL)) {
867 radlog(L_INFO, "WARNING: Detail file \"%s\" appears to use file globbing, but it is not supported on this system.", data->filename);
869 strlcpy(buffer, data->filename, sizeof(buffer));
870 p = strrchr(buffer, FR_DIR_SEP);
876 strlcat(buffer, "detail.work",
877 sizeof(buffer) - strlen(buffer));
880 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
883 free(data->filename_work);
884 data->filename_work = strdup(buffer); /* FIXME: leaked */
888 data->state = STATE_UNOPENED;
889 data->delay_time = data->poll_interval * USEC;
893 * Initialize the fake client.
895 client = &data->detail_client;
896 memset(client, 0, sizeof(*client));
897 client->ipaddr.af = AF_INET;
898 client->ipaddr.ipaddr.ip4addr.s_addr = INADDR_NONE;
900 client->longname = client->shortname = data->filename;
901 client->secret = client->shortname;
902 client->nastype = strdup("none");