Wrap _exit and exit. Prints error message, and when running under GDB, raises SIGTRA...
[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 RCSID("$Id$")
25
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/modules.h>
28 #include <freeradius-devel/detail.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/rad_assert.h>
31
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35
36 #ifdef HAVE_GLOB_H
37 #include <glob.h>
38 #endif
39
40 #include <fcntl.h>
41
42 #ifdef WITH_DETAIL
43
44 #define USEC (1000000)
45
46 static FR_NAME_NUMBER state_names[] = {
47         { "unopened", STATE_UNOPENED },
48         { "unlocked", STATE_UNLOCKED },
49         { "header", STATE_HEADER },
50         { "reading", STATE_READING },
51         { "queued", STATE_QUEUED },
52         { "running", STATE_RUNNING },
53         { "no-reply", STATE_NO_REPLY },
54         { "replied", STATE_REPLIED },
55
56         { NULL, 0 }
57 };
58
59 /*
60  *      If we're limiting outstanding packets, then mark the response
61  *      as being sent.
62  */
63 int detail_send(rad_listen_t *listener, REQUEST *request)
64 {
65         int rtt;
66         struct timeval now;
67         listen_detail_t *data = listener->data;
68
69         rad_assert(request->listener == listener);
70         rad_assert(listener->send == detail_send);
71
72         /*
73          *      This request timed out.  Remember that, and tell the
74          *      caller it's OK to read more "detail" file stuff.
75          */
76         if (request->reply->code == 0) {
77                 data->delay_time = data->retry_interval * USEC;
78                 data->signal = 1;
79                 data->state = STATE_NO_REPLY;
80
81                 RDEBUG("Detail - No response configured for request %d.  Will retry in %d seconds",
82                        request->number, data->retry_interval);
83
84                 radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
85                 return 0;
86         }
87
88         /*
89          *      We call gettimeofday a lot.  But it should be OK,
90          *      because there's nothing else to do.
91          */
92         gettimeofday(&now, NULL);
93
94         /*
95          *      If we haven't sent a packet in the last second, reset
96          *      the RTT.
97          */
98         now.tv_sec -= 1;
99         if (timercmp(&data->last_packet, &now, <)) {
100                 data->has_rtt = false;
101         }
102         now.tv_sec += 1;
103
104         /*
105          *      Only one detail packet may be outstanding at a time,
106          *      so it's safe to update some entries in the detail
107          *      structure.
108          *
109          *      We keep smoothed round trip time (SRTT), but not round
110          *      trip timeout (RTO).  We use SRTT to calculate a rough
111          *      load factor.
112          */
113         rtt = now.tv_sec - request->packet->timestamp.tv_sec;
114         rtt *= USEC;
115         rtt += now.tv_usec;
116         rtt -= request->packet->timestamp.tv_usec;
117
118         /*
119          *      If we're proxying, the RTT is our processing time,
120          *      plus the network delay there and back, plus the time
121          *      on the other end to process the packet.  Ideally, we
122          *      should remove the network delays from the RTT, but we
123          *      don't know what they are.
124          *
125          *      So, to be safe, we over-estimate the total cost of
126          *      processing the packet.
127          */
128         if (!data->has_rtt) {
129                 data->has_rtt = true;
130                 data->srtt = rtt;
131                 data->rttvar = rtt / 2;
132
133         } else {
134                 data->rttvar -= data->rttvar >> 2;
135                 data->rttvar += (data->srtt - rtt);
136                 data->srtt -= data->srtt >> 3;
137                 data->srtt += rtt >> 3;
138         }
139
140         /*
141          *      Calculate the time we wait before sending the next
142          *      packet.
143          *
144          *      rtt / (rtt + delay) = load_factor / 100
145          */
146         data->delay_time = (data->srtt * (100 - data->load_factor)) / (data->load_factor);
147
148         /*
149          *      Cap delay at 4 packets/s.  If the end system can't
150          *      handle this, then it's very broken.
151          */
152         if (data->delay_time > (USEC / 4)) data->delay_time= USEC / 4;
153
154         RDEBUG3("Received response for request %d.  Will read the next packet in %d seconds",
155                 request->number, data->delay_time / USEC);
156
157         data->last_packet = now;
158         data->signal = 1;
159         data->state = STATE_REPLIED;
160         data->counter++;
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                                 globfree(&files);
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                         ERROR("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         vp_cursor_t     cursor;
304         VALUE_PAIR      *vp;
305         RADIUS_PACKET   *packet;
306         char            buffer[2048];
307         listen_detail_t *data = listener->data;
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                                 ERROR("FATAL: Failed to re-open detail file %s: %s",
360                                        data->filename, strerror(errno));
361                                 fr_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                                 if (fstat(listener->fd, &buf) < 0) {
385                                         ERROR("Failed to stat "
386                                                "detail file %s: %s",
387                                                 data->filename,
388                                                 strerror(errno));
389
390                                         goto cleanup;
391                                 }
392                                 if (((off_t) ftell(data->fp)) == buf.st_size) {
393                                         goto cleanup;
394                                 }
395                         }
396
397                         /*
398                          *      End of file.  Delete it, and re-set
399                          *      everything.
400                          */
401                         if (feof(data->fp)) {
402                         cleanup:
403                                 DEBUG("Detail - unlinking %s",
404                                       data->filename_work);
405                                 unlink(data->filename_work);
406                                 if (data->fp) fclose(data->fp);
407                                 data->fp = NULL;
408                                 listener->fd = -1;
409                                 data->state = STATE_UNOPENED;
410                                 rad_assert(data->vps == NULL);
411
412                                 if (data->one_shot) {
413                                         INFO("Finished reading \"one shot\" detail file - Exiting");
414                                         radius_signal_self(RADIUS_SIGNAL_SELF_EXIT);
415                                 }
416
417                                 return 0;
418                         }
419
420                         /*
421                          *      Else go read something.
422                          */
423                         break;
424
425                         /*
426                          *      Read more value-pair's, unless we're
427                          *      at EOF.  In that case, queue whatever
428                          *      we have.
429                          */
430                 case STATE_READING:
431                         if (data->fp && !feof(data->fp)) break;
432                         data->state = STATE_QUEUED;
433
434                         /* FALL-THROUGH */
435
436                 case STATE_QUEUED:
437                         goto alloc_packet;
438
439                         /*
440                          *      Periodically check what's going on.
441                          *      If the request is taking too long,
442                          *      retry it.
443                          */
444                 case STATE_RUNNING:
445                         if (time(NULL) < (data->running + data->retry_interval)) {
446                                 return 0;
447                         }
448
449                         DEBUG("No response to detail request.  Retrying");
450                         data->state = STATE_NO_REPLY;
451                         /* FALL-THROUGH */
452
453                         /*
454                          *      If there's no reply, keep
455                          *      retransmitting the current packet
456                          *      forever.
457                          */
458                 case STATE_NO_REPLY:
459                         data->state = STATE_QUEUED;
460                         goto alloc_packet;
461
462                         /*
463                          *      We have a reply.  Clean up the old
464                          *      request, and go read another one.
465                          */
466                 case STATE_REPLIED:
467                         pairfree(&data->vps);
468                         data->state = STATE_HEADER;
469                         goto do_header;
470         }
471
472         paircursor(&cursor, &data->vps);
473
474         /*
475          *      Read a header, OR a value-pair.
476          */
477         while (fgets(buffer, sizeof(buffer), data->fp)) {
478                 data->offset = ftell(data->fp); /* for statistics */
479
480                 /*
481                  *      Badly formatted file: delete it.
482                  *
483                  *      FIXME: Maybe flag an error?
484                  */
485                 if (!strchr(buffer, '\n')) {
486                         pairfree(&data->vps);
487                         goto cleanup;
488                 }
489
490                 /*
491                  *      We're reading VP's, and got a blank line.
492                  *      Queue the packet.
493                  */
494                 if ((data->state == STATE_READING) &&
495                     (buffer[0] == '\n')) {
496                         data->state = STATE_QUEUED;
497                         break;
498                 }
499
500                 /*
501                  *      Look for date/time header, and read VP's if
502                  *      found.  If not, keep reading lines until we
503                  *      find one.
504                  */
505                 if (data->state == STATE_HEADER) {
506                         int y;
507
508                         if (sscanf(buffer, "%*s %*s %*d %*d:%*d:%*d %d", &y)) {
509                                 data->state = STATE_READING;
510                         }
511                         continue;
512                 }
513
514                 /*
515                  *      We have a full "attribute = value" line.
516                  *      If it doesn't look reasonable, skip it.
517                  *
518                  *      FIXME: print an error for badly formatted attributes?
519                  */
520                 if (sscanf(buffer, "%255s %8s %1023s", key, op, value) != 3) {
521                         WDEBUG2("Skipping badly formatted line %s",
522                                buffer);
523                         continue;
524                 }
525
526                 /*
527                  *      Should be =, :=, +=, ...
528                  */
529                 if (!strchr(op, '=')) continue;
530
531                 /*
532                  *      Skip non-protocol attributes.
533                  */
534                 if (!strcasecmp(key, "Request-Authenticator")) continue;
535
536                 /*
537                  *      Set the original client IP address, based on
538                  *      what's in the detail file.
539                  *
540                  *      Hmm... we don't set the server IP address.
541                  *      or port.  Oh well.
542                  */
543                 if (!strcasecmp(key, "Client-IP-Address")) {
544                         data->client_ip.af = AF_INET;
545                         if (ip_hton(value, AF_INET, &data->client_ip) < 0) {
546                                 ERROR("Failed parsing Client-IP-Address");
547
548                                 pairfree(&data->vps);
549                                 goto cleanup;
550                         }
551                         continue;
552                 }
553
554                 /*
555                  *      The original time at which we received the
556                  *      packet.  We need this to properly calculate
557                  *      Acct-Delay-Time.
558                  */
559                 if (!strcasecmp(key, "Timestamp")) {
560                         data->timestamp = atoi(value);
561
562                         vp = paircreate(data, PW_PACKET_ORIGINAL_TIMESTAMP, 0);
563                         if (vp) {
564                                 vp->vp_date = (uint32_t) data->timestamp;
565                                 vp->type = VT_DATA;
566                                 pairinsert(&cursor, vp);
567                         }
568                         continue;
569                 }
570
571                 /*
572                  *      Read one VP.
573                  *
574                  *      FIXME: do we want to check for non-protocol
575                  *      attributes like radsqlrelay does?
576                  */
577                 vp = NULL;
578                 if ((userparse(data, buffer, &vp) > 0) &&
579                     (vp != NULL)) {
580                         pairinsert(&cursor, vp);
581                 }
582         }
583
584         /*
585          *      Some kind of error.
586          *
587          *      FIXME: Leave the file in-place, and warn the
588          *      administrator?
589          */
590         if (ferror(data->fp)) goto cleanup;
591
592         data->tries = 0;
593         data->packets++;
594
595         /*
596          *      Process the packet.
597          */
598  alloc_packet:
599         data->tries++;
600
601         /*
602          *      The writer doesn't check that the record was
603          *      completely written.  If the disk is full, this can
604          *      result in a truncated record.  When that happens,
605          *      treat it as EOF.
606          */
607         if (data->state != STATE_QUEUED) {
608                 ERROR("Truncated record: treating it as EOF for detail file %s", data->filename_work);
609                 goto cleanup;
610         }
611
612         /*
613          *      We're done reading the file, but we didn't read
614          *      anything.  Clean up, and don't return anything.
615          */
616         if (!data->vps) {
617                 data->state = STATE_HEADER;
618                 if (!data->fp || feof(data->fp)) goto cleanup;
619                 return 0;
620         }
621
622         /*
623          *      Allocate the packet.  If we fail, it's a serious
624          *      problem.
625          */
626         packet = rad_alloc(NULL, 1);
627         if (!packet) {
628                 ERROR("FATAL: Failed allocating memory for detail");
629                 fr_exit(1);
630         }
631
632         memset(packet, 0, sizeof(*packet));
633         packet->sockfd = -1;
634         packet->src_ipaddr.af = AF_INET;
635         packet->src_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
636         packet->code = PW_ACCOUNTING_REQUEST;
637         gettimeofday(&packet->timestamp, NULL);
638
639         /*
640          *      Remember where it came from, so that we don't
641          *      proxy it to the place it came from...
642          */
643         if (data->client_ip.af != AF_UNSPEC) {
644                 packet->src_ipaddr = data->client_ip;
645         }
646
647         vp = pairfind(packet->vps, PW_PACKET_SRC_IP_ADDRESS, 0, TAG_ANY);
648         if (vp) {
649                 packet->src_ipaddr.af = AF_INET;
650                 packet->src_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
651         } else {
652                 vp = pairfind(packet->vps, PW_PACKET_SRC_IPV6_ADDRESS, 0, TAG_ANY);
653                 if (vp) {
654                         packet->src_ipaddr.af = AF_INET6;
655                         memcpy(&packet->src_ipaddr.ipaddr.ip6addr,
656                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
657                 }
658         }
659
660         vp = pairfind(packet->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
661         if (vp) {
662                 packet->dst_ipaddr.af = AF_INET;
663                 packet->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
664         } else {
665                 vp = pairfind(packet->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY);
666                 if (vp) {
667                         packet->dst_ipaddr.af = AF_INET6;
668                         memcpy(&packet->dst_ipaddr.ipaddr.ip6addr,
669                                &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
670                 }
671         }
672
673         /*
674          *      Generate packet ID, ports, IP via a counter.
675          */
676         packet->id = data->counter & 0xff;
677         packet->src_port = 1024 + ((data->counter >> 8) & 0xff);
678         packet->dst_port = 1024 + ((data->counter >> 16) & 0xff);
679
680         packet->dst_ipaddr.af = AF_INET;
681         packet->dst_ipaddr.ipaddr.ip4addr.s_addr = htonl((INADDR_LOOPBACK & ~0xffffff) | ((data->counter >> 24) & 0xff));
682
683         /*
684          *      If everything's OK, this is a waste of memory.
685          *      Otherwise, it lets us re-send the original packet
686          *      contents, unmolested.
687          */
688         packet->vps = paircopy(packet, data->vps);
689
690         /*
691          *      Prefer the Event-Timestamp in the packet, if it
692          *      exists.  That is when the event occurred, whereas the
693          *      "Timestamp" field is when we wrote the packet to the
694          *      detail file, which could have been much later.
695          */
696         vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP, 0, TAG_ANY);
697         if (vp) {
698                 data->timestamp = vp->vp_integer;
699         }
700
701         /*
702          *      Look for Acct-Delay-Time, and update
703          *      based on Acct-Delay-Time += (time(NULL) - timestamp)
704          */
705         vp = pairfind(packet->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
706         if (!vp) {
707                 vp = paircreate(packet, PW_ACCT_DELAY_TIME, 0);
708                 rad_assert(vp != NULL);
709                 pairadd(&packet->vps, vp);
710         }
711         if (data->timestamp != 0) {
712                 vp->vp_integer += time(NULL) - data->timestamp;
713         }
714
715         /*
716          *      Set the transmission count.
717          */
718         vp = pairfind(packet->vps, PW_PACKET_TRANSMIT_COUNTER, 0, TAG_ANY);
719         if (!vp) {
720                 vp = paircreate(packet, PW_PACKET_TRANSMIT_COUNTER, 0);
721                 rad_assert(vp != NULL);
722                 pairadd(&packet->vps, vp);
723         }
724         vp->vp_integer = data->tries;
725
726         if (debug_flag) {
727                 fr_printf_log("detail_recv: Read packet from %s\n", data->filename_work);
728                 for (vp = paircursor(&cursor, &packet->vps);
729                      vp;
730                      vp = pairnext(&cursor)) {
731                         debug_pair(vp);
732                 }
733         }
734
735         /*
736          *      Don't bother doing limit checks, etc.
737          */
738         if (!request_receive(listener, packet, &data->detail_client,
739                              rad_accounting)) {
740                 rad_free(&packet);
741                 data->state = STATE_NO_REPLY;   /* try again later */
742                 return 0;
743         }
744
745         data->state = STATE_RUNNING;
746         data->running = packet->timestamp.tv_sec;
747
748         return 1;
749 }
750
751
752 /*
753  *      Free detail-specific stuff.
754  */
755 void detail_free(rad_listen_t *this)
756 {
757         listen_detail_t *data = this->data;
758
759         talloc_free(data->filename);
760         data->filename = NULL;
761         pairfree(&data->vps);
762
763         if (data->fp != NULL) {
764                 fclose(data->fp);
765                 data->fp = NULL;
766         }
767 }
768
769
770 int detail_print(rad_listen_t const *this, char *buffer, size_t bufsize)
771 {
772         if (!this->server) {
773                 return snprintf(buffer, bufsize, "%s",
774                                 ((listen_detail_t *)(this->data))->filename);
775         }
776
777         return snprintf(buffer, bufsize, "detail file %s as server %s",
778                         ((listen_detail_t *)(this->data))->filename,
779                         this->server);
780 }
781
782 /*
783  *      Overloaded to return delay times.
784  */
785 int detail_encode(rad_listen_t *this, UNUSED REQUEST *request)
786 {
787         listen_detail_t *data = this->data;
788
789         /*
790          *      We haven't sent a packet... delay things a bit.
791          */
792         if (!data->signal) {
793                 int delay = (data->poll_interval - 1) * USEC;
794
795                 /*
796                  *      Add +/- 0.25s of jitter
797                  */
798                 delay += (USEC * 3) / 4;
799                 delay += fr_rand() % (USEC / 2);
800
801                 DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
802                        data->filename,
803                        fr_int2str(state_names, data->state, "?"), data->signal,
804                        (delay / USEC), delay % USEC);
805
806                 return delay;
807         }
808
809         data->signal = 0;
810
811         DEBUG2("Detail listener %s state %s signalled %d waiting %d.%06d sec",
812                data->filename, fr_int2str(state_names, data->state, "?"),
813                data->signal,
814                data->delay_time / USEC,
815                data->delay_time % USEC);
816
817         return data->delay_time;
818 }
819
820
821 /*
822  *      Overloaded to return "should we fix delay times"
823  */
824 int detail_decode(rad_listen_t *this, UNUSED REQUEST *request)
825 {
826         listen_detail_t *data = this->data;
827
828         return data->signal;
829 }
830
831
832 static const CONF_PARSER detail_config[] = {
833         { "detail",   PW_TYPE_FILE_OUTPUT | PW_TYPE_DEPRECATED,
834           offsetof(listen_detail_t, filename), NULL,  NULL },
835         { "filename",   PW_TYPE_FILE_OUTPUT | PW_TYPE_REQUIRED,
836           offsetof(listen_detail_t, filename), NULL,  NULL },
837         { "load_factor",   PW_TYPE_INTEGER,
838           offsetof(listen_detail_t, load_factor), NULL, STRINGIFY(10)},
839         { "poll_interval",   PW_TYPE_INTEGER,
840           offsetof(listen_detail_t, poll_interval), NULL, STRINGIFY(1)},
841         { "retry_interval",   PW_TYPE_INTEGER,
842           offsetof(listen_detail_t, retry_interval), NULL, STRINGIFY(30)},
843         { "one_shot",   PW_TYPE_BOOLEAN,
844           offsetof(listen_detail_t, one_shot), NULL, NULL},
845         { "max_outstanding",   PW_TYPE_INTEGER,
846           offsetof(listen_detail_t, load_factor), NULL, NULL},
847
848         { NULL, -1, 0, NULL, NULL }             /* end the list */
849 };
850
851 extern int check_config;
852
853 /*
854  *      Parse a detail section.
855  */
856 int detail_parse(CONF_SECTION *cs, rad_listen_t *this)
857 {
858         int             rcode;
859         listen_detail_t *data;
860         RADCLIENT       *client;
861         char buffer[2048];
862
863         if (check_config) return 0;
864
865         data = this->data;
866
867         rcode = cf_section_parse(cs, data, detail_config);
868         if (rcode < 0) {
869                 cf_log_err_cs(cs, "Failed parsing listen section");
870                 return -1;
871         }
872
873         /*
874          *      We don't do duplicate detection for "detail" sockets.
875          */
876         this->nodup = true;
877         this->synchronous = false;
878
879         if (!data->filename) {
880                 cf_log_err_cs(cs, "No detail file specified in listen section");
881                 return -1;
882         }
883
884         if ((data->load_factor < 1) || (data->load_factor > 100)) {
885                 cf_log_err_cs(cs, "Load factor must be between 1 and 100");
886                 return -1;
887         }
888
889         if ((data->poll_interval < 1) || (data->poll_interval > 20)) {
890                 cf_log_err_cs(cs, "poll_interval must be between 1 and 20");
891                 return -1;
892         }
893
894         if (data->max_outstanding == 0) data->max_outstanding = 1;
895
896         /*
897          *      If the filename is a glob, use "detail.work" as the
898          *      work file name.
899          */
900         if ((strchr(data->filename, '*') != NULL) ||
901             (strchr(data->filename, '[') != NULL)) {
902                 char *p;
903
904 #ifndef HAVE_GLOB_H
905                 WARN("Detail file \"%s\" appears to use file globbing, but it is not supported on this system.",
906                      data->filename);
907 #endif
908                 strlcpy(buffer, data->filename, sizeof(buffer));
909                 p = strrchr(buffer, FR_DIR_SEP);
910                 if (p) {
911                         p[1] = '\0';
912                 } else {
913                         buffer[0] = '\0';
914                 }
915                 strlcat(buffer, "detail.work",
916                         sizeof(buffer) - strlen(buffer));
917
918         } else {
919                 snprintf(buffer, sizeof(buffer), "%s.work", data->filename);
920         }
921
922         free(data->filename_work);
923         data->filename_work = strdup(buffer); /* FIXME: leaked */
924
925         data->vps = NULL;
926         data->fp = NULL;
927         data->state = STATE_UNOPENED;
928         data->delay_time = data->poll_interval * USEC;
929         data->signal = 1;
930
931         /*
932          *      Initialize the fake client.
933          */
934         client = &data->detail_client;
935         memset(client, 0, sizeof(*client));
936         client->ipaddr.af = AF_INET;
937         client->ipaddr.ipaddr.ip4addr.s_addr = INADDR_NONE;
938         client->prefix = 0;
939         client->longname = client->shortname = data->filename;
940         client->secret = client->shortname;
941         client->nas_type = strdup("none");
942
943         return 0;
944 }
945 #endif