Start of allowing multiple packets outstanding for detail file
[freeradius.git] / src / main / detail.c
1 /*
2  * detail.c     Process the detail file
3  *
4  * Version:     $Id$
5  *
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.
10  *
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.
15  *
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
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/detail.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef HAVE_GLOB_H
38 #include <glob.h>
39 #endif
40
41 #include <fcntl.h>
42
43 #ifdef WITH_DETAIL
44
45 #define USEC (1000000)
46
47 static FR_NAME_NUMBER state_names[] = {
48         { "unopened", STATE_UNOPENED },
49         { "unlocked", STATE_UNLOCKED },
50         { "header", STATE_HEADER },
51         { "reading", STATE_READING },
52         { "queued", STATE_QUEUED },
53         { "running", STATE_RUNNING },
54         { "no-reply", STATE_NO_REPLY },
55         { "replied", STATE_REPLIED },
56
57         { NULL, 0 }
58 };
59
60 /*
61  *      If we're limiting outstanding packets, then mark the response
62  *      as being sent.
63  */
64 int detail_send(rad_listen_t *listener, REQUEST *request)
65 {
66         int rtt;
67         struct timeval now;
68         listen_detail_t *data = listener->data;
69
70         rad_assert(request->listener == listener);
71         rad_assert(listener->send == detail_send);
72
73         /*
74          *      This request timed out.  Remember that, and tell the
75          *      caller it's OK to read more "detail" file stuff.
76          */
77         if (request->reply->code == 0) {
78                 data->delay_time = data->retry_interval * USEC;
79                 data->signal = 1;
80                 data->state = STATE_NO_REPLY;
81
82                 RDEBUG("Detail - No response configured for request %d.  Will retry in %d seconds",
83                        request->number, data->retry_interval);
84
85                 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
86                 return 0;
87         }
88
89         /*
90          *      We call gettimeofday a lot.  But it should be OK,
91          *      because there's nothing else to do.
92          */
93         gettimeofday(&now, NULL);
94
95         /*
96          *      If we haven't sent a packet in the last second, reset
97          *      the RTT.
98          */
99         now.tv_sec -= 1;
100         if (timercmp(&data->last_packet, &now, <)) {
101                 data->has_rtt = FALSE;
102         }
103         now.tv_sec += 1;
104
105         /*
106          *      Only one detail packet may be outstanding at a time,
107          *      so it's safe to update some entries in the detail
108          *      structure.
109          *
110          *      We keep smoothed round trip time (SRTT), but not round
111          *      trip timeout (RTO).  We use SRTT to calculate a rough
112          *      load factor.
113          */
114         rtt = now.tv_sec - request->packet->timestamp.tv_sec;
115         rtt *= USEC;
116         rtt += now.tv_usec;
117         rtt -= request->packet->timestamp.tv_usec;
118
119         /*
120          *      If we're proxying, the RTT is our processing time,
121          *      plus the network delay there and back, plus the time
122          *      on the other end to process the packet.  Ideally, we
123          *      should remove the network delays from the RTT, but we
124          *      don't know what they are.
125          *
126          *      So, to be safe, we over-estimate the total cost of
127          *      processing the packet.
128          */
129         if (!data->has_rtt) {
130                 data->has_rtt = TRUE;
131                 data->srtt = rtt;
132                 data->rttvar = rtt / 2;
133
134         } else {
135                 data->rttvar -= data->rttvar >> 2;
136                 data->rttvar += (data->srtt - rtt);
137                 data->srtt -= data->srtt >> 3;
138                 data->srtt += rtt >> 3;
139         }
140
141         /*
142          *      Calculate the time we wait before sending the next
143          *      packet.
144          *
145          *      rtt / (rtt + delay) = load_factor / 100
146          */
147         data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
148
149         /*
150          *      Cap delay at 4 packets/s.  If the end system can't
151          *      handle this, then it's very broken.
152          */
153         if (data->delay_time > (USEC / 4)) data->delay_time= USEC / 4;
154         
155         RDEBUG3("Received response for request %d.  Will read the next packet in %d seconds",
156                 request->number, data->delay_time / USEC);
157         
158         data->last_packet = now;
159         data->signal = 1;
160         data->state = STATE_REPLIED;
161         data->counter++;
162         radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
163
164         return 0;
165 }
166
167
168 /*
169  *      Open the detail file, if we can.
170  *
171  *      FIXME: create it, if it's not already there, so that the main
172  *      server select() will wake us up if there's anything to read.
173  */
174 static int detail_open(rad_listen_t *this)
175 {
176         struct stat st;
177         listen_detail_t *data = this->data;
178         char *filename = data->filename;
179
180         rad_assert(data->state == STATE_UNOPENED);
181         data->delay_time = USEC;
182
183         /*
184          *      Open detail.work first, so we don't lose
185          *      accounting packets.  It's probably better to
186          *      duplicate them than to lose them.
187          *
188          *      Note that we're not writing to the file, but
189          *      we've got to open it for writing in order to
190          *      establish the lock, to prevent rlm_detail from
191          *      writing to it.
192          *
193          *      This also means that if we're doing globbing,
194          *      this file will be read && processed before the
195          *      file globbing is done.
196          */
197         this->fd = open(data->filename_work, O_RDWR);
198         if (this->fd < 0) {
199                 DEBUG2("Polling for detail file %s", filename);
200
201                 /*
202                  *      Try reading the detail file.  If it
203                  *      doesn't exist, we can't do anything.
204                  *
205                  *      Doing the stat will tell us if the file
206                  *      exists, even if we don't have permissions
207                  *      to read it.
208                  */
209                 if (stat(filename, &st) < 0) {
210 #ifdef HAVE_GLOB_H
211                         unsigned int i;
212                         int found;
213                         time_t chtime;
214                         glob_t files;
215
216                         memset(&files, 0, sizeof(files));
217                         if (glob(filename, 0, NULL, &files) != 0) {
218                                 return 0;
219                         }
220
221                         chtime = 0;
222                         found = -1;
223                         for (i = 0; i < files.gl_pathc; i++) {
224                                 if (stat(files.gl_pathv[i], &st) < 0) continue;
225
226                                 if ((i == 0) ||
227                                     (st.st_ctime < chtime)) {
228                                         chtime = st.st_ctime;
229                                         found = i;
230                                 }
231                         }
232
233                         if (found < 0) {
234                                 globfree(&files);
235                                 return 0;
236                         }
237
238                         filename = strdup(files.gl_pathv[found]);
239                         globfree(&files);
240 #else
241                         return 0;
242 #endif
243                 }
244
245                 /*
246                  *      Open it BEFORE we rename it, just to
247                  *      be safe...
248                  */
249                 this->fd = open(filename, O_RDWR);
250                 if (this->fd < 0) {
251                         radlog(L_ERR, "Detail - Failed to open %s: %s",
252                                filename, strerror(errno));
253                         if (filename != data->filename) free(filename);
254                         return 0;
255                 }
256
257                 /*
258                  *      Rename detail to detail.work
259                  */
260                 DEBUG("Detail - Renaming %s -> %s", filename, data->filename_work);
261                 if (rename(filename, data->filename_work) < 0) {
262                         if (filename != data->filename) free(filename);
263                         close(this->fd);
264                         this->fd = -1;
265                         return 0;
266                 }
267                 if (filename != data->filename) free(filename);
268         } /* else detail.work existed, and we opened it */
269
270         rad_assert(data->vps == NULL);
271         rad_assert(data->fp == NULL);
272
273         data->state = STATE_UNLOCKED;
274
275         data->client_ip.af = AF_UNSPEC;
276         data->timestamp = 0;
277         data->offset = 0;
278         data->packets = 0;
279         data->tries = 0;
280
281         return 1;
282 }
283
284
285 /*
286  *      FIXME: add a configuration "exit when done" so that the detail
287  *      file reader can be used as a one-off tool to update stuff.
288  *
289  *      The time sequence for reading from the detail file is:
290  *
291  *      t_0             signalled that the server is idle, and we
292  *                      can read from the detail file.
293  *
294  *      t_rtt           the packet has been processed successfully,
295  *                      wait for t_delay to enforce load factor.
296  *                      
297  *      t_rtt + t_delay wait for signal that the server is idle.
298  *      
299  */
300 int detail_recv(rad_listen_t *listener)
301 {
302         char            key[256], op[8], value[1024];
303         VALUE_PAIR      *vp, **tail;
304         RADIUS_PACKET   *packet;
305         char            buffer[2048];
306         listen_detail_t *data = listener->data;
307         struct timeval  now;
308
309         /*
310          *      We may be in the main thread.  It needs to update the
311          *      timers before we try to read from the file again.
312          */
313         if (data->signal) return 0;
314
315         switch (data->state) {
316                 case STATE_UNOPENED:
317         open_file:
318                         rad_assert(listener->fd < 0);
319                         
320                         if (!detail_open(listener)) return 0;
321
322                         rad_assert(data->state == STATE_UNLOCKED);
323                         rad_assert(listener->fd >= 0);
324
325                         /* FALL-THROUGH */
326
327                         /*
328                          *      Try to lock fd.  If we can't, return.
329                          *      If we can, continue.  This means that
330                          *      the server doesn't block while waiting
331                          *      for the lock to open...
332                          */
333                 case STATE_UNLOCKED:
334                         /*
335                          *      Note that we do NOT block waiting for
336                          *      the lock.  We've re-named the file
337                          *      above, so we've already guaranteed
338                          *      that any *new* detail writer will not
339                          *      be opening this file.  The only
340                          *      purpose of the lock is to catch a race
341                          *      condition where the execution
342                          *      "ping-pongs" between radiusd &
343                          *      radrelay.
344                          */
345                         if (rad_lockfd_nonblock(listener->fd, 0) < 0) {
346                                 /*
347                                  *      Close the FD.  The main loop
348                                  *      will wake up in a second and
349                                  *      try again.
350                                  */
351                                 close(listener->fd);
352                                 listener->fd = -1;
353                                 data->state = STATE_UNOPENED;
354                                 return 0;
355                         }
356
357                         data->fp = fdopen(listener->fd, "r");
358                         if (!data->fp) {
359                                 radlog(L_ERR, "FATAL: Failed to re-open detail file %s: %s",
360                                        data->filename, strerror(errno));
361                                 exit(1);
362                         }
363
364                         /*
365                          *      Look for the header
366                          */
367                         data->state = STATE_HEADER;
368                         data->delay_time = USEC;
369                         data->vps = NULL;
370
371                         /* FALL-THROUGH */
372
373                 case STATE_HEADER:
374                 do_header:
375                         data->tries = 0;
376                         if (!data->fp) {
377                                 data->state = STATE_UNOPENED;
378                                 goto open_file;
379                         }
380
381                         {
382                                 struct stat buf;
383                                 
384                                 fstat(listener->fd, &buf);
385                                 if (((off_t) ftell(data->fp)) == buf.st_size) {
386                                         goto cleanup;
387                                 }
388                         }
389
390                         /*
391                          *      End of file.  Delete it, and re-set
392                          *      everything.
393                          */
394                         if (feof(data->fp)) {
395                         cleanup:
396                                 DEBUG("Detail - unlinking %s",
397                                       data->filename_work);
398                                 unlink(data->filename_work);
399                                 if (data->fp) fclose(data->fp);
400                                 data->fp = NULL;
401                                 listener->fd = -1;
402                                 data->state = STATE_UNOPENED;
403                                 rad_assert(data->vps == NULL);
404
405                                 if (data->one_shot) {
406                                         radlog(L_INFO, "Finished reading \"one shot\" detail file - Exiting");
407                                         radius_signal_self(RADIUS_SIGNAL_SELF_EXIT);
408                                 }
409
410                                 return 0;
411                         }
412
413                         /*
414                          *      Else go read something.
415                          */
416                         break;
417
418                         /*
419                          *      Read more value-pair's, unless we're
420                          *      at EOF.  In that case, queue whatever
421                          *      we have.
422                          */
423                 case STATE_READING:
424                         if (data->fp && !feof(data->fp)) break;
425                         data->state = STATE_QUEUED;
426
427                         /* FALL-THROUGH */
428
429                 case STATE_QUEUED:
430                         goto alloc_packet;
431
432                         /*
433                          *      Periodically check what's going on.
434                          *      If the request is taking too long,
435                          *      retry it.
436                          */
437                 case STATE_RUNNING:
438                         if (time(NULL) < (data->running + data->retry_interval)) {
439                                 return 0;
440                         }
441
442                         DEBUG("No response to detail request.  Retrying");
443                         data->state = STATE_NO_REPLY;
444                         /* FALL-THROUGH */
445
446                         /*
447                          *      If there's no reply, keep
448                          *      retransmitting the current packet
449                          *      forever.
450                          */
451                 case STATE_NO_REPLY:
452                         data->state = STATE_QUEUED;
453                         goto alloc_packet;
454                                 
455                         /*
456                          *      We have a reply.  Clean up the old
457                          *      request, and go read another one.
458                          */
459                 case STATE_REPLIED:
460                         pairfree(&data->vps);
461                         data->state = STATE_HEADER;
462                         goto do_header;
463         }
464         
465         tail = &data->vps;
466         while (*tail) tail = &(*tail)->next;
467
468         /*
469          *      Read a header, OR a value-pair.
470          */
471         while (fgets(buffer, sizeof(buffer), data->fp)) {
472                 data->offset = ftell(data->fp); /* for statistics */
473
474                 /*
475                  *      Badly formatted file: delete it.
476                  *
477                  *      FIXME: Maybe flag an error?
478                  */
479                 if (!strchr(buffer, '\n')) {
480                         pairfree(&data->vps);
481                         goto cleanup;
482                 }
483
484                 /*
485                  *      We're reading VP's, and got a blank line.
486                  *      Queue the packet.
487                  */
488                 if ((data->state == STATE_READING) &&
489                     (buffer[0] == '\n')) {
490                         data->state = STATE_QUEUED;
491                         break;
492                 }
493
494                 /*
495                  *      Look for date/time header, and read VP's if
496                  *      found.  If not, keep reading lines until we
497                  *      find one.
498                  */
499                 if (data->state == STATE_HEADER) {
500                         int y;
501
502                         if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
503                                 data->state = STATE_READING;
504                         }
505                         continue;
506                 }
507
508                 /*
509                  *      We have a full "attribute = value" line.
510                  *      If it doesn't look reasonable, skip it.
511                  *
512                  *      FIXME: print an error for badly formatted attributes?
513                  */
514                 if (sscanf(buffer, "%255s %8s %1023s", key, op, value) != 3) {
515                         DEBUG2("WARNING: Skipping badly formatted line %s",
516                                buffer);
517                         continue;
518                 }
519
520                 /*
521                  *      Should be =, :=, +=, ...
522                  */
523                 if (!strchr(op, '=')) continue;
524
525                 /*
526                  *      Skip non-protocol attributes.
527                  */
528                 if (!strcasecmp(key, "Request-Authenticator")) continue;
529
530                 /*
531                  *      Set the original client IP address, based on
532                  *      what's in the detail file.
533                  *
534                  *      Hmm... we don't set the server IP address.
535                  *      or port.  Oh well.
536                  */
537                 if (!strcasecmp(key, "Client-IP-Address")) {
538                         data->client_ip.af = AF_INET;
539                         ip_hton(value, AF_INET, &data->client_ip);
540                         continue;
541                 }
542
543                 /*
544                  *      The original time at which we received the
545                  *      packet.  We need this to properly calculate
546                  *      Acct-Delay-Time.
547                  */
548                 if (!strcasecmp(key, "Timestamp")) {
549                         data->timestamp = atoi(value);
550
551                         vp = paircreate(PW_PACKET_ORIGINAL_TIMESTAMP, 0,
552                                         PW_TYPE_DATE);
553                         if (vp) {
554                                 vp->vp_date = (uint32_t) data->timestamp;
555                                 *tail = vp;
556                                 tail = &(vp->next);
557                         }
558                         continue;
559                 }
560
561                 /*
562                  *      Read one VP.
563                  *
564                  *      FIXME: do we want to check for non-protocol
565                  *      attributes like radsqlrelay does?
566                  */
567                 vp = NULL;
568                 if ((userparse(buffer, &vp) > 0) &&
569                     (vp != NULL)) {
570                         *tail = vp;
571                         tail = &(vp->next);
572                 }
573         }
574
575         /*
576          *      Some kind of error.
577          *
578          *      FIXME: Leave the file in-place, and warn the
579          *      administrator?
580          */
581         if (ferror(data->fp)) goto cleanup;
582
583         data->tries = 0;
584         data->packets++;
585
586         /*
587          *      Process the packet.
588          */
589  alloc_packet:
590         data->tries++;
591         
592         /*
593          *      The writer doesn't check that the record was
594          *      completely written.  If the disk is full, this can
595          *      result in a truncated record.  When that happens,
596          *      treat it as EOF.
597          */
598         if (data->state != STATE_QUEUED) {
599                 radlog(L_ERR, "Truncated record: treating it as EOF for detail file %s", data->filename_work);
600                 goto cleanup;     
601         }
602
603         /*
604          *      We're done reading the file, but we didn't read
605          *      anything.  Clean up, and don't return anything.
606          */
607         if (!data->vps) {
608                 data->state = STATE_HEADER;
609                 if (!data->fp || feof(data->fp)) goto cleanup; 
610                 return 0;
611         }
612
613         /*
614          *      Allocate the packet.  If we fail, it's a serious
615          *      problem.
616          */
617         packet = rad_alloc(1);
618         if (!packet) {
619                 radlog(L_ERR, "FATAL: Failed allocating memory for detail");
620                 exit(1);
621         }
622
623         memset(packet, 0, sizeof(*packet));
624         packet->sockfd = -1;
625         packet->src_ipaddr.af = AF_INET;
626         packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
627         packet->code = PW_ACCOUNTING_REQUEST;
628         gettimeofday(&packet->timestamp, NULL);
629
630         /*
631          *      Remember where it came from, so that we don't
632          *      proxy it to the place it came from...
633          */
634         if (data->client_ip.af != AF_UNSPEC) {
635                 packet->src_ipaddr = data->client_ip;
636         }
637
638         vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS, 0);
639         if (vp) {
640                 packet->src_ipaddr.af = AF_INET;
641                 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
642         } else {
643                 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS, 0);
644                 if (vp) {
645                         packet->src_ipaddr.af = AF_INET6;
646                         memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
647                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
648                 }
649         }
650
651         vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS, 0);
652         if (vp) {
653                 packet->dst_ipaddr.af = AF_INET;
654                 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
655         } else {
656                 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS, 0);
657                 if (vp) {
658                         packet->dst_ipaddr.af = AF_INET6;
659                         memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
660                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
661                 }
662         }
663
664         /*
665          *      Generate packet ID, ports, IP via a counter.
666          */
667         packet->id = data->counter & 0xff;
668         packet->src_port = 1024 + ((data->counter >> 8) & 0xff);
669         packet->dst_port = 1024 + ((data->counter >> 16) & 0xff);
670
671         packet->dst_ipaddr.af = AF_INET;
672         packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | ((data->counter >> 24) & 0xff));
673
674         /*
675          *      If everything's OK, this is a waste of memory.
676          *      Otherwise, it lets us re-send the original packet
677          *      contents, unmolested.
678          */
679         packet->vps = paircopy(data->vps);
680
681         /*
682          *      Prefer the Event-Timestamp in the packet, if it
683          *      exists.  That is when the event occurred, whereas the
684          *      "Timestamp" field is when we wrote the packet to the
685          *      detail file, which could have been much later.
686          */
687         vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP, 0);
688         if (vp) {
689                 data->timestamp = vp->vp_integer;
690         }
691
692         /*
693          *      Look for Acct-Delay-Time, and update
694          *      based on Acct-Delay-Time += (time(NULL) - timestamp)
695          */
696         vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME, 0);
697         if (!vp) {
698                 vp = paircreate(PW_ACCT_DELAY_TIME, 0, PW_TYPE_INTEGER);
699                 rad_assert(vp != NULL);
700                 pairadd(&packet->vps, vp);
701         }
702         if (data->timestamp != 0) {
703                 vp->vp_integer += time(NULL) - data->timestamp;
704         }
705
706         /*
707          *      Set the transmission count.
708          */
709         vp = pairfind(packet->vps, PW_PACKET_TRANSMIT_COUNTER, 0);
710         if (!vp) {
711                 vp = paircreate(PW_PACKET_TRANSMIT_COUNTER, 0, PW_TYPE_INTEGER);
712                 rad_assert(vp != NULL);
713                 pairadd(&packet->vps, vp);
714         }
715         vp->vp_integer = data->tries;
716
717         if (debug_flag) {
718                 fr_printf_log("detail_recv: Read packet from %s\n", data->filename_work);
719                 for (vp = packet->vps; vp; vp = vp->next) {
720                         debug_pair(vp);
721                 }
722         }
723
724         /*
725          *      Don't bother doing limit checks, etc.
726          */
727         gettimeofday(&now, NULL);
728         if (!request_insert(listener, packet, &data->detail_client,
729                             rad_accounting, &now)) {
730                 rad_free(&packet);
731                 data->state = STATE_NO_REPLY;   /* try again later */
732                 return 0;
733         }
734
735         data->state = STATE_RUNNING;
736         data->running = packet->timestamp.tv_sec;
737
738         return 1;
739 }
740
741
742 /*
743  *      Free detail-specific stuff.
744  */
745 void detail_free(rad_listen_t *this)
746 {
747         listen_detail_t *data = this->data;
748
749         free(data->filename);
750         data->filename = NULL;
751         pairfree(&data->vps);
752
753         if (data->fp != NULL) {
754                 fclose(data->fp);
755                 data->fp = NULL;
756         }
757 }
758
759
760 int detail_print(const rad_listen_t *this, char *buffer, size_t bufsize)
761 {
762         if (!this->server) {
763                 return snprintf(buffer, bufsize, "%s",
764                                 ((listen_detail_t *)(this->data))->filename);
765         }
766
767         return snprintf(buffer, bufsize, "detail file %s as server %s",
768                         ((listen_detail_t *)(this->data))->filename,
769                         this->server);
770 }
771
772 /*
773  *      Overloaded to return delay times.
774  */
775 int detail_encode(rad_listen_t *this, UNUSED REQUEST *request)
776 {
777         listen_detail_t *data = this->data;
778
779         /*
780          *      We haven't sent a packet... delay things a bit.
781          */
782         if (!data->signal) {
783                 int delay = (data->poll_interval - 1) * USEC;
784
785                 /*
786                  *      Add +/- 0.25s of jitter
787                  */
788                 delay += (USEC * 3) / 4;
789                 delay += fr_rand() % (USEC / 2);
790
791                 DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
792                        data->filename,
793                        fr_int2str(state_names, data->state, "?"), data->signal,
794                        (delay / USEC), delay % USEC);
795
796                 return delay;
797         }
798
799         data->signal = 0;
800         
801         DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
802                data->filename, fr_int2str(state_names, data->state, "?"),
803                data->signal,
804                data->delay_time / USEC,
805                data->delay_time % USEC);
806
807         return data->delay_time;
808 }
809
810
811 /*
812  *      Overloaded to return "should we fix delay times"
813  */
814 int detail_decode(rad_listen_t *this, UNUSED REQUEST *request)
815 {
816         listen_detail_t *data = this->data;
817
818         return data->signal;
819 }
820
821
822 static const CONF_PARSER detail_config[] = {
823         { "filename",   PW_TYPE_STRING_PTR,
824           offsetof(listen_detail_t, filename), NULL,  NULL },
825         { "load_factor",   PW_TYPE_INTEGER,
826           offsetof(listen_detail_t, load_factor), NULL, Stringify(10)},
827         { "poll_interval",   PW_TYPE_INTEGER,
828           offsetof(listen_detail_t, poll_interval), NULL, Stringify(1)},
829         { "retry_interval",   PW_TYPE_INTEGER,
830           offsetof(listen_detail_t, retry_interval), NULL, Stringify(30)},
831         { "one_shot",   PW_TYPE_BOOLEAN,
832           offsetof(listen_detail_t, one_shot), NULL, NULL},
833         { "max_outstanding",   PW_TYPE_INTEGER,
834           offsetof(listen_detail_t, load_factor), NULL, NULL},
835
836         { NULL, -1, 0, NULL, NULL }             /* end the list */
837 };
838
839 extern int check_config;
840
841 /*
842  *      Parse a detail section.
843  */
844 int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
845 {
846         int             rcode;
847         listen_detail_t *data;
848         RADCLIENT       *client;
849         char buffer[2048];
850
851         if (check_config) return 0;
852
853         if (!this->data) {
854                 this->data = rad_malloc(sizeof(*data));
855                 memset(this->data, 0, sizeof(*data));
856         }
857
858         data = this->data;
859
860         rcode = cf_section_parse(cs, data, detail_config);
861         if (rcode < 0) {
862                 cf_log_err(cf_sectiontoitem(cs), "Failed parsing listen section");
863                 return -1;
864         }
865
866         if (!data->filename) {
867                 cf_log_err(cf_sectiontoitem(cs), "No detail file specified in listen section");
868                 return -1;
869         }
870
871         if ((data->load_factor < 1) || (data->load_factor > 100)) {
872                 cf_log_err(cf_sectiontoitem(cs), "Load factor must be between 1 and 100");
873                 return -1;
874         }
875
876         if ((data->poll_interval < 1) || (data->poll_interval > 20)) {
877                 cf_log_err(cf_sectiontoitem(cs), "poll_interval must be between 1 and 20");
878                 return -1;
879         }
880
881         if (data->max_outstanding == 0) data->max_outstanding = 1;
882         
883         /*
884          *      If the filename is a glob, use "detail.work" as the
885          *      work file name.
886          */
887         if ((strchr(data->filename, '*') != NULL) ||
888             (strchr(data->filename, '[') != NULL)) {
889                 char *p;
890
891 #ifndef HAVE_GLOB_H
892                 radlog(L_INFO, "WARNING: Detail file \"%s\" appears to use file globbing, but it is not supported on this system.", data->filename);
893 #endif
894                 strlcpy(buffer, data->filename, sizeof(buffer));
895                 p = strrchr(buffer, FR_DIR_SEP);
896                 if (p) {
897                         p[1] = '\0';
898                 } else {
899                         buffer[0] = '\0';
900                 }
901                 strlcat(buffer, "detail.work",
902                         sizeof(buffer) - strlen(buffer));
903                         
904         } else {
905                 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
906         }
907
908         free(data->filename_work);
909         data->filename_work = strdup(buffer); /* FIXME: leaked */
910
911         data->vps = NULL;
912         data->fp = NULL;
913         data->state = STATE_UNOPENED;
914         data->delay_time = data->poll_interval * USEC;
915         data->signal = 1;
916
917         /*
918          *      Initialize the fake client.
919          */
920         client = &data->detail_client;
921         memset(client, 0, sizeof(*client));
922         client->ipaddr.af = AF_INET;
923         client->ipaddr.ipaddr.ip4addr.s_addr = INADDR_NONE;
924         client->prefix = 0;
925         client->longname = client->shortname = data->filename;
926         client->secret = client->shortname;
927         client->nastype = strdup("none");
928
929         return 0;
930 }
931 #endif