Put state name into request->component
[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 RCSID("$Id$")
28
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
33
34 #include <freeradius-devel/rad_assert.h>
35
36 #ifdef WITH_DETAIL
37 #include <freeradius-devel/detail.h>
38 #endif
39
40 #include <signal.h>
41 #include <fcntl.h>
42
43 #ifdef HAVE_SYS_WAIT_H
44 #       include <sys/wait.h>
45 #endif
46
47 extern pid_t radius_pid;
48 extern fr_cond_t *debug_condition;
49
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static rbtree_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
55
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57         /* Currently we do not run a second event loop for modules. */
58         return el;
59 }
60
61 static char const *action_codes[] = {
62         "INVALID",
63         "run",
64         "done",
65         "dup",
66         "timer",
67 #ifdef WITH_PROXY
68         "proxy-reply"
69 #endif
70 };
71
72 #ifdef DEBUG_STATE_MACHINE
73 #  define TRACE_STATE_MACHINE \
74 if (rad_debug_lvl) do { \
75         struct timeval debug_tv; \
76         gettimeofday(&debug_tv, NULL); \
77         debug_tv.tv_sec -= fr_start_time; \
78         printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79                request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80                __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81                child_state_names[request->child_state]); \
82 } while (0)
83
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
85         "?",
86         "active",
87         "stop-processing",
88         "counted"
89 };
90
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
92         "?",
93         "queued",
94         "running",
95         "proxied",
96         "reject-delay",
97         "cleanup-delay",
98         "done"
99 };
100
101 #else
102 #  define TRACE_STATE_MACHINE {}
103 #endif
104
105 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
106 {
107         ERROR("%s[%u]: %s", file, line, msg);
108         fr_exit_now(1);
109 }
110
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
112
113 /** Declare a state in the state machine
114  *
115  * Expands to the start of a function definition for a given state.
116  *
117  * @param _x the name of the state.
118  */
119 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
120
121 static void request_timer(void *ctx);
122
123 /** Insert #REQUEST back into the event heap, to continue executing at a future time
124  *
125  * @param file the state machine timer call occurred in.
126  * @param line the state machine timer call occurred on.
127  * @param request to set add the timer event for.
128  * @param when the event should fine.
129  * @param action to perform when we resume processing the request.
130  */
131 static inline void state_machine_timer(char const *file, int line, REQUEST *request,
132                                        struct timeval *when, fr_state_action_t action)
133 {
134         request->timer_action = action;
135         if (!fr_event_insert(el, request_timer, request, when, &request->ev)) {
136                 _rad_panic(file, line, "Failed to insert event");
137         }
138 }
139
140 /** @copybrief state_machine_timer
141  *
142  * @param _x the action to perform when we resume processing the request.
143  */
144 #define STATE_MACHINE_TIMER(_x) state_machine_timer(__FILE__, __LINE__, request, &when, _x)
145
146 /*
147  *      We need a different VERIFY_REQUEST macro in process.c
148  *      To avoid the race conditions with the master thread
149  *      checking the REQUEST whilst it's being worked on by
150  *      the child.
151  */
152 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
153 #  undef VERIFY_REQUEST
154 #  define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
155 #endif
156
157 /**
158  * @section request_timeline
159  *
160  *      Time sequence of a request
161  * @code
162  *
163  *      RQ-----------------P=============================Y-J-C
164  *       ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
165  * @endcode
166  *
167  * -    R: received.  Duplicate detection is done, and request is
168  *         cached.
169  *
170  * -    Q: Request is placed onto a queue for child threads to pick up.
171  *         If there are no child threads, the request goes immediately
172  *         to P.
173  *
174  * -    P: Processing the request through the modules.
175  *
176  * -    Y: Reply is ready.  Rejects MAY be delayed here.  All other
177  *         replies are sent immediately.
178  *
179  * -    J: Reject is sent "response_delay" after the reply is ready.
180  *
181  * -    C: For Access-Requests, After "cleanup_delay", the request is
182  *         deleted.  Accounting-Request packets go directly from Y to C.
183  *
184  * -    M: Max request time.  If the request hits this timer, it is
185  *         forcibly stopped.
186  *
187  *      Other considerations include duplicate and conflicting
188  *      packets.  When a dupicate packet is received, it is ignored
189  *      until we've reached Y, as no response is ready.  If the reply
190  *      is a reject, duplicates are ignored until J, when we're ready
191  *      to send the reply.  In between the reply being sent (Y or J),
192  *      and C, the server responds to duplicates by sending the cached
193  *      reply.
194  *
195  *      Conflicting packets are sent in 2 situations.
196  *
197  *      The first is in between R and Y.  In that case, we consider
198  *      it as a hint that we're taking too long, and the NAS has given
199  *      up on the request.  We then behave just as if the M timer was
200  *      reached, and we discard the current request.  This allows us
201  *      to process the new one.
202  *
203  *      The second case is when we're at Y, but we haven't yet
204  *      finished processing the request.  This is a race condition in
205  *      the threading code (avoiding locks is faster).  It means that
206  *      a thread has actually encoded and sent the reply, and that the
207  *      NAS has responded with a new packet.  The server can then
208  *      safely mark the current request as "OK to delete", and behaves
209  *      just as if the M timer was reached.  This usually happens only
210  *      in high-load situations.
211  *
212  *      Duplicate packets are sent when the NAS thinks we're taking
213  *      too long, and wants a reply.  From R-Y, duplicates are
214  *      ignored.  From Y-J (for Access-Rejects), duplicates are also
215  *      ignored.  From Y-C, duplicates get a duplicate reply.  *And*,
216  *      they cause the "cleanup_delay" time to be extended.  This
217  *      extension means that we're more likely to send a duplicate
218  *      reply (if we have one), or to suppress processing the packet
219  *      twice if we didn't reply to it.
220  *
221  *      All functions in this file should be thread-safe, and should
222  *      assume thet the REQUEST structure is being accessed
223  *      simultaneously by the main thread, and by the child worker
224  *      threads.  This means that timers, etc. cannot be updated in
225  *      the child thread.
226  *
227  *      Instead, the master thread periodically calls request->process
228  *      with action TIMER.  It's up to the individual functions to
229  *      determine how to handle that.  They need to check if they're
230  *      being called from a child thread or the master, and then do
231  *      different things based on that.
232  */
233 #ifdef WITH_PROXY
234 static fr_packet_list_t *proxy_list = NULL;
235 static TALLOC_CTX *proxy_ctx = NULL;
236 #endif
237
238 #ifdef HAVE_PTHREAD_H
239 #  ifdef WITH_PROXY
240 static pthread_mutex_t proxy_mutex;
241 static bool proxy_no_new_sockets = false;
242 #  endif
243
244 #  define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
245 #  define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
246
247 static pthread_t NO_SUCH_CHILD_PID;
248 #  define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
249
250 #else
251 /*
252  *      This is easier than ifdef's throughout the code.
253  */
254 #  define PTHREAD_MUTEX_LOCK(_x)
255 #  define PTHREAD_MUTEX_UNLOCK(_x)
256 #  define NO_CHILD_THREAD
257 #endif
258
259 #ifdef HAVE_PTHREAD_H
260 static bool we_are_master(void)
261 {
262         if (spawn_flag &&
263             (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
264                 return false;
265         }
266
267         return true;
268 }
269
270 /*
271  *      Assertions are debug checks.
272  */
273 #  ifndef NDEBUG
274 #    define ASSERT_MASTER       if (!we_are_master()) rad_panic("We are not master")
275 #    endif
276 #else
277
278 /*
279  *      No threads: we're always master.
280  */
281 #  define we_are_master(_x) (1)
282 #endif  /* HAVE_PTHREAD_H */
283
284 #ifndef ASSERT_MASTER
285 #  define ASSERT_MASTER
286 #endif
287
288 /*
289  *      Make state transitions simpler.
290  */
291 #define FINAL_STATE(_x) NO_CHILD_THREAD; request->component = "<" #_x ">"; request->module = ""; request->child_state = _x
292
293
294 static int event_new_fd(rad_listen_t *this);
295
296 /*
297  *      We need mutexes around the event FD list *only* in certain
298  *      cases.
299  */
300 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
301 static rad_listen_t *new_listeners = NULL;
302
303 static pthread_mutex_t  fd_mutex;
304 #  define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
305 #  define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
306
307 void radius_update_listener(rad_listen_t *this)
308 {
309         /*
310          *      Just do it ourselves.
311          */
312         if (we_are_master()) {
313                 event_new_fd(this);
314                 return;
315         }
316
317         FD_MUTEX_LOCK(&fd_mutex);
318
319         /*
320          *      If it's already in the list, don't add it again.
321          */
322         if (this->next) {
323                 FD_MUTEX_UNLOCK(&fd_mutex);
324                 return;
325         }
326
327         /*
328          *      Otherwise, add it to the list
329          */
330         this->next = new_listeners;
331         new_listeners = this;
332         FD_MUTEX_UNLOCK(&fd_mutex);
333         radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
334 }
335 #else
336 void radius_update_listener(rad_listen_t *this)
337 {
338         /*
339          *      No threads.  Just insert it.
340          */
341         event_new_fd(this);
342 }
343 /*
344  *      This is easier than ifdef's throughout the code.
345  */
346 #  define FD_MUTEX_LOCK(_x)
347 #  define FD_MUTEX_UNLOCK(_x)
348 #endif
349
350 static int request_num_counter = 1;
351 #ifdef WITH_PROXY
352 static int request_will_proxy(REQUEST *request) CC_HINT(nonnull);
353 static int request_proxy(REQUEST *request, int retransmit) CC_HINT(nonnull);
354 STATE_MACHINE_DECL(request_ping) CC_HINT(nonnull);
355
356 STATE_MACHINE_DECL(request_response_delay) CC_HINT(nonnull);
357 STATE_MACHINE_DECL(request_cleanup_delay) CC_HINT(nonnull);
358 STATE_MACHINE_DECL(request_running) CC_HINT(nonnull);
359 STATE_MACHINE_DECL(request_done) CC_HINT(nonnull);
360
361 STATE_MACHINE_DECL(proxy_no_reply) CC_HINT(nonnull);
362 STATE_MACHINE_DECL(proxy_running) CC_HINT(nonnull);
363 STATE_MACHINE_DECL(proxy_wait_for_reply) CC_HINT(nonnull);
364
365 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply) CC_HINT(nonnull (1));
366 static void remove_from_proxy_hash(REQUEST *request) CC_HINT(nonnull);
367 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank) CC_HINT(nonnull);
368 static int insert_into_proxy_hash(REQUEST *request) CC_HINT(nonnull);
369 #endif
370
371 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
372                               RADCLIENT *client, RAD_REQUEST_FUNP fun);
373 static int request_pre_handler(REQUEST *request, UNUSED int action) CC_HINT(nonnull);
374
375 #ifdef WITH_COA
376 static void request_coa_originate(REQUEST *request) CC_HINT(nonnull);
377 STATE_MACHINE_DECL(coa_wait_for_reply) CC_HINT(nonnull);
378 STATE_MACHINE_DECL(coa_no_reply) CC_HINT(nonnull);
379 STATE_MACHINE_DECL(coa_running) CC_HINT(nonnull);
380 static void coa_separate(REQUEST *request) CC_HINT(nonnull);
381 #  define COA_SEPARATE if (request->coa) coa_separate(request->coa);
382 #else
383 #  define COA_SEPARATE
384 #endif
385
386 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
387
388 #undef USEC
389 #define USEC (1000000)
390
391 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
392
393 static void tv_add(struct timeval *tv, int usec_delay)
394 {
395         if (usec_delay >= USEC) {
396                 tv->tv_sec += usec_delay / USEC;
397                 usec_delay %= USEC;
398         }
399         tv->tv_usec += usec_delay;
400
401         if (tv->tv_usec >= USEC) {
402                 tv->tv_sec += tv->tv_usec / USEC;
403                 tv->tv_usec %= USEC;
404         }
405 }
406
407 /*
408  *      Debug the packet if requested.
409  */
410 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
411 {
412         char src_ipaddr[128];
413         char dst_ipaddr[128];
414
415         if (!packet) return;
416         if (!RDEBUG_ENABLED) return;
417
418         /*
419          *      Client-specific debugging re-prints the input
420          *      packet into the client log.
421          *
422          *      This really belongs in a utility library
423          */
424         if (is_radius_code(packet->code)) {
425                 RDEBUG("%s %s Id %i from %s%s%s:%i to %s%s%s:%i length %zu",
426                        received ? "Received" : "Sent",
427                        fr_packet_codes[packet->code],
428                        packet->id,
429                        packet->src_ipaddr.af == AF_INET6 ? "[" : "",
430                        inet_ntop(packet->src_ipaddr.af,
431                                  &packet->src_ipaddr.ipaddr,
432                                  src_ipaddr, sizeof(src_ipaddr)),
433                        packet->src_ipaddr.af == AF_INET6 ? "]" : "",
434                        packet->src_port,
435                        packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
436                        inet_ntop(packet->dst_ipaddr.af,
437                                  &packet->dst_ipaddr.ipaddr,
438                                  dst_ipaddr, sizeof(dst_ipaddr)),
439                        packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
440                        packet->dst_port,
441                        packet->data_len);
442         } else {
443                 RDEBUG("%s code %u Id %i from %s%s%s:%i to %s%s%s:%i length %zu\n",
444                        received ? "Received" : "Sent",
445                        packet->code,
446                        packet->id,
447                        packet->src_ipaddr.af == AF_INET6 ? "[" : "",
448                        inet_ntop(packet->src_ipaddr.af,
449                                  &packet->src_ipaddr.ipaddr,
450                                  src_ipaddr, sizeof(src_ipaddr)),
451                        packet->src_ipaddr.af == AF_INET6 ? "]" : "",
452                        packet->src_port,
453                        packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
454                        inet_ntop(packet->dst_ipaddr.af,
455                                  &packet->dst_ipaddr.ipaddr,
456                                  dst_ipaddr, sizeof(dst_ipaddr)),
457                        packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
458                        packet->dst_port,
459                        packet->data_len);
460         }
461
462         if (received) {
463                 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
464         } else {
465                 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
466         }
467 }
468
469
470 /***********************************************************************
471  *
472  *      Start of RADIUS server state machine.
473  *
474  ***********************************************************************/
475
476 static struct timeval *request_response_window(REQUEST *request)
477 {
478         VERIFY_REQUEST(request);
479
480         if (request->client) {
481                 /*
482                  *      The client hasn't set the response window.  Return
483                  *      either the home server one, if set, or the global one.
484                  */
485                 if (!timerisset(&request->client->response_window)) {
486                         return &request->home_server->response_window;
487                 }
488
489                 if (timercmp(&request->client->response_window,
490                              &request->home_server->response_window, <)) {
491                         return &request->client->response_window;
492                 }
493         }
494
495         rad_assert(request->home_server != NULL);
496         return &request->home_server->response_window;
497 }
498
499 /*
500  * Determine initial request processing delay.
501  */
502 static int request_init_delay(REQUEST *request)
503 {
504         struct timeval half_response_window;
505
506         VERIFY_REQUEST(request);
507
508         /* Allow client response window to lower initial delay */
509         if (timerisset(&request->client->response_window)) {
510                 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
511                 half_response_window.tv_usec =
512                         ((request->client->response_window.tv_sec & 1) * USEC +
513                                 request->client->response_window.tv_usec) >> 1;
514                 if (timercmp(&half_response_window, &request->root->init_delay, <))
515                         return (int)half_response_window.tv_sec * USEC +
516                                 (int)half_response_window.tv_usec;
517         }
518
519         return (int)request->root->init_delay.tv_sec * USEC +
520                 (int)request->root->init_delay.tv_usec;
521 }
522
523 /*
524  *      Callback for ALL timer events related to the request.
525  */
526 static void request_timer(void *ctx)
527 {
528         REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
529         int action;
530
531         action = request->timer_action;
532
533         TRACE_STATE_MACHINE;
534
535         request->process(request, action);
536 }
537
538 /*
539  *      Wrapper for talloc pools.  If there's no parent, just free the
540  *      request.  If there is a parent, free the parent INSTEAD of the
541  *      request.
542  */
543 static void request_free(REQUEST *request)
544 {
545         void *ptr;
546
547         rad_assert(request->ev == NULL);
548         rad_assert(!request->in_request_hash);
549         rad_assert(!request->in_proxy_hash);
550
551         if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
552                 talloc_free(request);
553                 return;
554         }
555
556         ptr = talloc_parent(request);
557         rad_assert(ptr != NULL);
558         talloc_free(ptr);
559 }
560
561
562 #ifdef WITH_PROXY
563 static void proxy_reply_too_late(REQUEST *request)
564 {
565         char buffer[128];
566
567         RDEBUG2("Reply from home server %s port %d  - ID: %d arrived too late.  Try increasing 'retry_delay' or 'max_request_time'",
568                 inet_ntop(request->proxy->dst_ipaddr.af,
569                           &request->proxy->dst_ipaddr.ipaddr,
570                           buffer, sizeof(buffer)),
571                 request->proxy->dst_port, request->proxy->id);
572 }
573 #endif
574
575
576 /** Mark a request DONE and clean it up.
577  *
578  *  When a request is DONE, it can have ties to a number of other
579  *  portions of the server.  The request hash, proxy hash, events,
580  *  child threads, etc.  This function takes care of either cleaning
581  *  up the request, or managing the timers to wait for the ties to be
582  *  removed.
583  *
584  *  \dot
585  *      digraph done {
586  *              done -> done [ label = "still running" ];
587  *      }
588  *  \enddot
589  */
590 static void request_done(REQUEST *request, int action)
591 {
592         struct timeval now, when;
593
594         VERIFY_REQUEST(request);
595
596         TRACE_STATE_MACHINE;
597
598         /*
599          *      Force this no matter what.
600          */
601         request->process = request_done;
602
603 #ifdef WITH_DETAIL
604         /*
605          *      Tell the detail listener that we're done.
606          */
607         if (request->listener &&
608             (request->listener->type == RAD_LISTEN_DETAIL) &&
609             (request->simul_max != 1)) {
610                 request->simul_max = 1;
611                 request->listener->send(request->listener,
612                                         request);
613         }
614 #endif
615
616 #ifdef HAVE_PTHREAD_H
617         /*
618          *      If called from a child thread, mark ourselves as done,
619          *      and wait for the master thread timer to clean us up.
620          */
621         if (!we_are_master()) {
622                 FINAL_STATE(REQUEST_DONE);
623                 return;
624         }
625 #endif
626
627         /*
628          *      Mark the request as STOP.
629          */
630         request->master_state = REQUEST_STOP_PROCESSING;
631
632 #ifdef WITH_COA
633         /*
634          *      Move the CoA request to its own handler.
635          */
636         if (request->coa) {
637                 coa_separate(request->coa);
638         } else if (request->parent && (request->parent->coa == request)) {
639                 coa_separate(request);
640         }
641 #endif
642
643         /*
644          *      It doesn't hurt to send duplicate replies.  All other
645          *      signals are ignored, as the request will be cleaned up
646          *      soon anyways.
647          */
648         switch (action) {
649         case FR_ACTION_DUP:
650 #ifdef WITH_DETAIL
651                 rad_assert(request->listener != NULL);
652 #endif
653                 if (request->reply->code != 0) {
654                         request->listener->send(request->listener, request);
655                         return;
656                 } else {
657                         RDEBUG("No reply.  Ignoring retransmit");
658                 }
659                 break;
660
661                 /*
662                  *      Mark the request as done.
663                  */
664         case FR_ACTION_DONE:
665 #ifdef HAVE_PTHREAD_H
666                 /*
667                  *      If the child is still running, leave it alone.
668                  */
669                 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
670                         break;
671                 }
672 #endif
673
674 #ifdef DEBUG_STATE_MACHINE
675                 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
676                                        request->number, __FUNCTION__,
677                                        child_state_names[request->child_state],
678                                        child_state_names[REQUEST_DONE]);
679 #endif
680                 request->child_state = REQUEST_DONE;
681                 break;
682
683                 /*
684                  *      Called when the child is taking too long to
685                  *      finish.  We've already marked it "please
686                  *      stop", so we don't complain any more.
687                  */
688         case FR_ACTION_TIMER:
689                 break;
690
691 #ifdef WITH_PROXY
692         case FR_ACTION_PROXY_REPLY:
693                 proxy_reply_too_late(request);
694                 break;
695 #endif
696
697         default:
698                 break;
699         }
700
701         /*
702          *      Remove it from the request hash.
703          */
704         if (request->in_request_hash) {
705                 if (!rbtree_deletebydata(pl, &request->packet)) {
706                         rad_assert(0 == 1);
707                 }
708                 request->in_request_hash = false;
709         }
710
711 #ifdef WITH_PROXY
712         /*
713          *      Wait for the proxy ID to expire.  This allows us to
714          *      avoid re-use of proxy IDs for a while.
715          */
716         if (request->in_proxy_hash) {
717                 rad_assert(request->proxy != NULL);
718
719                 fr_event_now(el, &now);
720                 when = request->proxy->timestamp;
721
722 #ifdef WITH_COA
723                 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
724                      (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
725                     (request->packet->code != request->proxy->code)) {
726                         when.tv_sec += request->home_server->coa_mrd;
727                 } else
728 #endif
729                         timeradd(&when, request_response_window(request), &when);
730
731                 /*
732                  *      We haven't received all responses, AND there's still
733                  *      time to wait.  Do so.
734                  */
735                 if ((request->num_proxied_requests > request->num_proxied_responses) &&
736 #ifdef WITH_TCP
737                     (request->home_server->proto != IPPROTO_TCP) &&
738 #endif
739                     timercmp(&now, &when, <)) {
740                         RDEBUG("Waiting for more responses from the home server");
741                         goto wait_some_more;
742                 }
743
744                 /*
745                  *      Time to remove it.
746                  */
747                 remove_from_proxy_hash(request);
748         }
749 #endif
750
751 #ifdef HAVE_PTHREAD_H
752         /*
753          *      If there's no children, we can mark the request as done.
754          */
755         if (!spawn_flag) request->child_state = REQUEST_DONE;
756 #endif
757
758         /*
759          *      If the child is still running, wait for it to be finished.
760          */
761         if (request->child_state <= REQUEST_RUNNING) {
762                 gettimeofday(&now, NULL);
763 #ifdef WITH_PROXY
764         wait_some_more:
765 #endif
766                 when = now;
767                 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
768                 tv_add(&when, request->delay);
769                 request->delay += request->delay >> 1;
770                 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
771
772                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
773                 return;
774         }
775
776 #ifdef HAVE_PTHREAD_H
777         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
778 #endif
779
780         /*
781          *      @todo: do final states for TCP sockets, too?
782          */
783         request_stats_final(request);
784 #ifdef WITH_TCP
785         if (request->listener) {
786                 request->listener->count--;
787
788                 /*
789                  *      If we're the last one, remove the listener now.
790                  */
791                 if ((request->listener->count == 0) &&
792                     (request->listener->status >= RAD_LISTEN_STATUS_FROZEN)) {
793                         event_new_fd(request->listener);
794                 }
795         }
796 #endif
797
798         if (request->packet) {
799                 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
800                         request->packet->id,
801                         (unsigned int) (request->timestamp - fr_start_time));
802         } /* else don't print anything */
803
804         ASSERT_MASTER;
805         fr_event_delete(el, &request->ev);
806         request_free(request);
807 }
808
809
810 static void request_cleanup_delay_init(REQUEST *request)
811 {
812         struct timeval now, when;
813
814         VERIFY_REQUEST(request);
815
816         /*
817          *      Do cleanup delay ONLY for RADIUS packets from a real
818          *      client.  Everything else just gets cleaned up
819          *      immediately.
820          */
821         if (request->packet->dst_port == 0) goto done;
822
823         /*
824          *      Accounting packets shouldn't be retransmitted.  They
825          *      should always be updated with Acct-Delay-Time.
826          */
827 #ifdef WITH_ACCOUNTING
828         if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
829 #endif
830
831 #ifdef WITH_DHCP
832         if (request->listener->type == RAD_LISTEN_DHCP) goto done;
833 #endif
834
835 #ifdef WITH_VMPS
836         if (request->listener->type == RAD_LISTEN_VQP) goto done;
837 #endif
838
839         if (!request->root->cleanup_delay) goto done;
840
841         gettimeofday(&now, NULL);
842
843         rad_assert(request->reply->timestamp.tv_sec != 0);
844         when = request->reply->timestamp;
845
846         request->delay = request->root->cleanup_delay;
847         when.tv_sec += request->delay;
848
849         /*
850          *      Set timer for when we need to clean it up.
851          */
852         if (timercmp(&when, &now, >)) {
853 #ifdef DEBUG_STATE_MACHINE
854                 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
855 #endif
856                 request->process = request_cleanup_delay;
857
858                 if (!we_are_master()) {
859                         FINAL_STATE(REQUEST_CLEANUP_DELAY);
860                         return;
861                 }
862
863                 /*
864                  *      Update this if we can, otherwise let the timers pick it up.
865                  */
866                 request->child_state = REQUEST_CLEANUP_DELAY;
867 #ifdef HAVE_PTHREAD_H
868                 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
869 #endif
870                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
871                 return;
872         }
873
874         /*
875          *      Otherwise just clean it up.
876          */
877 done:
878         request_done(request, FR_ACTION_DONE);
879 }
880
881
882 /*
883  *      Enforce max_request_time.
884  */
885 static bool request_max_time(REQUEST *request)
886 {
887         struct timeval now, when;
888         rad_assert(request->magic == REQUEST_MAGIC);
889 #ifdef DEBUG_STATE_MACHINE
890         int action = FR_ACTION_TIMER;
891 #endif
892
893         VERIFY_REQUEST(request);
894
895         TRACE_STATE_MACHINE;
896         ASSERT_MASTER;
897
898         /*
899          *      The child thread has acknowledged it's done.
900          *      Transition to the DONE state.
901          *
902          *      If the request was marked STOP, then the "check for
903          *      stop" macro already took care of it.
904          */
905         if (request->child_state == REQUEST_DONE) {
906         done:
907                 request_done(request, FR_ACTION_DONE);
908                 return true;
909         }
910
911         /*
912          *      The request is still running.  Enforce max_request_time.
913          */
914         fr_event_now(el, &now);
915         when = request->packet->timestamp;
916         when.tv_sec += request->root->max_request_time;
917
918         /*
919          *      Taking too long: tell it to die.
920          */
921         if (timercmp(&now, &when, >=)) {
922 #ifdef HAVE_PTHREAD_H
923                 /*
924                  *      If there's a child thread processing it,
925                  *      complain.
926                  */
927                 if (spawn_flag &&
928                     (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
929                         ERROR("Unresponsive child for request %u, in component %s module %s",
930                               request->number,
931                               request->component ? request->component : "<core>",
932                               request->module ? request->module : "<core>");
933                         exec_trigger(request, NULL, "server.thread.unresponsive", true);
934                 }
935 #endif
936                 /*
937                  *      Tell the request that it's done.
938                  */
939                 goto done;
940         }
941
942         /*
943          *      Sleep for some more.  We HOPE that the child will
944          *      become responsive at some point in the future.  We do
945          *      this by adding 50% to the current timer.
946          */
947         when = now;
948         tv_add(&when, request->delay);
949         request->delay += request->delay >> 1;
950         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
951         return false;
952 }
953
954 static void request_queue_or_run(REQUEST *request,
955                                  fr_request_process_t process)
956 {
957 #ifdef DEBUG_STATE_MACHINE
958         int action = FR_ACTION_TIMER;
959 #endif
960
961         VERIFY_REQUEST(request);
962
963         TRACE_STATE_MACHINE;
964
965         /*
966          *      Do this here so that fewer other functions need to do
967          *      it.
968          */
969         if (request->master_state == REQUEST_STOP_PROCESSING) {
970 #ifdef DEBUG_STATE_MACHINE
971                 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
972                                        request->number, __FUNCTION__,
973                                        master_state_names[request->master_state],
974                                        child_state_names[request->child_state],
975                                        child_state_names[REQUEST_DONE]);
976 #endif
977                 request_done(request, FR_ACTION_DONE);
978                 return;
979         }
980
981         request->process = process;
982
983         if (we_are_master()) {
984                 struct timeval when;
985
986                 /*
987                  *      (re) set the initial delay.
988                  */
989                 request->delay = request_init_delay(request);
990                 if (request->delay > USEC) request->delay = USEC;
991                 gettimeofday(&when, NULL);
992                 tv_add(&when, request->delay);
993                 request->delay += request->delay >> 1;
994
995                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
996
997 #ifdef HAVE_PTHREAD_H
998                 if (spawn_flag) {
999                         /*
1000                          *      A child thread will eventually pick it up.
1001                          */
1002                         if (request_enqueue(request)) return;
1003
1004                         /*
1005                          *      Otherwise we're not going to do anything with
1006                          *      it...
1007                          */
1008                         request_done(request, FR_ACTION_DONE);
1009                         return;
1010                 }
1011 #endif
1012         }
1013
1014         request->child_state = REQUEST_RUNNING;
1015         request->process(request, FR_ACTION_RUN);
1016
1017 #ifdef WNOHANG
1018         /*
1019          *      Requests that care about child process exit
1020          *      codes have already either called
1021          *      rad_waitpid(), or they've given up.
1022          */
1023         while (waitpid(-1, NULL, WNOHANG) > 0);
1024 #endif
1025 }
1026
1027
1028 static void request_dup(REQUEST *request)
1029 {
1030         ERROR("(%u) Ignoring duplicate packet from "
1031               "client %s port %d - ID: %u due to unfinished request "
1032               "in component %s module %s",
1033               request->number, request->client->shortname,
1034               request->packet->src_port,request->packet->id,
1035               request->component, request->module);
1036 }
1037
1038
1039 /** Sit on a request until it's time to clean it up.
1040  *
1041  *  A NAS may not see a response from the server.  When the NAS
1042  *  retransmits, we want to be able to send a cached reply back.  The
1043  *  alternative is to re-process the packet, which does bad things for
1044  *  EAP, among others.
1045  *
1046  *  IF we do see a NAS retransmit, we extend the cleanup delay,
1047  *  because the NAS might miss our cached reply.
1048  *
1049  *  Otherwise, once we reach cleanup_delay, we transition to DONE.
1050  *
1051  *  \dot
1052  *      digraph cleanup_delay {
1053  *              cleanup_delay;
1054  *              send_reply [ label = "send_reply\nincrease cleanup delay" ];
1055  *
1056  *              cleanup_delay -> send_reply [ label = "DUP" ];
1057  *              send_reply -> cleanup_delay;
1058  *              cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1059  *              cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
1060  *              cleanup_delay -> done [ label = "TIMER >= timeout" ];
1061  *      }
1062  *  \enddot
1063  */
1064 static void request_cleanup_delay(REQUEST *request, int action)
1065 {
1066         struct timeval when, now;
1067
1068         VERIFY_REQUEST(request);
1069
1070         TRACE_STATE_MACHINE;
1071         ASSERT_MASTER;
1072         COA_SEPARATE;
1073         CHECK_FOR_STOP;
1074
1075         switch (action) {
1076         case FR_ACTION_DUP:
1077                 if (request->reply->code != 0) {
1078                         request->listener->send(request->listener, request);
1079                 } else {
1080                         RDEBUG("No reply.  Ignoring retransmit");
1081                 }
1082
1083                 /*
1084                  *      Double the cleanup_delay to catch retransmits.
1085                  */
1086                 when = request->reply->timestamp;
1087                 request->delay += request->delay;
1088                 when.tv_sec += request->delay;
1089
1090                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1091                 break;
1092
1093 #ifdef WITH_PROXY
1094         case FR_ACTION_PROXY_REPLY:
1095                 proxy_reply_too_late(request);
1096                 break;
1097 #endif
1098
1099         case FR_ACTION_TIMER:
1100                 fr_event_now(el, &now);
1101
1102                 rad_assert(request->root->cleanup_delay > 0);
1103
1104                 when = request->reply->timestamp;
1105                 when.tv_sec += request->root->cleanup_delay;
1106
1107                 if (timercmp(&when, &now, >)) {
1108 #ifdef DEBUG_STATE_MACHINE
1109                         if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1110 #endif
1111                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1112                         return;
1113                 } /* else it's time to clean up */
1114
1115                 request_done(request, REQUEST_DONE);
1116                 break;
1117
1118         default:
1119                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1120                 break;
1121         }
1122 }
1123
1124
1125 /** Sit on a request until it's time to respond to it.
1126  *
1127  *  For security reasons, rejects (and maybe some other) packets are
1128  *  delayed for a while before we respond.  This delay means that
1129  *  badly behaved NASes don't hammer the server with authentication
1130  *  attempts.
1131  *
1132  *  Otherwise, once we reach response_delay, we send the reply, and
1133  *  transition to cleanup_delay.
1134  *
1135  *  \dot
1136  *      digraph response_delay {
1137  *              response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1138  *              response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1139  *              response_delay -> send_reply [ label = "TIMER >= timeout" ];
1140  *              send_reply -> cleanup_delay;
1141  *      }
1142  *  \enddot
1143  */
1144 static void request_response_delay(REQUEST *request, int action)
1145 {
1146         struct timeval when, now;
1147
1148         VERIFY_REQUEST(request);
1149
1150         TRACE_STATE_MACHINE;
1151         ASSERT_MASTER;
1152         COA_SEPARATE;
1153         CHECK_FOR_STOP;
1154
1155         switch (action) {
1156         case FR_ACTION_DUP:
1157                 ERROR("(%u) Discarding duplicate request from "
1158                       "client %s port %d - ID: %u due to delayed response",
1159                       request->number, request->client->shortname,
1160                       request->packet->src_port,request->packet->id);
1161                 break;
1162
1163 #ifdef WITH_PROXY
1164         case FR_ACTION_PROXY_REPLY:
1165                 proxy_reply_too_late(request);
1166                 break;
1167 #endif
1168
1169         case FR_ACTION_TIMER:
1170                 fr_event_now(el, &now);
1171
1172                 /*
1173                  *      See if it's time to send the reply.  If not,
1174                  *      we wait some more.
1175                  */
1176                 when = request->reply->timestamp;
1177
1178                 tv_add(&when, request->response_delay.tv_sec * USEC);
1179                 tv_add(&when, request->response_delay.tv_usec);
1180
1181                 if (timercmp(&when, &now, >)) {
1182 #ifdef DEBUG_STATE_MACHINE
1183                         if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1184 #endif
1185                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1186                         return;
1187                 } /* else it's time to send the reject */
1188
1189                 RDEBUG2("Sending delayed response");
1190                 debug_packet(request, request->reply, false);
1191                 request->listener->send(request->listener, request);
1192
1193                 /*
1194                  *      Clean up the request.
1195                  */
1196                 request_cleanup_delay_init(request);
1197                 break;
1198
1199         default:
1200                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1201                 break;
1202         }
1203 }
1204
1205
1206 static int request_pre_handler(REQUEST *request, UNUSED int action)
1207 {
1208         int rcode;
1209
1210         VERIFY_REQUEST(request);
1211
1212         TRACE_STATE_MACHINE;
1213
1214         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1215
1216         /*
1217          *      Don't decode the packet if it's an internal "fake"
1218          *      request.  Instead, just return so that the caller can
1219          *      process it.
1220          */
1221         if (request->packet->dst_port == 0) {
1222                 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1223                 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1224                 return 1;
1225         }
1226
1227         if (!request->packet->vps) { /* FIXME: check for correct state */
1228                 rcode = request->listener->decode(request->listener, request);
1229
1230 #ifdef WITH_UNLANG
1231                 if (debug_condition) {
1232                         /*
1233                          *      Ignore parse errors.
1234                          */
1235                         if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1236                                 request->log.lvl = L_DBG_LVL_2;
1237                                 request->log.func = vradlog_request;
1238                         }
1239                 }
1240 #endif
1241
1242                 debug_packet(request, request->packet, true);
1243         } else {
1244                 rcode = 0;
1245         }
1246
1247         if (rcode < 0) {
1248                 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1249                 request->reply->offset = -2; /* bad authenticator */
1250                 return 0;
1251         }
1252
1253         if (!request->username) {
1254                 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1255         }
1256
1257         return 1;
1258 }
1259
1260
1261 /**  Do the final processing of a request before we reply to the NAS.
1262  *
1263  *  Various cleanups, suppress responses, copy Proxy-State, and set
1264  *  response_delay or cleanup_delay;
1265  */
1266 static void request_finish(REQUEST *request, int action)
1267 {
1268         VALUE_PAIR *vp;
1269
1270         VERIFY_REQUEST(request);
1271
1272         TRACE_STATE_MACHINE;
1273         CHECK_FOR_STOP;
1274
1275         (void) action;  /* -Wunused */
1276
1277 #ifdef WITH_COA
1278         /*
1279          *      Don't do post-auth if we're a CoA request originated
1280          *      from an Access-Request.  See request_alloc_coa() for
1281          *      details.
1282          */
1283         if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1284 #endif
1285
1286         /*
1287          *      Override the response code if a control:Response-Packet-Type attribute is present.
1288          */
1289         vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1290         if (vp) {
1291                 if (vp->vp_integer == 256) {
1292                         RDEBUG2("Not responding to request");
1293                         request->reply->code = 0;
1294                 } else {
1295                         request->reply->code = vp->vp_integer;
1296                 }
1297         }
1298         /*
1299          *      Catch Auth-Type := Reject BEFORE proxying the packet.
1300          */
1301         else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1302                 if (request->reply->code == 0) {
1303                         vp = fr_pair_find_by_num(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1304                         if (!vp || (vp->vp_integer != 5)) {
1305                                 RDEBUG2("There was no response configured: "
1306                                         "rejecting request");
1307                         }
1308
1309                         request->reply->code = PW_CODE_ACCESS_REJECT;
1310                 }
1311         }
1312
1313         /*
1314          *      Copy Proxy-State from the request to the reply.
1315          */
1316         vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps,
1317                        PW_PROXY_STATE, 0, TAG_ANY);
1318         if (vp) fr_pair_add(&request->reply->vps, vp);
1319
1320         /*
1321          *      Call Post-Auth for Access-Request packets.
1322          */
1323         if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1324                 rad_postauth(request);
1325         }
1326
1327 #ifdef WITH_COA
1328         /*
1329          *      Maybe originate a CoA request.
1330          */
1331         if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1332                 request_coa_originate(request);
1333         }
1334 #endif
1335
1336         /*
1337          *      Clean up.  These are no longer needed.
1338          */
1339         gettimeofday(&request->reply->timestamp, NULL);
1340
1341         /*
1342          *      Fake packets get marked as "done", and have the
1343          *      proxy-reply section deal with the reply attributes.
1344          *      We therefore don't free the reply attributes.
1345          */
1346         if (request->packet->dst_port == 0) {
1347                 RDEBUG("Finished internally proxied request.");
1348                 FINAL_STATE(REQUEST_DONE);
1349                 return;
1350         }
1351
1352 #ifdef WITH_DETAIL
1353         /*
1354          *      Always send the reply to the detail listener.
1355          */
1356         if (request->listener->type == RAD_LISTEN_DETAIL) {
1357                 request->simul_max = 1;
1358
1359                 /*
1360                  *      But only print the reply if there is one.
1361                  */
1362                 if (request->reply->code != 0) {
1363                         debug_packet(request, request->reply, false);
1364                 }
1365
1366                 request->listener->send(request->listener, request);
1367                 goto done;
1368         }
1369 #endif
1370
1371         /*
1372          *      Ignore all "do not respond" packets.
1373          *      Except for the detail ones, which need to ping
1374          *      the detail file reader so that it will retransmit.
1375          */
1376         if (!request->reply->code) {
1377                 RDEBUG("Not sending reply to client.");
1378                 goto done;
1379         }
1380
1381         /*
1382          *      If it's not in the request hash, we MIGHT not want to
1383          *      send a reply.
1384          *
1385          *      If duplicate packets are allowed, then then only
1386          *      reason to NOT be in the request hash is because we
1387          *      don't want to send a reply.
1388          *
1389          *      FIXME: this is crap.  The rest of the state handling
1390          *      should use a different field so that we don't have two
1391          *      meanings for it.
1392          *
1393          *      Otherwise duplicates are forbidden, and the request is
1394          *      SUPPOSED to avoid the request hash.
1395          *
1396          *      In that case, we need to send a reply.
1397          */
1398         if (!request->in_request_hash &&
1399             !request->listener->nodup) {
1400                 RDEBUG("Suppressing reply to client.");
1401                 goto done;
1402         }
1403
1404         /*
1405          *      See if we need to delay an Access-Reject packet.
1406          */
1407         if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1408             (request->root->reject_delay.tv_sec > 0)) {
1409                 request->response_delay = request->root->reject_delay;
1410
1411                 vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY, 0, TAG_ANY);
1412                 if (vp) {
1413                         if (vp->vp_integer <= 10) {
1414                                 request->response_delay.tv_sec = vp->vp_integer;
1415                         } else {
1416                                 request->response_delay.tv_sec = 10;
1417                         }
1418                         request->response_delay.tv_usec = 0;
1419                 } else {
1420                         vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY_USEC, 0, TAG_ANY);
1421                         if (vp) {
1422                                 if (vp->vp_integer <= 10 * USEC) {
1423                                         request->response_delay.tv_sec = vp->vp_integer / USEC;
1424                                         request->response_delay.tv_usec = vp->vp_integer % USEC;
1425                                 } else {
1426                                         request->response_delay.tv_sec = 10;
1427                                         request->response_delay.tv_usec = 0;
1428                                 }
1429                         }
1430                 }
1431
1432 #ifdef WITH_PROXY
1433                 /*
1434                  *      If we timed out a proxy packet, don't delay
1435                  *      the reject any more.
1436                  */
1437                 if (request->proxy && !request->proxy_reply) {
1438                         request->response_delay.tv_sec = 0;
1439                         request->response_delay.tv_usec = 0;
1440                 }
1441 #endif
1442         }
1443
1444         /*
1445          *      Send the reply.
1446          */
1447         if ((request->response_delay.tv_sec == 0) &&
1448             (request->response_delay.tv_usec == 0)) {
1449
1450                 /*
1451                  *      Don't print a reply if there's none to send.
1452                  */
1453                 if (request->reply->code != 0) {
1454                         if (rad_debug_lvl && request->state &&
1455                             (request->reply->code == PW_CODE_ACCESS_ACCEPT)) {
1456                                 if (!fr_pair_find_by_num(request->packet->vps, PW_STATE, 0, TAG_ANY)) {
1457                                         RWDEBUG2("Unused attributes found in &session-state:");
1458                                 }
1459                         }
1460
1461                         debug_packet(request, request->reply, false);
1462                         request->listener->send(request->listener, request);
1463                 }
1464
1465         done:
1466                 RDEBUG2("Finished request");
1467                 request_cleanup_delay_init(request);
1468
1469         } else {
1470                 /*
1471                  *      Encode and sign it here, so that the master
1472                  *      thread can just send the encoded data, which
1473                  *      means it does less work.
1474                  */
1475                 RDEBUG2("Delaying response for %d.%06d seconds",
1476                         (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1477                 request->listener->encode(request->listener, request);
1478                 request->process = request_response_delay;
1479
1480                 FINAL_STATE(REQUEST_RESPONSE_DELAY);
1481         }
1482 }
1483
1484 /** Process a request from a client.
1485  *
1486  *  The outcome might be that the request is proxied.
1487  *
1488  *  \dot
1489  *      digraph running {
1490  *              running -> running [ label = "TIMER < max_request_time" ];
1491  *              running -> done [ label = "TIMER >= max_request_time" ];
1492  *              running -> proxy [ label = "proxied" ];
1493  *              running -> dup [ label = "DUP", arrowhead = "none" ];
1494  *      }
1495  *  \enddot
1496  */
1497 static void request_running(REQUEST *request, int action)
1498 {
1499         VERIFY_REQUEST(request);
1500
1501         TRACE_STATE_MACHINE;
1502         CHECK_FOR_STOP;
1503
1504         switch (action) {
1505         case FR_ACTION_TIMER:
1506                 COA_SEPARATE;
1507                 (void) request_max_time(request);
1508                 break;
1509
1510         case FR_ACTION_DUP:
1511                 request_dup(request);
1512                 break;
1513
1514         case FR_ACTION_RUN:
1515                 if (!request_pre_handler(request, action)) {
1516 #ifdef DEBUG_STATE_MACHINE
1517                         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1518                                                request->number, __FUNCTION__,
1519                                                child_state_names[request->child_state],
1520                                                child_state_names[REQUEST_DONE]);
1521 #endif
1522                         FINAL_STATE(REQUEST_DONE);
1523                         break;
1524                 }
1525
1526                 rad_assert(request->handle != NULL);
1527                 request->handle(request);
1528
1529 #ifdef WITH_PROXY
1530                 /*
1531                  *      We may need to send a proxied request.
1532                  */
1533                 if ((action == FR_ACTION_RUN) &&
1534                     request_will_proxy(request)) {
1535 #ifdef DEBUG_STATE_MACHINE
1536                         if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1537 #endif
1538                         /*
1539                          *      If this fails, it
1540                          *      takes care of setting
1541                          *      up the post proxy fail
1542                          *      handler.
1543                          */
1544                         if (request_proxy(request, 0) < 0) goto req_finished;
1545                 } else
1546 #endif
1547                 {
1548 #ifdef DEBUG_STATE_MACHINE
1549                         if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1550 #endif
1551
1552 #ifdef WITH_PROXY
1553                 req_finished:
1554 #endif
1555                         request_finish(request, action);
1556                 }
1557                 break;
1558
1559         default:
1560                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1561                 break;
1562         }
1563 }
1564
1565 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1566                     RADCLIENT *client, RAD_REQUEST_FUNP fun)
1567 {
1568         uint32_t count;
1569         RADIUS_PACKET **packet_p;
1570         REQUEST *request = NULL;
1571         struct timeval now;
1572         listen_socket_t *sock = NULL;
1573
1574         VERIFY_PACKET(packet);
1575
1576         /*
1577          *      Set the last packet received.
1578          */
1579         gettimeofday(&now, NULL);
1580
1581         packet->timestamp = now;
1582
1583 #ifdef WITH_ACCOUNTING
1584         if (listener->type != RAD_LISTEN_DETAIL)
1585 #endif
1586         {
1587                 sock = listener->data;
1588                 sock->last_packet = now.tv_sec;
1589
1590 #ifdef WITH_TCP
1591                 packet->proto = sock->proto;
1592 #endif
1593         }
1594
1595         /*
1596          *      Skip everything if required.
1597          */
1598         if (listener->nodup) goto skip_dup;
1599
1600         packet_p = rbtree_finddata(pl, &packet);
1601         if (packet_p) {
1602                 rad_child_state_t child_state;
1603
1604                 request = fr_packet2myptr(REQUEST, packet, packet_p);
1605                 rad_assert(request->in_request_hash);
1606                 child_state = request->child_state;
1607
1608                 /*
1609                  *      Same src/dst ip/port, length, and
1610                  *      authentication vector: must be a duplicate.
1611                  */
1612                 if ((request->packet->data_len == packet->data_len) &&
1613                     (memcmp(request->packet->vector, packet->vector,
1614                             sizeof(packet->vector)) == 0)) {
1615
1616 #ifdef WITH_STATS
1617                         switch (packet->code) {
1618                         case PW_CODE_ACCESS_REQUEST:
1619                                 FR_STATS_INC(auth, total_dup_requests);
1620                                 break;
1621
1622 #ifdef WITH_ACCOUNTING
1623                         case PW_CODE_ACCOUNTING_REQUEST:
1624                                 FR_STATS_INC(acct, total_dup_requests);
1625                                 break;
1626 #endif
1627 #ifdef WITH_COA
1628                         case PW_CODE_COA_REQUEST:
1629                                 FR_STATS_INC(coa, total_dup_requests);
1630                                 break;
1631
1632                         case PW_CODE_DISCONNECT_REQUEST:
1633                                 FR_STATS_INC(dsc, total_dup_requests);
1634                                 break;
1635 #endif
1636
1637                         default:
1638                                 break;
1639                         }
1640 #endif  /* WITH_STATS */
1641
1642                         /*
1643                          *      Tell the state machine that there's a
1644                          *      duplicate request.
1645                          */
1646                         request->process(request, FR_ACTION_DUP);
1647                         return 0; /* duplicate of live request */
1648                 }
1649
1650                 /*
1651                  *      Mark the request as done ASAP, and before we
1652                  *      log anything.  The child may stop processing
1653                  *      the request just as we're logging the
1654                  *      complaint.
1655                  */
1656                 request_done(request, FR_ACTION_DONE);
1657                 request = NULL;
1658
1659                 /*
1660                  *      It's a new request, not a duplicate.  If the
1661                  *      old one is done, then we can clean it up.
1662                  */
1663                 if (child_state <= REQUEST_RUNNING) {
1664                         /*
1665                          *      The request is still QUEUED or RUNNING.  That's a problem.
1666                          */
1667                         ERROR("Received conflicting packet from "
1668                               "client %s port %d - ID: %u due to "
1669                               "unfinished request.  Giving up on old request.",
1670                               client->shortname,
1671                               packet->src_port, packet->id);
1672                 }
1673
1674                 /*
1675                  *      Mark the old request as done.  If there's no
1676                  *      child, the request will be cleaned up
1677                  *      immediately.  If there is a child, we'll set a
1678                  *      timer to go clean up the request.
1679                  */
1680         } /* else the new packet is unique */
1681
1682         /*
1683          *      Quench maximum number of outstanding requests.
1684          */
1685         if (main_config.max_requests &&
1686             ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1687                 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1688                                  client->shortname,
1689                                  packet->src_port, packet->id);
1690                            WARN("Please check the configuration file.\n"
1691                                 "\tThe value for 'max_requests' is probably set too low.\n"));
1692
1693                 exec_trigger(NULL, NULL, "server.max_requests", true);
1694                 return 0;
1695         }
1696
1697 skip_dup:
1698         /*
1699          *      Rate-limit the incoming packets
1700          */
1701         if (sock && sock->max_rate) {
1702                 uint32_t pps;
1703
1704                 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1705                 if (pps > sock->max_rate) {
1706                         DEBUG("Dropping request due to rate limiting");
1707                         return 0;
1708                 }
1709                 sock->rate_pps_now++;
1710         }
1711
1712         /*
1713          *      Allocate a pool for the request.
1714          */
1715         if (!ctx) {
1716                 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1717                 if (!ctx) return 0;
1718                 talloc_set_name_const(ctx, "request_receive_pool");
1719
1720                 /*
1721                  *      The packet is still allocated from a different
1722                  *      context, but oh well.
1723                  */
1724                 (void) talloc_steal(ctx, packet);
1725         }
1726
1727         request = request_setup(ctx, listener, packet, client, fun);
1728         if (!request) {
1729                 talloc_free(ctx);
1730                 return 1;
1731         }
1732
1733         /*
1734          *      Mark it as a "real" request with a context.
1735          */
1736         request->options |= RAD_REQUEST_OPTION_CTX;
1737
1738         /*
1739          *      Remember the request in the list.
1740          */
1741         if (!listener->nodup) {
1742                 if (!rbtree_insert(pl, &request->packet)) {
1743                         RERROR("Failed to insert request in the list of live requests: discarding it");
1744                         request_done(request, FR_ACTION_DONE);
1745                         return 1;
1746                 }
1747
1748                 request->in_request_hash = true;
1749         }
1750
1751         /*
1752          *      Process it.  Send a response, and free it.
1753          */
1754         if (listener->synchronous) {
1755 #ifdef WITH_DETAIL
1756                 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1757 #endif
1758
1759                 request->listener->decode(request->listener, request);
1760                 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1761                 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1762
1763                 fun(request);
1764
1765                 if (request->reply->code != 0) {
1766                         request->listener->send(request->listener, request);
1767                 } else {
1768                         RDEBUG("Not sending reply");
1769                 }
1770
1771                 /*
1772                  *      Don't do delayed reject.  Oh well.
1773                  */
1774                 request_free(request);
1775                 return 1;
1776         }
1777
1778         /*
1779          *      Otherwise, insert it into the state machine.
1780          *      The child threads will take care of processing it.
1781          */
1782         request_queue_or_run(request, request_running);
1783
1784         return 1;
1785 }
1786
1787
1788 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1789                               RADCLIENT *client, RAD_REQUEST_FUNP fun)
1790 {
1791         REQUEST *request;
1792
1793         /*
1794          *      Create and initialize the new request.
1795          */
1796         request = request_alloc(ctx);
1797         if (!request) {
1798                 ERROR("No memory");
1799                 return NULL;
1800         }
1801         request->reply = rad_alloc(request, false);
1802         if (!request->reply) {
1803                 ERROR("No memory");
1804                 talloc_free(request);
1805                 return NULL;
1806         }
1807
1808         request->listener = listener;
1809         request->client = client;
1810         request->packet = talloc_steal(request, packet);
1811         request->number = request_num_counter++;
1812         request->priority = listener->type;
1813         request->master_state = REQUEST_ACTIVE;
1814         request->child_state = REQUEST_RUNNING;
1815 #ifdef DEBUG_STATE_MACHINE
1816         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1817                                request->number, __FUNCTION__,
1818                                child_state_names[request->child_state],
1819                                child_state_names[REQUEST_RUNNING]);
1820 #endif
1821         request->handle = fun;
1822         NO_CHILD_THREAD;
1823
1824 #ifdef WITH_STATS
1825         request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1826         if (packet->code == PW_CODE_ACCESS_REQUEST) {
1827                 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1828                 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1829 #ifdef WITH_ACCOUNTING
1830         } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1831                 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1832                 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1833 #endif
1834         }
1835 #endif  /* WITH_STATS */
1836
1837         /*
1838          *      Status-Server packets go to the head of the queue.
1839          */
1840         if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1841
1842         /*
1843          *      Set virtual server identity
1844          */
1845         if (client->server) {
1846                 request->server = client->server;
1847         } else if (listener->server) {
1848                 request->server = listener->server;
1849         } else {
1850                 request->server = NULL;
1851         }
1852
1853         request->root = &main_config;
1854 #ifdef WITH_TCP
1855         request->listener->count++;
1856 #endif
1857
1858         /*
1859          *      The request passes many of our sanity checks.
1860          *      From here on in, if anything goes wrong, we
1861          *      send a reject message, instead of dropping the
1862          *      packet.
1863          */
1864
1865         /*
1866          *      Build the reply template from the request.
1867          */
1868
1869         request->reply->sockfd = request->packet->sockfd;
1870         request->reply->dst_ipaddr = request->packet->src_ipaddr;
1871         request->reply->src_ipaddr = request->packet->dst_ipaddr;
1872         request->reply->dst_port = request->packet->src_port;
1873         request->reply->src_port = request->packet->dst_port;
1874         request->reply->id = request->packet->id;
1875         request->reply->code = 0; /* UNKNOWN code */
1876         memcpy(request->reply->vector, request->packet->vector,
1877                sizeof(request->reply->vector));
1878         request->reply->vps = NULL;
1879         request->reply->data = NULL;
1880         request->reply->data_len = 0;
1881
1882         return request;
1883 }
1884
1885 #ifdef WITH_TCP
1886 /***********************************************************************
1887  *
1888  *      TCP Handlers.
1889  *
1890  ***********************************************************************/
1891
1892 /*
1893  *      Timer function for all TCP sockets.
1894  */
1895 static void tcp_socket_timer(void *ctx)
1896 {
1897         rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1898         listen_socket_t *sock = listener->data;
1899         struct timeval end, now;
1900         char buffer[256];
1901         fr_socket_limit_t *limit;
1902
1903         ASSERT_MASTER;
1904
1905         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1906
1907         fr_event_now(el, &now);
1908
1909         switch (listener->type) {
1910 #ifdef WITH_PROXY
1911         case RAD_LISTEN_PROXY:
1912                 limit = &sock->home->limit;
1913                 break;
1914 #endif
1915
1916         case RAD_LISTEN_AUTH:
1917 #ifdef WITH_ACCOUNTING
1918         case RAD_LISTEN_ACCT:
1919 #endif
1920                 limit = &sock->limit;
1921                 break;
1922
1923         default:
1924                 return;
1925         }
1926
1927         /*
1928          *      If we enforce a lifetime, do it now.
1929          */
1930         if (limit->lifetime > 0) {
1931                 end.tv_sec = sock->opened + limit->lifetime;
1932                 end.tv_usec = 0;
1933
1934                 if (timercmp(&end, &now, <=)) {
1935                         listener->print(listener, buffer, sizeof(buffer));
1936                         DEBUG("Reached maximum lifetime on socket %s", buffer);
1937
1938                 do_close:
1939
1940 #ifdef WITH_PROXY
1941                         /*
1942                          *      Proxy sockets get frozen, so that we don't use
1943                          *      them for new requests.  But we do keep them
1944                          *      open to listen for replies to requests we had
1945                          *      previously sent.
1946                          */
1947                         if (listener->type == RAD_LISTEN_PROXY) {
1948                                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1949                                 if (!fr_packet_list_socket_freeze(proxy_list,
1950                                                                   listener->fd)) {
1951                                         ERROR("Fatal error freezing socket: %s", fr_strerror());
1952                                         fr_exit(1);
1953                                 }
1954                                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1955                         }
1956 #endif
1957
1958                         /*
1959                          *      Mark the socket as "don't use if at all possible".
1960                          */
1961                         listener->status = RAD_LISTEN_STATUS_FROZEN;
1962                         event_new_fd(listener);
1963                         return;
1964                 }
1965         } else {
1966                 end = now;
1967                 end.tv_sec += 3600;
1968         }
1969
1970         /*
1971          *      Enforce an idle timeout.
1972          */
1973         if (limit->idle_timeout > 0) {
1974                 struct timeval idle;
1975
1976                 rad_assert(sock->last_packet != 0);
1977                 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1978                 idle.tv_usec = 0;
1979
1980                 if (timercmp(&idle, &now, <=)) {
1981                         listener->print(listener, buffer, sizeof(buffer));
1982                         DEBUG("Reached idle timeout on socket %s", buffer);
1983                         goto do_close;
1984                 }
1985
1986                 /*
1987                  *      Enforce the minimum of idle timeout or lifetime.
1988                  */
1989                 if (timercmp(&idle, &end, <)) {
1990                         end = idle;
1991                 }
1992         }
1993
1994         /*
1995          *      Wake up at t + 0.5s.  The code above checks if the timers
1996          *      are <= t.  This addition gives us a bit of leeway.
1997          */
1998         end.tv_usec = USEC / 2;
1999
2000         ASSERT_MASTER;
2001         if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
2002                 rad_panic("Failed to insert event");
2003         }
2004 }
2005
2006
2007 #ifdef WITH_PROXY
2008 /*
2009  *      Add +/- 2s of jitter, as suggested in RFC 3539
2010  *      and in RFC 5080.
2011  */
2012 static void add_jitter(struct timeval *when)
2013 {
2014         uint32_t jitter;
2015
2016         when->tv_sec -= 2;
2017
2018         jitter = fr_rand();
2019         jitter ^= (jitter >> 10);
2020         jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
2021
2022         /*
2023          *      Add in ~ (4 * USEC) of jitter.
2024          */
2025         tv_add(when, jitter);
2026 }
2027
2028 /*
2029  *      Called by socket_del to remove requests with this socket
2030  */
2031 static int eol_proxy_listener(void *ctx, void *data)
2032 {
2033         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2034         RADIUS_PACKET **proxy_p = data;
2035         REQUEST *request;
2036
2037         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2038         if (request->proxy_listener != this) return 0;
2039
2040         /*
2041          *      The normal "remove_from_proxy_hash" tries to grab the
2042          *      proxy mutex.  We already have it held, so grabbing it
2043          *      again will cause a deadlock.  Instead, call the "no
2044          *      lock" version of the function.
2045          */
2046         rad_assert(request->in_proxy_hash == true);
2047         remove_from_proxy_hash_nl(request, false);
2048
2049         /*
2050          *      Don't mark it as DONE.  The client can retransmit, and
2051          *      the packet SHOULD be re-proxied somewhere else.
2052          *
2053          *      Return "2" means that the rbtree code will remove it
2054          *      from the tree, and we don't need to do it ourselves.
2055          */
2056         return 2;
2057 }
2058 #endif  /* WITH_PROXY */
2059
2060 static int eol_listener(void *ctx, void *data)
2061 {
2062         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2063         RADIUS_PACKET **packet_p = data;
2064         REQUEST *request;
2065
2066         request = fr_packet2myptr(REQUEST, packet, packet_p);
2067         if (request->listener != this) return 0;
2068
2069         request->master_state = REQUEST_STOP_PROCESSING;
2070         request->process = request_done;
2071
2072         return 0;
2073 }
2074 #endif  /* WITH_TCP */
2075
2076 #ifdef WITH_PROXY
2077 /***********************************************************************
2078  *
2079  *      Proxy handlers for the state machine.
2080  *
2081  ***********************************************************************/
2082
2083 /*
2084  *      Called with the proxy mutex held
2085  */
2086 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2087 {
2088         VERIFY_REQUEST(request);
2089
2090         if (!request->in_proxy_hash) return;
2091
2092         fr_packet_list_id_free(proxy_list, request->proxy, yank);
2093         request->in_proxy_hash = false;
2094
2095         /*
2096          *      On the FIRST reply, decrement the count of outstanding
2097          *      requests.  Note that this is NOT the count of sent
2098          *      packets, but whether or not the home server has
2099          *      responded at all.
2100          */
2101         if (request->home_server &&
2102             request->home_server->currently_outstanding) {
2103                 request->home_server->currently_outstanding--;
2104
2105                 /*
2106                  *      If we're NOT sending it packets, AND it's been
2107                  *      a while since we got a response, then we don't
2108                  *      know if it's alive or dead.
2109                  */
2110                 if ((request->home_server->currently_outstanding == 0) &&
2111                     (request->home_server->state == HOME_STATE_ALIVE)) {
2112                         struct timeval when, now;
2113
2114                         when.tv_sec = request->home_server->last_packet_recv ;
2115                         when.tv_usec = 0;
2116
2117                         timeradd(&when, request_response_window(request), &when);
2118                         gettimeofday(&now, NULL);
2119
2120                         /*
2121                          *      last_packet + response_window
2122                          *
2123                          *      We *administratively* mark the home
2124                          *      server as "unknown" state, because we
2125                          *      haven't seen a packet for a while.
2126                          */
2127                         if (timercmp(&now, &when, >)) {
2128                                 request->home_server->state = HOME_STATE_UNKNOWN;
2129                                 request->home_server->last_packet_sent = 0;
2130                                 request->home_server->last_packet_recv = 0;
2131                         }
2132                 }
2133         }
2134
2135 #ifdef WITH_TCP
2136         rad_assert(request->proxy_listener != NULL);
2137         request->proxy_listener->count--;
2138 #endif
2139         request->proxy_listener = NULL;
2140
2141         /*
2142          *      Got from YES in hash, to NO, not in hash while we hold
2143          *      the mutex.  This guarantees that when another thread
2144          *      grabs the mutex, the "not in hash" flag is correct.
2145          */
2146 }
2147
2148 static void remove_from_proxy_hash(REQUEST *request)
2149 {
2150         VERIFY_REQUEST(request);
2151
2152         /*
2153          *      Check this without grabbing the mutex because it's a
2154          *      lot faster that way.
2155          */
2156         if (!request->in_proxy_hash) return;
2157
2158         /*
2159          *      The "not in hash" flag is definitive.  However, if the
2160          *      flag says that it IS in the hash, there might still be
2161          *      a race condition where it isn't.
2162          */
2163         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2164
2165         if (!request->in_proxy_hash) {
2166                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2167                 return;
2168         }
2169
2170         remove_from_proxy_hash_nl(request, true);
2171
2172         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2173 }
2174
2175 static int insert_into_proxy_hash(REQUEST *request)
2176 {
2177         char buf[128];
2178         int tries;
2179         bool success = false;
2180         void *proxy_listener;
2181
2182         VERIFY_REQUEST(request);
2183
2184         rad_assert(request->proxy != NULL);
2185         rad_assert(request->home_server != NULL);
2186         rad_assert(proxy_list != NULL);
2187
2188
2189         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2190         proxy_listener = NULL;
2191         request->num_proxied_requests = 1;
2192         request->num_proxied_responses = 0;
2193
2194         for (tries = 0; tries < 2; tries++) {
2195                 rad_listen_t *this;
2196                 listen_socket_t *sock;
2197
2198                 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2199                 success = fr_packet_list_id_alloc(proxy_list,
2200                                                 request->home_server->proto,
2201                                                 &request->proxy, &proxy_listener);
2202                 if (success) break;
2203
2204                 if (tries > 0) continue; /* try opening new socket only once */
2205
2206 #ifdef HAVE_PTHREAD_H
2207                 if (proxy_no_new_sockets) break;
2208 #endif
2209
2210                 RDEBUG3("proxy: Trying to open a new listener to the home server");
2211                 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2212                 if (!this) {
2213                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2214                         goto fail;
2215                 }
2216
2217                 request->proxy->src_port = 0; /* Use any new socket */
2218                 proxy_listener = this;
2219
2220                 sock = this->data;
2221                 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2222                                                sock->proto,
2223                                                &sock->other_ipaddr, sock->other_port,
2224                                                this)) {
2225
2226 #ifdef HAVE_PTHREAD_H
2227                         proxy_no_new_sockets = true;
2228 #endif
2229                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2230
2231                         /*
2232                          *      This is bad.  However, the
2233                          *      packet list now supports 256
2234                          *      open sockets, which should
2235                          *      minimize this problem.
2236                          */
2237                         ERROR("Failed adding proxy socket: %s",
2238                               fr_strerror());
2239                         goto fail;
2240                 }
2241
2242                 /*
2243                  *      Add it to the event loop.  Ensure that we have
2244                  *      only one mutex locked at a time.
2245                  */
2246                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2247                 radius_update_listener(this);
2248                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2249         }
2250
2251         if (!proxy_listener || !success) {
2252                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2253                 REDEBUG2("proxy: Failed allocating Id for proxied request");
2254         fail:
2255                 request->proxy_listener = NULL;
2256                 request->in_proxy_hash = false;
2257                 return 0;
2258         }
2259
2260         rad_assert(request->proxy->id >= 0);
2261
2262         request->proxy_listener = proxy_listener;
2263         request->in_proxy_hash = true;
2264         RDEBUG3("proxy: request is now in proxy hash");
2265
2266         /*
2267          *      Keep track of maximum outstanding requests to a
2268          *      particular home server.  'max_outstanding' is
2269          *      enforced in home_server_ldb(), in realms.c.
2270          */
2271         request->home_server->currently_outstanding++;
2272
2273 #ifdef WITH_TCP
2274         request->proxy_listener->count++;
2275 #endif
2276
2277         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2278
2279         RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2280                inet_ntop(request->proxy->dst_ipaddr.af,
2281                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2282                request->proxy->dst_port,
2283                request->proxy->id);
2284
2285         return 1;
2286 }
2287
2288 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2289 {
2290         int rcode;
2291         int post_proxy_type = 0;
2292         VALUE_PAIR *vp;
2293
2294         VERIFY_REQUEST(request);
2295
2296         /*
2297          *      There may be a proxy reply, but it may be too late.
2298          */
2299         if (!request->home_server->server && !request->proxy_listener) return 0;
2300
2301         /*
2302          *      Delete any reply we had accumulated until now.
2303          */
2304         RDEBUG2("Clearing existing &reply: attributes");
2305         fr_pair_list_free(&request->reply->vps);
2306
2307         /*
2308          *      Run the packet through the post-proxy stage,
2309          *      BEFORE playing games with the attributes.
2310          */
2311         vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2312         if (vp) {
2313                 post_proxy_type = vp->vp_integer;
2314         /*
2315          *      If we have a proxy_reply, and it was a reject, or a NAK
2316          *      setup Post-Proxy <type>.
2317          *
2318          *      If the <type> doesn't have a section, then the Post-Proxy
2319          *      section is ignored.
2320          */
2321         } else if (reply) {
2322                 DICT_VALUE *dval = NULL;
2323
2324                 switch (reply->code) {
2325                 case PW_CODE_ACCESS_REJECT:
2326                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2327                         if (dval) post_proxy_type = dval->value;
2328                         break;
2329
2330                 case PW_CODE_DISCONNECT_NAK:
2331                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2332                         if (dval) post_proxy_type = dval->value;
2333                         break;
2334
2335                 case PW_CODE_COA_NAK:
2336                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2337                         if (dval) post_proxy_type = dval->value;
2338                         break;
2339
2340                 default:
2341                         break;
2342                 }
2343
2344                 /*
2345                  *      Create config:Post-Proxy-Type
2346                  */
2347                 if (dval) {
2348                         vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2349                         vp->vp_integer = dval->value;
2350                 }
2351         }
2352
2353         if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2354                                          dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2355
2356         if (reply) {
2357                 VERIFY_PACKET(reply);
2358
2359                 /*
2360                  *      Decode the packet if required.
2361                  */
2362                 if (request->proxy_listener) {
2363                         rcode = request->proxy_listener->decode(request->proxy_listener, request);
2364                         debug_packet(request, reply, true);
2365
2366                         /*
2367                          *      Pro-actively remove it from the proxy hash.
2368                          *      This is later than in 2.1.x, but it means that
2369                          *      the replies are authenticated before being
2370                          *      removed from the hash.
2371                          */
2372                         if ((rcode == 0) &&
2373                             (request->num_proxied_requests <= request->num_proxied_responses)) {
2374                                 remove_from_proxy_hash(request);
2375                         }
2376                 } else {
2377                         rad_assert(!request->in_proxy_hash);
2378                 }
2379         } else if (request->in_proxy_hash) {
2380                 remove_from_proxy_hash(request);
2381         }
2382
2383         if (request->home_pool && request->home_pool->virtual_server) {
2384                 char const *old_server = request->server;
2385
2386                 request->server = request->home_pool->virtual_server;
2387                 RDEBUG2("server %s {", request->server);
2388                 RINDENT();
2389                 rcode = process_post_proxy(post_proxy_type, request);
2390                 REXDENT();
2391                 RDEBUG2("}");
2392                 request->server = old_server;
2393         } else {
2394                 rcode = process_post_proxy(post_proxy_type, request);
2395         }
2396
2397 #ifdef WITH_COA
2398         if (request->packet->code == request->proxy->code)
2399           /*
2400            *    Don't run the next bit if we originated a CoA
2401            *    packet, after receiving an Access-Request or
2402            *    Accounting-Request.
2403            */
2404 #endif
2405
2406         /*
2407          *      There may NOT be a proxy reply, as we may be
2408          *      running Post-Proxy-Type = Fail.
2409          */
2410         if (reply) {
2411                 fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2412
2413                 /*
2414                  *      Delete the Proxy-State Attributes from
2415                  *      the reply.  These include Proxy-State
2416                  *      attributes from us and remote server.
2417                  */
2418                 fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2419         }
2420
2421         switch (rcode) {
2422         default:  /* Don't do anything */
2423                 break;
2424         case RLM_MODULE_FAIL:
2425                 return 0;
2426
2427         case RLM_MODULE_HANDLED:
2428                 return 0;
2429         }
2430
2431         return 1;
2432 }
2433
2434 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2435 {
2436         char buffer[128];
2437
2438         home->state = HOME_STATE_ALIVE;
2439         home->response_timeouts = 0;
2440         exec_trigger(request, home->cs, "home_server.alive", false);
2441         home->currently_outstanding = 0;
2442         home->num_sent_pings = 0;
2443         home->num_received_pings = 0;
2444         gettimeofday(&home->revive_time, NULL);
2445
2446         fr_event_delete(el, &home->ev);
2447
2448         RPROXY("Marking home server %s port %d alive",
2449                inet_ntop(request->proxy->dst_ipaddr.af,
2450                          &request->proxy->dst_ipaddr.ipaddr,
2451                          buffer, sizeof(buffer)),
2452                request->proxy->dst_port);
2453 }
2454
2455
2456 int request_proxy_reply(RADIUS_PACKET *packet)
2457 {
2458         RADIUS_PACKET **proxy_p;
2459         REQUEST *request;
2460         struct timeval now;
2461         char buffer[128];
2462
2463         VERIFY_PACKET(packet);
2464
2465         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2466         proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2467
2468         if (!proxy_p) {
2469                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2470                 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2471                        fr_packet_codes[packet->code],
2472                        inet_ntop(packet->src_ipaddr.af,
2473                                  &packet->src_ipaddr.ipaddr,
2474                                  buffer, sizeof(buffer)),
2475                        packet->src_port, packet->id);
2476                 return 0;
2477         }
2478
2479         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2480         request->num_proxied_responses++; /* needs to be protected by lock */
2481
2482         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2483
2484         /*
2485          *      No reply, BUT the current packet fails verification:
2486          *      ignore it.  This does the MD5 calculations in the
2487          *      server core, but I guess we can fix that later.
2488          */
2489         if (!request->proxy_reply &&
2490             (rad_verify(packet, request->proxy,
2491                         request->home_server->secret) != 0)) {
2492                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
2493                 return 0;
2494         }
2495
2496         /*
2497          *      The home server sent us a packet which doesn't match
2498          *      something we have: ignore it.  This is done only to
2499          *      catch the case of broken systems.
2500          */
2501         if (request->proxy_reply &&
2502             (memcmp(request->proxy_reply->vector,
2503                     packet->vector,
2504                     sizeof(request->proxy_reply->vector)) != 0)) {
2505                 RDEBUG2("Ignoring conflicting proxy reply");
2506                 return 0;
2507         }
2508
2509         gettimeofday(&now, NULL);
2510
2511         /*
2512          *      Status-Server packets don't count as real packets.
2513          */
2514         if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2515                 listen_socket_t *sock = request->proxy_listener->data;
2516
2517                 request->home_server->last_packet_recv = now.tv_sec;
2518                 sock->last_packet = now.tv_sec;
2519         }
2520
2521         /*
2522          *      If we have previously seen a reply, ignore the
2523          *      duplicate.
2524          */
2525         if (request->proxy_reply) {
2526                 RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d",
2527                         inet_ntop(packet->src_ipaddr.af,
2528                                   &packet->src_ipaddr.ipaddr,
2529                                   buffer, sizeof(buffer)),
2530                         packet->src_port, packet->id);
2531                 return 0;
2532         }
2533
2534         /*
2535          *      Call the state machine to do something useful with the
2536          *      request.
2537          */
2538         request->proxy_reply = talloc_steal(request, packet);
2539         packet->timestamp = now;
2540         request->priority = RAD_LISTEN_PROXY;
2541
2542 #ifdef WITH_STATS
2543         /*
2544          *      Update the proxy listener stats here, because only one
2545          *      thread accesses that at a time.  The home_server and
2546          *      main proxy_*_stats structures are updated once the
2547          *      request is cleaned up.
2548          */
2549         request->proxy_listener->stats.total_responses++;
2550
2551         request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2552         request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2553
2554         switch (request->proxy->code) {
2555         case PW_CODE_ACCESS_REQUEST:
2556                 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2557
2558                 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2559                         request->proxy_listener->stats.total_access_accepts++;
2560
2561                 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2562                         request->proxy_listener->stats.total_access_rejects++;
2563
2564                 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2565                         request->proxy_listener->stats.total_access_challenges++;
2566                 }
2567                 break;
2568
2569 #ifdef WITH_ACCOUNTING
2570         case PW_CODE_ACCOUNTING_REQUEST:
2571                 request->proxy_listener->stats.total_responses++;
2572                 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2573                 break;
2574
2575 #endif
2576
2577 #ifdef WITH_COA
2578         case PW_CODE_COA_REQUEST:
2579                 request->proxy_listener->stats.total_responses++;
2580                 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2581                 break;
2582
2583         case PW_CODE_DISCONNECT_REQUEST:
2584                 request->proxy_listener->stats.total_responses++;
2585                 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2586                 break;
2587
2588 #endif
2589         default:
2590                 break;
2591         }
2592 #endif
2593
2594         /*
2595          *      If we hadn't been sending the home server packets for
2596          *      a while, just mark it alive.  Or, if it was zombie,
2597          *      it's now responded, and is therefore alive.
2598          */
2599         if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2600             (request->home_server->state == HOME_STATE_ZOMBIE)) {
2601                 mark_home_server_alive(request, request->home_server);
2602         }
2603
2604         /*
2605          *      Tell the request state machine that we have a proxy
2606          *      reply.  Depending on the function, this should either
2607          *      ignore it, or process it.
2608          */
2609         request->process(request, FR_ACTION_PROXY_REPLY);
2610
2611         return 1;
2612 }
2613
2614
2615 static int setup_post_proxy_fail(REQUEST *request)
2616 {
2617         DICT_VALUE const *dval = NULL;
2618         VALUE_PAIR *vp;
2619
2620         VERIFY_REQUEST(request);
2621
2622         if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2623                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2624                                       "Fail-Authentication");
2625 #ifdef WITH_ACCOUNTING
2626         } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2627                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2628                                       "Fail-Accounting");
2629 #endif
2630
2631 #ifdef WITH_COA
2632         } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2633                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2634
2635         } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2636                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2637 #endif
2638         } else {
2639                 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2640                 return 0;
2641         }
2642
2643         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2644
2645         if (!dval) {
2646                 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2647                 return 0;
2648         }
2649
2650         vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2651         if (!vp) vp = radius_pair_create(request, &request->config,
2652                                         PW_POST_PROXY_TYPE, 0);
2653         vp->vp_integer = dval->value;
2654
2655         return 1;
2656 }
2657
2658
2659 /** Process a request after the proxy has timed out.
2660  *
2661  *  Run the packet through Post-Proxy-Type Fail
2662  *
2663  *  \dot
2664  *      digraph proxy_no_reply {
2665  *              proxy_no_reply;
2666  *
2667  *              proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2668  *              proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2669  *              proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2670  *              proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2671  *              proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2672  *      }
2673  *  \enddot
2674  */
2675 static void proxy_no_reply(REQUEST *request, int action)
2676 {
2677         VERIFY_REQUEST(request);
2678
2679         TRACE_STATE_MACHINE;
2680         CHECK_FOR_STOP;
2681
2682         switch (action) {
2683         case FR_ACTION_DUP:
2684                 request_dup(request);
2685                 break;
2686
2687         case FR_ACTION_TIMER:
2688                 (void) request_max_time(request);
2689                 break;
2690
2691         case FR_ACTION_PROXY_REPLY:
2692                 proxy_reply_too_late(request);
2693                 break;
2694
2695         case FR_ACTION_RUN:
2696                 if (process_proxy_reply(request, NULL)) {
2697                         request->handle(request);
2698                 }
2699                 request_finish(request, action);
2700                 break;
2701
2702         default:
2703                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2704                 break;
2705         }
2706 }
2707
2708 /** Process the request after receiving a proxy reply.
2709  *
2710  *  Throught the post-proxy section, and the through the handler
2711  *  function.
2712  *
2713  *  \dot
2714  *      digraph proxy_running {
2715  *              proxy_running;
2716  *
2717  *              proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2718  *              proxy_running -> timer [ label = "TIMER < max_request_time" ];
2719  *              proxy_running -> process_proxy_reply [ label = "RUN" ];
2720  *              proxy_running -> done [ label = "TIMER >= timeout" ];
2721  *      }
2722  *  \enddot
2723  */
2724 static void proxy_running(REQUEST *request, int action)
2725 {
2726         VERIFY_REQUEST(request);
2727
2728         TRACE_STATE_MACHINE;
2729         CHECK_FOR_STOP;
2730
2731         switch (action) {
2732         case FR_ACTION_DUP:
2733                 request_dup(request);
2734                 break;
2735
2736         case FR_ACTION_TIMER:
2737                 (void) request_max_time(request);
2738                 break;
2739
2740         case FR_ACTION_RUN:
2741                 if (process_proxy_reply(request, request->proxy_reply)) {
2742                         request->handle(request);
2743                 }
2744                 request_finish(request, action);
2745                 break;
2746
2747         default:                /* duplicate proxy replies are suppressed */
2748                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2749                 break;
2750         }
2751 }
2752
2753 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2754  *
2755  * Whether a request will be proxied is determined by the attributes present
2756  * in request->config. If any of the following attributes are found, the
2757  * request may be proxied.
2758  *
2759  * The key attributes are:
2760  *   - PW_PROXY_TO_REALM          - Specifies a realm the request should be proxied to.
2761  *   - PW_HOME_SERVER_POOL        - Specifies a specific home server pool to proxy to.
2762  *   - PW_PACKET_DST_IP_ADDRESS   - Specifies a specific IPv4 home server to proxy to.
2763  *   - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2764  *
2765  * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2766  *
2767  * If request should be proxied, will:
2768  *   - Add request:Proxy-State
2769  *   - Strip the current username value of its realm (depending on config)
2770  *   - Create a CHAP-Challenge from the original request vector, if one doesn't already
2771  *     exist.
2772  *   - Call the pre-process section in the current server, or in the virtual server
2773  *     associated with the home server pool we're proxying to.
2774  *
2775  * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2776  *      specific function.
2777  *
2778  * @param request The #REQUEST to evaluate for proxying.
2779  * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2780  */
2781 static int request_will_proxy(REQUEST *request)
2782 {
2783         int rcode, pre_proxy_type = 0;
2784         char const *realmname = NULL;
2785         VALUE_PAIR *vp, *strippedname;
2786         home_server_t *home;
2787         REALM *realm = NULL;
2788         home_pool_t *pool = NULL;
2789
2790         VERIFY_REQUEST(request);
2791
2792         if (!request->root->proxy_requests) return 0;
2793         if (request->packet->dst_port == 0) return 0;
2794         if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2795         if (request->in_proxy_hash) return 0;
2796
2797         /*
2798          *      FIXME: for 3.0, allow this only for rejects?
2799          */
2800         if (request->reply->code != 0) return 0;
2801
2802         vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2803         if (vp) {
2804                 realm = realm_find2(vp->vp_strvalue);
2805                 if (!realm) {
2806                         REDEBUG2("Cannot proxy to unknown realm %s",
2807                                 vp->vp_strvalue);
2808                         return 0;
2809                 }
2810
2811                 realmname = vp->vp_strvalue;
2812
2813                 /*
2814                  *      Figure out which pool to use.
2815                  */
2816                 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2817                         pool = realm->auth_pool;
2818
2819 #ifdef WITH_ACCOUNTING
2820                 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2821                         pool = realm->acct_pool;
2822 #endif
2823
2824 #ifdef WITH_COA
2825                 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2826                            (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2827                         pool = realm->coa_pool;
2828 #endif
2829
2830                 } else {
2831                         return 0;
2832                 }
2833
2834         } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2835                 int pool_type;
2836
2837                 switch (request->packet->code) {
2838                 case PW_CODE_ACCESS_REQUEST:
2839                         pool_type = HOME_TYPE_AUTH;
2840                         break;
2841
2842 #ifdef WITH_ACCOUNTING
2843                 case PW_CODE_ACCOUNTING_REQUEST:
2844                         pool_type = HOME_TYPE_ACCT;
2845                         break;
2846 #endif
2847
2848 #ifdef WITH_COA
2849                 case PW_CODE_COA_REQUEST:
2850                 case PW_CODE_DISCONNECT_REQUEST:
2851                         pool_type = HOME_TYPE_COA;
2852                         break;
2853 #endif
2854
2855                 default:
2856                         return 0;
2857                 }
2858
2859                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2860
2861                 /*
2862                  *      Send it directly to a home server (i.e. NAS)
2863                  */
2864         } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2865                    ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2866                 uint16_t dst_port;
2867                 fr_ipaddr_t dst_ipaddr;
2868
2869                 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2870
2871                 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2872                         dst_ipaddr.af = AF_INET;
2873                         dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2874                         dst_ipaddr.prefix = 32;
2875                 } else {
2876                         dst_ipaddr.af = AF_INET6;
2877                         memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2878                         dst_ipaddr.prefix = 128;
2879                 }
2880
2881                 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2882                 if (!vp) {
2883                         if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2884                                 dst_port = PW_AUTH_UDP_PORT;
2885
2886 #ifdef WITH_ACCOUNTING
2887                         } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2888                                 dst_port = PW_ACCT_UDP_PORT;
2889 #endif
2890
2891 #ifdef WITH_COA
2892                         } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2893                                    (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2894                                 dst_port = PW_COA_UDP_PORT;
2895 #endif
2896                         } else { /* shouldn't happen for RADIUS... */
2897                                 return 0;
2898                         }
2899
2900                 } else {
2901                         dst_port = vp->vp_integer;
2902                 }
2903
2904                 /*
2905                  *      Nothing does CoA over TCP.
2906                  */
2907                 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2908                 if (!home) {
2909                         char buffer[256];
2910
2911                         WARN("No such home server %s port %u",
2912                              inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2913                              (unsigned int) dst_port);
2914                         return 0;
2915                 }
2916
2917                 /*
2918                  *      The home server is alive (or may be alive).
2919                  *      Send the packet to the IP.
2920                  */
2921                 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2922
2923                 /*
2924                  *      The home server is dead.  If you wanted
2925                  *      fail-over, you should have proxied to a pool.
2926                  *      Sucks to be you.
2927                  */
2928
2929                 return 0;
2930
2931         } else {
2932                 return 0;
2933         }
2934
2935         if (!pool) {
2936                 RWDEBUG2("Cancelling proxy as no home pool exists");
2937                 return 0;
2938         }
2939
2940         if (request->listener->synchronous) {
2941                 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2942                 return 0;
2943         }
2944
2945         request->home_pool = pool;
2946
2947         home = home_server_ldb(realmname, pool, request);
2948
2949         if (!home) {
2950                 REDEBUG2("Failed to find live home server: Cancelling proxy");
2951                 return 0;
2952         }
2953
2954 do_home:
2955         home_server_update_request(home, request);
2956
2957 #ifdef WITH_COA
2958         /*
2959          *      Once we've decided to proxy a request, we cannot send
2960          *      a CoA packet.  So we free up any CoA packet here.
2961          */
2962         if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2963 #endif
2964
2965         /*
2966          *      Remember that we sent the request to a Realm.
2967          */
2968         if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2969
2970         /*
2971          *      Strip the name, if told to.
2972          *
2973          *      Doing it here catches the case of proxied tunneled
2974          *      requests.
2975          */
2976         if (realm && (realm->strip_realm == true) &&
2977            (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2978                 /*
2979                  *      If there's a Stripped-User-Name attribute in
2980                  *      the request, then use THAT as the User-Name
2981                  *      for the proxied request, instead of the
2982                  *      original name.
2983                  *
2984                  *      This is done by making a copy of the
2985                  *      Stripped-User-Name attribute, turning it into
2986                  *      a User-Name attribute, deleting the
2987                  *      Stripped-User-Name and User-Name attributes
2988                  *      from the vps list, and making the new
2989                  *      User-Name the head of the vps list.
2990                  */
2991                 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2992                 if (!vp) {
2993                         vp_cursor_t cursor;
2994                         vp = radius_pair_create(NULL, NULL,
2995                                                PW_USER_NAME, 0);
2996                         rad_assert(vp != NULL); /* handled by above function */
2997                         /* Insert at the START of the list */
2998                         /* FIXME: Can't make assumptions about ordering */
2999                         fr_cursor_init(&cursor, &vp);
3000                         fr_cursor_merge(&cursor, request->proxy->vps);
3001                         request->proxy->vps = vp;
3002                 }
3003                 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
3004
3005                 /*
3006                  *      Do NOT delete Stripped-User-Name.
3007                  */
3008         }
3009
3010         /*
3011          *      If there is no PW_CHAP_CHALLENGE attribute but
3012          *      there is a PW_CHAP_PASSWORD we need to add it
3013          *      since we can't use the request authenticator
3014          *      anymore - we changed it.
3015          */
3016         if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
3017             fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
3018             fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
3019                 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
3020                 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
3021         }
3022
3023         /*
3024          *      The RFC's say we have to do this, but FreeRADIUS
3025          *      doesn't need it.
3026          */
3027         vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3028         fr_pair_value_sprintf(vp, "%u", request->packet->id);
3029
3030         /*
3031          *      Should be done BEFORE inserting into proxy hash, as
3032          *      pre-proxy may use this information, or change it.
3033          */
3034         request->proxy->code = request->packet->code;
3035
3036         /*
3037          *      Call the pre-proxy routines.
3038          */
3039         vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3040         if (vp) {
3041                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3042                 /* Must be a validation issue */
3043                 rad_assert(dval);
3044                 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3045                 pre_proxy_type = vp->vp_integer;
3046         }
3047
3048         /*
3049          *      home_pool may be NULL when originating CoA packets,
3050          *      because they go directly to an IP address.
3051          */
3052         if (request->home_pool && request->home_pool->virtual_server) {
3053                 char const *old_server = request->server;
3054
3055                 request->server = request->home_pool->virtual_server;
3056
3057                 RDEBUG2("server %s {", request->server);
3058                 RINDENT();
3059                 rcode = process_pre_proxy(pre_proxy_type, request);
3060                 REXDENT();
3061                 RDEBUG2("}");
3062
3063                 request->server = old_server;
3064         } else {
3065                 rcode = process_pre_proxy(pre_proxy_type, request);
3066         }
3067
3068         switch (rcode) {
3069         case RLM_MODULE_FAIL:
3070         case RLM_MODULE_INVALID:
3071         case RLM_MODULE_NOTFOUND:
3072         case RLM_MODULE_USERLOCK:
3073         default:
3074                 /* FIXME: debug print failed stuff */
3075                 return -1;
3076
3077         case RLM_MODULE_REJECT:
3078         case RLM_MODULE_HANDLED:
3079                 return 0;
3080
3081         /*
3082          *      Only proxy the packet if the pre-proxy code succeeded.
3083          */
3084         case RLM_MODULE_NOOP:
3085         case RLM_MODULE_OK:
3086         case RLM_MODULE_UPDATED:
3087                 return 1;
3088         }
3089 }
3090
3091 static int proxy_to_virtual_server(REQUEST *request)
3092 {
3093         REQUEST *fake;
3094
3095         if (request->packet->dst_port == 0) {
3096                 WARN("Cannot proxy an internal request");
3097                 return 0;
3098         }
3099
3100         DEBUG("Proxying to virtual server %s",
3101               request->home_server->server);
3102
3103         /*
3104          *      Packets to virtual servers don't get
3105          *      retransmissions sent to them.  And the virtual
3106          *      server is run ONLY if we have no child
3107          *      threads, or we're running in a child thread.
3108          */
3109         rad_assert(!spawn_flag || !we_are_master());
3110
3111         fake = request_alloc_fake(request);
3112
3113         fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3114         talloc_free(request->proxy);
3115
3116         fake->server = request->home_server->server;
3117         fake->handle = request->handle;
3118         fake->process = NULL; /* should never be run for anything */
3119
3120         /*
3121          *      Run the virtual server.
3122          */
3123         request_running(fake, FR_ACTION_RUN);
3124
3125         request->proxy = talloc_steal(request, fake->packet);
3126         fake->packet = NULL;
3127         request->proxy_reply = talloc_steal(request, fake->reply);
3128         fake->reply = NULL;
3129
3130         talloc_free(fake);
3131
3132         /*
3133          *      No reply code, toss the reply we have,
3134          *      and do post-proxy-type Fail.
3135          */
3136         if (!request->proxy_reply->code) {
3137                 TALLOC_FREE(request->proxy_reply);
3138                 setup_post_proxy_fail(request);
3139         }
3140
3141         /*
3142          *      Do the proxy reply (if any)
3143          */
3144         if (process_proxy_reply(request, request->proxy_reply)) {
3145                 request->handle(request);
3146         }
3147
3148         return -1;      /* so we call request_finish */
3149 }
3150
3151
3152 static int request_proxy(REQUEST *request, int retransmit)
3153 {
3154         char buffer[128];
3155
3156         VERIFY_REQUEST(request);
3157
3158         rad_assert(request->parent == NULL);
3159         rad_assert(request->home_server != NULL);
3160
3161         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3162
3163 #ifdef WITH_COA
3164         if (request->coa) {
3165                 RWDEBUG("Cannot proxy and originate CoA packets at the same time.  Cancelling CoA request");
3166                 request_done(request->coa, FR_ACTION_DONE);
3167         }
3168 #endif
3169
3170         /*
3171          *      The request may need sending to a virtual server.
3172          *      This code is more than a little screwed up.  The rest
3173          *      of the state machine doesn't handle parent / child
3174          *      relationships well.  i.e. if the child request takes
3175          *      too long, the core will mark the *parent* as "stop
3176          *      processing".  And the child will continue without
3177          *      knowing anything...
3178          *
3179          *      So, we have some horrible hacks to get around that.
3180          */
3181         if (request->home_server->server) return proxy_to_virtual_server(request);
3182
3183         /*
3184          *      We're actually sending a proxied packet.  Do that now.
3185          */
3186         if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3187                 RPROXY("Failed to insert request into the proxy list");
3188                 return -1;
3189         }
3190
3191         rad_assert(request->proxy->id >= 0);
3192
3193         if (rad_debug_lvl) {
3194                 struct timeval *response_window;
3195
3196                 response_window = request_response_window(request);
3197
3198 #ifdef WITH_TLS
3199                 if (request->home_server->tls) {
3200                         RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3201                                 inet_ntop(request->proxy->dst_ipaddr.af,
3202                                           &request->proxy->dst_ipaddr.ipaddr,
3203                                           buffer, sizeof(buffer)),
3204                                 request->proxy->dst_port,
3205                                 (int) response_window->tv_sec, (int) response_window->tv_usec);
3206                 } else
3207 #endif
3208                         RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3209                                 inet_ntop(request->proxy->dst_ipaddr.af,
3210                                           &request->proxy->dst_ipaddr.ipaddr,
3211                                           buffer, sizeof(buffer)),
3212                                 request->proxy->dst_port,
3213                                 (int) response_window->tv_sec, (int) response_window->tv_usec);
3214
3215
3216         }
3217
3218         gettimeofday(&request->proxy_retransmit, NULL);
3219         if (!retransmit) {
3220                 request->proxy->timestamp = request->proxy_retransmit;
3221         }
3222         request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3223
3224         /*
3225          *      Encode the packet before we do anything else.
3226          */
3227         request->proxy_listener->encode(request->proxy_listener, request);
3228         debug_packet(request, request->proxy, false);
3229
3230         /*
3231          *      Set the state function, then the state, no child, and
3232          *      send the packet.
3233          *
3234          *      The order here is different from other state changes
3235          *      due to race conditions with replies from the home
3236          *      server.
3237          */
3238         request->process = proxy_wait_for_reply;
3239         request->child_state = REQUEST_PROXIED;
3240         request->component = "<REQUEST_PROXIED>";
3241         request->module = "";
3242         NO_CHILD_THREAD;
3243
3244         /*
3245          *      And send the packet.
3246          */
3247         request->proxy_listener->send(request->proxy_listener, request);
3248         return 1;
3249 }
3250
3251 /*
3252  *      Proxy the packet as if it was new.
3253  */
3254 static int request_proxy_anew(REQUEST *request)
3255 {
3256         home_server_t *home;
3257
3258         VERIFY_REQUEST(request);
3259
3260         /*
3261          *      Delete the request from the proxy list.
3262          *
3263          *      The packet list code takes care of ensuring that IDs
3264          *      aren't reused until all 256 IDs have been used.  So
3265          *      there's a 1/256 chance of re-using the same ID when
3266          *      we're sending to the same home server.  Which is
3267          *      acceptable.
3268          */
3269         remove_from_proxy_hash(request);
3270
3271         /*
3272          *      Find a live home server for the request.
3273          */
3274         home = home_server_ldb(NULL, request->home_pool, request);
3275         if (!home) {
3276                 REDEBUG2("Failed to find live home server for request");
3277         post_proxy_fail:
3278                 if (setup_post_proxy_fail(request)) {
3279                         request_queue_or_run(request, proxy_running);
3280                 } else {
3281                         gettimeofday(&request->reply->timestamp, NULL);
3282                         request_cleanup_delay_init(request);
3283                 }
3284                 return 0;
3285         }
3286
3287 #ifdef WITH_ACCOUNTING
3288         /*
3289          *      Update the Acct-Delay-Time attribute.
3290          */
3291         if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3292                 VALUE_PAIR *vp;
3293
3294                 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3295                 if (!vp) vp = radius_pair_create(request->proxy,
3296                                                 &request->proxy->vps,
3297                                                 PW_ACCT_DELAY_TIME, 0);
3298                 if (vp) {
3299                         struct timeval now;
3300
3301                         gettimeofday(&now, NULL);
3302                         vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3303                 }
3304         }
3305 #endif
3306
3307         /*
3308          *      May have failed over to a "fallback" virtual server.
3309          *      If so, run that instead of doing proxying to a real
3310          *      server.
3311          */
3312         if (home->server) {
3313                 request->home_server = home;
3314                 TALLOC_FREE(request->proxy);
3315
3316                 (void) proxy_to_virtual_server(request);
3317                 return 0;
3318         }
3319
3320         home_server_update_request(home, request);
3321
3322         if (!insert_into_proxy_hash(request)) {
3323                 RPROXY("Failed to insert retransmission into the proxy list");
3324                 goto post_proxy_fail;
3325         }
3326
3327         /*
3328          *      Free the old packet, to force re-encoding
3329          */
3330         talloc_free(request->proxy->data);
3331         request->proxy->data = NULL;
3332         request->proxy->data_len = 0;
3333
3334         if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3335
3336         return 1;
3337 }
3338
3339
3340 /** Ping a home server.
3341  *
3342  */
3343 static void request_ping(REQUEST *request, int action)
3344 {
3345         home_server_t *home = request->home_server;
3346         char buffer[128];
3347
3348         VERIFY_REQUEST(request);
3349
3350         TRACE_STATE_MACHINE;
3351         ASSERT_MASTER;
3352
3353         switch (action) {
3354         case FR_ACTION_TIMER:
3355                 ERROR("No response to status check %d ID %u for home server %s port %d",
3356                        request->number,
3357                        request->proxy->id,
3358                        inet_ntop(request->proxy->dst_ipaddr.af,
3359                                  &request->proxy->dst_ipaddr.ipaddr,
3360                                  buffer, sizeof(buffer)),
3361                        request->proxy->dst_port);
3362                 break;
3363
3364         case FR_ACTION_PROXY_REPLY:
3365                 rad_assert(request->in_proxy_hash);
3366
3367                 request->home_server->num_received_pings++;
3368                 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3369                        request->number, request->proxy->id, home->num_received_pings);
3370
3371                 /*
3372                  *      Remove the request from any hashes
3373                  */
3374                 fr_event_delete(el, &request->ev);
3375                 remove_from_proxy_hash(request);
3376
3377                 /*
3378                  *      The control socket may have marked the home server as
3379                  *      alive.  OR, it may have suddenly started responding to
3380                  *      requests again.  If so, don't re-do the "make alive"
3381                  *      work.
3382                  */
3383                 if (home->state == HOME_STATE_ALIVE) break;
3384
3385                 /*
3386                  *      It's dead, and we haven't received enough ping
3387                  *      responses to mark it "alive".  Wait a bit.
3388                  *
3389                  *      If it's zombie, we mark it alive immediately.
3390                  */
3391                 if ((home->state == HOME_STATE_IS_DEAD) &&
3392                     (home->num_received_pings < home->num_pings_to_alive)) {
3393                         return;
3394                 }
3395
3396                 /*
3397                  *      Mark it alive and delete any outstanding
3398                  *      pings.
3399                  */
3400                 mark_home_server_alive(request, home);
3401                 break;
3402
3403         default:
3404                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3405                 break;
3406         }
3407
3408         rad_assert(!request->in_request_hash);
3409         rad_assert(request->ev == NULL);
3410         NO_CHILD_THREAD;
3411         request_done(request, FR_ACTION_DONE);
3412 }
3413
3414 /*
3415  *      Called from start of zombie period, OR after control socket
3416  *      marks the home server dead.
3417  */
3418 static void ping_home_server(void *ctx)
3419 {
3420         home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3421         REQUEST *request;
3422         VALUE_PAIR *vp;
3423         struct timeval when, now;
3424
3425         if ((home->state == HOME_STATE_ALIVE) ||
3426 #ifdef WITH_TCP
3427             (home->proto == IPPROTO_TCP) ||
3428 #endif
3429             (home->ev != NULL)) {
3430                 return;
3431         }
3432
3433         gettimeofday(&now, NULL);
3434         ASSERT_MASTER;
3435
3436         /*
3437          *      We've run out of zombie time.  Mark it dead.
3438          */
3439         if (home->state == HOME_STATE_ZOMBIE) {
3440                 when = home->zombie_period_start;
3441                 when.tv_sec += home->zombie_period;
3442
3443                 if (timercmp(&when, &now, <)) {
3444                         DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3445                         mark_home_server_dead(home, &now);
3446                 }
3447         }
3448
3449         /*
3450          *      We're not supposed to be pinging it.  Just wake up
3451          *      when we're supposed to mark it dead.
3452          */
3453         if (home->ping_check == HOME_PING_CHECK_NONE) {
3454                 if (home->state == HOME_STATE_ZOMBIE) {
3455                         home->when = home->zombie_period_start;
3456                         home->when.tv_sec += home->zombie_period;
3457                         INSERT_EVENT(ping_home_server, home);
3458                 }
3459
3460                 /*
3461                  *      Else mark_home_server_dead will set a timer
3462                  *      for revive_interval.
3463                  */
3464                 return;
3465         }
3466
3467
3468         request = request_alloc(NULL);
3469         if (!request) return;
3470         request->number = request_num_counter++;
3471         NO_CHILD_THREAD;
3472
3473         request->proxy = rad_alloc(request, true);
3474         rad_assert(request->proxy != NULL);
3475
3476         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3477                 request->proxy->code = PW_CODE_STATUS_SERVER;
3478
3479                 fr_pair_make(request->proxy, &request->proxy->vps,
3480                          "Message-Authenticator", "0x00", T_OP_SET);
3481
3482         } else if (home->type == HOME_TYPE_AUTH) {
3483                 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3484
3485                 fr_pair_make(request->proxy, &request->proxy->vps,
3486                          "User-Name", home->ping_user_name, T_OP_SET);
3487                 fr_pair_make(request->proxy, &request->proxy->vps,
3488                          "User-Password", home->ping_user_password, T_OP_SET);
3489                 fr_pair_make(request->proxy, &request->proxy->vps,
3490                          "Service-Type", "Authenticate-Only", T_OP_SET);
3491                 fr_pair_make(request->proxy, &request->proxy->vps,
3492                          "Message-Authenticator", "0x00", T_OP_SET);
3493
3494         } else {
3495 #ifdef WITH_ACCOUNTING
3496                 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3497
3498                 fr_pair_make(request->proxy, &request->proxy->vps,
3499                          "User-Name", home->ping_user_name, T_OP_SET);
3500                 fr_pair_make(request->proxy, &request->proxy->vps,
3501                          "Acct-Status-Type", "Stop", T_OP_SET);
3502                 fr_pair_make(request->proxy, &request->proxy->vps,
3503                          "Acct-Session-Id", "00000000", T_OP_SET);
3504                 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3505                               "Event-Timestamp", "0", T_OP_SET);
3506                 vp->vp_date = now.tv_sec;
3507 #else
3508                 rad_assert("Internal sanity check failed");
3509 #endif
3510         }
3511
3512         vp = fr_pair_make(request->proxy, &request->proxy->vps,
3513                       "NAS-Identifier", "", T_OP_SET);
3514         if (vp) {
3515                 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3516                             home->num_sent_pings);
3517         }
3518
3519 #ifdef WITH_TCP
3520         request->proxy->proto = home->proto;
3521 #endif
3522         request->proxy->src_ipaddr = home->src_ipaddr;
3523         request->proxy->dst_ipaddr = home->ipaddr;
3524         request->proxy->dst_port = home->port;
3525         request->home_server = home;
3526 #ifdef DEBUG_STATE_MACHINE
3527         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3528                                child_state_names[request->child_state],
3529                                child_state_names[REQUEST_DONE]);
3530         if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3531 #endif
3532 #ifdef HAVE_PTHREAD_H
3533         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3534 #endif
3535         request->child_state = REQUEST_PROXIED;
3536         request->process = request_ping;
3537
3538         rad_assert(request->proxy_listener == NULL);
3539
3540         if (!insert_into_proxy_hash(request)) {
3541                 RPROXY("Failed to insert status check %d into proxy list.  Discarding it.",
3542                        request->number);
3543
3544                 rad_assert(!request->in_request_hash);
3545                 rad_assert(!request->in_proxy_hash);
3546                 rad_assert(request->ev == NULL);
3547                 talloc_free(request);
3548                 return;
3549         }
3550
3551         /*
3552          *      Set up the timer callback.
3553          */
3554         when = now;
3555         when.tv_sec += home->ping_timeout;
3556
3557         DEBUG("PING: Waiting %u seconds for response to ping",
3558               home->ping_timeout);
3559
3560         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3561         home->num_sent_pings++;
3562
3563         rad_assert(request->proxy_listener != NULL);
3564         debug_packet(request, request->proxy, false);
3565         request->proxy_listener->send(request->proxy_listener,
3566                                       request);
3567
3568         /*
3569          *      Add +/- 2s of jitter, as suggested in RFC 3539
3570          *      and in the Issues and Fixes draft.
3571          */
3572         home->when = now;
3573         home->when.tv_sec += home->ping_interval;
3574
3575         add_jitter(&home->when);
3576
3577         DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3578         INSERT_EVENT(ping_home_server, home);
3579 }
3580
3581 static void home_trigger(home_server_t *home, char const *trigger)
3582 {
3583         REQUEST *my_request;
3584         RADIUS_PACKET *my_packet;
3585
3586         my_request = talloc_zero(NULL, REQUEST);
3587         my_packet = talloc_zero(my_request, RADIUS_PACKET);
3588         my_request->proxy = my_packet;
3589         my_packet->dst_ipaddr = home->ipaddr;
3590         my_packet->src_ipaddr = home->src_ipaddr;
3591
3592         exec_trigger(my_request, home->cs, trigger, false);
3593         talloc_free(my_request);
3594 }
3595
3596 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3597 {
3598         time_t start;
3599         char buffer[128];
3600
3601         ASSERT_MASTER;
3602
3603         rad_assert((home->state == HOME_STATE_ALIVE) ||
3604                    (home->state == HOME_STATE_UNKNOWN));
3605
3606 #ifdef WITH_TCP
3607         if (home->proto == IPPROTO_TCP) {
3608                 WARN("Not marking TCP server %s zombie", home->log_name);
3609                 return;
3610         }
3611 #endif
3612
3613         /*
3614          *      We've received a real packet recently.  Don't mark the
3615          *      server as zombie until we've received NO packets for a
3616          *      while.  The "1/4" of zombie period was chosen rather
3617          *      arbitrarily.  It's a balance between too short, which
3618          *      gives quick fail-over and fail-back, or too long,
3619          *      where the proxy still sends packets to an unresponsive
3620          *      home server.
3621          */
3622         start = now->tv_sec - ((home->zombie_period + 3) / 4);
3623         if (home->last_packet_recv >= start) {
3624                 DEBUG("Recieved reply from home server %d seconds ago.  Might not be zombie.",
3625                       (int) (now->tv_sec - home->last_packet_recv));
3626                 return;
3627         }
3628
3629         home->state = HOME_STATE_ZOMBIE;
3630         home_trigger(home, "home_server.zombie");
3631
3632         /*
3633          *      Set the home server to "zombie", as of the time
3634          *      calculated above.
3635          */
3636         home->zombie_period_start.tv_sec = start;
3637         home->zombie_period_start.tv_usec = USEC / 2;
3638
3639         fr_event_delete(el, &home->ev);
3640
3641         home->num_sent_pings = 0;
3642         home->num_received_pings = 0;
3643
3644         PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3645                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3646                          buffer, sizeof(buffer)),
3647                home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3648
3649         ping_home_server(home);
3650 }
3651
3652
3653 void revive_home_server(void *ctx)
3654 {
3655         home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3656         char buffer[128];
3657
3658 #ifdef WITH_TCP
3659         rad_assert(home->proto != IPPROTO_TCP);
3660 #endif
3661
3662         home->state = HOME_STATE_ALIVE;
3663         home->response_timeouts = 0;
3664         home_trigger(home, "home_server.alive");
3665         home->currently_outstanding = 0;
3666         gettimeofday(&home->revive_time, NULL);
3667
3668         /*
3669          *      Delete any outstanding events.
3670          */
3671         ASSERT_MASTER;
3672         if (home->ev) fr_event_delete(el, &home->ev);
3673
3674         PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3675                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3676                          buffer, sizeof(buffer)),
3677                home->port);
3678 }
3679
3680 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3681 {
3682         int previous_state = home->state;
3683         char buffer[128];
3684
3685 #ifdef WITH_TCP
3686         if (home->proto == IPPROTO_TCP) {
3687                 WARN("Not marking TCP server dead");
3688                 return;
3689         }
3690 #endif
3691
3692         PROXY( "Marking home server %s port %d as dead.",
3693                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3694                          buffer, sizeof(buffer)),
3695                home->port);
3696
3697         home->state = HOME_STATE_IS_DEAD;
3698         home_trigger(home, "home_server.dead");
3699
3700         if (home->ping_check != HOME_PING_CHECK_NONE) {
3701                 /*
3702                  *      If the control socket marks us dead, start
3703                  *      pinging.  Otherwise, we already started
3704                  *      pinging when it was marked "zombie".
3705                  */
3706                 if (previous_state == HOME_STATE_ALIVE) {
3707                         ping_home_server(home);
3708                 } else {
3709                         DEBUG("PING: Already pinging home server %s", home->log_name);
3710                 }
3711
3712         } else {
3713                 /*
3714                  *      Revive it after a fixed period of time.  This
3715                  *      is very, very, bad.
3716                  */
3717                 home->when = *when;
3718                 home->when.tv_sec += home->revive_interval;
3719
3720                 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3721                 ASSERT_MASTER;
3722                 INSERT_EVENT(revive_home_server, home);
3723         }
3724 }
3725
3726 /** Wait for a reply after proxying a request.
3727  *
3728  *  Retransmit the proxied packet, or time out and go to
3729  *  proxy_no_reply.  Mark the home server unresponsive, etc.
3730  *
3731  *  If we do receive a reply, we transition to proxy_running.
3732  *
3733  *  \dot
3734  *      digraph proxy_wait_for_reply {
3735  *              proxy_wait_for_reply;
3736  *
3737  *              proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3738  *              proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3739  *              proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3740  *              proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3741  *              proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3742  *      }
3743  *  \enddot
3744  */
3745 static void proxy_wait_for_reply(REQUEST *request, int action)
3746 {
3747         struct timeval now, when;
3748         struct timeval *response_window = NULL;
3749         home_server_t *home = request->home_server;
3750         char buffer[128];
3751
3752         VERIFY_REQUEST(request);
3753
3754         TRACE_STATE_MACHINE;
3755         CHECK_FOR_STOP;
3756
3757         rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3758         rad_assert(request->home_server != NULL);
3759
3760         gettimeofday(&now, NULL);
3761
3762         switch (action) {
3763         case FR_ACTION_DUP:
3764                 /*
3765                  *      We have a reply, ignore the retransmit.
3766                  */
3767                 if (request->proxy_reply) return;
3768
3769                 /*
3770                  *      The request was proxied to a virtual server.
3771                  *      Ignore the retransmit.
3772                  */
3773                 if (request->home_server->server) return;
3774
3775                 /*
3776                  *      Use a new connection when the home server is
3777                  *      dead, or when there's no proxy listener, or
3778                  *      when the listener is failed or dead.
3779                  *
3780                  *      If the listener is known or frozen, use it for
3781                  *      retransmits.
3782                  */
3783                 if ((home->state == HOME_STATE_IS_DEAD) ||
3784                     !request->proxy_listener ||
3785                     (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3786                         request_proxy_anew(request);
3787                         return;
3788                 }
3789
3790 #ifdef WITH_TCP
3791                 /*
3792                  *      The home server is still alive, but TCP.  We
3793                  *      rely on TCP to get the request and reply back.
3794                  *      So there's no need to retransmit.
3795                  */
3796                 if (home->proto == IPPROTO_TCP) {
3797                         DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3798                                inet_ntop(request->proxy->dst_ipaddr.af,
3799                                          &request->proxy->dst_ipaddr.ipaddr,
3800                                          buffer, sizeof(buffer)),
3801                                request->proxy->dst_port,
3802                                request->proxy->id);
3803                         return;
3804                 }
3805 #endif
3806
3807                 /*
3808                  *      More than one retransmit a second is stupid,
3809                  *      and should be suppressed by the proxy.
3810                  */
3811                 when = request->proxy_retransmit;
3812                 when.tv_sec++;
3813
3814                 if (timercmp(&now, &when, <)) {
3815                         DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3816                                inet_ntop(request->proxy->dst_ipaddr.af,
3817                                          &request->proxy->dst_ipaddr.ipaddr,
3818                                          buffer, sizeof(buffer)),
3819                                request->proxy->dst_port,
3820                                request->proxy->id);
3821                         return;
3822                 }
3823
3824 #ifdef WITH_ACCOUNTING
3825                 /*
3826                  *      If we update the Acct-Delay-Time, we need to
3827                  *      get a new ID.
3828                  */
3829                 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3830                     fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3831                         request_proxy_anew(request);
3832                         return;
3833                 }
3834 #endif
3835
3836                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3837                         inet_ntop(request->proxy->dst_ipaddr.af,
3838                                   &request->proxy->dst_ipaddr.ipaddr,
3839                                   buffer, sizeof(buffer)),
3840                         request->proxy->dst_port,
3841                         request->proxy->id);
3842                 request->num_proxied_requests++;
3843
3844                 rad_assert(request->proxy_listener != NULL);
3845                 FR_STATS_TYPE_INC(home->stats.total_requests);
3846                 home->last_packet_sent = now.tv_sec;
3847                 request->proxy_retransmit = now;
3848                 debug_packet(request, request->proxy, false);
3849                 request->proxy_listener->send(request->proxy_listener, request);
3850                 break;
3851
3852         case FR_ACTION_TIMER:
3853                 response_window = request_response_window(request);
3854
3855 #ifdef WITH_TCP
3856                 if (!request->proxy_listener ||
3857                     (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3858                         remove_from_proxy_hash(request);
3859
3860                         when = request->packet->timestamp;
3861                         when.tv_sec += request->root->max_request_time;
3862
3863                         if (timercmp(&when, &now, >)) {
3864                                 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3865                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3866                                 return;
3867                         }
3868                 } else
3869 #endif
3870                 {
3871                         /*
3872                          *      Wake up "response_window" time in the future.
3873                          *      i.e. when MY packet hasn't received a response.
3874                          *
3875                          *      Note that we DO NOT mark the home server as
3876                          *      zombie if it doesn't respond to us.  It may be
3877                          *      responding to other (better looking) packets.
3878                          */
3879                         when = request->proxy->timestamp;
3880                         timeradd(&when, response_window, &when);
3881
3882                         /*
3883                          *      Not at the response window.  Set the timer for
3884                          *      that.
3885                          */
3886                         if (timercmp(&when, &now, >)) {
3887                                 struct timeval diff;
3888                                 timersub(&when, &now, &diff);
3889
3890                                 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3891                                        (int) diff.tv_sec, (int) diff.tv_usec);
3892                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3893                                 return;
3894                         }
3895                 }
3896
3897                 RDEBUG("No proxy response, giving up on request and marking it done");
3898
3899                 /*
3900                  *      If we haven't received any packets for
3901                  *      "response_window", then mark the home server
3902                  *      as zombie.
3903                  *
3904                  *      If the connection is TCP, then another
3905                  *      "watchdog timer" function takes care of pings,
3906                  *      etc.  So we don't need to do it here.
3907                  *
3908                  *      This check should really be part of a home
3909                  *      server state machine.
3910                  */
3911                 if (((home->state == HOME_STATE_ALIVE) ||
3912                      (home->state == HOME_STATE_UNKNOWN))
3913 #ifdef WITH_TCP
3914                     && (home->proto != IPPROTO_TCP)
3915 #endif
3916                         ) {
3917                         home->response_timeouts++;
3918                         if (home->response_timeouts >= home->max_response_timeouts)
3919                                 mark_home_server_zombie(home, &now, response_window);
3920                 }
3921
3922                 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3923                 if (home->type == HOME_TYPE_AUTH) {
3924                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3925                         FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3926                 }
3927 #ifdef WITH_ACCT
3928                 else if (home->type == HOME_TYPE_ACCT) {
3929                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3930                         FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3931                 }
3932 #endif
3933
3934                 /*
3935                  *      There was no response within the window.  Stop
3936                  *      the request.  If the client retransmitted, it
3937                  *      may have failed over to another home server.
3938                  *      But that one may be dead, too.
3939                  *
3940                  *      The extra verbose message if we have a username,
3941                  *      is extremely useful if the proxy is part of a chain
3942                  *      and the final home server, is not the one we're
3943                  *      proxying to.
3944                  */
3945                 if (request->username) {
3946                         RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3947                                "server %s port %d",
3948                                request->username->vp_strvalue,
3949                                inet_ntop(request->proxy->dst_ipaddr.af,
3950                                          &request->proxy->dst_ipaddr.ipaddr,
3951                                          buffer, sizeof(buffer)),
3952                                request->proxy->dst_port);
3953                 } else {
3954                         RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3955                                inet_ntop(request->proxy->dst_ipaddr.af,
3956                                          &request->proxy->dst_ipaddr.ipaddr,
3957                                          buffer, sizeof(buffer)),
3958                                request->proxy->dst_port);
3959                 }
3960
3961                 if (setup_post_proxy_fail(request)) {
3962                         request_queue_or_run(request, proxy_no_reply);
3963                 } else {
3964                         gettimeofday(&request->reply->timestamp, NULL);
3965                         request_cleanup_delay_init(request);
3966                 }
3967                 break;
3968
3969                 /*
3970                  *      We received a new reply.  Go process it.
3971                  */
3972         case FR_ACTION_PROXY_REPLY:
3973                 request_queue_or_run(request, proxy_running);
3974                 break;
3975
3976         default:
3977                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3978                 break;
3979         }
3980 }
3981 #endif  /* WITH_PROXY */
3982
3983
3984 /***********************************************************************
3985  *
3986  *  CoA code
3987  *
3988  ***********************************************************************/
3989 #ifdef WITH_COA
3990 static int null_handler(UNUSED REQUEST *request)
3991 {
3992         return 0;
3993 }
3994
3995 /*
3996  *      See if we need to originate a CoA request.
3997  */
3998 static void request_coa_originate(REQUEST *request)
3999 {
4000         int rcode, pre_proxy_type = 0;
4001         VALUE_PAIR *vp;
4002         REQUEST *coa;
4003         fr_ipaddr_t ipaddr;
4004         char buffer[256];
4005
4006         VERIFY_REQUEST(request);
4007
4008         rad_assert(request->coa != NULL);
4009         rad_assert(request->proxy == NULL);
4010         rad_assert(!request->in_proxy_hash);
4011         rad_assert(request->proxy_reply == NULL);
4012
4013         /*
4014          *      Check whether we want to originate one, or cancel one.
4015          */
4016         vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4017         if (!vp) {
4018                 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4019         }
4020
4021         if (vp) {
4022                 if (vp->vp_integer == 0) {
4023                 fail:
4024                         TALLOC_FREE(request->coa);
4025                         return;
4026                 }
4027         }
4028
4029         coa = request->coa;
4030
4031         /*
4032          *      src_ipaddr will be set up in proxy_encode.
4033          */
4034         memset(&ipaddr, 0, sizeof(ipaddr));
4035         vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4036         if (vp) {
4037                 ipaddr.af = AF_INET;
4038                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4039                 ipaddr.prefix = 32;
4040         } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4041                 ipaddr.af = AF_INET6;
4042                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4043                 ipaddr.prefix = 128;
4044         } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4045                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4046                                                   HOME_TYPE_COA);
4047                 if (!coa->home_pool) {
4048                         RWDEBUG2("No such home_server_pool %s",
4049                                vp->vp_strvalue);
4050                         goto fail;
4051                 }
4052
4053                 /*
4054                  *      Prefer the pool to one server
4055                  */
4056         } else if (request->client->coa_pool) {
4057                 coa->home_pool = request->client->coa_pool;
4058
4059         } else if (request->client->coa_server) {
4060                 coa->home_server = request->client->coa_server;
4061
4062         } else {
4063                 /*
4064                  *      If all else fails, send it to the client that
4065                  *      originated this request.
4066                  */
4067                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4068         }
4069
4070         /*
4071          *      Use the pool, if it exists.
4072          */
4073         if (coa->home_pool) {
4074                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4075                 if (!coa->home_server) {
4076                         RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4077                         goto fail;
4078                 }
4079                 home_server_update_request(coa->home_server, coa);
4080
4081         } else if (!coa->home_server) {
4082                 uint16_t port = PW_COA_UDP_PORT;
4083
4084                 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4085                 if (vp) port = vp->vp_integer;
4086
4087                 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4088                 if (!coa->home_server) {
4089                         RWDEBUG2("Unknown destination %s:%d for CoA request.",
4090                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4091                                          buffer, sizeof(buffer)), port);
4092                         goto fail;
4093                 }
4094         }
4095
4096         vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4097         if (vp) {
4098                 switch (vp->vp_integer) {
4099                 case PW_CODE_COA_REQUEST:
4100                 case PW_CODE_DISCONNECT_REQUEST:
4101                         coa->proxy->code = vp->vp_integer;
4102                         break;
4103
4104                 default:
4105                         DEBUG("Cannot set CoA Packet-Type to code %d",
4106                               vp->vp_integer);
4107                         goto fail;
4108                 }
4109         }
4110
4111         if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4112
4113         /*
4114          *      The rest of the server code assumes that
4115          *      request->packet && request->reply exist.  Copy them
4116          *      from the original request.
4117          */
4118         rad_assert(coa->packet != NULL);
4119         rad_assert(coa->packet->vps == NULL);
4120
4121         coa->packet = rad_copy_packet(coa, request->packet);
4122         coa->reply = rad_copy_packet(coa, request->reply);
4123
4124         coa->config = fr_pair_list_copy(coa, request->config);
4125         coa->num_coa_requests = 0;
4126         coa->handle = null_handler;
4127         coa->number = request->number; /* it's associated with the same request */
4128
4129         /*
4130          *      Call the pre-proxy routines.
4131          */
4132         vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4133         if (vp) {
4134                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4135                 /* Must be a validation issue */
4136                 rad_assert(dval);
4137                 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4138                 pre_proxy_type = vp->vp_integer;
4139         }
4140
4141         if (coa->home_pool && coa->home_pool->virtual_server) {
4142                 char const *old_server = coa->server;
4143
4144                 coa->server = coa->home_pool->virtual_server;
4145                 RDEBUG2("server %s {", coa->server);
4146                 RINDENT();
4147                 rcode = process_pre_proxy(pre_proxy_type, coa);
4148                 REXDENT();
4149                 RDEBUG2("}");
4150                 coa->server = old_server;
4151         } else {
4152                 rcode = process_pre_proxy(pre_proxy_type, coa);
4153         }
4154         switch (rcode) {
4155         default:
4156                 goto fail;
4157
4158         /*
4159          *      Only send the CoA packet if the pre-proxy code succeeded.
4160          */
4161         case RLM_MODULE_NOOP:
4162         case RLM_MODULE_OK:
4163         case RLM_MODULE_UPDATED:
4164                 break;
4165         }
4166
4167         /*
4168          *      Source IP / port is set when the proxy socket
4169          *      is chosen.
4170          */
4171         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4172         coa->proxy->dst_port = coa->home_server->port;
4173
4174         if (!insert_into_proxy_hash(coa)) {
4175                 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4176                 goto fail;
4177         }
4178
4179         /*
4180          *      We CANNOT divorce the CoA request from the parent
4181          *      request.  This function is running in a child thread,
4182          *      and we need access to the main event loop in order to
4183          *      to add the timers for the CoA packet.
4184          *
4185          *      Instead, we wait for the timer on the parent request
4186          *      to fire.
4187          */
4188         gettimeofday(&coa->proxy->timestamp, NULL);
4189         coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4190         coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4191         coa->delay = 0;         /* need to calculate a new delay */
4192
4193         /*
4194          *      If requested, put a State attribute into the packet,
4195          *      and cache the VPS.
4196          */
4197         fr_state_put_vps(coa, NULL, coa->packet);
4198
4199         /*
4200          *      Encode the packet before we do anything else.
4201          */
4202         coa->proxy_listener->encode(coa->proxy_listener, coa);
4203         debug_packet(coa, coa->proxy, false);
4204
4205 #ifdef DEBUG_STATE_MACHINE
4206         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4207                                child_state_names[request->child_state],
4208                                child_state_names[REQUEST_PROXIED]);
4209 #endif
4210
4211         /*
4212          *      Set the state function, then the state, no child, and
4213          *      send the packet.
4214          */
4215         coa->process = coa_wait_for_reply;
4216         coa->child_state = REQUEST_PROXIED;
4217
4218 #ifdef HAVE_PTHREAD_H
4219         coa->child_pid = NO_SUCH_CHILD_PID;
4220 #endif
4221
4222         if (we_are_master()) coa_separate(request->coa);
4223
4224         /*
4225          *      And send the packet.
4226          */
4227         coa->proxy_listener->send(coa->proxy_listener, coa);
4228 }
4229
4230
4231 static void coa_retransmit(REQUEST *request)
4232 {
4233         uint32_t delay, frac;
4234         struct timeval now, when, mrd;
4235         char buffer[128];
4236
4237         VERIFY_REQUEST(request);
4238
4239         fr_event_now(el, &now);
4240
4241         if (request->delay == 0) {
4242                 /*
4243                  *      Implement re-transmit algorithm as per RFC 5080
4244                  *      Section 2.2.1.
4245                  *
4246                  *      We want IRT + RAND*IRT
4247                  *      or 0.9 IRT + rand(0,.2) IRT
4248                  *
4249                  *      2^20 ~ USEC, and we want 2.
4250                  *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4251                  */
4252                 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4253                 request->delay = delay * request->home_server->coa_irt;
4254                 delay = request->home_server->coa_irt * USEC;
4255                 delay -= delay / 10;
4256                 delay += request->delay;
4257                 request->delay = delay;
4258
4259                 when = request->proxy->timestamp;
4260                 tv_add(&when, delay);
4261
4262                 if (timercmp(&when, &now, >)) {
4263                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4264                         return;
4265                 }
4266         }
4267
4268         /*
4269          *      Retransmit CoA request.
4270          */
4271
4272         /*
4273          *      Cap count at MRC, if it is non-zero.
4274          */
4275         if (request->home_server->coa_mrc &&
4276             (request->num_coa_requests >= request->home_server->coa_mrc)) {
4277                 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4278                        request->proxy->id,
4279                                inet_ntop(request->proxy->dst_ipaddr.af,
4280                                          &request->proxy->dst_ipaddr.ipaddr,
4281                                          buffer, sizeof(buffer)),
4282                                request->proxy->dst_port);
4283
4284                 if (setup_post_proxy_fail(request)) {
4285                         request_queue_or_run(request, coa_no_reply);
4286                 } else {
4287                         request_done(request, FR_ACTION_DONE);
4288                 }
4289                 return;
4290         }
4291
4292         /*
4293          *      RFC 5080 Section 2.2.1
4294          *
4295          *      RT = 2*RTprev + RAND*RTprev
4296          *         = 1.9 * RTprev + rand(0,.2) * RTprev
4297          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4298          */
4299         delay = fr_rand();
4300         delay ^= (delay >> 16);
4301         delay &= 0xffff;
4302         frac = request->delay / 5;
4303         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4304
4305         delay += (2 * request->delay) - (request->delay / 10);
4306
4307         /*
4308          *      Cap delay at MRT, if MRT is non-zero.
4309          */
4310         if (request->home_server->coa_mrt &&
4311             (delay > (request->home_server->coa_mrt * USEC))) {
4312                 int mrt_usec = request->home_server->coa_mrt * USEC;
4313
4314                 /*
4315                  *      delay = MRT + RAND * MRT
4316                  *            = 0.9 MRT + rand(0,.2)  * MRT
4317                  */
4318                 delay = fr_rand();
4319                 delay ^= (delay >> 15);
4320                 delay &= 0x1ffff;
4321                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4322                 delay += mrt_usec - (mrt_usec / 10);
4323         }
4324
4325         request->delay = delay;
4326         when = now;
4327         tv_add(&when, request->delay);
4328         mrd = request->proxy->timestamp;
4329         mrd.tv_sec += request->home_server->coa_mrd;
4330
4331         /*
4332          *      Cap duration at MRD.
4333          */
4334         if (timercmp(&mrd, &when, <)) {
4335                 when = mrd;
4336         }
4337         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4338
4339         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4340
4341         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4342
4343         RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4344                 inet_ntop(request->proxy->dst_ipaddr.af,
4345                           &request->proxy->dst_ipaddr.ipaddr,
4346                           buffer, sizeof(buffer)),
4347                 request->proxy->dst_port,
4348                 request->proxy->id);
4349
4350         request->proxy_listener->send(request->proxy_listener,
4351                                       request);
4352 }
4353
4354
4355 /** Wait for a reply after originating a CoA a request.
4356  *
4357  *  Retransmit the proxied packet, or time out and go to
4358  *  coa_no_reply.  Mark the home server unresponsive, etc.
4359  *
4360  *  If we do receive a reply, we transition to coa_running.
4361  *
4362  *  \dot
4363  *      digraph coa_wait_for_reply {
4364  *              coa_wait_for_reply;
4365  *
4366  *              coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4367  *              coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4368  *              coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4369  *              coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4370  *      }
4371  *  \enddot
4372  */
4373 static void coa_wait_for_reply(REQUEST *request, int action)
4374 {
4375         VERIFY_REQUEST(request);
4376
4377         TRACE_STATE_MACHINE;
4378         ASSERT_MASTER;
4379         CHECK_FOR_STOP;
4380
4381         if (request->parent) coa_separate(request);
4382
4383         switch (action) {
4384         case FR_ACTION_TIMER:
4385                 if (request_max_time(request)) break;
4386
4387                 coa_retransmit(request);
4388                 break;
4389
4390         case FR_ACTION_PROXY_REPLY:
4391                 request_queue_or_run(request, coa_running);
4392                 break;
4393
4394         default:
4395                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4396                 break;
4397         }
4398 }
4399
4400 static void coa_separate(REQUEST *request)
4401 {
4402         VERIFY_REQUEST(request);
4403 #ifdef DEBUG_STATE_MACHINE
4404         int action = FR_ACTION_TIMER;
4405 #endif
4406
4407         TRACE_STATE_MACHINE;
4408         ASSERT_MASTER;
4409
4410         rad_assert(request->parent != NULL);
4411         rad_assert(request->parent->coa == request);
4412         rad_assert(request->ev == NULL);
4413         rad_assert(!request->in_request_hash);
4414         rad_assert(request->coa == NULL);
4415
4416         rad_assert(request->proxy_reply || request->proxy_listener);
4417
4418         (void) talloc_steal(NULL, request);
4419         request->parent->coa = NULL;
4420         request->parent = NULL;
4421
4422         if (we_are_master()) {
4423                 request->delay = 0;
4424                 coa_retransmit(request);
4425         }
4426 }
4427
4428
4429 /** Process a request after the CoA has timed out.
4430  *
4431  *  Run the packet through Post-Proxy-Type Fail
4432  *
4433  *  \dot
4434  *      digraph coa_no_reply {
4435  *              coa_no_reply;
4436  *
4437  *              coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4438  *              coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4439  *              coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4440  *              coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4441  *              coa_no_reply -> done [ label = "TIMER >= timeout" ];
4442  *      }
4443  *  \enddot
4444  */
4445 static void coa_no_reply(REQUEST *request, int action)
4446 {
4447         char buffer[128];
4448
4449         VERIFY_REQUEST(request);
4450
4451         TRACE_STATE_MACHINE;
4452         CHECK_FOR_STOP;
4453
4454         switch (action) {
4455         case FR_ACTION_TIMER:
4456                 (void) request_max_time(request);
4457                 break;
4458
4459         case FR_ACTION_PROXY_REPLY: /* too late! */
4460                 RDEBUG2("Reply from CoA server %s port %d  - ID: %d arrived too late.",
4461                         inet_ntop(request->proxy->src_ipaddr.af,
4462                                   &request->proxy->src_ipaddr.ipaddr,
4463                                   buffer, sizeof(buffer)),
4464                         request->proxy->dst_port, request->proxy->id);
4465                 break;
4466
4467         case FR_ACTION_RUN:
4468                 if (process_proxy_reply(request, NULL)) {
4469                         request->handle(request);
4470                 }
4471                 request_done(request, FR_ACTION_DONE);
4472                 break;
4473
4474         default:
4475                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4476                 break;
4477         }
4478 }
4479
4480
4481 /** Process the request after receiving a coa reply.
4482  *
4483  *  Throught the post-proxy section, and the through the handler
4484  *  function.
4485  *
4486  *  \dot
4487  *      digraph coa_running {
4488  *              coa_running;
4489  *
4490  *              coa_running -> timer [ label = "TIMER < max_request_time" ];
4491  *              coa_running -> process_proxy_reply [ label = "RUN" ];
4492  *              coa_running -> done [ label = "TIMER >= timeout" ];
4493  *      }
4494  *  \enddot
4495  */
4496 static void coa_running(REQUEST *request, int action)
4497 {
4498         VERIFY_REQUEST(request);
4499
4500         TRACE_STATE_MACHINE;
4501         CHECK_FOR_STOP;
4502
4503         switch (action) {
4504         case FR_ACTION_TIMER:
4505                 (void) request_max_time(request);
4506                 break;
4507
4508         case FR_ACTION_RUN:
4509                 if (process_proxy_reply(request, request->proxy_reply)) {
4510                         request->handle(request);
4511                 }
4512                 request_done(request, FR_ACTION_DONE);
4513                 break;
4514
4515         default:
4516                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4517                 break;
4518         }
4519 }
4520 #endif  /* WITH_COA */
4521
4522 /***********************************************************************
4523  *
4524  *  End of the State machine.  Start of additional helper code.
4525  *
4526  ***********************************************************************/
4527
4528 /***********************************************************************
4529  *
4530  *      Event handlers.
4531  *
4532  ***********************************************************************/
4533 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4534 {
4535         rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4536
4537         rad_assert(xel == el);
4538
4539         if ((listener->fd < 0)
4540 #ifdef WITH_DETAIL
4541 #ifndef WITH_DETAIL_THREAD
4542             && (listener->type != RAD_LISTEN_DETAIL)
4543 #endif
4544 #endif
4545                 ) {
4546                 char buffer[256];
4547
4548                 listener->print(listener, buffer, sizeof(buffer));
4549                 ERROR("FATAL: Asked to read from closed socket: %s",
4550                        buffer);
4551
4552                 rad_panic("Socket was closed on us!");
4553                 fr_exit_now(1);
4554         }
4555
4556         listener->recv(listener);
4557 }
4558
4559 #ifdef WITH_DETAIL
4560 #ifdef WITH_DETAIL_THREAD
4561 #else
4562 /*
4563  *      This function is called periodically to see if this detail
4564  *      file is available for reading.
4565  */
4566 static void event_poll_detail(void *ctx)
4567 {
4568         int delay;
4569         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4570         struct timeval when, now;
4571         listen_detail_t *detail = this->data;
4572
4573         rad_assert(this->type == RAD_LISTEN_DETAIL);
4574
4575  redo:
4576         event_socket_handler(el, this->fd, this);
4577
4578         fr_event_now(el, &now);
4579         when = now;
4580
4581         /*
4582          *      Backdoor API to get the delay until the next poll
4583          *      time.
4584          */
4585         delay = this->encode(this, NULL);
4586         if (delay == 0) goto redo;
4587
4588         tv_add(&when, delay);
4589
4590         ASSERT_MASTER;
4591         if (!fr_event_insert(el, event_poll_detail, this,
4592                              &when, &detail->ev)) {
4593                 ERROR("Failed creating handler");
4594                 fr_exit(1);
4595         }
4596 }
4597 #endif  /* WITH_DETAIL_THREAD */
4598 #endif  /* WITH_DETAIL */
4599
4600 static void event_status(struct timeval *wake)
4601 {
4602 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4603         int argval;
4604 #endif
4605
4606         if (rad_debug_lvl == 0) {
4607                 if (just_started) {
4608                         INFO("Ready to process requests");
4609                         just_started = false;
4610                 }
4611                 return;
4612         }
4613
4614         if (!wake) {
4615                 INFO("Ready to process requests");
4616
4617         } else if ((wake->tv_sec != 0) ||
4618                    (wake->tv_usec >= 100000)) {
4619                 DEBUG("Waking up in %d.%01u seconds.",
4620                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4621         }
4622
4623
4624         /*
4625          *      FIXME: Put this somewhere else, where it isn't called
4626          *      all of the time...
4627          */
4628
4629 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4630         /*
4631          *      If there are no child threads, then there may
4632          *      be child processes.  In that case, wait for
4633          *      their exit status, and throw that exit status
4634          *      away.  This helps get rid of zxombie children.
4635          */
4636         while (waitpid(-1, &argval, WNOHANG) > 0) {
4637                 /* do nothing */
4638         }
4639 #endif
4640
4641 }
4642
4643 #ifdef WITH_TCP
4644 static void listener_free_cb(void *ctx)
4645 {
4646         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4647         char buffer[1024];
4648
4649         if (this->count > 0) {
4650                 struct timeval when;
4651                 listen_socket_t *sock = this->data;
4652
4653                 fr_event_now(el, &when);
4654                 when.tv_sec += 3;
4655
4656                 ASSERT_MASTER;
4657                 if (!fr_event_insert(el, listener_free_cb, this, &when,
4658                                      &(sock->ev))) {
4659                         rad_panic("Failed to insert event");
4660                 }
4661
4662                 return;
4663         }
4664
4665         /*
4666          *      It's all free, close the socket.
4667          */
4668
4669         this->print(this, buffer, sizeof(buffer));
4670         DEBUG("... cleaning up socket %s", buffer);
4671         rad_assert(this->next == NULL);
4672         talloc_free(this);
4673 }
4674 #endif
4675
4676 #ifdef WITH_PROXY
4677 static int proxy_eol_cb(void *ctx, void *data)
4678 {
4679         struct timeval when;
4680         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4681
4682         if (request->proxy_listener != ctx) return 0;
4683
4684         /*
4685          *      We don't care if it's being processed in a child thread.
4686          */
4687
4688 #ifdef WITH_ACCOUNTING
4689         /*
4690          *      Accounting packets should be deleted immediately.
4691          *      They will never be retransmitted by the client.
4692          */
4693         if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4694                 RDEBUG("Stopping request due to failed connection to home server");
4695                 request->master_state = REQUEST_STOP_PROCESSING;
4696         }
4697 #endif
4698
4699         /*
4700          *      Reset the timer to be now, so that the request is
4701          *      quickly updated.  But spread the requests randomly
4702          *      over the next second, so that we don't overload the
4703          *      server.
4704          */
4705         fr_event_now(el, &when);
4706         tv_add(&when, fr_rand() % USEC);
4707         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4708
4709         /*
4710          *      Don't delete it from the list.
4711          */
4712         return 0;
4713 }
4714 #endif
4715
4716 static int event_new_fd(rad_listen_t *this)
4717 {
4718         char buffer[1024];
4719
4720         ASSERT_MASTER;
4721
4722         if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4723
4724         this->print(this, buffer, sizeof(buffer));
4725
4726         if (this->status == RAD_LISTEN_STATUS_INIT) {
4727                 listen_socket_t *sock = this->data;
4728
4729                 rad_assert(sock != NULL);
4730                 if (just_started) {
4731                         DEBUG("Listening on %s", buffer);
4732                 } else {
4733                         INFO(" ... adding new socket %s", buffer);
4734                 }
4735
4736 #ifdef WITH_PROXY
4737                 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4738                         home_server_t *home;
4739                         
4740                         home = sock->home;
4741                         if (!home || !home->limit.max_connections) {
4742                                 INFO(" ... adding new socket %s", buffer);
4743                         } else {
4744                                 INFO(" ... adding new socket %s (%u of %u)", buffer,
4745                                      home->limit.num_connections, home->limit.max_connections);
4746                         }
4747
4748 #endif
4749                 }
4750
4751                 switch (this->type) {
4752 #ifdef WITH_DETAIL
4753                 /*
4754                  *      Detail files are always known, and aren't
4755                  *      put into the socket event loop.
4756                  */
4757                 case RAD_LISTEN_DETAIL:
4758                         this->status = RAD_LISTEN_STATUS_KNOWN;
4759
4760 #ifndef WITH_DETAIL_THREAD
4761                         /*
4762                          *      Set up the first poll interval.
4763                          */
4764                         event_poll_detail(this);
4765                         return 1;
4766 #else
4767                         break;  /* add the FD to the list */
4768 #endif
4769 #endif  /* WITH_DETAIL */
4770
4771 #ifdef WITH_PROXY
4772                 /*
4773                  *      Add it to the list of sockets we can use.
4774                  *      Server sockets (i.e. auth/acct) are never
4775                  *      added to the packet list.
4776                  */
4777                 case RAD_LISTEN_PROXY:
4778 #ifdef WITH_TCP
4779                         rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4780
4781                         /*
4782                          *      Add timers to outgoing child sockets, if necessary.
4783                          */
4784                         if (sock->proto == IPPROTO_TCP && sock->opened &&
4785                             (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4786                                 struct timeval when;
4787
4788                                 when.tv_sec = sock->opened + 1;
4789                                 when.tv_usec = 0;
4790
4791                                 ASSERT_MASTER;
4792                                 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4793                                                      &(sock->ev))) {
4794                                         rad_panic("Failed to insert event");
4795                                 }
4796                         }
4797 #endif
4798                         break;
4799 #endif  /* WITH_PROXY */
4800
4801                         /*
4802                          *      FIXME: put idle timers on command sockets.
4803                          */
4804
4805                 default:
4806 #ifdef WITH_TCP
4807                         /*
4808                          *      Add timers to incoming child sockets, if necessary.
4809                          */
4810                         if (sock->proto == IPPROTO_TCP && sock->opened &&
4811                             (sock->limit.lifetime || sock->limit.idle_timeout)) {
4812                                 struct timeval when;
4813
4814                                 when.tv_sec = sock->opened + 1;
4815                                 when.tv_usec = 0;
4816
4817                                 ASSERT_MASTER;
4818                                 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4819                                                      &(sock->ev))) {
4820                                         ERROR("Failed adding timer for socket: %s", fr_strerror());
4821                                         fr_exit(1);
4822                                 }
4823                         }
4824 #endif
4825                         break;
4826                 } /* switch over listener types */
4827
4828                 /*
4829                  *      All sockets: add the FD to the event handler.
4830                  */
4831                 if (!fr_event_fd_insert(el, 0, this->fd,
4832                                         event_socket_handler, this)) {
4833                         ERROR("Failed adding event handler for socket: %s", fr_strerror());
4834                         fr_exit(1);
4835                 }
4836
4837                 this->status = RAD_LISTEN_STATUS_KNOWN;
4838                 return 1;
4839         } /* end of INIT */
4840
4841 #ifdef WITH_TCP
4842         /*
4843          *      The socket has reached a timeout.  Try to close it.
4844          */
4845         if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4846                 /*
4847                  *      Requests are still using the socket.  Wait for
4848                  *      them to finish.
4849                  */
4850                 if (this->count > 0) {
4851                         struct timeval when;
4852                         listen_socket_t *sock = this->data;
4853
4854                         /*
4855                          *      Try again to clean up the socket in 30
4856                          *      seconds.
4857                          */
4858                         gettimeofday(&when, NULL);
4859                         when.tv_sec += 30;
4860
4861                         ASSERT_MASTER;
4862                         if (!fr_event_insert(el,
4863                                              (fr_event_callback_t) event_new_fd,
4864                                              this, &when, &sock->ev)) {
4865                                 rad_panic("Failed to insert event");
4866                         }
4867
4868                         return 1;
4869                 }
4870
4871                 fr_event_fd_delete(el, 0, this->fd);
4872                 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4873         }
4874
4875         /*
4876          *      The socket has had a catastrophic error.  Close it.
4877          */
4878         if (this->status == RAD_LISTEN_STATUS_EOL) {
4879                 /*
4880                  *      Remove it from the list of live FD's.
4881                  */
4882                 fr_event_fd_delete(el, 0, this->fd);
4883
4884 #ifdef WITH_PROXY
4885                 /*
4886                  *      Tell all requests using this socket that the socket is dead.
4887                  */
4888                 if (this->type == RAD_LISTEN_PROXY) {
4889                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
4890                         if (!fr_packet_list_socket_freeze(proxy_list,
4891                                                           this->fd)) {
4892                                 ERROR("Fatal error freezing socket: %s", fr_strerror());
4893                                 fr_exit(1);
4894                         }
4895
4896                         if (this->count > 0) {
4897                                 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4898                         }
4899                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4900                 }
4901 #endif
4902
4903                 /*
4904                  *      Requests are still using the socket.  Wait for
4905                  *      them to finish.
4906                  */
4907                 if (this->count > 0) {
4908                         struct timeval when;
4909                         listen_socket_t *sock = this->data;
4910
4911                         /*
4912                          *      Try again to clean up the socket in 30
4913                          *      seconds.
4914                          */
4915                         gettimeofday(&when, NULL);
4916                         when.tv_sec += 30;
4917
4918                         ASSERT_MASTER;
4919                         if (!fr_event_insert(el,
4920                                              (fr_event_callback_t) event_new_fd,
4921                                              this, &when, &sock->ev)) {
4922                                 rad_panic("Failed to insert event");
4923                         }
4924
4925                         return 1;
4926                 }
4927
4928                 /*
4929                  *      No one is using the socket.  We can remove it now.
4930                  */
4931                 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4932         } /* socket is at EOL */
4933 #endif
4934
4935         /*
4936          *      Nuke the socket.
4937          */
4938         if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4939                 int devnull;
4940 #ifdef WITH_TCP
4941                 listen_socket_t *sock = this->data;
4942 #endif
4943                 struct timeval when;
4944
4945                 /*
4946                  *      Re-open the socket, pointing it to /dev/null.
4947                  *      This means that all writes proceed without
4948                  *      blocking, and all reads return "no data".
4949                  *
4950                  *      This leaves the socket active, so any child
4951                  *      threads won't go insane.  But it means that
4952                  *      they cannot send or receive any packets.
4953                  *
4954                  *      This is EXTRA work in the normal case, when
4955                  *      sockets are closed without error.  But it lets
4956                  *      us have one simple processing method for all
4957                  *      sockets.
4958                  */
4959                 devnull = open("/dev/null", O_RDWR);
4960                 if (devnull < 0) {
4961                         ERROR("FATAL failure opening /dev/null: %s",
4962                                fr_syserror(errno));
4963                         fr_exit(1);
4964                 }
4965                 if (dup2(devnull, this->fd) < 0) {
4966                         ERROR("FATAL failure closing socket: %s",
4967                                fr_syserror(errno));
4968                         fr_exit(1);
4969                 }
4970                 close(devnull);
4971
4972 #ifdef WITH_DETAIL
4973                 rad_assert(this->type != RAD_LISTEN_DETAIL);
4974 #endif
4975
4976 #ifdef WITH_TCP
4977 #ifdef WITH_PROXY
4978                 /*
4979                  *      The socket is dead.  Force all proxied packets
4980                  *      to stop using it.  And then remove it from the
4981                  *      list of outgoing sockets.
4982                  */
4983                 if (this->type == RAD_LISTEN_PROXY) {
4984                         home_server_t *home;
4985
4986                         home = sock->home;
4987                         if (!home || !home->limit.max_connections) {
4988                                 INFO(" ... shutting down socket %s", buffer);
4989                         } else {
4990                                 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4991                                      home->limit.num_connections, home->limit.max_connections);
4992                         }
4993
4994                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
4995                         fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4996
4997                         if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4998                                 ERROR("Fatal error removing socket %s: %s",
4999                                       buffer, fr_strerror());
5000                                 fr_exit(1);
5001                         }
5002                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
5003                 } else
5004 #endif
5005                 {
5006                         INFO(" ... shutting down socket %s", buffer);
5007
5008                         /*
5009                          *      EOL all requests using this socket.
5010                          */
5011                         rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
5012                 }
5013
5014                 /*
5015                  *      No child threads, clean it up now.
5016                  */
5017                 if (!spawn_flag) {
5018                         ASSERT_MASTER;
5019                         if (sock->ev) fr_event_delete(el, &sock->ev);
5020                         listen_free(&this);
5021                         return 1;
5022                 }
5023
5024                 /*
5025                  *      Wait until all requests using this socket are done.
5026                  */
5027                 gettimeofday(&when, NULL);
5028                 when.tv_sec += 3;
5029
5030                 ASSERT_MASTER;
5031                 if (!fr_event_insert(el, listener_free_cb, this, &when,
5032                                      &(sock->ev))) {
5033                         rad_panic("Failed to insert event");
5034                 }
5035         }
5036 #endif  /* WITH_TCP */
5037
5038         return 1;
5039 }
5040
5041 /***********************************************************************
5042  *
5043  *      Signal handlers.
5044  *
5045  ***********************************************************************/
5046
5047 static void handle_signal_self(int flag)
5048 {
5049         ASSERT_MASTER;
5050
5051         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5052                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5053                         INFO("Signalled to exit");
5054                         fr_event_loop_exit(el, 1);
5055                 } else {
5056                         INFO("Signalled to terminate");
5057                         fr_event_loop_exit(el, 2);
5058                 }
5059
5060                 return;
5061         } /* else exit/term flags weren't set */
5062
5063         /*
5064          *      Tell the even loop to stop processing.
5065          */
5066         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5067                 time_t when;
5068                 static time_t last_hup = 0;
5069
5070                 when = time(NULL);
5071                 if ((int) (when - last_hup) < 5) {
5072                         INFO("Ignoring HUP (less than 5s since last one)");
5073                         return;
5074                 }
5075
5076                 INFO("Received HUP signal");
5077
5078                 last_hup = when;
5079
5080                 exec_trigger(NULL, NULL, "server.signal.hup", true);
5081                 fr_event_loop_exit(el, 0x80);
5082         }
5083
5084 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5085         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5086                 rad_listen_t *this;
5087
5088                 /*
5089                  *      FIXME: O(N) loops suck.
5090                  */
5091                 for (this = main_config.listen;
5092                      this != NULL;
5093                      this = this->next) {
5094                         if (this->type != RAD_LISTEN_DETAIL) continue;
5095
5096                         /*
5097                          *      This one didn't send the signal, skip
5098                          *      it.
5099                          */
5100                         if (!this->decode(this, NULL)) continue;
5101
5102                         /*
5103                          *      Go service the interrupt.
5104                          */
5105                         event_poll_detail(this);
5106                 }
5107         }
5108 #endif
5109
5110 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5111         /*
5112          *      There are new listeners in the list.  Run
5113          *      event_new_fd() on them.
5114          */
5115         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5116                 rad_listen_t *this, *next;
5117
5118                 FD_MUTEX_LOCK(&fd_mutex);
5119
5120                 /*
5121                  *      FIXME: unlock the mutex before calling
5122                  *      event_new_fd()?
5123                  */
5124                 for (this = new_listeners; this != NULL; this = next) {
5125                         next = this->next;
5126                         this->next = NULL;
5127
5128                         event_new_fd(this);
5129                 }
5130
5131                 new_listeners = NULL;
5132                 FD_MUTEX_UNLOCK(&fd_mutex);
5133         }
5134 #endif
5135 }
5136
5137 #ifndef HAVE_PTHREAD_H
5138 void radius_signal_self(int flag)
5139 {
5140         return handle_signal_self(flag);
5141 }
5142
5143 #else
5144 static int self_pipe[2] = { -1, -1 };
5145
5146 /*
5147  *      Inform ourselves that we received a signal.
5148  */
5149 void radius_signal_self(int flag)
5150 {
5151         ssize_t rcode;
5152         uint8_t buffer[16];
5153
5154         /*
5155          *      The read MUST be non-blocking for this to work.
5156          */
5157         rcode = read(self_pipe[0], buffer, sizeof(buffer));
5158         if (rcode > 0) {
5159                 ssize_t i;
5160
5161                 for (i = 0; i < rcode; i++) {
5162                         buffer[0] |= buffer[i];
5163                 }
5164         } else {
5165                 buffer[0] = 0;
5166         }
5167
5168         buffer[0] |= flag;
5169
5170         if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5171 }
5172
5173
5174 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5175                                  UNUSED int fd, UNUSED void *ctx)
5176 {
5177         ssize_t i, rcode;
5178         uint8_t buffer[32];
5179
5180         rcode = read(self_pipe[0], buffer, sizeof(buffer));
5181         if (rcode <= 0) return;
5182
5183         /*
5184          *      Merge pending signals.
5185          */
5186         for (i = 0; i < rcode; i++) {
5187                 buffer[0] |= buffer[i];
5188         }
5189
5190         handle_signal_self(buffer[0]);
5191 }
5192 #endif  /* HAVE_PTHREAD_H */
5193
5194 /***********************************************************************
5195  *
5196  *      Bootstrapping code.
5197  *
5198  ***********************************************************************/
5199
5200 /*
5201  *      Externally-visibly functions.
5202  */
5203 int radius_event_init(TALLOC_CTX *ctx) {
5204         el = fr_event_list_create(ctx, event_status);
5205         if (!el) return 0;
5206
5207         return 1;
5208 }
5209
5210 static int packet_entry_cmp(void const *one, void const *two)
5211 {
5212         RADIUS_PACKET const * const *a = one;
5213         RADIUS_PACKET const * const *b = two;
5214
5215         return fr_packet_cmp(*a, *b);
5216 }
5217
5218 #ifdef WITH_PROXY
5219 /*
5220  *      They haven't defined a proxy listener.  Automatically
5221  *      add one for them, with the correct address family.
5222  */
5223 static void create_default_proxy_listener(int af)
5224 {
5225         uint16_t        port = 0;
5226         home_server_t   home;
5227         listen_socket_t *sock;
5228         rad_listen_t    *this;
5229
5230         memset(&home, 0, sizeof(home));
5231
5232         /*
5233          *      Open a default UDP port
5234          */
5235         home.proto = IPPROTO_UDP;
5236         port = 0;
5237
5238         /*
5239          *      Set the address family.
5240          */
5241         home.src_ipaddr.af = af;
5242         home.ipaddr.af = af;
5243
5244         /*
5245          *      Get the correct listener.
5246          */
5247         this = proxy_new_listener(proxy_ctx, &home, port);
5248         if (!this) {
5249                 fr_exit_now(1);
5250         }
5251
5252         sock = this->data;
5253         if (!fr_packet_list_socket_add(proxy_list, this->fd,
5254                                        sock->proto,
5255                                        &sock->other_ipaddr, sock->other_port,
5256                                        this)) {
5257                 ERROR("Failed adding proxy socket");
5258                 fr_exit_now(1);
5259         }
5260
5261         /*
5262          *      Insert the FD into list of FDs to listen on.
5263          */
5264         radius_update_listener(this);
5265 }
5266
5267 /*
5268  *      See if we automatically need to open a proxy socket.
5269  */
5270 static void check_proxy(rad_listen_t *head)
5271 {
5272         bool            defined_proxy;
5273         bool            has_v4, has_v6;
5274         rad_listen_t    *this;
5275
5276         if (check_config) return;
5277         if (!main_config.proxy_requests) return;
5278         if (!head) return;
5279         if (!home_servers_udp) return;
5280
5281         /*
5282          *      We passed "-i" on the command line.  Use that address
5283          *      family for the proxy socket.
5284          */
5285         if (main_config.myip.af != AF_UNSPEC) {
5286                 create_default_proxy_listener(main_config.myip.af);
5287                 return;
5288         }
5289
5290         defined_proxy = has_v4 = has_v6 = false;
5291
5292         /*
5293          *      Figure out if we need to open a proxy socket, and if
5294          *      so, which one.
5295          */
5296         for (this = head; this != NULL; this = this->next) {
5297                 listen_socket_t *sock;
5298
5299                 switch (this->type) {
5300                 case RAD_LISTEN_PROXY:
5301                         defined_proxy = true;
5302                         break;
5303
5304                 case RAD_LISTEN_AUTH:
5305 #ifdef WITH_ACCT
5306                 case RAD_LISTEN_ACCT:
5307 #endif
5308 #ifdef WITH_COA
5309                 case RAD_LISTEN_COA:
5310 #endif
5311                         sock = this->data;
5312                         if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5313                         if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5314                         break;
5315                         
5316                 default:
5317                         break;
5318                 }
5319         }
5320
5321         /*
5322          *      Assume they know what they're doing.
5323          */
5324         if (defined_proxy) return;
5325
5326         if (has_v4) create_default_proxy_listener(AF_INET);
5327
5328         if (has_v6) create_default_proxy_listener(AF_INET6);
5329 }
5330 #endif
5331
5332 int radius_event_start(CONF_SECTION *cs, bool have_children)
5333 {
5334         rad_listen_t *head = NULL;
5335
5336         if (fr_start_time != (time_t)-1) return 0;
5337
5338         time(&fr_start_time);
5339
5340         if (!check_config) {
5341                 /*
5342                  *  radius_event_init() must be called first
5343                  */
5344                 rad_assert(el);
5345
5346                 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5347                 if (!pl) return 0;      /* leak el */
5348         }
5349
5350         request_num_counter = 0;
5351
5352 #ifdef WITH_PROXY
5353         if (main_config.proxy_requests && !check_config) {
5354                 /*
5355                  *      Create the tree for managing proxied requests and
5356                  *      responses.
5357                  */
5358                 proxy_list = fr_packet_list_create(1);
5359                 if (!proxy_list) return 0;
5360
5361 #ifdef HAVE_PTHREAD_H
5362                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5363                         ERROR("FATAL: Failed to initialize proxy mutex: %s",
5364                                fr_syserror(errno));
5365                         fr_exit(1);
5366                 }
5367 #endif
5368
5369                 /*
5370                  *      The "init_delay" is set to "response_window".
5371                  *      Reset it to half of "response_window" in order
5372                  *      to give the event loop enough time to service
5373                  *      the event before hitting "response_window".
5374                  */
5375                 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5376                 main_config.init_delay.tv_usec >>= 1;
5377                 main_config.init_delay.tv_sec >>= 1;
5378
5379                 proxy_ctx = talloc_init("proxy");
5380         }
5381 #endif
5382
5383         /*
5384          *      Move all of the thread calls to this file?
5385          *
5386          *      It may be best for the mutexes to be in this file...
5387          */
5388         spawn_flag = have_children;
5389
5390 #ifdef HAVE_PTHREAD_H
5391         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5392
5393         /*
5394          *      Initialize the threads ONLY if we're spawning, AND
5395          *      we're running normally.
5396          */
5397         if (have_children && !check_config &&
5398             (thread_pool_init(cs, &spawn_flag) < 0)) {
5399                 fr_exit(1);
5400         }
5401 #endif
5402
5403         if (check_config) {
5404                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5405                        main_config.name);
5406                 if (listen_init(cs, &head, spawn_flag) < 0) {
5407                         fflush(NULL);
5408                         fr_exit(1);
5409                 }
5410                 return 1;
5411         }
5412
5413 #ifdef HAVE_PTHREAD_H
5414         /*
5415          *      Child threads need a pipe to signal us, as do the
5416          *      signal handlers.
5417          */
5418         if (pipe(self_pipe) < 0) {
5419                 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5420                 fr_exit(1);
5421         }
5422         if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5423             (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5424                 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5425                 fr_exit(1);
5426         }
5427         if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5428             (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5429                 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5430                 fr_exit(1);
5431         }
5432         DEBUG4("Created signal pipe.  Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5433
5434         if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5435                 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5436                 fr_exit(1);
5437         }
5438 #endif
5439
5440         DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5441
5442         /*
5443          *      The server temporarily switches to an unprivileged
5444          *      user very early in the bootstrapping process.
5445          *      However, some sockets MAY require privileged access
5446          *      (bind to device, or to port < 1024, or to raw
5447          *      sockets).  Those sockets need to call suid up/down
5448          *      themselves around the functions that need a privileged
5449          *      uid.
5450          */
5451         if (listen_init(cs, &head, spawn_flag) < 0) {
5452                 fr_exit_now(1);
5453         }
5454
5455         main_config.listen = head;
5456
5457 #ifdef WITH_PROXY
5458         check_proxy(head);
5459 #endif
5460
5461         /*
5462          *      At this point, no one has any business *ever* going
5463          *      back to root uid.
5464          */
5465         rad_suid_down_permanent();
5466
5467         return 1;
5468 }
5469
5470
5471 #ifdef WITH_PROXY
5472 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5473 {
5474         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5475
5476         VERIFY_REQUEST(request);
5477
5478         request->master_state = REQUEST_STOP_PROCESSING;
5479
5480 #ifdef HAVE_PTHREAD_H
5481         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5482 #endif
5483
5484         /*
5485          *      If it's queued we can't delete it from the queue.
5486          *
5487          *      Otherwise, it's OK to delete it.  Even RUNNING, because
5488          *      that will get caught by the check above.
5489          */
5490         if (request->child_state == REQUEST_QUEUED) return 0;
5491
5492         request->in_proxy_hash = false;
5493
5494         if (!request->in_request_hash) {
5495                 request_done(request, FR_ACTION_DONE);
5496         }
5497
5498         /*
5499          *      Delete it from the list.
5500          */
5501         return 2;
5502 }
5503 #endif
5504
5505
5506 static int request_delete_cb(UNUSED void *ctx, void *data)
5507 {
5508         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5509
5510         VERIFY_REQUEST(request);
5511
5512         request->master_state = REQUEST_STOP_PROCESSING;
5513
5514         /*
5515          *      Not done, or the child thread is still processing it.
5516          */
5517         if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5518
5519 #ifdef HAVE_PTHREAD_H
5520         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5521 #endif
5522
5523 #ifdef WITH_PROXY
5524         rad_assert(request->in_proxy_hash == false);
5525 #endif
5526
5527         request->in_request_hash = false;
5528         ASSERT_MASTER;
5529         if (request->ev) fr_event_delete(el, &request->ev);
5530
5531         if (main_config.memory_report) {
5532                 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5533                         request->packet->id,
5534                         (unsigned int) (request->timestamp - fr_start_time));
5535         }
5536
5537 #ifdef WITH_COA
5538         if (request->coa) {
5539                 rad_assert(!request->coa->in_proxy_hash);
5540         }
5541 #endif
5542
5543         request_free(request);
5544
5545         /*
5546          *      Delete it from the list, and continue;
5547          */
5548         return 2;
5549 }
5550
5551
5552 void radius_event_free(void)
5553 {
5554         ASSERT_MASTER;
5555
5556 #ifdef WITH_PROXY
5557         /*
5558          *      There are requests in the proxy hash that aren't
5559          *      referenced from anywhere else.  Remove them first.
5560          */
5561         if (proxy_list) {
5562                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5563         }
5564 #endif
5565
5566         rbtree_walk(pl, RBTREE_DELETE_ORDER,  request_delete_cb, NULL);
5567
5568         if (spawn_flag) {
5569                 /*
5570                  *      Now that all requests have been marked "please stop",
5571                  *      ensure that all of the threads have exited.
5572                  */
5573 #ifdef HAVE_PTHREAD_H
5574                 thread_pool_stop();
5575 #endif
5576
5577                 /*
5578                  *      Walk the lists again, ensuring that all
5579                  *      requests are done.
5580                  */
5581                 if (main_config.memory_report) {
5582                         int num;
5583
5584 #ifdef WITH_PROXY
5585                         if (proxy_list) {
5586                                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5587                                 num = fr_packet_list_num_elements(proxy_list);
5588                                 if (num > 0) {
5589                                         ERROR("Proxy list has %d requests still in it.", num);
5590                                 }
5591                         }
5592 #endif
5593
5594                         rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5595                         num = rbtree_num_elements(pl);
5596                         if (num > 0) {
5597                                 ERROR("Request list has %d requests still in it.", num);
5598                         }
5599                 }
5600         }
5601
5602         rbtree_free(pl);
5603         pl = NULL;
5604
5605 #ifdef WITH_PROXY
5606         fr_packet_list_free(proxy_list);
5607         proxy_list = NULL;
5608
5609         if (proxy_ctx) talloc_free(proxy_ctx);
5610 #endif
5611
5612         TALLOC_FREE(el);
5613
5614         if (debug_condition) talloc_free(debug_condition);
5615 }
5616
5617 int radius_event_process(void)
5618 {
5619         if (!el) return 0;
5620
5621         return fr_event_loop(el);
5622 }