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