b78e1a496cda3558c6ac29c1d8548a02917aca05
[freeradius.git] / src / main / process.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /*
18  * $Id$
19  *
20  * @file process.c
21  * @brief Defines the state machines that control how requests are processed.
22  *
23  * @copyright 2012  The FreeRADIUS server project
24  * @copyright 2012  Alan DeKok <aland@deployingradius.com>
25  */
26
27 #include <freeradius-devel/ident.h>
28 RCSID("$Id$")
29
30 #include <freeradius-devel/radiusd.h>
31 #include <freeradius-devel/process.h>
32 #include <freeradius-devel/event.h>
33 #include <freeradius-devel/packet.h>
34 #include <freeradius-devel/modules.h>
35
36 #include <freeradius-devel/rad_assert.h>
37
38 #ifdef WITH_DETAIL
39 #include <freeradius-devel/detail.h>
40 #endif
41
42 #include <signal.h>
43 #include <fcntl.h>
44
45 #ifdef HAVE_SYS_WAIT_H
46 #       include <sys/wait.h>
47 #endif
48
49 #define NDEBUG
50
51 extern pid_t radius_pid;
52 extern int check_config;
53 extern char *debug_condition;
54
55 static int spawn_flag = 0;
56 static int just_started = TRUE;
57 time_t                          fr_start_time;
58 static fr_packet_list_t *pl = NULL;
59 static fr_event_list_t *el = NULL;
60
61 static const char *action_codes[] = {
62         "INVALID",
63         "run",
64         "done",
65         "dup",
66         "conflicting",
67         "timer",
68 #ifdef WITH_PROXY
69         "proxy-reply"
70 #endif
71 };
72
73 #ifdef DEBUG_STATE_MACHINE
74 #define TRACE_STATE_MACHINE if (debug_flag) printf("(%u) ********\tSTATE %s action %s live M%u C%u\t********\n", request->number, __FUNCTION__, action_codes[action], request->master_state, request->child_state)
75 #else
76 #define TRACE_STATE_MACHINE {}
77 #endif
78
79 /*
80  *      Declare a state in the state machine.
81  *
82  */
83 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
84
85 #define STATE_MACHINE_TIMER(_x) request->timer_action = _x; \
86                 fr_event_insert(el, request_timer, request, \
87                                 &when, &request->ev);
88
89
90
91 /**
92  * @section request_timeline
93  *
94  *      Time sequence of a request
95  * @code
96  *
97  *      RQ-----------------P=============================Y-J-C
98  *       ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
99  * @endcode
100  *
101  * -    R: received.  Duplicate detection is done, and request is
102  *         cached.
103  *
104  * -    Q: Request is placed onto a queue for child threads to pick up.
105  *         If there are no child threads, the request goes immediately
106  *         to P.
107  *
108  * -    P: Processing the request through the modules.
109  *
110  * -    Y: Reply is ready.  Rejects MAY be delayed here.  All other
111  *         replies are sent immediately.
112  *
113  * -    J: Reject is sent "reject_delay" after the reply is ready.
114  *
115  * -    C: For Access-Requests, After "cleanup_delay", the request is
116  *         deleted.  Accounting-Request packets go directly from Y to C.
117  *
118  * -    M: Max request time.  If the request hits this timer, it is
119  *         forcibly stopped.
120  *
121  *      Other considerations include duplicate and conflicting
122  *      packets.  When a dupicate packet is received, it is ignored
123  *      until we've reached Y, as no response is ready.  If the reply
124  *      is a reject, duplicates are ignored until J, when we're ready
125  *      to send the reply.  In between the reply being sent (Y or J),
126  *      and C, the server responds to duplicates by sending the cached
127  *      reply.
128  *
129  *      Conflicting packets are sent in 2 situations.
130  *
131  *      The first is in between R and Y.  In that case, we consider
132  *      it as a hint that we're taking too long, and the NAS has given
133  *      up on the request.  We then behave just as if the M timer was
134  *      reached, and we discard the current request.  This allows us
135  *      to process the new one.
136  *
137  *      The second case is when we're at Y, but we haven't yet
138  *      finished processing the request.  This is a race condition in
139  *      the threading code (avoiding locks is faster).  It means that
140  *      a thread has actually encoded and sent the reply, and that the
141  *      NAS has responded with a new packet.  The server can then
142  *      safely mark the current request as "OK to delete", and behaves
143  *      just as if the M timer was reached.  This usually happens only
144  *      in high-load situations.
145  *
146  *      Duplicate packets are sent when the NAS thinks we're taking
147  *      too long, and wants a reply.  From R-Y, duplicates are
148  *      ignored.  From Y-J (for Access-Rejects), duplicates are also
149  *      ignored.  From Y-C, duplicates get a duplicate reply.  *And*,
150  *      they cause the "cleanup_delay" time to be extended.  This
151  *      extension means that we're more likely to send a duplicate
152  *      reply (if we have one), or to suppress processing the packet
153  *      twice if we didn't reply to it.
154  *
155  *      All functions in this file should be thread-safe, and should
156  *      assume thet the REQUEST structure is being accessed
157  *      simultaneously by the main thread, and by the child worker
158  *      threads.  This means that timers, etc. cannot be updated in
159  *      the child thread.
160  *
161  *      Instead, the master thread periodically calls request->process
162  *      with action TIMER.  It's up to the individual functions to
163  *      determine how to handle that.  They need to check if they're
164  *      being called from a child thread or the master, and then do
165  *      different things based on that.
166  */
167
168
169 #ifdef WITH_PROXY
170 static fr_packet_list_t *proxy_list = NULL;
171 #endif
172
173 #ifdef HAVE_PTHREAD_H
174 #ifdef WITH_PROXY
175 static pthread_mutex_t  proxy_mutex;
176 static rad_listen_t *proxy_listener_list = NULL;
177 static int proxy_no_new_sockets = FALSE;
178 #endif
179
180 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
181 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
182
183 static pthread_t NO_SUCH_CHILD_PID;
184 #else
185 /*
186  *      This is easier than ifdef's throughout the code.
187  */
188 #define PTHREAD_MUTEX_LOCK(_x)
189 #define PTHREAD_MUTEX_UNLOCK(_x)
190 #endif
191
192 /*
193  *      We need mutexes around the event FD list *only* in certain
194  *      cases.
195  */
196 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
197 static pthread_mutex_t  fd_mutex;
198 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
199 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
200 #else
201 /*
202  *      This is easier than ifdef's throughout the code.
203  */
204 #define FD_MUTEX_LOCK(_x)
205 #define FD_MUTEX_UNLOCK(_x)
206 #endif
207
208 static int request_num_counter = 0;
209 #ifdef WITH_PROXY
210 static int request_will_proxy(REQUEST *request);
211 static int request_proxy(REQUEST *request, int retransmit);
212 STATE_MACHINE_DECL(proxy_wait_for_reply);
213 STATE_MACHINE_DECL(proxy_running);
214 static int process_proxy_reply(REQUEST *request);
215 static void remove_from_proxy_hash(REQUEST *request);
216 static void remove_from_proxy_hash_nl(REQUEST *request);
217 static int insert_into_proxy_hash(REQUEST *request);
218 #endif
219
220 STATE_MACHINE_DECL(request_common);
221
222 #if  defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
223 static int we_are_master(void)
224 {
225         if (spawn_flag &&
226             (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
227                 return 0;
228         }
229
230         return 1;
231 }
232 #define ASSERT_MASTER   if (!we_are_master()) rad_panic("We are not master")
233
234 #else
235 #define we_are_master(_x) (1)
236 #define ASSERT_MASTER
237 #endif
238
239 STATE_MACHINE_DECL(request_reject_delay);
240 STATE_MACHINE_DECL(request_cleanup_delay);
241 STATE_MACHINE_DECL(request_running);
242 #ifdef WITH_COA
243 static void request_coa_timer(REQUEST *request);
244 static void request_coa_originate(REQUEST *request);
245 STATE_MACHINE_DECL(request_coa_process);
246 static void request_coa_separate(REQUEST *coa);
247 #endif
248
249 #undef USEC
250 #define USEC (1000000)
251
252 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
253
254 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
255                                     const char *msg)
256 {
257         radlog(L_ERR, "[%s:%d] %s", file, line, msg);
258         _exit(1);
259 }
260
261 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
262
263 static void tv_add(struct timeval *tv, int usec_delay)
264 {
265         if (usec_delay >= USEC) {
266                 tv->tv_sec += usec_delay / USEC;
267                 usec_delay %= USEC;
268         }
269         tv->tv_usec += usec_delay;
270
271         if (tv->tv_usec >= USEC) {
272                 tv->tv_sec += tv->tv_usec / USEC;
273                 tv->tv_usec %= USEC;
274         }
275 }
276
277 /*
278  *      In daemon mode, AND this request has debug flags set.
279  */
280 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
281
282 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
283 {
284         VALUE_PAIR *vp;
285         char buffer[1024];
286         const char *received, *from;
287         const fr_ipaddr_t *ip;
288         int port;
289
290         if (!packet) return;
291
292         rad_assert(request->radlog != NULL);
293
294         if (direction == 0) {
295                 received = "Received";
296                 from = "from";  /* what else? */
297                 ip = &packet->src_ipaddr;
298                 port = packet->src_port;
299
300         } else {
301                 received = "Sending";
302                 from = "to";    /* hah! */
303                 ip = &packet->dst_ipaddr;
304                 port = packet->dst_port;
305         }
306         
307         /*
308          *      Client-specific debugging re-prints the input
309          *      packet into the client log.
310          *
311          *      This really belongs in a utility library
312          */
313         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
314                 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
315                        received, fr_packet_codes[packet->code], from,
316                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
317                        port, packet->id, packet->data_len);
318         } else {
319                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
320                        received, from,
321                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
322                        port,
323                        packet->code, packet->id, packet->data_len);
324         }
325
326         for (vp = packet->vps; vp != NULL; vp = vp->next) {
327                 vp_prints(buffer, sizeof(buffer), vp);
328                 request->radlog(L_DBG, 0, request, "\t%s", buffer);
329         }
330 }
331
332
333 /***********************************************************************
334  *
335  *      Start of RADIUS server state machine.
336  *
337  ***********************************************************************/
338
339 /*
340  *      Callback for ALL timer events related to the request.
341  */
342 static void request_timer(void *ctx)
343 {
344         REQUEST *request = ctx;
345         int action = request->timer_action;
346
347         TRACE_STATE_MACHINE;
348
349         request->process(request, action);
350 }
351
352 #define USEC (1000000)
353
354 /*
355  *      Only ever called from the master thread.
356  */
357 STATE_MACHINE_DECL(request_done)
358 {
359         struct timeval now, when;
360
361         TRACE_STATE_MACHINE;
362
363 #ifdef WITH_COA
364         /*
365          *      CoA requests can be cleaned up in the child thread,
366          *      but ONLY if they aren't tied into anything.
367          */
368         if (request->parent && (request->parent->coa == request)) {
369                 rad_assert(!request->in_request_hash);
370                 rad_assert(!request->in_proxy_hash);
371                 rad_assert(action == FR_ACTION_DONE);
372                 rad_assert(request->ev == NULL);
373         } else
374 #endif
375           {
376                   ASSERT_MASTER;
377           }
378
379         /*
380          *      Mark ourselves as handling the request.
381          */
382         request->process = request_done;
383         request->master_state = REQUEST_STOP_PROCESSING;
384
385 #ifdef WITH_COA
386         /*
387          *      Move the CoA request to its own handler.
388          */
389         if (request->coa) request_coa_separate(request->coa);
390
391         /*
392          *      If we're the CoA request, make the parent forget about
393          *      us.
394          */
395         if (request->parent && (request->parent->coa == request)) {
396                 request->parent->coa = NULL;
397         }
398
399 #endif
400
401         /*
402          *      It doesn't hurt to send duplicate replies.  All other
403          *      signals are ignored, as the request will be cleaned up
404          *      soon anyways.
405          */
406         switch (action) {
407         case FR_ACTION_DUP:
408                 if (request->reply->code != 0) {
409                         request->listener->send(request->listener, request);
410                         return;
411                 }
412                 break;
413
414                 /*
415                  *      This is only called from the master thread
416                  *      when there is a child thread processing the
417                  *      request.
418                  */
419         case FR_ACTION_CONFLICTING:
420                 if (request->child_state == REQUEST_DONE) break;
421
422                 /*
423                  *      If there's a reply packet, then we presume
424                  *      that the child has sent the reply, and we get
425                  *      pinged here before the child has a chance to
426                  *      say "I'm done!"
427                  */
428                 if (request->reply->data) break;
429
430                 radlog_request(L_ERR, 0, request,
431                                "Received conflicting packet from "
432                                "client %s port %d - ID: %d due to "
433                                "unfinished request.  Giving up on old request.",
434                                request->client->shortname,
435                                request->packet->src_port, request->packet->id);
436                 break;
437
438                 /*
439                  *      Called only when there's an error remembering
440                  *      the packet, or when the socket gets closed from
441                  *      under us.
442                  */
443         case FR_ACTION_DONE:
444 #ifdef HAVE_PTHREAD_H
445                 /*
446                  *      If we have child threads and we're NOT the
447                  *      thread handling the request, don't do anything.
448                  */
449                 if (spawn_flag &&
450                     !pthread_equal(pthread_self(), request->child_pid)) {
451                         break;
452                 }
453 #endif
454 #ifdef DEBUG_STATE_MACHINE
455                 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
456 #endif
457                 request->child_state = REQUEST_DONE;
458                 break;
459
460                 /*
461                  *      Called when the child is taking too long to
462                  *      finish.  We've already marked it "please
463                  *      stop", so we don't complain any more.
464                  */
465         case FR_ACTION_TIMER:
466                 break;
467                 
468 #ifdef WITH_PROXY
469                 /*
470                  *      Child is still alive, and we're receiving more
471                  *      packets from the home server.
472                  */
473         case FR_ACTION_PROXY_REPLY:
474                 request_common(request, action);
475                 break;
476 #endif
477                 
478         default:
479                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
480                 break;
481         }
482
483         /*
484          *      Remove it from the request hash.
485          */
486         if (request->in_request_hash) {
487                 fr_packet_list_yank(pl, request->packet);
488                 request->in_request_hash = FALSE;
489                 
490                 request_stats_final(request);
491                 
492 #ifdef WITH_TCP
493                 request->listener->count--;
494 #endif
495         }
496         
497 #ifdef WITH_PROXY
498         /*
499          *      Wait for the proxy ID to expire.  This allows us to
500          *      avoid re-use of proxy IDs for a while.
501          */
502         if (request->in_proxy_hash) {
503                 rad_assert(request->proxy != NULL);
504
505                 fr_event_now(el, &now);
506                 when = request->proxy->timestamp;
507
508 #ifdef WITH_COA
509                 if (((request->proxy->code == PW_COA_REQUEST) ||
510                      (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
511                     (request->packet->code != request->proxy->code)) {
512                         when.tv_sec += request->home_server->coa_mrd;
513                 } else
514 #endif
515                 when.tv_sec += request->home_server->response_window;
516
517                 /*
518                  *      We haven't received all responses, AND there's still
519                  *      time to wait.  Do so.
520                  */
521                 if ((request->num_proxied_requests > request->num_proxied_responses) &&
522 #ifdef WITH_TCP
523                     (request->home_server->proto != IPPROTO_TCP) &&
524 #endif
525                     timercmp(&now, &when, <)) {
526                         RDEBUG("Waiting for more responses from the home server");
527                         goto wait_some_more;
528                 }
529
530                 /*
531                  *      Time to remove it.
532                  */
533                 remove_from_proxy_hash(request);
534         }
535 #endif
536
537         if (request->child_state != REQUEST_DONE) {
538
539 #ifdef HAVE_PTHREAD_H
540                 if (!spawn_flag)
541 #endif
542                 {
543                         rad_assert("Internal sanity check failed");
544                         exit(2);
545                 }
546                 
547                 gettimeofday(&now, NULL);
548 #ifdef WITH_PROXY
549         wait_some_more:
550 #endif
551
552 #ifdef HAVE_PTHREAD_H
553                 if (spawn_flag &&
554                     (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
555                         RDEBUG("Waiting for child thread to stop");
556                 }
557 #endif
558
559                 when = now;
560                 tv_add(&when, request->delay);
561                 request->delay += request->delay >> 1;
562                 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
563
564                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
565                 return;
566         }
567
568 #ifdef HAVE_PTHREAD_H
569         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
570 #endif
571
572         if (request->packet) {
573                 RDEBUG2("Cleaning up request packet ID %d with timestamp +%d",
574                         request->packet->id,
575                         (unsigned int) (request->timestamp - fr_start_time));
576         } /* else don't print anything */
577
578         if (request->ev) fr_event_delete(el, &request->ev);
579
580         request_free(&request);
581 }
582
583
584 static void request_cleanup_delay_init(REQUEST *request, const struct timeval *pnow)
585 {
586         struct timeval now, when;
587
588         if (request->packet->code == PW_ACCOUNTING_REQUEST) goto done;
589         if (!request->root->cleanup_delay) goto done;
590
591         if (pnow) {
592                 now = *pnow;
593         } else {
594                 gettimeofday(&now, NULL);
595         }
596
597         if (request->reply->timestamp.tv_sec == 0) {
598                 when = now;
599         } else {
600                 when = request->reply->timestamp;
601         }
602         request->delay = request->root->cleanup_delay;
603         when.tv_sec += request->delay;
604
605         /*
606          *      Set timer for when we need to clean it up.
607          */
608         if (timercmp(&when, &now, >)) {
609 #ifdef DEBUG_STATE_MACHINE
610                 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
611 #endif
612                 request->process = request_cleanup_delay;
613                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
614                 return;
615         }
616
617         /*
618          *      Otherwise just clean it up.
619          */
620 done:
621         request_done(request, FR_ACTION_DONE);
622 }
623
624
625 /*
626  *      Function to do all time-related events.
627  */
628 static void request_process_timer(REQUEST *request)
629 {
630         struct timeval now, when;
631         rad_assert(request->magic == REQUEST_MAGIC);
632 #ifdef DEBUG_STATE_MACHINE
633         int action = FR_ACTION_TIMER;
634 #endif
635
636         TRACE_STATE_MACHINE;
637         ASSERT_MASTER;
638
639 #ifdef WITH_COA
640         /*
641          *      If we originated a CoA request, divorce it from the
642          *      parent.  Then, set up the timers so that we can clean
643          *      it up as appropriate.
644          */
645         if (request->coa) request_coa_separate(request->coa);
646
647         /*
648          *      Check request stuff ONLY if we're running the request.
649          */
650         if (!request->proxy || (request->packet->code == request->proxy->code))
651 #endif
652         {
653                 rad_assert(request->listener != NULL);
654                 
655                 /*
656                  *      The socket was closed.  Tell the request that
657                  *      there is no point in continuing.
658                  */
659                 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
660                         DEBUGW("Socket was closed while processing request %u: Stopping it.", request->number);
661                         goto done;
662                 }
663         }
664
665         gettimeofday(&now, NULL);
666
667         /*
668          *      A child thread is still working on the request,
669          *      OR it was proxied, and there was no response,
670          *      OR it was sitting in the queue for too long.
671          */
672         if ((request->child_state != REQUEST_DONE) &&
673             (request->master_state != REQUEST_STOP_PROCESSING)) {
674                 when = request->packet->timestamp;
675                 when.tv_sec += request->root->max_request_time;
676                 
677                 /*
678                  *      Taking too long: tell it to die.
679                  */
680                 if (timercmp(&now, &when, >=)) {
681 #ifdef HAVE_PTHREAD_H
682                         /*
683                          *      If there's a child thread processing it,
684                          *      complain.
685                          */
686                         if (spawn_flag &&
687                             (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
688                                 radlog(L_ERR, "WARNING: Unresponsive child for request %u, in component %s module %s",
689                                        request->number,
690                                        request->component ? request->component : "<server core>",
691                                request->module ? request->module : "<server core>");
692                                 exec_trigger(request, NULL, "server.thread.unresponsive", TRUE);
693                         }
694 #endif
695
696                         /*
697                          *      Tell the request to stop it.
698                          */
699                         goto done;
700                 } /* else we're not at max_request_time */
701
702 #ifdef WITH_PROXY
703                 if ((request->master_state != REQUEST_STOP_PROCESSING) &&
704                     request->proxy &&
705                     (request->process == request_running)) {
706 #ifdef DEBUG_STATE_MACHINE
707                         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_proxied");
708 #endif
709                         request->process = proxy_wait_for_reply;
710                 }
711 #endif
712
713                 /*
714                  *      Wake up again in the future, to check for
715                  *      more things to do.
716                  */
717                 when = now;
718                 tv_add(&when, request->delay);
719                 request->delay += request->delay >> 1;
720
721                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
722                 return;
723         }
724
725 #ifdef WITH_ACCOUNTING
726         if (request->reply->code == PW_ACCOUNTING_RESPONSE) {
727         done:
728                 request_done(request, FR_ACTION_DONE);
729                 return;
730         }
731 #endif
732
733 #ifdef WITH_COA
734         if (!request->proxy || (request->packet->code == request->proxy->code))
735 #endif
736
737         if ((request->reply->code == PW_AUTHENTICATION_REJECT) &&
738             (request->root->reject_delay)) {
739                 when = request->reply->timestamp; 
740                 when.tv_sec += request->root->reject_delay;
741
742                 /*
743                  *      Set timer for when we need to send it.
744                  */
745                 if (timercmp(&when, &now, >)) {
746 #ifdef DEBUG_STATE_MACHINE
747                         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_reject_delay");
748 #endif
749                         request->process = request_reject_delay;
750
751                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
752                         return;
753                 }
754
755                 if (request->process == request_reject_delay) {
756                         /*
757                          *      Assume we're at (or near) the reject
758                          *      delay time.
759                          */
760                         request->reply->timestamp = now;
761                         
762                         RDEBUG2("Sending delayed reject");
763                         DEBUG_PACKET(request, request->reply, 1);
764                         request->process = request_cleanup_delay;
765                         request->listener->send(request->listener, request);
766                 }
767         }
768
769         /*
770          *      The cleanup_delay is zero for accounting packets, and
771          *      enforced for all other packets.  We do the
772          *      cleanup_delay even if we don't respond to the NAS, so
773          *      that any retransmit is *not* processed as a new packet.
774          */
775         request_cleanup_delay_init(request, &now);
776         return;
777 }
778
779 static void request_queue_or_run(UNUSED REQUEST *request,
780                                  fr_request_process_t process)
781 {
782         struct timeval when;
783 #ifdef DEBUG_STATE_MACHINE
784         int action = FR_ACTION_TIMER;
785 #endif
786
787         TRACE_STATE_MACHINE;
788         ASSERT_MASTER;
789
790         /*
791          *      (re) set the initial delay.
792          */
793         request->delay = USEC / 3;
794         gettimeofday(&when, NULL);
795         tv_add(&when, request->delay);
796         request->delay += request->delay >> 1;
797
798         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
799
800         /*
801          *      Do this here so that fewer other functions need to do
802          *      it.
803          */
804         if (request->master_state == REQUEST_STOP_PROCESSING) {
805 #ifdef DEBUG_STATE_MACHINE
806                 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
807 #endif
808                 request_done(request, FR_ACTION_DONE);
809                 return;
810         }
811
812         request->process = process;
813
814 #ifdef HAVE_PTHREAD_H
815         if (spawn_flag) {
816                 if (!request_enqueue(request)) {
817                         request_done(request, FR_ACTION_DONE);
818                         return;
819                 }
820
821         } else
822 #endif
823         {
824                 request->process(request, FR_ACTION_RUN);
825
826 #ifdef WNOHANG
827                 /*
828                  *      Requests that care about child process exit
829                  *      codes have already either called
830                  *      rad_waitpid(), or they've given up.
831                  */
832                 wait(NULL);
833 #endif
834         }
835 }
836
837 STATE_MACHINE_DECL(request_common)
838 {
839 #ifdef WITH_PROXY
840         char buffer[128];
841 #endif
842
843         TRACE_STATE_MACHINE;
844
845         switch (action) {
846         case FR_ACTION_DUP:
847 #ifdef WITH_PROXY
848                 if ((request->master_state != REQUEST_STOP_PROCESSING) &&
849                      request->proxy && !request->proxy_reply) {
850                         /*
851                          *      TODO: deal with this in a better way?
852                          */
853                         proxy_wait_for_reply(request, action);
854                         return;
855                 }
856 #endif
857                 radlog(L_ERR, "(%u) Discarding duplicate request from "
858                        "client %s port %d - ID: %u due to unfinished request",
859                        request->number, request->client->shortname,
860                        request->packet->src_port,request->packet->id);
861                 break;
862
863         case FR_ACTION_CONFLICTING:
864                 /*
865                  *      We're in the master thread, ask the child to
866                  *      stop processing the request.
867                  */
868                 request_done(request, action);
869                 return;
870
871         case FR_ACTION_TIMER:
872                 request_process_timer(request);
873                 return;
874
875 #ifdef WITH_PROXY
876         case FR_ACTION_PROXY_REPLY:
877                 DEBUG2("Reply from home server %s port %d  - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
878                        inet_ntop(request->proxy->src_ipaddr.af,
879                                  &request->proxy->src_ipaddr.ipaddr,
880                                  buffer, sizeof(buffer)),
881                        request->proxy->dst_port, request->proxy->id,
882                        request->number);
883                 return;
884 #endif
885
886         default:
887                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
888                 break;
889         }
890 }
891
892 STATE_MACHINE_DECL(request_cleanup_delay)
893 {
894         struct timeval when;
895
896         TRACE_STATE_MACHINE;
897         ASSERT_MASTER;
898
899         switch (action) {
900         case FR_ACTION_DUP:
901                 if (request->reply->code != 0) {
902                         request->listener->send(request->listener, request);
903                 } else {
904                         RDEBUG("No reply.  Ignoring retransmit.");
905                 }
906
907                 /*
908                  *      Double the cleanup_delay to catch retransmits.
909                  */
910                 when = request->reply->timestamp;
911                 request->delay += request->delay ;
912                 when.tv_sec += request->delay;
913
914                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
915                 return;
916
917 #ifdef WITH_PROXY
918         case FR_ACTION_PROXY_REPLY:
919 #endif
920         case FR_ACTION_CONFLICTING:
921         case FR_ACTION_TIMER:
922                 request_common(request, action);
923                 return;
924
925         default:
926                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
927                 break;
928         }
929 }
930
931 STATE_MACHINE_DECL(request_reject_delay)
932 {
933         TRACE_STATE_MACHINE;
934         ASSERT_MASTER;
935
936         switch (action) {
937         case FR_ACTION_DUP:
938                 radlog(L_ERR, "(%u) Discarding duplicate request from "
939                        "client %s port %d - ID: %u due to delayed reject",
940                        request->number, request->client->shortname,
941                        request->packet->src_port,request->packet->id);
942                 return;
943
944 #ifdef WITH_PROXY
945         case FR_ACTION_PROXY_REPLY:
946 #endif
947         case FR_ACTION_CONFLICTING:
948         case FR_ACTION_TIMER:
949                 request_common(request, action);
950                 break;
951
952         default:
953                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
954                 break;
955         }
956 }
957
958
959 static int request_pre_handler(REQUEST *request, UNUSED int action)
960 {
961         TRACE_STATE_MACHINE;
962
963         int rcode;
964
965         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
966
967         /*
968          *      Don't decode the packet if it's an internal "fake"
969          *      request.  Instead, just return so that the caller can
970          *      process it.
971          */
972         if (request->packet->dst_port == 0) {
973                 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
974                 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
975                 return 1;
976         }
977
978 #ifdef WITH_PROXY
979         /*
980          *      Put the decoded packet into it's proper place.
981          */
982         if (request->proxy_reply != NULL) {
983                 rcode = request->proxy_listener->decode(request->proxy_listener, request);
984                 DEBUG_PACKET(request, request->proxy_reply, 0);
985
986                 /*
987                  *      Pro-actively remove it from the proxy hash.
988                  *      This is later than in 2.1.x, but it means that
989                  *      the replies are authenticated before being
990                  *      removed from the hash.
991                  */
992                 if ((rcode == 0) &&
993                     (request->num_proxied_requests <= request->num_proxied_responses)) {
994                         remove_from_proxy_hash(request);
995                 }
996
997         } else
998 #endif
999         if (request->packet->vps == NULL) {
1000                 rcode = request->listener->decode(request->listener, request);
1001                 
1002 #ifdef WITH_UNLANG
1003                 if (debug_condition) {
1004                         int result = FALSE;
1005                         const char *my_debug = debug_condition;
1006
1007                         /*
1008                          *      Ignore parse errors.
1009                          */
1010                         (void) radius_evaluate_condition(request, RLM_MODULE_OK,
1011                                                          0, &my_debug, 1,
1012                                                          &result);
1013                         if (result) {
1014                                 request->options = 2;
1015                                 request->radlog = radlog_request;
1016                         }
1017                 }
1018 #endif
1019                 
1020                 DEBUG_PACKET(request, request->packet, 0);
1021         } else {
1022                 rcode = 0;
1023         }
1024
1025         if (rcode < 0) {
1026                 RDEBUG("Dropping packet without response because of error %s", fr_strerror());
1027                 request->reply->offset = -2; /* bad authenticator */
1028                 return 0;
1029         }
1030
1031         if (!request->username) {
1032                 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1033         }
1034
1035 #ifdef WITH_PROXY
1036         if (action == FR_ACTION_PROXY_REPLY) {
1037                 return process_proxy_reply(request);
1038         }
1039 #endif
1040
1041         return 1;
1042 }
1043
1044 STATE_MACHINE_DECL(request_finish)
1045 {
1046         VALUE_PAIR *vp;
1047
1048         TRACE_STATE_MACHINE;
1049
1050         action = action;        /* -Wunused */
1051
1052         if (request->master_state == REQUEST_STOP_PROCESSING) return;
1053
1054         /*
1055          *      Don't send replies if there are none to send.
1056          */
1057         if (!request->in_request_hash) return;
1058
1059         /*
1060          *      Catch Auth-Type := Reject BEFORE proxying the packet.
1061          */
1062         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1063                 /*
1064                  *      Override the response code if a 
1065                  *      control:Response-Packet-Type attribute is present.
1066                  */
1067                 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1068                 if (vp) {
1069                         if (vp->vp_integer == 256) {
1070                                 RDEBUG2("Not responding to request");
1071
1072                                 request->reply->code = 0;
1073                         } else {
1074                                 request->reply->code = vp->vp_integer;
1075                         }
1076                 } else if (request->reply->code == 0) {
1077                         vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1078                         
1079                         if (!vp || (vp->vp_integer != PW_AUTHENTICATION_REJECT)) {
1080                                 RDEBUG2("There was no response configured: "
1081                                         "rejecting request");
1082                         }
1083                         
1084                         request->reply->code = PW_AUTHENTICATION_REJECT;
1085                 }
1086         }
1087         
1088         /*
1089          *      Copy Proxy-State from the request to the reply.
1090          */
1091         vp = paircopy2(request->packet->vps, PW_PROXY_STATE, 0, TAG_ANY);
1092         if (vp) pairadd(&request->reply->vps, vp);
1093
1094         switch (request->reply->code)
1095         {
1096         case PW_AUTHENTICATION_ACK:
1097                 rad_postauth(request);
1098                 break;
1099         case PW_ACCESS_CHALLENGE:
1100                 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1101                            TAG_ANY);
1102                 vp = radius_pairmake(request, &request->config_items,
1103                                      "Post-Auth-Type", "Challenge",
1104                                      T_OP_SET);
1105                                      
1106                 if (vp) rad_postauth(request);
1107                 break;
1108         default:
1109                 break;
1110         }
1111
1112         /*
1113          *      Run rejected packets through
1114          *
1115          *      Post-Auth-Type = Reject
1116          *
1117          *      We do this separately so ACK and challenge can change the code
1118          *      to reject if a module returns reject.
1119          */
1120         if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1121                 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1122                 vp = radius_pairmake(request, &request->config_items,
1123                                      "Post-Auth-Type", "Reject",
1124                                      T_OP_SET);
1125                 if (vp) rad_postauth(request);
1126         }
1127
1128         /*
1129          *      Send the reply here.
1130          */
1131         if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1132             (request->root->reject_delay == 0)) {
1133                 DEBUG_PACKET(request, request->reply, 1);
1134                 request->listener->send(request->listener,
1135                                         request);
1136         }
1137
1138         gettimeofday(&request->reply->timestamp, NULL);
1139
1140         /*
1141          *      Clean up.  These are no longer needed.
1142          */
1143         pairfree(&request->config_items);
1144
1145         pairfree(&request->packet->vps);
1146         request->username = NULL;
1147         request->password = NULL;
1148         
1149         if (request->reply->code != PW_AUTHENTICATION_REJECT) {
1150                 pairfree(&request->reply->vps);
1151         }
1152
1153 #ifdef WITH_PROXY
1154         if (request->proxy) {
1155                 pairfree(&request->proxy->vps);
1156
1157                 if (request->proxy_reply) {
1158                         pairfree(&request->proxy_reply->vps);
1159                 }
1160         }
1161 #endif
1162         
1163         RDEBUG2("Finished request %u.", request->number);
1164 }
1165
1166 STATE_MACHINE_DECL(request_running)
1167 {
1168         TRACE_STATE_MACHINE;
1169
1170         switch (action) {
1171         case FR_ACTION_CONFLICTING:
1172         case FR_ACTION_DUP:
1173         case FR_ACTION_TIMER:
1174                 request_common(request, action);
1175                 return;
1176
1177 #ifdef WITH_PROXY
1178         case FR_ACTION_PROXY_REPLY:
1179 #ifdef HAVE_PTHREAD_H
1180                 /*
1181                  *      Catch the case of a proxy reply when called
1182                  *      from the main worker thread.
1183                  */
1184                 if (we_are_master() &&
1185                     (request->process != proxy_running)) {
1186                         request_queue_or_run(request, proxy_running);
1187                         return;
1188                 }
1189                 /* FALL-THROUGH */
1190 #endif
1191 #endif
1192
1193         case FR_ACTION_RUN:
1194                 if (!request_pre_handler(request, action)) goto done;
1195
1196                 rad_assert(request->handle != NULL);
1197                 request->handle(request);
1198
1199 #ifdef WITH_PROXY
1200                 /*
1201                  *      We may need to send a proxied request.
1202                  */
1203                 if ((action == FR_ACTION_RUN) &&
1204                     request_will_proxy(request)) {
1205 #ifdef DEBUG_STATE_MACHINE
1206                         if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1207 #endif
1208                         /*
1209                          *      If this fails, it
1210                          *      takes care of setting
1211                          *      up the post proxy fail
1212                          *      handler.
1213                          */
1214                         if (request_proxy(request, 0) < 0) goto finished;
1215                 } else
1216 #endif
1217                 {
1218 #ifdef DEBUG_STATE_MACHINE
1219                         if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1220 #endif
1221
1222 #ifdef WITH_COA
1223                         /*
1224                          *      Maybe originate a CoA request.
1225                          */
1226                         if ((action == FR_ACTION_RUN) && request->coa) {
1227                                 request_coa_originate(request);
1228                         }
1229 #endif
1230
1231                 finished:
1232                         request_finish(request, action);
1233
1234                 done:
1235 #ifdef DEBUG_STATE_MACHINE
1236                         if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
1237 #endif
1238
1239 #ifdef HAVE_PTHREAD_H
1240                         request->child_pid = NO_SUCH_CHILD_PID;
1241 #endif  
1242                         request->child_state = REQUEST_DONE;
1243                 }
1244                 break;
1245
1246         default:
1247                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1248                 break;
1249         }
1250 }
1251
1252 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1253                     RADCLIENT *client, RAD_REQUEST_FUNP fun)
1254 {
1255         int count;
1256         RADIUS_PACKET **packet_p;
1257         REQUEST *request = NULL;
1258         struct timeval now;
1259         listen_socket_t *sock = listener->data;
1260
1261         /*
1262          *      Set the last packet received.
1263          */
1264         gettimeofday(&now, NULL);
1265         sock->last_packet = now.tv_sec;
1266
1267         packet_p = fr_packet_list_find(pl, packet);
1268         if (packet_p) {
1269                 request = fr_packet2myptr(REQUEST, packet, packet_p);
1270                 rad_assert(request->in_request_hash);
1271
1272                 /*
1273                  *      Same src/dst ip/port, length, and
1274                  *      authentication vector: must be a duplicate.
1275                  */
1276                 if ((request->packet->data_len == packet->data_len) &&
1277                     (memcmp(request->packet->vector, packet->vector,
1278                             sizeof(packet->vector)) == 0)) {
1279
1280 #ifdef WITH_STATS
1281                         switch (packet->code) {
1282                         case PW_AUTHENTICATION_REQUEST:
1283                                 FR_STATS_INC(auth, total_dup_requests);
1284                                 break;
1285
1286 #ifdef WITH_ACCOUNTING
1287                         case PW_ACCOUNTING_REQUEST:
1288                                 FR_STATS_INC(acct, total_dup_requests);
1289                                 break;
1290 #endif                                       
1291 #ifdef WITH_COA
1292                         case PW_COA_REQUEST:
1293                                 FR_STATS_INC(coa, total_dup_requests);
1294                                 break;
1295
1296                         case PW_DISCONNECT_REQUEST:
1297                                 FR_STATS_INC(dsc, total_dup_requests);
1298                                 break;
1299 #endif
1300
1301                         default:
1302                           break;
1303                         }
1304 #endif  /* WITH_STATS */
1305
1306                         request->process(request, FR_ACTION_DUP);
1307                         return 0;
1308                 }
1309
1310                 /*
1311                  *      Say we're ignoring the old one, and continue
1312                  *      to process the new one.
1313                  */
1314                 request->process(request, FR_ACTION_CONFLICTING);
1315                 request = NULL;
1316         }
1317
1318         /*
1319          *      Quench maximum number of outstanding requests.
1320          */
1321         if (mainconfig.max_requests &&
1322             ((count = fr_packet_list_num_elements(pl)) > mainconfig.max_requests)) {
1323                 radlog(L_ERR, "Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1324                        client->shortname,
1325                        packet->src_port, packet->id);
1326                 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
1327                        "\tThe value for 'max_requests' is probably set too low.\n");
1328
1329                 exec_trigger(NULL, NULL, "server.max_requests", TRUE);
1330                 return 0;
1331         }
1332
1333         /*
1334          *      Rate-limit the incoming packets
1335          */
1336         if (sock->max_rate) {
1337                 int pps;
1338
1339                 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now,
1340                               &sock->rate_time, &now);
1341
1342                 if (pps > sock->max_rate) {
1343                         DEBUG("Dropping request due to rate limiting");
1344                         return 0;
1345                 }
1346                 sock->rate_pps_now++;
1347         }
1348
1349         return request_insert(listener, packet, client, fun, &now);
1350 }
1351
1352 int request_insert(rad_listen_t *listener, RADIUS_PACKET *packet,
1353                    RADCLIENT *client, RAD_REQUEST_FUNP fun,
1354                    struct timeval *pnow)
1355 {
1356         REQUEST *request;
1357
1358         /*
1359          *      Create and initialize the new request.
1360          */
1361         request = request_alloc(); /* never fails */
1362         
1363         if ((request->reply = rad_alloc(0)) == NULL) {
1364                 radlog(L_ERR, "No memory");
1365                 request_free(&request);
1366                 return 1;
1367         }
1368
1369         request->listener = listener;
1370         request->client = client;
1371         request->packet = packet;
1372         request->packet->timestamp = *pnow;
1373         request->number = request_num_counter++;
1374         request->priority = listener->type;
1375         request->master_state = REQUEST_ACTIVE;
1376 #ifdef DEBUG_STATE_MACHINE
1377         if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_ACTIVE);
1378 #endif
1379         request->child_state = REQUEST_ACTIVE;
1380         request->handle = fun;
1381 #ifdef HAVE_PTHREAD_H
1382         request->child_pid = NO_SUCH_CHILD_PID;
1383 #endif
1384
1385 #ifdef WITH_STATS
1386         request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1387         if (packet->code == PW_AUTHENTICATION_REQUEST) {
1388                 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1389                 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1390 #ifdef WITH_ACCOUNTING
1391         } else if (packet->code == PW_ACCOUNTING_REQUEST) {
1392                 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1393                 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1394 #endif
1395         }
1396 #endif  /* WITH_STATS */
1397
1398         /*
1399          *      Status-Server packets go to the head of the queue.
1400          */
1401         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
1402
1403         /*
1404          *      Set virtual server identity
1405          */
1406         if (client->server) {
1407                 request->server = client->server;
1408         } else if (listener->server) {
1409                 request->server = listener->server;
1410         } else {
1411                 request->server = NULL;
1412         }
1413
1414         /*
1415          *      Remember the request in the list.
1416          */
1417         if (!fr_packet_list_insert(pl, &request->packet)) {
1418                 radlog_request(L_ERR, 0, request, "Failed to insert request in the list of live requests: discarding it");
1419                 request_done(request, FR_ACTION_DONE);
1420                 return 1;
1421         }
1422
1423         request->in_request_hash = TRUE;
1424         request->root = &mainconfig;
1425         mainconfig.refcount++;
1426 #ifdef WITH_TCP
1427         request->listener->count++;
1428 #endif
1429
1430         /*
1431          *      The request passes many of our sanity checks.
1432          *      From here on in, if anything goes wrong, we
1433          *      send a reject message, instead of dropping the
1434          *      packet.
1435          */
1436
1437         /*
1438          *      Build the reply template from the request.
1439          */
1440
1441         request->reply->sockfd = request->packet->sockfd;
1442         request->reply->dst_ipaddr = request->packet->src_ipaddr;
1443         request->reply->src_ipaddr = request->packet->dst_ipaddr;
1444         request->reply->dst_port = request->packet->src_port;
1445         request->reply->src_port = request->packet->dst_port;
1446         request->reply->id = request->packet->id;
1447         request->reply->code = 0; /* UNKNOWN code */
1448         memcpy(request->reply->vector, request->packet->vector,
1449                sizeof(request->reply->vector));
1450         request->reply->vps = NULL;
1451         request->reply->data = NULL;
1452         request->reply->data_len = 0;
1453
1454         request_queue_or_run(request, request_running);
1455
1456         return 1;
1457 }
1458
1459 #ifdef WITH_TCP
1460 #ifdef WITH_PROXY
1461 /***********************************************************************
1462  *
1463  *      TCP Handlers.
1464  *
1465  ***********************************************************************/
1466
1467 /*
1468  *      Timer function for all TCP sockets.
1469  */
1470 static void tcp_socket_timer(void *ctx)
1471 {
1472         rad_listen_t *listener = ctx;
1473         listen_socket_t *sock = listener->data;
1474         struct timeval end, now;
1475         char buffer[256];
1476         fr_socket_limit_t *limit;
1477
1478         fr_event_now(el, &now);
1479
1480         switch (listener->type) {
1481         case RAD_LISTEN_PROXY:
1482                 limit = &sock->home->limit;
1483                 break;
1484
1485         case RAD_LISTEN_AUTH:
1486         case RAD_LISTEN_ACCT:
1487                 limit = &sock->limit;
1488                 break;
1489
1490         default:
1491                 return;
1492         }
1493
1494         /*
1495          *      If we enforce a lifetime, do it now.
1496          */
1497         if (limit->lifetime > 0) {
1498                 end.tv_sec = sock->opened + limit->lifetime;
1499                 end.tv_usec = 0;
1500
1501                 if (timercmp(&end, &now, <=)) {
1502                         listener->print(listener, buffer, sizeof(buffer));
1503                         DEBUG("Reached maximum lifetime on socket %s", buffer);
1504                         
1505                 do_close:
1506                         
1507                         listener->status = RAD_LISTEN_STATUS_CLOSED;
1508                         event_new_fd(listener);
1509                         return;
1510                 }
1511         } else {
1512                 end = now;
1513                 end.tv_sec += 3600;
1514         }
1515
1516         /*
1517          *      Enforce an idle timeout.
1518          */
1519         if (limit->idle_timeout > 0) {
1520                 struct timeval idle;
1521
1522                 rad_assert(sock->last_packet != 0);
1523                 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1524                 idle.tv_usec = 0;
1525
1526                 if (timercmp(&idle, &now, <=)) {
1527                         listener->print(listener, buffer, sizeof(buffer));
1528                         DEBUG("Reached idle timeout on socket %s", buffer);
1529                         goto do_close;
1530                 }
1531
1532                 /*
1533                  *      Enforce the minimum of idle timeout or lifetime.
1534                  */
1535                 if (timercmp(&idle, &end, <)) {
1536                         end = idle;
1537                 }
1538         }
1539
1540         /*
1541          *      Wake up at t + 0.5s.  The code above checks if the timers
1542          *      are <= t.  This addition gives us a bit of leeway.
1543          */
1544         end.tv_usec = USEC / 2;
1545
1546         if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1547                 rad_panic("Failed to insert event");
1548         }
1549 }
1550
1551
1552 /*
1553  *      Add +/- 2s of jitter, as suggested in RFC 3539
1554  *      and in RFC 5080.
1555  */
1556 static void add_jitter(struct timeval *when)
1557 {
1558         uint32_t jitter;
1559
1560         when->tv_sec -= 2;
1561
1562         jitter = fr_rand();
1563         jitter ^= (jitter >> 10);
1564         jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1565
1566         /*
1567          *      Add in ~ (4 * USEC) of jitter.
1568          */
1569         tv_add(when, jitter);
1570 }
1571
1572
1573 static int disconnect_all_proxied_requests(void *ctx, void *data)
1574 {
1575         rad_listen_t *this = ctx;
1576         RADIUS_PACKET **proxy_p = data;
1577         REQUEST *request;
1578         
1579         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1580         if (request->proxy->sockfd != this->fd) return 0;
1581
1582         /*
1583          *      The normal "remove_from_proxy_hash" tries to grab the
1584          *      proxy mutex.  We already have it held, so grabbing it
1585          *      again will cause a deadlock.  Instead, call the "no
1586          *      lock" version of the function.
1587          */
1588         if (request->in_proxy_hash) {
1589                 remove_from_proxy_hash_nl(request);
1590         }
1591         request->proxy_listener = NULL;
1592
1593         /*
1594          *      Don't mark it as DONE.  The client can retransmit, and
1595          *      the packet SHOULD be re-proxied somewhere else.
1596          */
1597         return 0;
1598 }
1599 #endif  /* WITH_PROXY */
1600
1601 static int remove_all_requests(void *ctx, void *data)
1602 {
1603         rad_listen_t *this = ctx;
1604         RADIUS_PACKET **packet_p = data;
1605         REQUEST *request;
1606         
1607         request = fr_packet2myptr(REQUEST, packet, packet_p);
1608         if (request->packet->sockfd != this->fd) return 0;
1609
1610         request_done(request, FR_ACTION_DONE);
1611         return 0;
1612 }
1613 #endif  /* WITH_TCP */
1614
1615 #ifdef WITH_PROXY
1616 /***********************************************************************
1617  *
1618  *      Proxy handlers for the state machine.
1619  *
1620  ***********************************************************************/
1621
1622 static void remove_from_proxy_hash_nl(REQUEST *request)
1623 {
1624         fr_packet_list_yank(proxy_list, request->proxy);
1625         fr_packet_list_id_free(proxy_list, request->proxy);
1626
1627         /*
1628          *      On the FIRST reply, decrement the count of outstanding
1629          *      requests.  Note that this is NOT the count of sent
1630          *      packets, but whether or not the home server has
1631          *      responded at all.
1632          */
1633         if (request->home_server &&
1634             request->home_server->currently_outstanding) {
1635                 request->home_server->currently_outstanding--;
1636
1637                 /*
1638                  *      If we're NOT sending it packets, then we don't know
1639                  *      if it's alive or dead.
1640                  */
1641                 if ((request->home_server->currently_outstanding == 0) &&
1642                     (request->home_server->state == HOME_STATE_ALIVE)) {
1643                         request->home_server->state = HOME_STATE_UNKNOWN;
1644                         request->home_server->last_packet_sent = 0;
1645                         request->home_server->last_packet_recv = 0;
1646                 }
1647         }
1648
1649 #ifdef WITH_TCP
1650         request->proxy_listener->count--;
1651 #endif
1652         request->proxy_listener = NULL;
1653
1654         /*
1655          *      Got from YES in hash, to NO, not in hash while we hold
1656          *      the mutex.  This guarantees that when another thread
1657          *      grabs the mutex, the "not in hash" flag is correct.
1658          */
1659         request->in_proxy_hash = FALSE;
1660 }
1661
1662 static void remove_from_proxy_hash(REQUEST *request)
1663 {
1664         /*
1665          *      Check this without grabbing the mutex because it's a
1666          *      lot faster that way.
1667          */
1668         if (!request->in_proxy_hash) return;
1669
1670         /*
1671          *      The "not in hash" flag is definitive.  However, if the
1672          *      flag says that it IS in the hash, there might still be
1673          *      a race condition where it isn't.
1674          */
1675         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1676
1677         if (!request->in_proxy_hash) {
1678                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1679                 return;
1680         }
1681
1682         remove_from_proxy_hash_nl(request);
1683
1684         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1685 }
1686
1687 static int insert_into_proxy_hash(REQUEST *request)
1688 {
1689         char buf[128];
1690         int rcode, tries;
1691         void *proxy_listener;
1692
1693         rad_assert(request->proxy != NULL);
1694         rad_assert(request->home_server != NULL);
1695         rad_assert(proxy_list != NULL);
1696
1697         tries = 1;
1698 retry:
1699         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1700         rcode = fr_packet_list_id_alloc(proxy_list,
1701                                         request->home_server->proto,
1702                                         request->proxy, &proxy_listener);
1703         request->num_proxied_requests = 1;
1704         request->num_proxied_responses = 0;
1705         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1706         
1707         if (!rcode) {
1708 #ifdef HAVE_PTHREAD_H
1709                 if (proxy_no_new_sockets) return 0;
1710 #endif
1711
1712                 /*
1713                  *      Also locks the proxy mutex, so we have to call
1714                  *      it with the mutex unlocked.  Some systems
1715                  *      don't support recursive mutexes.
1716                  */
1717                 if (!proxy_new_listener(request->home_server, 0)) {
1718                         radlog(L_ERR, "Failed to create a new socket for proxying requests.");
1719                         return 0;
1720                 }
1721                 request->proxy->src_port = 0; /* Use any new socket */
1722
1723                 tries++;
1724                 if (tries > 2) {
1725                         RDEBUG2E("Failed allocating Id for new socket when proxying requests.");
1726                         return 0;
1727                 }
1728                 
1729                 goto retry;
1730         }
1731
1732         request->proxy_listener = proxy_listener;
1733
1734         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1735         if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
1736                 fr_packet_list_id_free(proxy_list, request->proxy);
1737                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1738                 radlog_request(L_PROXY, 0, request, "Failed to insert entry into proxy list.");
1739                 return 0;
1740         }
1741
1742         request->in_proxy_hash = TRUE;
1743
1744         /*
1745          *      Keep track of maximum outstanding requests to a
1746          *      particular home server.  'max_outstanding' is
1747          *      enforced in home_server_ldb(), in realms.c.
1748          */
1749         request->home_server->currently_outstanding++;
1750
1751 #ifdef WITH_TCP
1752         request->proxy_listener->count++;
1753 #endif
1754
1755         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1756
1757         RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
1758                inet_ntop(request->proxy->dst_ipaddr.af,
1759                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
1760                request->proxy->dst_port,
1761                request->proxy->id);
1762
1763         return 1;
1764 }
1765
1766 static int process_proxy_reply(REQUEST *request)
1767 {
1768         int rcode;
1769         int post_proxy_type = 0;
1770         VALUE_PAIR *vp;
1771         
1772         /*
1773          *      Delete any reply we had accumulated until now.
1774          */
1775         pairfree(&request->reply->vps);
1776         
1777         /*
1778          *      Run the packet through the post-proxy stage,
1779          *      BEFORE playing games with the attributes.
1780          */
1781         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
1782         
1783         /*
1784          *      If we have a proxy_reply, and it was a reject, setup
1785          *      post-proxy-type Reject
1786          */
1787         if (!vp && request->proxy_reply &&
1788             request->proxy_reply->code == PW_AUTHENTICATION_REJECT) {
1789                 DICT_VALUE      *dval;
1790
1791                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
1792                 if (dval) {
1793                         vp = radius_paircreate(request, &request->config_items,
1794                                                PW_POST_PROXY_TYPE, 0);
1795
1796                         vp->vp_integer = dval->value;
1797                 }
1798         }
1799         
1800         if (vp) {
1801                 post_proxy_type = vp->vp_integer;
1802                 
1803                 RDEBUG2("  Found Post-Proxy-Type %s",
1804                         dict_valnamebyattr(PW_POST_PROXY_TYPE, 0,
1805                                            post_proxy_type));
1806         }
1807         
1808         if (request->home_pool && request->home_pool->virtual_server) {
1809                 const char *old_server = request->server;
1810                 
1811                 request->server = request->home_pool->virtual_server;
1812                 RDEBUG2(" server %s {", request->server);
1813                 rcode = module_post_proxy(post_proxy_type, request);
1814                 RDEBUG2(" }");
1815                 request->server = old_server;
1816         } else {
1817                 rcode = module_post_proxy(post_proxy_type, request);
1818         }
1819
1820 #ifdef WITH_COA
1821         if (request->packet->code == request->proxy->code)
1822           /*
1823            *    Don't run the next bit if we originated a CoA
1824            *    packet, after receiving an Access-Request or
1825            *    Accounting-Request.
1826            */
1827 #endif
1828
1829         /*
1830          *      There may NOT be a proxy reply, as we may be
1831          *      running Post-Proxy-Type = Fail.
1832          */
1833         if (request->proxy_reply) {
1834                 /*
1835                  *      Delete the Proxy-State Attributes from
1836                  *      the reply.  These include Proxy-State
1837                  *      attributes from us and remote server.
1838                  */
1839                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
1840                 
1841                 /*
1842                  *      Add the attributes left in the proxy
1843                  *      reply to the reply list.
1844                  */
1845                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1846                 request->proxy_reply->vps = NULL;
1847                 
1848                 /*
1849                  *      Free proxy request pairs.
1850                  */
1851                 pairfree(&request->proxy->vps);
1852         }
1853         
1854         switch (rcode) {
1855         default:  /* Don't do anything */
1856                 break;
1857         case RLM_MODULE_FAIL:
1858                 return 0;
1859                 
1860         case RLM_MODULE_HANDLED:
1861                 return 0;
1862         }
1863
1864         return 1;
1865 }
1866
1867 int request_proxy_reply(RADIUS_PACKET *packet)
1868 {
1869         RADIUS_PACKET **proxy_p;
1870         REQUEST *request;
1871         struct timeval now;
1872         char buffer[128];
1873
1874         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1875         proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
1876
1877         if (!proxy_p) {
1878                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1879                 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
1880                        inet_ntop(packet->src_ipaddr.af,
1881                                  &packet->src_ipaddr.ipaddr,
1882                                  buffer, sizeof(buffer)),
1883                        packet->src_port, packet->id);
1884                 return 0;
1885         }
1886
1887         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1888         request->num_proxied_responses++; /* needs to be protected by lock */
1889
1890         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1891
1892         /*
1893          *      No reply, BUT the current packet fails verification:
1894          *      ignore it.  This does the MD5 calculations in the
1895          *      server core, but I guess we can fix that later.
1896          */
1897         if (!request->proxy_reply &&
1898             (rad_verify(packet, request->proxy,
1899                         request->home_server->secret) != 0)) {
1900                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
1901                 return 0;
1902         }
1903
1904         /*
1905          *      The home server sent us a packet which doesn't match
1906          *      something we have: ignore it.  This is done only to
1907          *      catch the case of broken systems.
1908          */
1909         if (request->proxy_reply &&
1910             (memcmp(request->proxy_reply->vector,
1911                     packet->vector,
1912                     sizeof(request->proxy_reply->vector)) != 0)) {
1913                 RDEBUG2("Ignoring conflicting proxy reply");
1914                 return 0;
1915         }
1916
1917         gettimeofday(&now, NULL);
1918
1919         /*
1920          *      Status-Server packets don't count as real packets.
1921          */
1922         if (request->proxy->code != PW_STATUS_SERVER) {
1923                 listen_socket_t *sock = request->proxy_listener->data;
1924
1925                 request->home_server->last_packet_recv = now.tv_sec;
1926                 sock->last_packet = now.tv_sec;
1927         }
1928
1929         /*
1930          *      If we have previously seen a reply, ignore the
1931          *      duplicate.
1932          */
1933         if (request->proxy_reply) {
1934                 RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d",
1935                         inet_ntop(packet->src_ipaddr.af,
1936                                   &packet->src_ipaddr.ipaddr,
1937                                   buffer, sizeof(buffer)),
1938                         packet->src_port, packet->id);
1939                 return 0;
1940         }
1941
1942         /*
1943          *      Call the state machine to do something useful with the
1944          *      request.
1945          */
1946         request->proxy_reply = packet;
1947         packet->timestamp = now;
1948         request->priority = RAD_LISTEN_PROXY;
1949
1950         /*
1951          *      We've received a reply.  If we hadn't been sending it
1952          *      packets for a while, just mark it alive.
1953          */
1954         if (request->home_server->state == HOME_STATE_UNKNOWN) {
1955                 request->home_server->state = HOME_STATE_ALIVE;
1956         }
1957
1958 #ifdef WITH_STATS
1959         request->home_server->stats.last_packet = packet->timestamp.tv_sec;
1960         request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
1961
1962         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1963                 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
1964 #ifdef WITH_ACCOUNTING
1965         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1966                 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
1967 #endif
1968         }
1969 #endif  /* WITH_STATS */
1970
1971 #ifdef WITH_COA
1972         /*
1973          *      When we originate CoA requests, we patch them in here
1974          *      so that they don't affect the rest of the state
1975          *      machine.
1976          */
1977         if (request->parent) {
1978                 rad_assert(request->parent->coa == request);
1979                 rad_assert((request->proxy->code == PW_COA_REQUEST) ||
1980                            (request->proxy->code == PW_DISCONNECT_REQUEST));
1981                 rad_assert(request->process != NULL);
1982                 request_coa_separate(request);
1983         }
1984 #endif
1985
1986         request->process(request, FR_ACTION_PROXY_REPLY);
1987         
1988         return 1;
1989 }
1990
1991
1992 static int setup_post_proxy_fail(REQUEST *request)
1993 {
1994         const DICT_VALUE *dval = NULL;
1995         VALUE_PAIR *vp;
1996
1997         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1998                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
1999                                       "Fail-Authentication");
2000                 
2001         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
2002                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2003                                       "Fail-Accounting");
2004 #ifdef WITH_COA
2005         } else if (request->proxy->code == PW_COA_REQUEST) {
2006                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2007
2008         } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
2009                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2010 #endif
2011         } else {
2012                 DEBUGW("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2013                 request_cleanup_delay_init(request, NULL);
2014                 return 0;
2015         }
2016         
2017         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2018         
2019         if (!dval) {
2020                 DEBUG("No Post-Proxy-Type Fail: ignoring");
2021                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2022                 request_cleanup_delay_init(request, NULL);
2023                 return 0;
2024         }
2025         
2026         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2027         if (!vp) vp = radius_paircreate(request, &request->config_items,
2028                                         PW_POST_PROXY_TYPE, 0);
2029         vp->vp_integer = dval->value;
2030
2031         return 1;
2032 }
2033
2034 STATE_MACHINE_DECL(proxy_running)
2035 {
2036         TRACE_STATE_MACHINE;
2037
2038         switch (action) {
2039         case FR_ACTION_CONFLICTING:
2040         case FR_ACTION_DUP:
2041         case FR_ACTION_TIMER:
2042         case FR_ACTION_PROXY_REPLY:
2043                 request_common(request, action);
2044                 break;
2045
2046         case FR_ACTION_RUN:
2047                 request_running(request, FR_ACTION_PROXY_REPLY);
2048                 break;
2049
2050         default:
2051                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2052                 break;
2053         }
2054 }
2055
2056 STATE_MACHINE_DECL(request_virtual_server)
2057 {
2058         TRACE_STATE_MACHINE;
2059
2060         switch (action) {
2061         case FR_ACTION_CONFLICTING:
2062         case FR_ACTION_DUP:
2063         case FR_ACTION_TIMER:
2064         case FR_ACTION_PROXY_REPLY:
2065                 request_common(request, action);
2066                 break;
2067
2068         case FR_ACTION_RUN:
2069                 request_running(request, action);
2070                 break;
2071
2072         default:
2073                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2074                 break;
2075         }
2076 }
2077
2078
2079 static int request_will_proxy(REQUEST *request)
2080 {
2081         int rcode, pre_proxy_type = 0;
2082         const char *realmname = NULL;
2083         VALUE_PAIR *vp, *strippedname;
2084         home_server *home;
2085         REALM *realm = NULL;
2086         home_pool_t *pool = NULL;
2087
2088         if (!request->root->proxy_requests) return 0;
2089         if (request->packet->dst_port == 0) return 0;
2090         if (request->packet->code == PW_STATUS_SERVER) return 0;
2091         if (request->in_proxy_hash) return 0;
2092
2093         /*
2094          *      FIXME: for 3.0, allow this only for rejects?
2095          */
2096         if (request->reply->code != 0) return 0;
2097
2098         vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2099         if (vp) {
2100                 realm = realm_find2(vp->vp_strvalue);
2101                 if (!realm) {
2102                         RDEBUG2E("Cannot proxy to unknown realm %s",
2103                                 vp->vp_strvalue);
2104                         return 0;
2105                 }
2106
2107                 realmname = vp->vp_strvalue;
2108
2109                 /*
2110                  *      Figure out which pool to use.
2111                  */
2112                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2113                         pool = realm->auth_pool;
2114                         
2115 #ifdef WITH_ACCOUNTING
2116                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2117                         pool = realm->acct_pool;
2118 #endif
2119
2120 #ifdef WITH_COA
2121                 } else if ((request->packet->code == PW_COA_REQUEST) ||
2122                            (request->packet->code == PW_DISCONNECT_REQUEST)) {
2123                         pool = realm->coa_pool;
2124 #endif
2125
2126                 } else {
2127                         return 0;
2128                 }
2129
2130         } else {
2131                 int pool_type;
2132
2133                 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2134                 if (!vp) return 0;
2135
2136                 switch (request->packet->code) {
2137                 case PW_AUTHENTICATION_REQUEST:
2138                         pool_type = HOME_TYPE_AUTH;
2139                         break;
2140                         
2141 #ifdef WITH_ACCOUNTING
2142                 case PW_ACCOUNTING_REQUEST:
2143                         pool_type = HOME_TYPE_ACCT;
2144                         break;
2145 #endif
2146
2147 #ifdef WITH_COA
2148                 case PW_COA_REQUEST:
2149                 case PW_DISCONNECT_REQUEST:
2150                         pool_type = HOME_TYPE_COA;
2151                         break;
2152 #endif
2153
2154                 default:
2155                         return 0;
2156                 }
2157
2158                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2159         }
2160         
2161         if (!pool) {
2162                 RDEBUG2W("Cancelling proxy as no home pool exists");
2163                 return 0;
2164         }
2165
2166         request->home_pool = pool;
2167
2168         home = home_server_ldb(realmname, pool, request);
2169         if (!home) {
2170                 RDEBUG2E("Failed to find live home server: Cancelling proxy");
2171                 return 0;
2172         }
2173         home_server_update_request(home, request);
2174
2175 #ifdef WITH_COA
2176         /*
2177          *      Once we've decided to proxy a request, we cannot send
2178          *      a CoA packet.  So we free up any CoA packet here.
2179          */
2180         if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2181 #endif
2182
2183         /*
2184          *      Remember that we sent the request to a Realm.
2185          */
2186         if (realmname) pairadd(&request->packet->vps,
2187                                pairmake("Realm", realmname, T_OP_EQ));
2188
2189         /*
2190          *      Strip the name, if told to.
2191          *
2192          *      Doing it here catches the case of proxied tunneled
2193          *      requests.
2194          */
2195         if (realm && (realm->striprealm == TRUE) &&
2196            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2197                 /*
2198                  *      If there's a Stripped-User-Name attribute in
2199                  *      the request, then use THAT as the User-Name
2200                  *      for the proxied request, instead of the
2201                  *      original name.
2202                  *
2203                  *      This is done by making a copy of the
2204                  *      Stripped-User-Name attribute, turning it into
2205                  *      a User-Name attribute, deleting the
2206                  *      Stripped-User-Name and User-Name attributes
2207                  *      from the vps list, and making the new
2208                  *      User-Name the head of the vps list.
2209                  */
2210                 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2211                 if (!vp) {
2212                         vp = radius_paircreate(request, NULL,
2213                                                PW_USER_NAME, 0);
2214                         rad_assert(vp != NULL); /* handled by above function */
2215                         /* Insert at the START of the list */
2216                         vp->next = request->proxy->vps;
2217                         request->proxy->vps = vp;
2218                 }
2219                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2220                        sizeof(vp->vp_strvalue));
2221                 vp->length = strippedname->length;
2222
2223                 /*
2224                  *      Do NOT delete Stripped-User-Name.
2225                  */
2226         }
2227
2228         /*
2229          *      If there is no PW_CHAP_CHALLENGE attribute but
2230          *      there is a PW_CHAP_PASSWORD we need to add it
2231          *      since we can't use the request authenticator
2232          *      anymore - we changed it.
2233          */
2234         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2235             pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2236             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2237                 vp = radius_paircreate(request, &request->proxy->vps,
2238                                        PW_CHAP_CHALLENGE, 0);
2239                 memcpy(vp->vp_strvalue, request->packet->vector,
2240                        sizeof(request->packet->vector));
2241                 vp->length = sizeof(request->packet->vector);
2242         }
2243
2244         /*
2245          *      The RFC's say we have to do this, but FreeRADIUS
2246          *      doesn't need it.
2247          */
2248         vp = radius_paircreate(request, &request->proxy->vps,
2249                                PW_PROXY_STATE, 0);
2250         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2251                  request->packet->id);
2252         vp->length = strlen(vp->vp_strvalue);
2253
2254         /*
2255          *      Should be done BEFORE inserting into proxy hash, as
2256          *      pre-proxy may use this information, or change it.
2257          */
2258         request->proxy->code = request->packet->code;
2259
2260         /*
2261          *      Call the pre-proxy routines.
2262          */
2263         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2264         if (vp) {
2265                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
2266                 pre_proxy_type = vp->vp_integer;
2267         }
2268
2269         rad_assert(request->home_pool != NULL);
2270
2271         if (request->home_pool->virtual_server) {
2272                 const char *old_server = request->server;
2273                 
2274                 request->server = request->home_pool->virtual_server;
2275                 RDEBUG2(" server %s {", request->server);
2276                 rcode = module_pre_proxy(pre_proxy_type, request);
2277                 RDEBUG2(" }");
2278                         request->server = old_server;
2279         } else {
2280                 rcode = module_pre_proxy(pre_proxy_type, request);
2281         }
2282         switch (rcode) {
2283         case RLM_MODULE_FAIL:
2284         case RLM_MODULE_INVALID:
2285         case RLM_MODULE_NOTFOUND:
2286         case RLM_MODULE_USERLOCK:
2287         default:
2288                 /* FIXME: debug print failed stuff */
2289                 return -1;
2290
2291         case RLM_MODULE_REJECT:
2292         case RLM_MODULE_HANDLED:
2293                 return 0;
2294
2295         /*
2296          *      Only proxy the packet if the pre-proxy code succeeded.
2297          */
2298         case RLM_MODULE_NOOP:
2299         case RLM_MODULE_OK:
2300         case RLM_MODULE_UPDATED:
2301                 break;
2302         }
2303
2304         return 1;
2305 }
2306
2307 static int request_proxy(REQUEST *request, int retransmit)
2308 {
2309         char buffer[128];
2310
2311         rad_assert(request->parent == NULL);
2312         rad_assert(request->home_server != NULL);
2313
2314         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2315
2316 #ifdef WITH_COA
2317         if (request->coa) {
2318                 RDEBUGW("Cannot proxy and originate CoA packets at the same time.  Cancelling CoA request");
2319                 request_done(request->coa, FR_ACTION_DONE);
2320         }
2321 #endif
2322
2323         /*
2324          *      The request may be sent to a virtual server.  If we're
2325          *      in a child thread, just process it here. If we're the
2326          *      master, push it back onto the queue for later
2327          *      processing.
2328          */
2329         if (request->home_server->server) {
2330                 DEBUG("Proxying to virtual server %s",
2331                       request->home_server->server);
2332
2333                 if (!we_are_master()) {
2334                         request_virtual_server(request, FR_ACTION_RUN);
2335 #ifdef HAVE_PTHREAD_H
2336                         request->child_pid = NO_SUCH_CHILD_PID;
2337 #endif
2338                         return 1;
2339                 }
2340
2341                 request_queue_or_run(request, request_virtual_server);
2342                 return 1;
2343         }
2344
2345         /*
2346          *      We're actually sending a proxied packet.  Do that now.
2347          */
2348         if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2349                 radlog_request(L_PROXY, 0, request, "Failed to insert initial packet into the proxy list.");
2350                 return -1;
2351         }
2352
2353         RDEBUG2("Proxying request to home server %s port %d",
2354                inet_ntop(request->proxy->dst_ipaddr.af,
2355                          &request->proxy->dst_ipaddr.ipaddr,
2356                          buffer, sizeof(buffer)),
2357                 request->proxy->dst_port);
2358
2359         DEBUG_PACKET(request, request->proxy, 1);
2360
2361         gettimeofday(&request->proxy_retransmit, NULL);
2362         if (!retransmit) {
2363                 request->proxy->timestamp = request->proxy_retransmit;
2364                 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2365         }
2366
2367 #ifdef HAVE_PTHREAD_H
2368         request->child_pid = NO_SUCH_CHILD_PID;
2369 #endif
2370         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2371         request->proxy_listener->send(request->proxy_listener,
2372                                       request);
2373         return 1;
2374 }
2375
2376 /*
2377  *      Proxy the packet as if it was new.
2378  */
2379 static int request_proxy_anew(REQUEST *request)
2380 {
2381         /*
2382          *      Keep a copy of the old Id so that the
2383          *      re-transmitted request doesn't re-use the old
2384          *      Id.  Note that in certain cases (socket crash)
2385          *      there is no Id as they have been purged from
2386          *      proxy_list, but there should still be a leftover
2387          *      packet hung off this request.
2388          */
2389         RADIUS_PACKET old = *request->proxy;
2390         int old_hash = request->in_proxy_hash;
2391         home_server *home;
2392         home_server *old_home = request->home_server;
2393 #ifdef WITH_TCP
2394         rad_listen_t *listener = request->proxy_listener;
2395 #endif
2396
2397         rad_assert(old_home != NULL);
2398         
2399         /*
2400          *      Find a live home server for the request.
2401          */
2402         home = home_server_ldb(NULL, request->home_pool, request);
2403         if (!home) {
2404                 RDEBUG2E("Failed to find live home server for request");
2405         post_proxy_fail:
2406                 remove_from_proxy_hash(request);
2407
2408                 if (!setup_post_proxy_fail(request)) {
2409                         return 0;
2410                 }
2411                 
2412                 request_queue_or_run(request, proxy_running);
2413                 return 0;
2414         }
2415         home_server_update_request(home, request);
2416
2417         /*
2418          *      Don't free the old Id (if any) on error.
2419          */
2420         if (!insert_into_proxy_hash(request)) {
2421                 radlog_request(L_PROXY, 0, request, "Failed to insert retransmission into the proxy list.");
2422                 goto post_proxy_fail;
2423         }
2424
2425         /*
2426          *      Now that we have a new Id, free the old one (if any)
2427          *      and update the various statistics.
2428          */
2429         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2430         if (old_hash) {
2431                 fr_packet_list_yank(proxy_list, &old);
2432                 fr_packet_list_id_free(proxy_list, &old);
2433                 old_home->currently_outstanding--;
2434 #ifdef WITH_TCP
2435                 if (listener) listener->count--;
2436 #endif
2437         }
2438         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2439
2440         /*
2441          *      Free the old packet, to force re-encoding
2442          */
2443         free(request->proxy->data);
2444         request->proxy->data = NULL;
2445         request->proxy->data_len = 0;
2446
2447 #ifdef WITH_ACCOUNTING
2448         /*
2449          *      Update the Acct-Delay-Time attribute.
2450          */
2451         if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2452                 VALUE_PAIR *vp;
2453
2454                 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2455                 if (!vp) vp = radius_paircreate(request,
2456                                                 &request->proxy->vps,
2457                                                 PW_ACCT_DELAY_TIME, 0);
2458                 if (vp) {
2459                         struct timeval now;
2460                         
2461                         gettimeofday(&now, NULL);
2462                         vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2463                 }
2464         }
2465 #endif
2466
2467         if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2468
2469         return 1;
2470 }
2471
2472 STATE_MACHINE_DECL(request_ping)
2473 {
2474         home_server *home = request->home_server;
2475         char buffer[128];
2476
2477         TRACE_STATE_MACHINE;
2478         ASSERT_MASTER;
2479
2480         switch (action) {
2481         case FR_ACTION_TIMER:
2482                 radlog(L_ERR, "No response to status check %d for home server %s port %d",
2483                        request->number,
2484                        inet_ntop(request->proxy->dst_ipaddr.af,
2485                                  &request->proxy->dst_ipaddr.ipaddr,
2486                                  buffer, sizeof(buffer)),
2487                        request->proxy->dst_port);
2488                 break;
2489
2490         case FR_ACTION_PROXY_REPLY:
2491                 rad_assert(request->in_proxy_hash);
2492
2493                 request->home_server->num_received_pings++;
2494                 radlog_request(L_PROXY, 0, request, "Received response to status check %d (%d in current sequence)",
2495                        request->number, home->num_received_pings);
2496
2497                 /*
2498                  *      Remove the request from any hashes
2499                  */
2500                 fr_event_delete(el, &request->ev);
2501                 remove_from_proxy_hash(request);
2502
2503                 /*
2504                  *      The control socket may have marked the home server as
2505                  *      alive.  OR, it may have suddenly started responding to
2506                  *      requests again.  If so, don't re-do the "make alive"
2507                  *      work.
2508                  */
2509                 if (home->state == HOME_STATE_ALIVE) break;
2510                 
2511                 /*
2512                  *      We haven't received enough ping responses to mark it
2513                  *      "alive".  Wait a bit.
2514                  */
2515                 if (home->num_received_pings < home->num_pings_to_alive) {
2516                         break;
2517                 }
2518
2519                 /*
2520                  *      Mark it alive and delete any outstanding
2521                  *      pings.
2522                  */
2523                 home->state = HOME_STATE_ALIVE;
2524                 exec_trigger(request, request->home_server->cs, "home_server.alive", FALSE);
2525                 home->currently_outstanding = 0;
2526                 home->num_sent_pings = 0;
2527                 home->num_received_pings = 0;
2528                 gettimeofday(&home->revive_time, NULL);
2529                 
2530                 fr_event_delete(el, &home->ev);
2531
2532                 radlog_request(L_PROXY, 0, request, "Marking home server %s port %d alive",
2533                        inet_ntop(request->proxy->dst_ipaddr.af,
2534                                  &request->proxy->dst_ipaddr.ipaddr,
2535                                  buffer, sizeof(buffer)),
2536                        request->proxy->dst_port);
2537                 break;
2538
2539         default:
2540                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2541                 break;
2542         }
2543
2544         rad_assert(!request->in_request_hash);
2545         rad_assert(request->ev == NULL);
2546         request_done(request, FR_ACTION_DONE);
2547 }
2548
2549 /*
2550  *      Called from start of zombie period, OR after control socket
2551  *      marks the home server dead.
2552  */
2553 static void ping_home_server(void *ctx)
2554 {
2555         home_server *home = ctx;
2556         REQUEST *request;
2557         VALUE_PAIR *vp;
2558         struct timeval when, now;
2559
2560         if ((home->state == HOME_STATE_ALIVE) ||
2561             (home->ping_check == HOME_PING_CHECK_NONE) ||
2562 #ifdef WITH_TCP
2563             (home->proto == IPPROTO_TCP) ||
2564 #endif
2565             (home->ev != NULL)) {
2566                 return;
2567         }
2568
2569         gettimeofday(&now, NULL);
2570
2571         if (home->state == HOME_STATE_ZOMBIE) {
2572                 when = home->zombie_period_start;
2573                 when.tv_sec += home->zombie_period;
2574
2575                 if (timercmp(&when, &now, <)) {
2576                         DEBUG("PING: Zombie period is over for home server %s",
2577                                 home->name);
2578                         mark_home_server_dead(home, &now);
2579                 }
2580         }
2581
2582         request = request_alloc();
2583         request->number = request_num_counter++;
2584 #ifdef HAVE_PTHREAD_H
2585         request->child_pid = NO_SUCH_CHILD_PID;
2586 #endif
2587
2588         request->proxy = rad_alloc(1);
2589         rad_assert(request->proxy != NULL);
2590
2591         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2592                 request->proxy->code = PW_STATUS_SERVER;
2593
2594                 radius_pairmake(request, &request->proxy->vps,
2595                                 "Message-Authenticator", "0x00", T_OP_SET);
2596
2597         } else if (home->type == HOME_TYPE_AUTH) {
2598                 request->proxy->code = PW_AUTHENTICATION_REQUEST;
2599
2600                 radius_pairmake(request, &request->proxy->vps,
2601                                 "User-Name", home->ping_user_name, T_OP_SET);
2602                 radius_pairmake(request, &request->proxy->vps,
2603                                 "User-Password", home->ping_user_password, T_OP_SET);
2604                 radius_pairmake(request, &request->proxy->vps,
2605                                 "Service-Type", "Authenticate-Only", T_OP_SET);
2606                 radius_pairmake(request, &request->proxy->vps,
2607                                 "Message-Authenticator", "0x00", T_OP_SET);
2608
2609         } else {
2610 #ifdef WITH_ACCOUNTING
2611                 request->proxy->code = PW_ACCOUNTING_REQUEST;
2612                 
2613                 radius_pairmake(request, &request->proxy->vps,
2614                                 "User-Name", home->ping_user_name, T_OP_SET);
2615                 radius_pairmake(request, &request->proxy->vps,
2616                                 "Acct-Status-Type", "Stop", T_OP_SET);
2617                 radius_pairmake(request, &request->proxy->vps,
2618                                 "Acct-Session-Id", "00000000", T_OP_SET);
2619                 vp = radius_pairmake(request, &request->proxy->vps,
2620                                      "Event-Timestamp", "0", T_OP_SET);
2621                 vp->vp_date = now.tv_sec;
2622 #else
2623                 rad_assert("Internal sanity check failed");
2624 #endif
2625         }
2626
2627         vp = radius_pairmake(request, &request->proxy->vps,
2628                              "NAS-Identifier", "", T_OP_SET);
2629         if (vp) {
2630                 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue),
2631                          "Status Check %u. Are you alive?",
2632                          home->num_sent_pings);
2633                 vp->length = strlen(vp->vp_strvalue);
2634         }
2635
2636         request->proxy->src_ipaddr = home->src_ipaddr;
2637         request->proxy->dst_ipaddr = home->ipaddr;
2638         request->proxy->dst_port = home->port;
2639         request->home_server = home;
2640 #ifdef DEBUG_STATE_MACHINE
2641         if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
2642         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2643 #endif
2644 #ifdef HAVE_PTHREAD_H
2645         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2646 #endif
2647         request->child_state = REQUEST_DONE;
2648         request->process = request_ping;
2649
2650         rad_assert(request->proxy_listener == NULL);
2651
2652         if (!insert_into_proxy_hash(request)) {
2653                 radlog_request(L_PROXY, 0, request, "Failed to insert status check %d into proxy list.  Discarding it.",
2654                        request->number);
2655
2656                 rad_assert(!request->in_request_hash);
2657                 rad_assert(!request->in_proxy_hash);
2658                 rad_assert(request->ev == NULL);
2659                 request_free(&request);
2660                 return;
2661         }
2662
2663         /*
2664          *      Set up the timer callback.
2665          */
2666         when = now;
2667         when.tv_sec += home->ping_timeout;
2668
2669         DEBUG("PING: Waiting %u seconds for response to ping",
2670               home->ping_timeout);
2671
2672         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2673         home->num_sent_pings++;
2674
2675         rad_assert(request->proxy_listener != NULL);
2676         request->proxy_listener->send(request->proxy_listener,
2677                                       request);
2678
2679         /*
2680          *      Add +/- 2s of jitter, as suggested in RFC 3539
2681          *      and in the Issues and Fixes draft.
2682          */
2683         home->when = now;
2684         home->when.tv_sec += home->ping_interval;
2685
2686         add_jitter(&home->when);
2687
2688         DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
2689         INSERT_EVENT(ping_home_server, home);
2690 }
2691
2692 static void home_trigger(home_server *home, const char *trigger)
2693 {
2694         REQUEST my_request;
2695         RADIUS_PACKET my_packet;
2696
2697         memset(&my_request, 0, sizeof(my_request));
2698         memset(&my_packet, 0, sizeof(my_packet));
2699         my_request.proxy = &my_packet;
2700         my_packet.dst_ipaddr = home->ipaddr;
2701         my_packet.src_ipaddr = home->src_ipaddr;
2702
2703         exec_trigger(&my_request, home->cs, trigger, FALSE);
2704 }
2705
2706 static void mark_home_server_zombie(home_server *home)
2707 {
2708         char buffer[128];
2709
2710         ASSERT_MASTER;
2711
2712         rad_assert((home->state == HOME_STATE_ALIVE) ||
2713                    (home->state == HOME_STATE_UNKNOWN));
2714
2715 #ifdef WITH_TCP
2716         if (home->proto == IPPROTO_TCP) {
2717                 DEBUGW("Not marking TCP server %s zombie", home->name);
2718                 return;
2719         }
2720 #endif
2721
2722         home->state = HOME_STATE_ZOMBIE;
2723         home_trigger(home, "home_server.zombie");
2724
2725         /*
2726          *      Back-date the zombie period to when we last expected
2727          *      to see a response.  i.e. when we last sent a request.
2728          */
2729         if (home->last_packet_sent == 0) {
2730                 gettimeofday(&home->zombie_period_start, NULL);
2731         } else {
2732                 home->zombie_period_start.tv_sec = home->last_packet_sent;
2733                 home->zombie_period_start.tv_usec = 0;
2734         }
2735         
2736         fr_event_delete(el, &home->ev);
2737         home->num_sent_pings = 0;
2738         home->num_received_pings = 0;
2739         
2740         radlog(L_PROXY, "Marking home server %s port %d as zombie (it has not responded in %d seconds).",
2741                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2742                          buffer, sizeof(buffer)),
2743                home->port, home->response_window);
2744
2745         ping_home_server(home);
2746 }
2747
2748
2749 void revive_home_server(void *ctx)
2750 {
2751         home_server *home = ctx;
2752         char buffer[128];
2753
2754 #ifdef WITH_TCP
2755         rad_assert(home->proto != IPPROTO_TCP);
2756 #endif
2757
2758         home->state = HOME_STATE_ALIVE;
2759         home_trigger(home, "home_server.alive");
2760         home->currently_outstanding = 0;
2761         gettimeofday(&home->revive_time, NULL);
2762
2763         /*
2764          *      Delete any outstanding events.
2765          */
2766         if (home->ev) fr_event_delete(el, &home->ev);
2767
2768         radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
2769                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2770                          buffer, sizeof(buffer)),
2771                home->port);
2772 }
2773
2774 void mark_home_server_dead(home_server *home, struct timeval *when)
2775 {
2776         int previous_state = home->state;
2777         char buffer[128];
2778
2779 #ifdef WITH_TCP
2780         if (home->proto == IPPROTO_TCP) {
2781                 DEBUGW("Not marking TCP server dead");
2782                 return;
2783         }
2784 #endif
2785
2786         radlog(L_PROXY, "Marking home server %s port %d as dead.",
2787                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2788                          buffer, sizeof(buffer)),
2789                home->port);
2790
2791         home->state = HOME_STATE_IS_DEAD;
2792         home_trigger(home, "home_server.dead");
2793
2794         if (home->ping_check != HOME_PING_CHECK_NONE) {
2795                 /*
2796                  *      If the control socket marks us dead, start
2797                  *      pinging.  Otherwise, we already started
2798                  *      pinging when it was marked "zombie".
2799                  */
2800                 if (previous_state == HOME_STATE_ALIVE) {
2801                         ping_home_server(home);
2802                 } else {
2803                         DEBUG("PING: Already pinging home server %s",
2804                               home->name);
2805                 }
2806
2807         } else {
2808                 /*
2809                  *      Revive it after a fixed period of time.  This
2810                  *      is very, very, bad.
2811                  */
2812                 home->when = *when;
2813                 home->when.tv_sec += home->revive_interval;
2814
2815                 DEBUG("PING: Reviving home server %s in %u seconds",
2816                       home->name, home->revive_interval);
2817                 INSERT_EVENT(revive_home_server, home);
2818         }
2819 }
2820
2821 STATE_MACHINE_DECL(proxy_wait_for_reply)
2822 {
2823         struct timeval now, when;
2824         home_server *home = request->home_server;
2825         char buffer[128];
2826
2827         TRACE_STATE_MACHINE;
2828
2829         rad_assert(request->packet->code != PW_STATUS_SERVER);
2830         rad_assert(request->home_server != NULL);
2831
2832         gettimeofday(&now, NULL);
2833
2834         rad_assert(request->child_state != REQUEST_DONE);
2835
2836         if (request->master_state == REQUEST_STOP_PROCESSING) {
2837                 request_done(request, FR_ACTION_DONE);
2838                 return;
2839         }
2840
2841         switch (action) {
2842         case FR_ACTION_DUP:
2843                 if (request->proxy_reply) return;
2844
2845                 if ((home->state == HOME_STATE_IS_DEAD) ||
2846                     !request->proxy_listener ||
2847                     (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
2848                         request_proxy_anew(request);
2849                         return;
2850                 }
2851
2852 #ifdef WITH_TCP
2853                 if (home->proto == IPPROTO_TCP) {
2854                         DEBUG2("Suppressing duplicate proxied request to home server %s port %d proto TCP - ID: %d",
2855                                inet_ntop(request->proxy->dst_ipaddr.af,
2856                                          &request->proxy->dst_ipaddr.ipaddr,
2857                                          buffer, sizeof(buffer)),
2858                                request->proxy->dst_port,
2859                                request->proxy->id);
2860                         return;
2861                 }
2862 #endif
2863
2864 #ifdef WITH_ACCOUNTING
2865                 /*
2866                  *      If we update the Acct-Delay-Time, we need to
2867                  *      get a new ID.
2868                  */
2869                 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
2870                     pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
2871                         request_proxy_anew(request);
2872                         return;
2873                 }
2874 #endif
2875
2876                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2877                         inet_ntop(request->proxy->dst_ipaddr.af,
2878                                   &request->proxy->dst_ipaddr.ipaddr,
2879                                   buffer, sizeof(buffer)),
2880                         request->proxy->dst_port,
2881                         request->proxy->id);
2882                 request->num_proxied_requests++;
2883
2884                 rad_assert(request->proxy_listener != NULL);;
2885                 DEBUG_PACKET(request, request->proxy, 1);
2886                 FR_STATS_TYPE_INC(home->stats.total_requests);
2887                 home->last_packet_sent = now.tv_sec;
2888                 request->proxy_listener->send(request->proxy_listener,
2889                                               request);
2890                 break;
2891
2892         case FR_ACTION_TIMER:
2893                 /*
2894                  *      Wake up "response_window" time in the future.
2895                  *      i.e. when MY packet hasn't received a response.
2896                  *
2897                  *      Note that we DO NOT mark the home server as
2898                  *      zombie if it doesn't respond to us.  It may be
2899                  *      responding to other (better looking) packets.
2900                  */
2901                 when = request->proxy->timestamp;
2902                 when.tv_sec += home->response_window;
2903
2904                 /*
2905                  *      Not at the response window.  Set the timer for
2906                  *      that.
2907                  */
2908                 if (timercmp(&when, &now, >)) {
2909                         RDEBUG("Expecting proxy response no later than %d seconds from now", home->response_window);
2910                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2911                         return;
2912                 }
2913
2914                 RDEBUG("No proxy response, giving up on request and marking it done");
2915
2916                 /*
2917                  *      If we haven't received any packets for
2918                  *      "response_window", then mark the home server
2919                  *      as zombie.
2920                  *
2921                  *      If the connection is TCP, then another
2922                  *      "watchdog timer" function takes care of pings,
2923                  *      etc.  So we don't need to do it here.
2924                  *
2925                  *      This check should really be part of a home
2926                  *      server state machine.
2927                  */
2928                 if (((home->state == HOME_STATE_ALIVE) ||
2929                      (home->state == HOME_STATE_UNKNOWN)) &&
2930 #ifdef WITH_TCP
2931                     (home->proto != IPPROTO_TCP) &&
2932 #endif
2933                     ((home->last_packet_recv + home->response_window) <= now.tv_sec)) {
2934                         mark_home_server_zombie(home);
2935                 }
2936
2937                 FR_STATS_TYPE_INC(home->stats.total_timeouts);
2938                 if (home->type == HOME_TYPE_AUTH) {
2939                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
2940                         FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
2941                 }
2942 #ifdef WITH_ACCT
2943                 else if (home->type == HOME_TYPE_ACCT) {
2944                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
2945                         FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
2946                 }
2947 #endif
2948
2949                 /*
2950                  *      There was no response within the window.  Stop
2951                  *      the request.  If the client retransmitted, it
2952                  *      may have failed over to another home server.
2953                  *      But that one may be dead, too.
2954                  */
2955                 radlog_request(L_ERR, 0, request, "Failing request due to lack of any response from home server %s port %d",
2956                                inet_ntop(request->proxy->dst_ipaddr.af,
2957                                          &request->proxy->dst_ipaddr.ipaddr,
2958                                          buffer, sizeof(buffer)),
2959                                request->proxy->dst_port);
2960
2961                 if (!setup_post_proxy_fail(request)) {
2962                         return;
2963                 }
2964                 /* FALL-THROUGH */
2965
2966                 /*
2967                  *      Duplicate proxy replies have been quenched by
2968                  *      now.  This state is only called ONCE, when we
2969                  *      receive a new reply from the home server.
2970                  */
2971         case FR_ACTION_PROXY_REPLY:
2972                 request_queue_or_run(request, proxy_running);
2973                 break;
2974
2975         case FR_ACTION_CONFLICTING:
2976                 request_done(request, action);
2977                 return;
2978
2979         default:
2980                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2981                 break;
2982         }
2983 }
2984 #endif  /* WITH_PROXY */
2985
2986 /***********************************************************************
2987  *
2988  *  CoA code
2989  *
2990  ***********************************************************************/
2991 #ifdef WITH_COA
2992 static int null_handler(UNUSED REQUEST *request)
2993 {
2994         return 0;
2995 }
2996
2997 /*
2998  *      See if we need to originate a CoA request.
2999  */
3000 static void request_coa_originate(REQUEST *request)
3001 {
3002         int rcode, pre_proxy_type = 0;
3003         VALUE_PAIR *vp;
3004         REQUEST *coa;
3005         fr_ipaddr_t ipaddr;
3006         char buffer[256];
3007
3008         rad_assert(request != NULL);
3009         rad_assert(request->coa != NULL);
3010         rad_assert(request->proxy == NULL);
3011         rad_assert(!request->in_proxy_hash);
3012         rad_assert(request->proxy_reply == NULL);
3013
3014         /*
3015          *      Check whether we want to originate one, or cancel one.
3016          */
3017         vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3018         if (!vp) {
3019                 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3020         }
3021
3022         if (vp) {
3023                 if (vp->vp_integer == 0) {
3024                 fail:
3025                         request_done(request->coa, FR_ACTION_DONE);
3026                         return;
3027                 }
3028         }
3029
3030         coa = request->coa;
3031
3032         /*
3033          *      src_ipaddr will be set up in proxy_encode.
3034          */
3035         memset(&ipaddr, 0, sizeof(ipaddr));
3036         vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3037         if (vp) {
3038                 ipaddr.af = AF_INET;
3039                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3040
3041         } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3042                 ipaddr.af = AF_INET6;
3043                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3044                 
3045         } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3046                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3047                                                   HOME_TYPE_COA);
3048                 if (!coa->home_pool) {
3049                         RDEBUG2W("No such home_server_pool %s",
3050                                vp->vp_strvalue);
3051                         goto fail;
3052                 }
3053
3054                 /*
3055                  *      Prefer the pool to one server
3056                  */
3057         } else if (request->client->coa_pool) {
3058                 coa->home_pool = request->client->coa_pool;
3059
3060         } else if (request->client->coa_server) {
3061                 coa->home_server = request->client->coa_server;
3062
3063         } else {
3064                 /*
3065                  *      If all else fails, send it to the client that
3066                  *      originated this request.
3067                  */
3068                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3069         }
3070
3071         /*
3072          *      Use the pool, if it exists.
3073          */
3074         if (coa->home_pool) {
3075                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3076                 if (!coa->home_server) {
3077                         RDEBUGW("No live home server for home_server_pool %s", vp->vp_strvalue);
3078                         goto fail;
3079                 }
3080                 home_server_update_request(coa->home_server, coa);
3081
3082         } else if (!coa->home_server) {
3083                 int port = PW_COA_UDP_PORT;
3084
3085                 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3086                 if (vp) port = vp->vp_integer;
3087
3088                 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3089                 if (!coa->home_server) {
3090                         RDEBUG2W("Unknown destination %s:%d for CoA request.",
3091                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3092                                          buffer, sizeof(buffer)), port);
3093                         goto fail;
3094                 }
3095         }
3096
3097         vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3098         if (vp) {
3099                 switch (vp->vp_integer) {
3100                 case PW_COA_REQUEST:
3101                 case PW_DISCONNECT_REQUEST:
3102                         coa->proxy->code = vp->vp_integer;
3103                         break;
3104                         
3105                 default:
3106                         DEBUG("Cannot set CoA Packet-Type to code %d",
3107                               vp->vp_integer);
3108                         goto fail;
3109                 }
3110         }
3111
3112         if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
3113
3114         /*
3115          *      The rest of the server code assumes that
3116          *      request->packet && request->reply exist.  Copy them
3117          *      from the original request.
3118          */
3119         rad_assert(coa->packet != NULL);
3120         rad_assert(coa->packet->vps == NULL);
3121         memcpy(coa->packet, request->packet, sizeof(*request->packet));
3122         coa->packet->vps = paircopy(request->packet->vps);
3123         coa->packet->data = NULL;
3124         rad_assert(coa->reply != NULL);
3125         rad_assert(coa->reply->vps == NULL);
3126         memcpy(coa->reply, request->reply, sizeof(*request->reply));
3127         coa->reply->vps = paircopy(request->reply->vps);
3128         coa->reply->data = NULL;
3129         coa->config_items = paircopy(request->config_items);
3130         coa->num_coa_requests = 0;
3131         coa->handle = null_handler;
3132         coa->number = request->number ^ (1 << 24);
3133
3134         /*
3135          *      Call the pre-proxy routines.
3136          */
3137         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3138         if (vp) {
3139                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
3140                 pre_proxy_type = vp->vp_integer;
3141         }
3142
3143         if (coa->home_pool && coa->home_pool->virtual_server) {
3144                 const char *old_server = coa->server;
3145                 
3146                 coa->server = coa->home_pool->virtual_server;
3147                 RDEBUG2(" server %s {", coa->server);
3148                 rcode = module_pre_proxy(pre_proxy_type, coa);
3149                 RDEBUG2(" }");
3150                 coa->server = old_server;
3151         } else {
3152                 rcode = module_pre_proxy(pre_proxy_type, coa);
3153         }
3154         switch (rcode) {
3155         default:
3156                 goto fail;
3157
3158         /*
3159          *      Only send the CoA packet if the pre-proxy code succeeded.
3160          */
3161         case RLM_MODULE_NOOP:
3162         case RLM_MODULE_OK:
3163         case RLM_MODULE_UPDATED:
3164                 break;
3165         }
3166
3167         /*
3168          *      Source IP / port is set when the proxy socket
3169          *      is chosen.
3170          */
3171         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3172         coa->proxy->dst_port = coa->home_server->port;
3173
3174         if (!insert_into_proxy_hash(coa)) {
3175                 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list.");
3176                 goto fail;
3177         }
3178
3179         /*
3180          *      We CANNOT divorce the CoA request from the parent
3181          *      request.  This function is running in a child thread,
3182          *      and we need access to the main event loop in order to
3183          *      to add the timers for the CoA packet.
3184          *
3185          *      Instead, we wait for the timer on the parent request
3186          *      to fire.
3187          */
3188         gettimeofday(&coa->proxy->timestamp, NULL);
3189         coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3190         coa->delay = 0;         /* need to calculate a new delay */
3191
3192         DEBUG_PACKET(coa, coa->proxy, 1);
3193
3194         coa->process = request_coa_process;
3195 #ifdef DEBUG_STATE_MACHINE
3196         if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_ACTIVE);
3197 #endif
3198         coa->child_state = REQUEST_ACTIVE;
3199         rad_assert(coa->proxy_reply == NULL);
3200         FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3201         coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3202         coa->proxy_listener->send(coa->proxy_listener, coa);
3203 }
3204
3205
3206 static void request_coa_separate(REQUEST *request)
3207 {
3208 #ifdef DEBUG_STATE_MACHINE
3209         int action = FR_ACTION_TIMER;
3210 #endif
3211         TRACE_STATE_MACHINE;
3212
3213         rad_assert(request->parent != NULL);
3214         rad_assert(request->parent->coa == request);
3215         rad_assert(request->ev == NULL);
3216         rad_assert(!request->in_request_hash);
3217
3218         request->parent->coa = NULL;
3219         request->parent = NULL;
3220
3221         /*
3222          *      Set up timers for the CoA request.  These do all kinds
3223          *      of different things....
3224          */
3225         request_coa_timer(request);
3226 }
3227
3228 static void request_coa_timer(REQUEST *request)
3229 {
3230         int delay, frac;
3231         struct timeval now, when, mrd;
3232
3233         rad_assert(request->parent == NULL);
3234
3235         if (request->proxy_reply) return request_process_timer(request);
3236
3237         gettimeofday(&now, NULL);
3238
3239         if (request->delay == 0) {
3240                 /*
3241                  *      Implement re-transmit algorithm as per RFC 5080
3242                  *      Section 2.2.1.
3243                  *
3244                  *      We want IRT + RAND*IRT
3245                  *      or 0.9 IRT + rand(0,.2) IRT
3246                  *
3247                  *      2^20 ~ USEC, and we want 2.
3248                  *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3249                  */
3250                 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3251                 request->delay = delay * request->home_server->coa_irt;
3252                 delay = request->home_server->coa_irt * USEC;
3253                 delay -= delay / 10;
3254                 delay += request->delay;
3255                 request->delay = delay;
3256                 
3257                 when = request->proxy->timestamp;
3258                 tv_add(&when, delay);
3259
3260                 if (timercmp(&when, &now, >)) {
3261                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3262                         return;
3263                 }
3264         }
3265
3266         /*
3267          *      Retransmit CoA request.
3268          */
3269
3270         /*
3271          *      Cap count at MRC, if it is non-zero.
3272          */
3273         if (request->home_server->coa_mrc &&
3274             (request->num_coa_requests >= request->home_server->coa_mrc)) {
3275                 if (!setup_post_proxy_fail(request)) {
3276                         return;
3277                 }
3278                 
3279                 request_queue_or_run(request, proxy_running);
3280                 return;
3281         }
3282
3283         /*
3284          *      RFC 5080 Section 2.2.1
3285          *
3286          *      RT = 2*RTprev + RAND*RTprev
3287          *         = 1.9 * RTprev + rand(0,.2) * RTprev
3288          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3289          */
3290         delay = fr_rand();
3291         delay ^= (delay >> 16);
3292         delay &= 0xffff;
3293         frac = request->delay / 5;
3294         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3295
3296         delay += (2 * request->delay) - (request->delay / 10);
3297
3298         /*
3299          *      Cap delay at MRT, if MRT is non-zero.
3300          */
3301         if (request->home_server->coa_mrt &&
3302             (delay > (request->home_server->coa_mrt * USEC))) {
3303                 int mrt_usec = request->home_server->coa_mrt * USEC;
3304
3305                 /*
3306                  *      delay = MRT + RAND * MRT
3307                  *            = 0.9 MRT + rand(0,.2)  * MRT
3308                  */
3309                 delay = fr_rand();
3310                 delay ^= (delay >> 15);
3311                 delay &= 0x1ffff;
3312                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3313                 delay += mrt_usec - (mrt_usec / 10);
3314         }
3315
3316         request->delay = delay;
3317         when = now;
3318         tv_add(&when, request->delay);
3319         mrd = request->proxy->timestamp;
3320         mrd.tv_sec += request->home_server->coa_mrd;
3321
3322         /*
3323          *      Cap duration at MRD.
3324          */
3325         if (timercmp(&mrd, &when, <)) {
3326                 when = mrd;
3327         }
3328         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3329
3330         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3331
3332         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3333
3334         /*
3335          *      Status servers don't count as real packets sent.
3336          */
3337         request->proxy_listener->send(request->proxy_listener,
3338                                       request);
3339 }
3340
3341
3342 #ifdef HAVE_PTHREAD_H
3343 STATE_MACHINE_DECL(coa_running)
3344 {
3345         TRACE_STATE_MACHINE;
3346
3347         switch (action) {
3348         case FR_ACTION_TIMER:
3349                 request_coa_timer(request);
3350                 break;
3351                
3352         case FR_ACTION_PROXY_REPLY:
3353                 request_common(request, action);
3354                 break;
3355
3356         case FR_ACTION_RUN:
3357                 request_running(request, FR_ACTION_PROXY_REPLY);
3358                 break;
3359
3360         default:
3361                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3362                 break;
3363         }
3364 }
3365 #endif  /* HAVE_PTHREAD_H */
3366
3367
3368 /*
3369  *      Process CoA requests that we originated.
3370  */
3371 STATE_MACHINE_DECL(request_coa_process)
3372 {
3373         TRACE_STATE_MACHINE;
3374
3375         switch (action) {
3376         case FR_ACTION_TIMER:
3377                 request_coa_timer(request);
3378                 break;
3379                 
3380         case FR_ACTION_PROXY_REPLY:
3381                 rad_assert(request->parent == NULL);
3382 #ifdef HAVE_PTHREAD_H
3383                 /*
3384                  *      Catch the case of a proxy reply when called
3385                  *      from the main worker thread.
3386                  */
3387                 if (we_are_master() &&
3388                     (request->process != coa_running)) {
3389                         request_queue_or_run(request, coa_running);
3390                         return;
3391                 }
3392                 /* FALL-THROUGH */
3393 #endif
3394         case FR_ACTION_RUN:
3395                 request_running(request, action);
3396                 break;
3397                 
3398         default:
3399                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3400                 break;
3401         }
3402 }
3403
3404 #endif  /* WITH_COA */
3405
3406 /***********************************************************************
3407  *
3408  *  End of the State machine.  Start of additional helper code.
3409  *
3410  ***********************************************************************/
3411
3412 /***********************************************************************
3413  *
3414  *      Event handlers.
3415  *
3416  ***********************************************************************/
3417 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3418                                  void *ctx)
3419 {
3420         rad_listen_t *listener = ctx;
3421
3422         rad_assert(xel == el);
3423
3424         xel = xel;
3425
3426         if (
3427 #ifdef WITH_DETAIL
3428             (listener->type != RAD_LISTEN_DETAIL) &&
3429 #endif
3430             (listener->fd < 0)) {
3431                 char buffer[256];
3432
3433                 listener->print(listener, buffer, sizeof(buffer));
3434                 radlog(L_ERR, "FATAL: Asked to read from closed socket: %s",
3435                        buffer);
3436         
3437                 rad_panic("Socket was closed on us!");
3438                 _exit(1);
3439         }
3440         
3441         listener->recv(listener);
3442 }
3443
3444 #ifdef WITH_DETAIL
3445 /*
3446  *      This function is called periodically to see if this detail
3447  *      file is available for reading.
3448  */
3449 static void event_poll_detail(void *ctx)
3450 {
3451         int delay;
3452         rad_listen_t *this = ctx;
3453         struct timeval when, now;
3454         listen_detail_t *detail = this->data;
3455
3456         rad_assert(this->type == RAD_LISTEN_DETAIL);
3457
3458  redo:
3459         event_socket_handler(el, this->fd, this);
3460
3461         fr_event_now(el, &now);
3462         when = now;
3463
3464         /*
3465          *      Backdoor API to get the delay until the next poll
3466          *      time.
3467          */
3468         delay = this->encode(this, NULL);
3469         if (delay == 0) goto redo;
3470
3471         tv_add(&when, delay);
3472
3473         if (!fr_event_insert(el, event_poll_detail, this,
3474                              &when, &detail->ev)) {
3475                 radlog(L_ERR, "Failed creating handler");
3476                 exit(1);
3477         }
3478 }
3479 #endif
3480
3481 static void event_status(struct timeval *wake)
3482 {
3483 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3484         int argval;
3485 #endif
3486
3487         if (debug_flag == 0) {
3488                 if (just_started) {
3489                         radlog(L_INFO, "Ready to process requests.");
3490                         just_started = FALSE;
3491                 }
3492                 return;
3493         }
3494
3495         if (!wake) {
3496                 radlog(L_INFO, "Ready to process requests.");
3497
3498         } else if ((wake->tv_sec != 0) ||
3499                    (wake->tv_usec >= 100000)) {
3500                 DEBUG("Waking up in %d.%01u seconds.",
3501                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3502         }
3503
3504
3505         /*
3506          *      FIXME: Put this somewhere else, where it isn't called
3507          *      all of the time...
3508          */
3509
3510 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3511         /*
3512          *      If there are no child threads, then there may
3513          *      be child processes.  In that case, wait for
3514          *      their exit status, and throw that exit status
3515          *      away.  This helps get rid of zxombie children.
3516          */
3517         while (waitpid(-1, &argval, WNOHANG) > 0) {
3518                 /* do nothing */
3519         }
3520 #endif
3521
3522 }
3523
3524
3525 int event_new_fd(rad_listen_t *this)
3526 {
3527         char buffer[1024];
3528
3529         if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
3530
3531         this->print(this, buffer, sizeof(buffer));
3532
3533         if (this->status == RAD_LISTEN_STATUS_INIT) {
3534                 listen_socket_t *sock = this->data;
3535
3536                 if (just_started) {
3537                         DEBUG("Listening on %s", buffer);
3538                 } else {
3539                         radlog(L_INFO, " ... adding new socket %s", buffer);
3540                 }
3541
3542 #ifdef WITH_PROXY
3543                 /*
3544                  *      Add it to the list of sockets we can use.
3545                  *      Server sockets (i.e. auth/acct) are never
3546                  *      added to the packet list.
3547                  */
3548                 if (this->type == RAD_LISTEN_PROXY) {
3549                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3550                         if (!fr_packet_list_socket_add(proxy_list, this->fd,
3551                                                        sock->proto,
3552                                                        &sock->other_ipaddr, sock->other_port,
3553                                                        this)) {
3554
3555 #ifdef HAVE_PTHREAD_H
3556                                 proxy_no_new_sockets = TRUE;
3557 #endif
3558                                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3559
3560                                 /*
3561                                  *      This is bad.  However, the
3562                                  *      packet list now supports 256
3563                                  *      open sockets, which should
3564                                  *      minimize this problem.
3565                                  */
3566                                 radlog(L_ERR, "Failed adding proxy socket: %s",
3567                                        fr_strerror());
3568                                 return 0;
3569                         }
3570
3571                         if (sock->home) {
3572                                 sock->home->limit.num_connections++;
3573                                 
3574 #ifdef HAVE_PTHREAD_H
3575                                 /*
3576                                  *      If necessary, add it to the list of
3577                                  *      new proxy listeners.
3578                                  */
3579                                 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3580                                         this->next = proxy_listener_list;
3581                                         proxy_listener_list = this;
3582                                 }
3583 #endif
3584                         }
3585                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3586
3587                         /*
3588                          *      Tell the main thread that we've added
3589                          *      a proxy listener, but only if we need
3590                          *      to update the event list.  Do this
3591                          *      with the mutex unlocked, to reduce
3592                          *      contention.
3593                          */
3594                         if (sock->home) {
3595                                 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3596                                         radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3597                                 }
3598                         }
3599                 }
3600 #endif          
3601
3602 #ifdef WITH_DETAIL
3603                 /*
3604                  *      Detail files are always known, and aren't
3605                  *      put into the socket event loop.
3606                  */
3607                 if (this->type == RAD_LISTEN_DETAIL) {
3608                         this->status = RAD_LISTEN_STATUS_KNOWN;
3609                         
3610                         /*
3611                          *      Set up the first poll interval.
3612                          */
3613                         event_poll_detail(this);
3614                         return 1;
3615                 }
3616 #endif
3617
3618 #ifdef WITH_TCP
3619                 /*
3620                  *      Add timers to child sockets, if necessary.
3621                  */
3622                 if (sock->proto == IPPROTO_TCP && sock->opened &&
3623                     (sock->limit.lifetime || sock->limit.idle_timeout)) {
3624                         struct timeval when;
3625
3626                         ASSERT_MASTER;
3627
3628                         when.tv_sec = sock->opened + 1;
3629                         when.tv_usec = 0;
3630
3631                         if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3632                                              &(sock->ev))) {
3633                                 rad_panic("Failed to insert event");
3634                         }
3635                 }
3636 #endif
3637
3638                 FD_MUTEX_LOCK(&fd_mutex);
3639                 if (!fr_event_fd_insert(el, 0, this->fd,
3640                                         event_socket_handler, this)) {
3641                         radlog(L_ERR, "Failed adding event handler for socket!");
3642                         exit(1);
3643                 }
3644                 FD_MUTEX_UNLOCK(&fd_mutex);
3645                 
3646                 this->status = RAD_LISTEN_STATUS_KNOWN;
3647                 return 1;
3648         }
3649
3650         /*
3651          *      Something went wrong with the socket: make it harmless.
3652          */
3653         if (this->status == RAD_LISTEN_STATUS_REMOVE_FD) {
3654                 int devnull;
3655
3656                 /*
3657                  *      Remove it from the list of live FD's.
3658                  */
3659                 FD_MUTEX_LOCK(&fd_mutex);
3660                 fr_event_fd_delete(el, 0, this->fd);
3661                 FD_MUTEX_UNLOCK(&fd_mutex);
3662
3663 #ifdef WITH_TCP
3664                 /*
3665                  *      We track requests using this socket only for
3666                  *      TCP.  For UDP, we don't currently close
3667                  *      sockets.
3668                  */
3669 #ifdef WITH_PROXY
3670                 if (this->type != RAD_LISTEN_PROXY)
3671 #endif
3672                 {
3673                         if (this->count != 0) {
3674                                 fr_packet_list_walk(pl, this,
3675                                                     remove_all_requests);
3676                         }
3677
3678                         if (this->count == 0) {
3679                                 this->status = RAD_LISTEN_STATUS_FINISH;
3680                                 goto finish;
3681                         }
3682                 }               
3683 #ifdef WITH_PROXY
3684                 else {
3685                         int count;
3686
3687                         /*
3688                          *      Duplicate code
3689                          */
3690                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3691                         if (!fr_packet_list_socket_freeze(proxy_list,
3692                                                           this->fd)) {
3693                                 radlog(L_ERR, "Fatal error freezing socket: %s",
3694                                        fr_strerror());
3695                                 exit(1);
3696                         }
3697
3698                         /*
3699                          *      Doing this with the proxy mutex held
3700                          *      is a Bad Thing.  We should move to
3701                          *      finer-grained mutexes.
3702                          */
3703                         count = this->count;
3704                         if (count > 0) {
3705                                 fr_packet_list_walk(proxy_list, this,
3706                                                     disconnect_all_proxied_requests);
3707                         }
3708                         count = this->count; /* protected by mutex */
3709                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3710
3711                         if (count == 0) {
3712                                 this->status = RAD_LISTEN_STATUS_FINISH;
3713                                 goto finish;
3714                         }
3715                 }
3716 #endif  /* WITH_PROXY */
3717 #endif  /* WITH_TCP */
3718
3719                 /*
3720                  *      Re-open the socket, pointing it to /dev/null.
3721                  *      This means that all writes proceed without
3722                  *      blocking, and all reads return "no data".
3723                  *
3724                  *      This leaves the socket active, so any child
3725                  *      threads won't go insane.  But it means that
3726                  *      they cannot send or receive any packets.
3727                  *
3728                  *      This is EXTRA work in the normal case, when
3729                  *      sockets are closed without error.  But it lets
3730                  *      us have one simple processing method for all
3731                  *      sockets.
3732                  */
3733                 devnull = open("/dev/null", O_RDWR);
3734                 if (devnull < 0) {
3735                         radlog(L_ERR, "FATAL failure opening /dev/null: %s",
3736                                strerror(errno));
3737                         exit(1);
3738                 }
3739                 if (dup2(devnull, this->fd) < 0) {
3740                         radlog(L_ERR, "FATAL failure closing socket: %s",
3741                                strerror(errno));
3742                         exit(1);
3743                 }
3744                 close(devnull);
3745
3746                 this->status = RAD_LISTEN_STATUS_CLOSED;
3747
3748                 /*
3749                  *      Fall through to the next section.
3750                  */
3751         }
3752
3753 #ifdef WITH_TCP
3754         /*
3755          *      Called ONLY from the main thread.  On the following
3756          *      conditions:
3757          *
3758          *      idle timeout
3759          *      max lifetime
3760          *
3761          *      (and falling through from "forcibly close FD" above)
3762          *      client closed connection on us
3763          *      client sent us a bad packet.
3764          */
3765         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3766                 int count = this->count;
3767
3768 #ifdef WITH_DETAIL
3769                 rad_assert(this->type != RAD_LISTEN_DETAIL);
3770 #endif
3771
3772 #ifdef WITH_PROXY
3773                 /*
3774                  *      Remove it from the list of active sockets, so
3775                  *      that it isn't used when proxying new packets.
3776                  */
3777                 if (this->type == RAD_LISTEN_PROXY) {
3778                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3779                         if (!fr_packet_list_socket_freeze(proxy_list,
3780                                                           this->fd)) {
3781                                 radlog(L_ERR, "Fatal error freezing socket: %s",
3782                                        fr_strerror());
3783                                 exit(1);
3784                         }
3785                         count = this->count; /* protected by mutex */
3786                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3787                 }
3788 #endif
3789
3790                 /*
3791                  *      Requests are still using the socket.  Wait for
3792                  *      them to finish.
3793                  */
3794                 if (count != 0) {
3795                         struct timeval when;
3796                         listen_socket_t *sock = this->data;
3797
3798                         /*
3799                          *      Try again to clean up the socket in 30
3800                          *      seconds.
3801                          */
3802                         gettimeofday(&when, NULL);
3803                         when.tv_sec += 30;
3804                         
3805                         if (!fr_event_insert(el,
3806                                              (fr_event_callback_t) event_new_fd,
3807                                              this, &when, &sock->ev)) {
3808                                 rad_panic("Failed to insert event");
3809                         }
3810                        
3811                         return 1;
3812                 }
3813
3814                 /*
3815                  *      No one is using this socket: we can delete it
3816                  *      immediately.
3817                  */
3818                 this->status = RAD_LISTEN_STATUS_FINISH;
3819         }
3820         
3821 finish:
3822         if (this->status == RAD_LISTEN_STATUS_FINISH) {
3823                 listen_socket_t *sock = this->data;
3824
3825                 rad_assert(this->count == 0);
3826                 radlog(L_INFO, " ... closing socket %s", buffer);
3827
3828                 /*
3829                  *      Remove it from the list of live FD's.  Note
3830                  *      that it MAY also have been removed above.  We
3831                  *      do it again here, to catch the case of sockets
3832                  *      closing on idle timeout, or max
3833                  *      lifetime... AFTER all requests have finished
3834                  *      using it.
3835                  */
3836                 FD_MUTEX_LOCK(&fd_mutex);
3837                 fr_event_fd_delete(el, 0, this->fd);
3838                 FD_MUTEX_UNLOCK(&fd_mutex);
3839                 
3840 #ifdef WITH_PROXY
3841                 /*
3842                  *      Remove it from the list of sockets to be used
3843                  *      when proxying.
3844                  */
3845                 if (this->type == RAD_LISTEN_PROXY) {
3846                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3847                         if (!fr_packet_list_socket_remove(proxy_list,
3848                                                           this->fd, NULL)) {
3849                                 radlog(L_ERR, "Fatal error removing socket: %s",
3850                                        fr_strerror());
3851                                 exit(1);
3852                         }
3853                         if (sock->home) sock->home->limit.num_connections--;
3854                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3855                 }
3856 #endif
3857
3858                 /*
3859                  *      Remove any pending cleanups.
3860                  */
3861                 if (sock->ev) fr_event_delete(el, &sock->ev);
3862
3863                 /*
3864                  *      And finally, close the socket.
3865                  */
3866                 listen_free(&this);
3867         }
3868 #endif  /* WITH_TCP */
3869
3870         return 1;
3871 }
3872
3873 /***********************************************************************
3874  *
3875  *      Signal handlers.
3876  *
3877  ***********************************************************************/
3878
3879 static void handle_signal_self(int flag)
3880 {
3881         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3882                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3883                         radlog(L_INFO, "Signalled to exit");
3884                         fr_event_loop_exit(el, 1);
3885                 } else {
3886                         radlog(L_INFO, "Signalled to terminate");
3887                         exec_trigger(NULL, NULL, "server.signal.term", TRUE);
3888                         fr_event_loop_exit(el, 2);
3889                 }
3890
3891                 return;
3892         } /* else exit/term flags weren't set */
3893
3894         /*
3895          *      Tell the even loop to stop processing.
3896          */
3897         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3898                 time_t when;
3899                 static time_t last_hup = 0;
3900
3901                 when = time(NULL);
3902                 if ((int) (when - last_hup) < 5) {
3903                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3904                         return;
3905                 }
3906
3907                 radlog(L_INFO, "Received HUP signal.");
3908
3909                 last_hup = when;
3910
3911                 exec_trigger(NULL, NULL, "server.signal.hup", TRUE);
3912                 fr_event_loop_exit(el, 0x80);
3913         }
3914
3915 #ifdef WITH_DETAIL
3916         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3917                 rad_listen_t *this;
3918                 
3919                 /*
3920                  *      FIXME: O(N) loops suck.
3921                  */
3922                 for (this = mainconfig.listen;
3923                      this != NULL;
3924                      this = this->next) {
3925                         if (this->type != RAD_LISTEN_DETAIL) continue;
3926
3927                         /*
3928                          *      This one didn't send the signal, skip
3929                          *      it.
3930                          */
3931                         if (!this->decode(this, NULL)) continue;
3932
3933                         /*
3934                          *      Go service the interrupt.
3935                          */
3936                         event_poll_detail(this);
3937                 }
3938         }
3939 #endif
3940
3941 #ifdef WITH_TCP
3942 #ifdef WITH_PROXY
3943 #ifdef HAVE_PTHREAD_H
3944         /*
3945          *      Add event handlers for idle timeouts && maximum lifetime.
3946          */
3947         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3948                 struct timeval when, now;
3949
3950                 fr_event_now(el, &now);
3951
3952                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3953
3954                 while (proxy_listener_list) {
3955                         rad_listen_t *this = proxy_listener_list;
3956                         listen_socket_t *sock = this->data;
3957
3958                         rad_assert(sock->proto == IPPROTO_TCP);
3959                         proxy_listener_list = this->next;
3960                         this->next = NULL;
3961
3962                         if (!sock->home) continue; /* skip UDP sockets */
3963
3964                         when = now;
3965
3966                         /*
3967                          *      Sockets should only be added to the
3968                          *      proxy_listener_list if they have limits.
3969                          *      
3970                          */
3971                         rad_assert(sock->home->limit.lifetime || sock->home->limit.idle_timeout);
3972
3973                         if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3974                                              &(sock->ev))) {
3975                                 rad_panic("Failed to insert event");
3976                         }
3977                 }
3978
3979                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3980         }
3981 #endif  /* HAVE_PTHREAD_H */
3982 #endif  /* WITH_PROXY */
3983 #endif  /* WITH_TCP */
3984 }
3985
3986 #ifndef WITH_SELF_PIPE
3987 void radius_signal_self(int flag)
3988 {
3989         handle_signal_self(flag);
3990 }
3991 #else
3992 /*
3993  *      Inform ourselves that we received a signal.
3994  */
3995 void radius_signal_self(int flag)
3996 {
3997         ssize_t rcode;
3998         uint8_t buffer[16];
3999
4000         /*
4001          *      The read MUST be non-blocking for this to work.
4002          */
4003         rcode = read(self_pipe[0], buffer, sizeof(buffer));
4004         if (rcode > 0) {
4005                 ssize_t i;
4006
4007                 for (i = 0; i < rcode; i++) {
4008                         buffer[0] |= buffer[i];
4009                 }
4010         } else {
4011                 buffer[0] = 0;
4012         }
4013
4014         buffer[0] |= flag;
4015
4016         write(self_pipe[1], buffer, 1);
4017 }
4018
4019
4020 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4021                                  UNUSED int fd, UNUSED void *ctx)
4022 {
4023         ssize_t i, rcode;
4024         uint8_t buffer[32];
4025
4026         rcode = read(self_pipe[0], buffer, sizeof(buffer));
4027         if (rcode <= 0) return;
4028
4029         /*
4030          *      Merge pending signals.
4031          */
4032         for (i = 0; i < rcode; i++) {
4033                 buffer[0] |= buffer[i];
4034         }
4035
4036         handle_signal_self(buffer[0]);
4037 }
4038 #endif
4039
4040 /***********************************************************************
4041  *
4042  *      Bootstrapping code.
4043  *
4044  ***********************************************************************/
4045
4046 /*
4047  *      Externally-visibly functions.
4048  */
4049 int radius_event_init(CONF_SECTION *cs, int have_children)
4050 {
4051         rad_listen_t *head = NULL;
4052
4053         if (el) return 0;
4054
4055         time(&fr_start_time);
4056
4057         el = fr_event_list_create(event_status);
4058         if (!el) return 0;
4059
4060         pl = fr_packet_list_create(0);
4061         if (!pl) return 0;      /* leak el */
4062
4063         request_num_counter = 0;
4064
4065 #ifdef WITH_PROXY
4066         if (mainconfig.proxy_requests) {
4067                 /*
4068                  *      Create the tree for managing proxied requests and
4069                  *      responses.
4070                  */
4071                 proxy_list = fr_packet_list_create(1);
4072                 if (!proxy_list) return 0;
4073
4074 #ifdef HAVE_PTHREAD_H
4075                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4076                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
4077                                strerror(errno));
4078                         exit(1);
4079                 }
4080 #endif
4081         }
4082 #endif
4083
4084 #ifdef HAVE_PTHREAD_H
4085         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4086
4087         /*
4088          *      Initialize the threads ONLY if we're spawning, AND
4089          *      we're running normally.
4090          */
4091         if (have_children && !check_config &&
4092             (thread_pool_init(cs, &have_children) < 0)) {
4093                 exit(1);
4094         }
4095 #endif
4096
4097         /*
4098          *      Move all of the thread calls to this file?
4099          *
4100          *      It may be best for the mutexes to be in this file...
4101          */
4102         spawn_flag = have_children;
4103
4104         if (check_config) {
4105                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4106                        mainconfig.name);
4107                 if (listen_init(cs, &head, spawn_flag) < 0) {
4108                         fflush(NULL);
4109                         exit(1);
4110                 }
4111                 return 1;
4112         }
4113
4114 #ifdef WITH_SELF_PIPE
4115         /*
4116          *      Child threads need a pipe to signal us, as do the
4117          *      signal handlers.
4118          */
4119         if (pipe(self_pipe) < 0) {
4120                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
4121                        strerror(errno));
4122                 exit(1);
4123         }
4124         if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4125             (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4126                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
4127                        strerror(errno));
4128                 exit(1);
4129         }
4130         if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4131             (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4132                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
4133                        strerror(errno));
4134                 exit(1);
4135         }
4136
4137         if (!fr_event_fd_insert(el, 0, self_pipe[0],
4138                                   event_signal_handler, el)) {
4139                 radlog(L_ERR, "Failed creating handler for signals");
4140                 exit(1);
4141         }
4142 #endif  /* WITH_SELF_PIPE */
4143
4144        DEBUG("%s: #### Opening IP addresses and Ports ####",
4145                mainconfig.name);
4146
4147        /*
4148         *       The server temporarily switches to an unprivileged
4149         *       user very early in the bootstrapping process.
4150         *       However, some sockets MAY require privileged access
4151         *       (bind to device, or to port < 1024, or to raw
4152         *       sockets).  Those sockets need to call suid up/down
4153         *       themselves around the functions that need a privileged
4154         *       uid.
4155         */
4156        if (listen_init(cs, &head, spawn_flag) < 0) {
4157                 _exit(1);
4158         }
4159         
4160         mainconfig.listen = head;
4161
4162         /*
4163          *      At this point, no one has any business *ever* going
4164          *      back to root uid.
4165          */
4166         fr_suid_down_permanent();
4167
4168         return 1;
4169 }
4170
4171
4172 static int request_hash_cb(UNUSED void *ctx, void *data)
4173 {
4174         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4175
4176 #ifdef WITH_PROXY
4177         rad_assert(request->in_proxy_hash == FALSE);
4178 #endif
4179
4180         request_done(request, FR_ACTION_DONE);
4181
4182         return 0;
4183 }
4184
4185
4186 #ifdef WITH_PROXY
4187 static int proxy_hash_cb(UNUSED void *ctx, void *data)
4188 {
4189         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4190
4191         request_done(request, FR_ACTION_DONE);
4192
4193         return 0;
4194 }
4195 #endif
4196
4197 void radius_event_free(void)
4198 {
4199         /*
4200          *      Stop and join all threads.
4201          */
4202 #ifdef HAVE_PTHREAD_H
4203         thread_pool_stop();
4204 #endif
4205
4206 #ifdef WITH_PROXY
4207         /*
4208          *      There are requests in the proxy hash that aren't
4209          *      referenced from anywhere else.  Remove them first.
4210          */
4211         if (proxy_list) {
4212                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
4213                 fr_packet_list_free(proxy_list);
4214                 proxy_list = NULL;
4215         }
4216 #endif
4217
4218         fr_packet_list_walk(pl, NULL, request_hash_cb);
4219
4220         fr_packet_list_free(pl);
4221         pl = NULL;
4222
4223         fr_event_list_free(el);
4224 }
4225
4226 int radius_event_process(void)
4227 {
4228         if (!el) return 0;
4229
4230         return fr_event_loop(el);
4231 }