741e5aa5528c654157068f769fc93f590a705fd3
[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) 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, FR_ACTION_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                 RDEBUG("(%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) 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 #ifdef WITH_TCP
1588         {
1589                 sock = listener->data;
1590                 sock->last_packet = now.tv_sec;
1591
1592                 packet->proto = sock->proto;
1593         }
1594 #endif
1595
1596         /*
1597          *      Skip everything if required.
1598          */
1599         if (listener->nodup) goto skip_dup;
1600
1601         packet_p = rbtree_finddata(pl, &packet);
1602         if (packet_p) {
1603                 rad_child_state_t child_state;
1604
1605                 request = fr_packet2myptr(REQUEST, packet, packet_p);
1606                 rad_assert(request->in_request_hash);
1607                 child_state = request->child_state;
1608
1609                 /*
1610                  *      Same src/dst ip/port, length, and
1611                  *      authentication vector: must be a duplicate.
1612                  */
1613                 if ((request->packet->data_len == packet->data_len) &&
1614                     (memcmp(request->packet->vector, packet->vector,
1615                             sizeof(packet->vector)) == 0)) {
1616
1617 #ifdef WITH_STATS
1618                         switch (packet->code) {
1619                         case PW_CODE_ACCESS_REQUEST:
1620                                 FR_STATS_INC(auth, total_dup_requests);
1621                                 break;
1622
1623 #ifdef WITH_ACCOUNTING
1624                         case PW_CODE_ACCOUNTING_REQUEST:
1625                                 FR_STATS_INC(acct, total_dup_requests);
1626                                 break;
1627 #endif
1628 #ifdef WITH_COA
1629                         case PW_CODE_COA_REQUEST:
1630                                 FR_STATS_INC(coa, total_dup_requests);
1631                                 break;
1632
1633                         case PW_CODE_DISCONNECT_REQUEST:
1634                                 FR_STATS_INC(dsc, total_dup_requests);
1635                                 break;
1636 #endif
1637
1638                         default:
1639                                 break;
1640                         }
1641 #endif  /* WITH_STATS */
1642
1643                         /*
1644                          *      Tell the state machine that there's a
1645                          *      duplicate request.
1646                          */
1647                         request->process(request, FR_ACTION_DUP);
1648                         return 0; /* duplicate of live request */
1649                 }
1650
1651                 /*
1652                  *      Mark the request as done ASAP, and before we
1653                  *      log anything.  The child may stop processing
1654                  *      the request just as we're logging the
1655                  *      complaint.
1656                  */
1657                 request_done(request, FR_ACTION_DONE);
1658                 request = NULL;
1659
1660                 /*
1661                  *      It's a new request, not a duplicate.  If the
1662                  *      old one is done, then we can clean it up.
1663                  */
1664                 if (child_state <= REQUEST_RUNNING) {
1665                         /*
1666                          *      The request is still QUEUED or RUNNING.  That's a problem.
1667                          */
1668                         ERROR("Received conflicting packet from "
1669                               "client %s port %d - ID: %u due to "
1670                               "unfinished request.  Giving up on old request.",
1671                               client->shortname,
1672                               packet->src_port, packet->id);
1673                 }
1674
1675                 /*
1676                  *      Mark the old request as done.  If there's no
1677                  *      child, the request will be cleaned up
1678                  *      immediately.  If there is a child, we'll set a
1679                  *      timer to go clean up the request.
1680                  */
1681         } /* else the new packet is unique */
1682
1683         /*
1684          *      Quench maximum number of outstanding requests.
1685          */
1686         if (main_config.max_requests &&
1687             ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1688                 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1689                                  client->shortname,
1690                                  packet->src_port, packet->id);
1691                            WARN("Please check the configuration file.\n"
1692                                 "\tThe value for 'max_requests' is probably set too low.\n"));
1693
1694                 exec_trigger(NULL, NULL, "server.max_requests", true);
1695                 return 0;
1696         }
1697
1698 skip_dup:
1699         /*
1700          *      Rate-limit the incoming packets
1701          */
1702         if (sock && sock->max_rate) {
1703                 uint32_t pps;
1704
1705                 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1706                 if (pps > sock->max_rate) {
1707                         DEBUG("Dropping request due to rate limiting");
1708                         return 0;
1709                 }
1710                 sock->rate_pps_now++;
1711         }
1712
1713         /*
1714          *      Allocate a pool for the request.
1715          */
1716         if (!ctx) {
1717                 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1718                 if (!ctx) return 0;
1719                 talloc_set_name_const(ctx, "request_receive_pool");
1720
1721                 /*
1722                  *      The packet is still allocated from a different
1723                  *      context, but oh well.
1724                  */
1725                 (void) talloc_steal(ctx, packet);
1726         }
1727
1728         request = request_setup(ctx, listener, packet, client, fun);
1729         if (!request) {
1730                 talloc_free(ctx);
1731                 return 1;
1732         }
1733
1734         /*
1735          *      Mark it as a "real" request with a context.
1736          */
1737         request->options |= RAD_REQUEST_OPTION_CTX;
1738
1739         /*
1740          *      Remember the request in the list.
1741          */
1742         if (!listener->nodup) {
1743                 if (!rbtree_insert(pl, &request->packet)) {
1744                         RERROR("Failed to insert request in the list of live requests: discarding it");
1745                         request_done(request, FR_ACTION_DONE);
1746                         return 1;
1747                 }
1748
1749                 request->in_request_hash = true;
1750         }
1751
1752         /*
1753          *      Process it.  Send a response, and free it.
1754          */
1755         if (listener->synchronous) {
1756 #ifdef WITH_DETAIL
1757                 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1758 #endif
1759
1760                 request->listener->decode(request->listener, request);
1761                 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1762                 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1763
1764                 fun(request);
1765
1766                 if (request->reply->code != 0) {
1767                         request->listener->send(request->listener, request);
1768                 } else {
1769                         RDEBUG("Not sending reply");
1770                 }
1771
1772                 /*
1773                  *      Don't do delayed reject.  Oh well.
1774                  */
1775                 request_free(request);
1776                 return 1;
1777         }
1778
1779         /*
1780          *      Otherwise, insert it into the state machine.
1781          *      The child threads will take care of processing it.
1782          */
1783         request_queue_or_run(request, request_running);
1784
1785         return 1;
1786 }
1787
1788
1789 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1790                               RADCLIENT *client, RAD_REQUEST_FUNP fun)
1791 {
1792         REQUEST *request;
1793
1794         /*
1795          *      Create and initialize the new request.
1796          */
1797         request = request_alloc(ctx);
1798         if (!request) {
1799                 ERROR("No memory");
1800                 return NULL;
1801         }
1802         request->reply = rad_alloc_reply(request, packet);
1803         if (!request->reply) {
1804                 ERROR("No memory");
1805                 talloc_free(request);
1806                 return NULL;
1807         }
1808
1809         request->listener = listener;
1810         request->client = client;
1811         request->packet = talloc_steal(request, packet);
1812         request->number = request_num_counter++;
1813         request->priority = listener->type;
1814         request->master_state = REQUEST_ACTIVE;
1815         request->child_state = REQUEST_RUNNING;
1816 #ifdef DEBUG_STATE_MACHINE
1817         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1818                                request->number, __FUNCTION__,
1819                                child_state_names[request->child_state],
1820                                child_state_names[REQUEST_RUNNING]);
1821 #endif
1822         request->handle = fun;
1823         NO_CHILD_THREAD;
1824
1825 #ifdef WITH_STATS
1826         request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1827         if (packet->code == PW_CODE_ACCESS_REQUEST) {
1828                 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1829                 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1830 #ifdef WITH_ACCOUNTING
1831         } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1832                 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1833                 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1834 #endif
1835         }
1836 #endif  /* WITH_STATS */
1837
1838         /*
1839          *      Status-Server packets go to the head of the queue.
1840          */
1841         if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1842
1843         /*
1844          *      Set virtual server identity
1845          */
1846         if (client->server) {
1847                 request->server = client->server;
1848         } else if (listener->server) {
1849                 request->server = listener->server;
1850         } else {
1851                 request->server = NULL;
1852         }
1853
1854         request->root = &main_config;
1855 #ifdef WITH_TCP
1856         request->listener->count++;
1857 #endif
1858
1859         /*
1860          *      The request passes many of our sanity checks.
1861          *      From here on in, if anything goes wrong, we
1862          *      send a reject message, instead of dropping the
1863          *      packet.
1864          */
1865
1866         /*
1867          *      Build the reply template from the request.
1868          */
1869
1870         request->reply->sockfd = request->packet->sockfd;
1871         request->reply->dst_ipaddr = request->packet->src_ipaddr;
1872         request->reply->src_ipaddr = request->packet->dst_ipaddr;
1873         request->reply->dst_port = request->packet->src_port;
1874         request->reply->src_port = request->packet->dst_port;
1875         request->reply->id = request->packet->id;
1876         request->reply->code = 0; /* UNKNOWN code */
1877         memcpy(request->reply->vector, request->packet->vector,
1878                sizeof(request->reply->vector));
1879         request->reply->vps = NULL;
1880         request->reply->data = NULL;
1881         request->reply->data_len = 0;
1882
1883         return request;
1884 }
1885
1886 #ifdef WITH_TCP
1887 /***********************************************************************
1888  *
1889  *      TCP Handlers.
1890  *
1891  ***********************************************************************/
1892
1893 /*
1894  *      Timer function for all TCP sockets.
1895  */
1896 static void tcp_socket_timer(void *ctx)
1897 {
1898         rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1899         listen_socket_t *sock = listener->data;
1900         struct timeval end, now;
1901         char buffer[256];
1902         fr_socket_limit_t *limit;
1903
1904         ASSERT_MASTER;
1905
1906         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1907
1908         fr_event_now(el, &now);
1909
1910         switch (listener->type) {
1911 #ifdef WITH_PROXY
1912         case RAD_LISTEN_PROXY:
1913                 limit = &sock->home->limit;
1914                 break;
1915 #endif
1916
1917         case RAD_LISTEN_AUTH:
1918 #ifdef WITH_ACCOUNTING
1919         case RAD_LISTEN_ACCT:
1920 #endif
1921                 limit = &sock->limit;
1922                 break;
1923
1924         default:
1925                 return;
1926         }
1927
1928         /*
1929          *      If we enforce a lifetime, do it now.
1930          */
1931         if (limit->lifetime > 0) {
1932                 end.tv_sec = sock->opened + limit->lifetime;
1933                 end.tv_usec = 0;
1934
1935                 if (timercmp(&end, &now, <=)) {
1936                         listener->print(listener, buffer, sizeof(buffer));
1937                         DEBUG("Reached maximum lifetime on socket %s", buffer);
1938
1939                 do_close:
1940
1941 #ifdef WITH_PROXY
1942                         /*
1943                          *      Proxy sockets get frozen, so that we don't use
1944                          *      them for new requests.  But we do keep them
1945                          *      open to listen for replies to requests we had
1946                          *      previously sent.
1947                          */
1948                         if (listener->type == RAD_LISTEN_PROXY) {
1949                                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1950                                 if (!fr_packet_list_socket_freeze(proxy_list,
1951                                                                   listener->fd)) {
1952                                         ERROR("Fatal error freezing socket: %s", fr_strerror());
1953                                         fr_exit(1);
1954                                 }
1955                                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1956                         }
1957 #endif
1958
1959                         /*
1960                          *      Mark the socket as "don't use if at all possible".
1961                          */
1962                         listener->status = RAD_LISTEN_STATUS_FROZEN;
1963                         event_new_fd(listener);
1964                         return;
1965                 }
1966         } else {
1967                 end = now;
1968                 end.tv_sec += 3600;
1969         }
1970
1971         /*
1972          *      Enforce an idle timeout.
1973          */
1974         if (limit->idle_timeout > 0) {
1975                 struct timeval idle;
1976
1977                 rad_assert(sock->last_packet != 0);
1978                 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1979                 idle.tv_usec = 0;
1980
1981                 if (timercmp(&idle, &now, <=)) {
1982                         listener->print(listener, buffer, sizeof(buffer));
1983                         DEBUG("Reached idle timeout on socket %s", buffer);
1984                         goto do_close;
1985                 }
1986
1987                 /*
1988                  *      Enforce the minimum of idle timeout or lifetime.
1989                  */
1990                 if (timercmp(&idle, &end, <)) {
1991                         end = idle;
1992                 }
1993         }
1994
1995         /*
1996          *      Wake up at t + 0.5s.  The code above checks if the timers
1997          *      are <= t.  This addition gives us a bit of leeway.
1998          */
1999         end.tv_usec = USEC / 2;
2000
2001         ASSERT_MASTER;
2002         if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
2003                 rad_panic("Failed to insert event");
2004         }
2005 }
2006
2007
2008 #ifdef WITH_PROXY
2009 /*
2010  *      Called by socket_del to remove requests with this socket
2011  */
2012 static int eol_proxy_listener(void *ctx, void *data)
2013 {
2014         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2015         RADIUS_PACKET **proxy_p = data;
2016         REQUEST *request;
2017
2018         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2019         if (request->proxy_listener != this) return 0;
2020
2021         /*
2022          *      The normal "remove_from_proxy_hash" tries to grab the
2023          *      proxy mutex.  We already have it held, so grabbing it
2024          *      again will cause a deadlock.  Instead, call the "no
2025          *      lock" version of the function.
2026          */
2027         rad_assert(request->in_proxy_hash == true);
2028         remove_from_proxy_hash_nl(request, false);
2029
2030         /*
2031          *      Don't mark it as DONE.  The client can retransmit, and
2032          *      the packet SHOULD be re-proxied somewhere else.
2033          *
2034          *      Return "2" means that the rbtree code will remove it
2035          *      from the tree, and we don't need to do it ourselves.
2036          */
2037         return 2;
2038 }
2039 #endif  /* WITH_PROXY */
2040
2041 static int eol_listener(void *ctx, void *data)
2042 {
2043         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2044         RADIUS_PACKET **packet_p = data;
2045         REQUEST *request;
2046
2047         request = fr_packet2myptr(REQUEST, packet, packet_p);
2048         if (request->listener != this) return 0;
2049
2050         request->master_state = REQUEST_STOP_PROCESSING;
2051         request->process = request_done;
2052
2053         return 0;
2054 }
2055 #endif  /* WITH_TCP */
2056
2057 #ifdef WITH_PROXY
2058 /***********************************************************************
2059  *
2060  *      Proxy handlers for the state machine.
2061  *
2062  ***********************************************************************/
2063
2064 /*
2065  *      Called with the proxy mutex held
2066  */
2067 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2068 {
2069         VERIFY_REQUEST(request);
2070
2071         if (!request->in_proxy_hash) return;
2072
2073         fr_packet_list_id_free(proxy_list, request->proxy, yank);
2074         request->in_proxy_hash = false;
2075
2076         /*
2077          *      On the FIRST reply, decrement the count of outstanding
2078          *      requests.  Note that this is NOT the count of sent
2079          *      packets, but whether or not the home server has
2080          *      responded at all.
2081          */
2082         if (request->home_server &&
2083             request->home_server->currently_outstanding) {
2084                 request->home_server->currently_outstanding--;
2085
2086                 /*
2087                  *      If we're NOT sending it packets, AND it's been
2088                  *      a while since we got a response, then we don't
2089                  *      know if it's alive or dead.
2090                  */
2091                 if ((request->home_server->currently_outstanding == 0) &&
2092                     (request->home_server->state == HOME_STATE_ALIVE)) {
2093                         struct timeval when, now;
2094
2095                         when.tv_sec = request->home_server->last_packet_recv ;
2096                         when.tv_usec = 0;
2097
2098                         timeradd(&when, request_response_window(request), &when);
2099                         gettimeofday(&now, NULL);
2100
2101                         /*
2102                          *      last_packet + response_window
2103                          *
2104                          *      We *administratively* mark the home
2105                          *      server as "unknown" state, because we
2106                          *      haven't seen a packet for a while.
2107                          */
2108                         if (timercmp(&now, &when, >)) {
2109                                 request->home_server->state = HOME_STATE_UNKNOWN;
2110                                 request->home_server->last_packet_sent = 0;
2111                                 request->home_server->last_packet_recv = 0;
2112                         }
2113                 }
2114         }
2115
2116 #ifdef WITH_TCP
2117         rad_assert(request->proxy_listener != NULL);
2118         request->proxy_listener->count--;
2119 #endif
2120         request->proxy_listener = NULL;
2121
2122         /*
2123          *      Got from YES in hash, to NO, not in hash while we hold
2124          *      the mutex.  This guarantees that when another thread
2125          *      grabs the mutex, the "not in hash" flag is correct.
2126          */
2127 }
2128
2129 static void remove_from_proxy_hash(REQUEST *request)
2130 {
2131         VERIFY_REQUEST(request);
2132
2133         /*
2134          *      Check this without grabbing the mutex because it's a
2135          *      lot faster that way.
2136          */
2137         if (!request->in_proxy_hash) return;
2138
2139         /*
2140          *      The "not in hash" flag is definitive.  However, if the
2141          *      flag says that it IS in the hash, there might still be
2142          *      a race condition where it isn't.
2143          */
2144         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2145
2146         if (!request->in_proxy_hash) {
2147                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2148                 return;
2149         }
2150
2151         remove_from_proxy_hash_nl(request, true);
2152
2153         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2154 }
2155
2156 static int insert_into_proxy_hash(REQUEST *request)
2157 {
2158         char buf[128];
2159         int tries;
2160         bool success = false;
2161         void *proxy_listener;
2162
2163         VERIFY_REQUEST(request);
2164
2165         rad_assert(request->proxy != NULL);
2166         rad_assert(request->home_server != NULL);
2167         rad_assert(proxy_list != NULL);
2168
2169
2170         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2171         proxy_listener = NULL;
2172         request->num_proxied_requests = 1;
2173         request->num_proxied_responses = 0;
2174
2175         for (tries = 0; tries < 2; tries++) {
2176                 rad_listen_t *this;
2177                 listen_socket_t *sock;
2178
2179                 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2180                 success = fr_packet_list_id_alloc(proxy_list,
2181                                                 request->home_server->proto,
2182                                                 &request->proxy, &proxy_listener);
2183                 if (success) break;
2184
2185                 if (tries > 0) continue; /* try opening new socket only once */
2186
2187 #ifdef HAVE_PTHREAD_H
2188                 if (proxy_no_new_sockets) break;
2189 #endif
2190
2191                 RDEBUG3("proxy: Trying to open a new listener to the home server");
2192                 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2193                 if (!this) {
2194                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2195                         goto fail;
2196                 }
2197
2198                 request->proxy->src_port = 0; /* Use any new socket */
2199                 proxy_listener = this;
2200
2201                 sock = this->data;
2202                 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2203                                                sock->proto,
2204                                                &sock->other_ipaddr, sock->other_port,
2205                                                this)) {
2206
2207 #ifdef HAVE_PTHREAD_H
2208                         proxy_no_new_sockets = true;
2209 #endif
2210                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2211
2212                         /*
2213                          *      This is bad.  However, the
2214                          *      packet list now supports 256
2215                          *      open sockets, which should
2216                          *      minimize this problem.
2217                          */
2218                         ERROR("Failed adding proxy socket: %s",
2219                               fr_strerror());
2220                         goto fail;
2221                 }
2222
2223                 /*
2224                  *      Add it to the event loop.  Ensure that we have
2225                  *      only one mutex locked at a time.
2226                  */
2227                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2228                 radius_update_listener(this);
2229                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2230         }
2231
2232         if (!proxy_listener || !success) {
2233                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2234                 REDEBUG2("proxy: Failed allocating Id for proxied request");
2235         fail:
2236                 request->proxy_listener = NULL;
2237                 request->in_proxy_hash = false;
2238                 return 0;
2239         }
2240
2241         rad_assert(request->proxy->id >= 0);
2242
2243         request->proxy_listener = proxy_listener;
2244         request->in_proxy_hash = true;
2245         RDEBUG3("proxy: request is now in proxy hash");
2246
2247         /*
2248          *      Keep track of maximum outstanding requests to a
2249          *      particular home server.  'max_outstanding' is
2250          *      enforced in home_server_ldb(), in realms.c.
2251          */
2252         request->home_server->currently_outstanding++;
2253
2254 #ifdef WITH_TCP
2255         request->proxy_listener->count++;
2256 #endif
2257
2258         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2259
2260         RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2261                inet_ntop(request->proxy->dst_ipaddr.af,
2262                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2263                request->proxy->dst_port,
2264                request->proxy->id);
2265
2266         return 1;
2267 }
2268
2269 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2270 {
2271         int rcode;
2272         int post_proxy_type = 0;
2273         VALUE_PAIR *vp;
2274
2275         VERIFY_REQUEST(request);
2276
2277         /*
2278          *      There may be a proxy reply, but it may be too late.
2279          */
2280         if (!request->home_server->server && !request->proxy_listener) return 0;
2281
2282         /*
2283          *      Delete any reply we had accumulated until now.
2284          */
2285         RDEBUG2("Clearing existing &reply: attributes");
2286         fr_pair_list_free(&request->reply->vps);
2287
2288         /*
2289          *      Run the packet through the post-proxy stage,
2290          *      BEFORE playing games with the attributes.
2291          */
2292         vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2293         if (vp) {
2294                 post_proxy_type = vp->vp_integer;
2295         /*
2296          *      If we have a proxy_reply, and it was a reject, or a NAK
2297          *      setup Post-Proxy <type>.
2298          *
2299          *      If the <type> doesn't have a section, then the Post-Proxy
2300          *      section is ignored.
2301          */
2302         } else if (reply) {
2303                 DICT_VALUE *dval = NULL;
2304
2305                 switch (reply->code) {
2306                 case PW_CODE_ACCESS_REJECT:
2307                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2308                         if (dval) post_proxy_type = dval->value;
2309                         break;
2310
2311                 case PW_CODE_DISCONNECT_NAK:
2312                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2313                         if (dval) post_proxy_type = dval->value;
2314                         break;
2315
2316                 case PW_CODE_COA_NAK:
2317                         dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2318                         if (dval) post_proxy_type = dval->value;
2319                         break;
2320
2321                 default:
2322                         break;
2323                 }
2324
2325                 /*
2326                  *      Create config:Post-Proxy-Type
2327                  */
2328                 if (dval) {
2329                         vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2330                         vp->vp_integer = dval->value;
2331                 }
2332         }
2333
2334         if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2335                                          dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2336
2337         if (reply) {
2338                 VERIFY_PACKET(reply);
2339
2340                 /*
2341                  *      Decode the packet if required.
2342                  */
2343                 if (request->proxy_listener) {
2344                         rcode = request->proxy_listener->decode(request->proxy_listener, request);
2345                         debug_packet(request, reply, true);
2346
2347                         /*
2348                          *      Pro-actively remove it from the proxy hash.
2349                          *      This is later than in 2.1.x, but it means that
2350                          *      the replies are authenticated before being
2351                          *      removed from the hash.
2352                          */
2353                         if ((rcode == 0) &&
2354                             (request->num_proxied_requests <= request->num_proxied_responses)) {
2355                                 remove_from_proxy_hash(request);
2356                         }
2357                 } else {
2358                         rad_assert(!request->in_proxy_hash);
2359                 }
2360         } else if (request->in_proxy_hash) {
2361                 remove_from_proxy_hash(request);
2362         }
2363
2364         if (request->home_pool && request->home_pool->virtual_server) {
2365                 char const *old_server = request->server;
2366
2367                 request->server = request->home_pool->virtual_server;
2368                 RDEBUG2("server %s {", request->server);
2369                 RINDENT();
2370                 rcode = process_post_proxy(post_proxy_type, request);
2371                 REXDENT();
2372                 RDEBUG2("}");
2373                 request->server = old_server;
2374         } else {
2375                 rcode = process_post_proxy(post_proxy_type, request);
2376         }
2377
2378 #ifdef WITH_COA
2379         if (request->packet->code == request->proxy->code) {
2380           /*
2381            *    Don't run the next bit if we originated a CoA
2382            *    packet, after receiving an Access-Request or
2383            *    Accounting-Request.
2384            */
2385 #endif
2386
2387                 /*
2388                  *      There may NOT be a proxy reply, as we may be
2389                  *      running Post-Proxy-Type = Fail.
2390                  */
2391                 if (reply) {
2392                         fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2393
2394                         /*
2395                          *      Delete the Proxy-State Attributes from
2396                          *      the reply.  These include Proxy-State
2397                          *      attributes from us and remote server.
2398                          */
2399                         fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2400
2401                 } else {
2402                         vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
2403                         if (vp && (vp->vp_integer != 256)) {
2404                                 request->proxy_reply = rad_alloc_reply(request, request->proxy);
2405                                 request->proxy_reply->code = vp->vp_integer;
2406                         }
2407                 }
2408 #ifdef WITH_COA
2409         }
2410 #endif
2411         switch (rcode) {
2412         default:  /* Don't do anything */
2413                 break;
2414         case RLM_MODULE_FAIL:
2415                 return 0;
2416
2417         case RLM_MODULE_HANDLED:
2418                 return 0;
2419         }
2420
2421         return 1;
2422 }
2423
2424 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2425 {
2426         char buffer[128];
2427
2428         home->state = HOME_STATE_ALIVE;
2429         home->response_timeouts = 0;
2430         exec_trigger(request, home->cs, "home_server.alive", false);
2431         home->currently_outstanding = 0;
2432         home->num_sent_pings = 0;
2433         home->num_received_pings = 0;
2434         gettimeofday(&home->revive_time, NULL);
2435
2436         fr_event_delete(el, &home->ev);
2437
2438         RPROXY("Marking home server %s port %d alive",
2439                inet_ntop(request->proxy->dst_ipaddr.af,
2440                          &request->proxy->dst_ipaddr.ipaddr,
2441                          buffer, sizeof(buffer)),
2442                request->proxy->dst_port);
2443 }
2444
2445
2446 int request_proxy_reply(RADIUS_PACKET *packet)
2447 {
2448         RADIUS_PACKET **proxy_p;
2449         REQUEST *request;
2450         struct timeval now;
2451         char buffer[128];
2452
2453         VERIFY_PACKET(packet);
2454
2455         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2456         proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2457
2458         if (!proxy_p) {
2459                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2460                 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2461                        fr_packet_codes[packet->code],
2462                        inet_ntop(packet->src_ipaddr.af,
2463                                  &packet->src_ipaddr.ipaddr,
2464                                  buffer, sizeof(buffer)),
2465                        packet->src_port, packet->id);
2466                 return 0;
2467         }
2468
2469         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2470
2471         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2472
2473         /*
2474          *      No reply, BUT the current packet fails verification:
2475          *      ignore it.  This does the MD5 calculations in the
2476          *      server core, but I guess we can fix that later.
2477          */
2478         if (!request->proxy_reply &&
2479             (rad_verify(packet, request->proxy,
2480                         request->home_server->secret) != 0)) {
2481                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
2482                 return 0;
2483         }
2484
2485         /*
2486          *      The home server sent us a packet which doesn't match
2487          *      something we have: ignore it.  This is done only to
2488          *      catch the case of broken systems.
2489          */
2490         if (request->proxy_reply &&
2491             (memcmp(request->proxy_reply->vector,
2492                     packet->vector,
2493                     sizeof(request->proxy_reply->vector)) != 0)) {
2494                 RDEBUG2("Ignoring conflicting proxy reply");
2495                 return 0;
2496         }
2497
2498         gettimeofday(&now, NULL);
2499
2500         /*
2501          *      Status-Server packets don't count as real packets.
2502          */
2503         if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2504 #ifdef WITH_TCP
2505                 listen_socket_t *sock = request->proxy_listener->data;
2506
2507                 sock->last_packet = now.tv_sec;
2508 #endif
2509                 request->home_server->last_packet_recv = now.tv_sec;
2510         }
2511
2512         request->num_proxied_responses++;
2513
2514         /*
2515          *      If we have previously seen a reply, ignore the
2516          *      duplicate.
2517          */
2518         if (request->proxy_reply) {
2519                 RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d",
2520                         inet_ntop(packet->src_ipaddr.af,
2521                                   &packet->src_ipaddr.ipaddr,
2522                                   buffer, sizeof(buffer)),
2523                         packet->src_port, packet->id);
2524                 return 0;
2525         }
2526
2527         /*
2528          *      Call the state machine to do something useful with the
2529          *      request.
2530          */
2531         request->proxy_reply = talloc_steal(request, packet);
2532         packet->timestamp = now;
2533         request->priority = RAD_LISTEN_PROXY;
2534
2535 #ifdef WITH_STATS
2536         /*
2537          *      Update the proxy listener stats here, because only one
2538          *      thread accesses that at a time.  The home_server and
2539          *      main proxy_*_stats structures are updated once the
2540          *      request is cleaned up.
2541          */
2542         request->proxy_listener->stats.total_responses++;
2543
2544         request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2545         request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2546
2547         switch (request->proxy->code) {
2548         case PW_CODE_ACCESS_REQUEST:
2549                 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2550
2551                 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2552                         request->proxy_listener->stats.total_access_accepts++;
2553
2554                 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2555                         request->proxy_listener->stats.total_access_rejects++;
2556
2557                 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2558                         request->proxy_listener->stats.total_access_challenges++;
2559                 }
2560                 break;
2561
2562 #ifdef WITH_ACCOUNTING
2563         case PW_CODE_ACCOUNTING_REQUEST:
2564                 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2565
2566                 request->proxy_listener->stats.total_responses++;
2567                 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2568                 break;
2569
2570 #endif
2571
2572 #ifdef WITH_COA
2573         case PW_CODE_COA_REQUEST:
2574                 request->proxy_listener->stats.total_responses++;
2575                 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2576                 break;
2577
2578         case PW_CODE_DISCONNECT_REQUEST:
2579                 request->proxy_listener->stats.total_responses++;
2580                 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2581                 break;
2582
2583 #endif
2584         default:
2585                 break;
2586         }
2587 #endif
2588
2589         /*
2590          *      If we hadn't been sending the home server packets for
2591          *      a while, just mark it alive.  Or, if it was zombie,
2592          *      it's now responded, and is therefore alive.
2593          */
2594         if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2595             (request->home_server->state == HOME_STATE_ZOMBIE)) {
2596                 mark_home_server_alive(request, request->home_server);
2597         }
2598
2599         /*
2600          *      Tell the request state machine that we have a proxy
2601          *      reply.  Depending on the function, this should either
2602          *      ignore it, or process it.
2603          */
2604         request->process(request, FR_ACTION_PROXY_REPLY);
2605
2606         return 1;
2607 }
2608
2609
2610 static int setup_post_proxy_fail(REQUEST *request)
2611 {
2612         DICT_VALUE const *dval = NULL;
2613         VALUE_PAIR *vp;
2614
2615         VERIFY_REQUEST(request);
2616
2617         if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2618                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2619                                       "Fail-Authentication");
2620 #ifdef WITH_ACCOUNTING
2621         } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2622                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2623                                       "Fail-Accounting");
2624 #endif
2625
2626 #ifdef WITH_COA
2627         } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2628                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2629
2630         } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2631                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2632 #endif
2633         } else {
2634                 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2635                 return 0;
2636         }
2637
2638         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2639
2640         if (!dval) {
2641                 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2642                 return 0;
2643         }
2644
2645         vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2646         if (!vp) vp = radius_pair_create(request, &request->config,
2647                                         PW_POST_PROXY_TYPE, 0);
2648         vp->vp_integer = dval->value;
2649
2650         return 1;
2651 }
2652
2653
2654 /** Process a request after the proxy has timed out.
2655  *
2656  *  Run the packet through Post-Proxy-Type Fail
2657  *
2658  *  \dot
2659  *      digraph proxy_no_reply {
2660  *              proxy_no_reply;
2661  *
2662  *              proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2663  *              proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2664  *              proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2665  *              proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2666  *              proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2667  *      }
2668  *  \enddot
2669  */
2670 static void proxy_no_reply(REQUEST *request, int action)
2671 {
2672         VERIFY_REQUEST(request);
2673
2674         TRACE_STATE_MACHINE;
2675         CHECK_FOR_STOP;
2676
2677         switch (action) {
2678         case FR_ACTION_DUP:
2679                 request_dup(request);
2680                 break;
2681
2682         case FR_ACTION_TIMER:
2683                 (void) request_max_time(request);
2684                 break;
2685
2686         case FR_ACTION_PROXY_REPLY:
2687                 proxy_reply_too_late(request);
2688                 break;
2689
2690         case FR_ACTION_RUN:
2691                 if (process_proxy_reply(request, NULL)) {
2692                         request->handle(request);
2693                 }
2694                 request_finish(request, action);
2695                 break;
2696
2697         default:
2698                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2699                 break;
2700         }
2701 }
2702
2703 /** Process the request after receiving a proxy reply.
2704  *
2705  *  Throught the post-proxy section, and the through the handler
2706  *  function.
2707  *
2708  *  \dot
2709  *      digraph proxy_running {
2710  *              proxy_running;
2711  *
2712  *              proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2713  *              proxy_running -> timer [ label = "TIMER < max_request_time" ];
2714  *              proxy_running -> process_proxy_reply [ label = "RUN" ];
2715  *              proxy_running -> done [ label = "TIMER >= timeout" ];
2716  *      }
2717  *  \enddot
2718  */
2719 static void proxy_running(REQUEST *request, int action)
2720 {
2721         VERIFY_REQUEST(request);
2722
2723         TRACE_STATE_MACHINE;
2724         CHECK_FOR_STOP;
2725
2726         switch (action) {
2727         case FR_ACTION_DUP:
2728                 request_dup(request);
2729                 break;
2730
2731         case FR_ACTION_TIMER:
2732                 (void) request_max_time(request);
2733                 break;
2734
2735         case FR_ACTION_RUN:
2736                 if (process_proxy_reply(request, request->proxy_reply)) {
2737                         request->handle(request);
2738                 }
2739                 request_finish(request, action);
2740                 break;
2741
2742         default:                /* duplicate proxy replies are suppressed */
2743                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2744                 break;
2745         }
2746 }
2747
2748 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2749  *
2750  * Whether a request will be proxied is determined by the attributes present
2751  * in request->config. If any of the following attributes are found, the
2752  * request may be proxied.
2753  *
2754  * The key attributes are:
2755  *   - PW_PROXY_TO_REALM          - Specifies a realm the request should be proxied to.
2756  *   - PW_HOME_SERVER_POOL        - Specifies a specific home server pool to proxy to.
2757  *   - PW_PACKET_DST_IP_ADDRESS   - Specifies a specific IPv4 home server to proxy to.
2758  *   - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2759  *
2760  * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2761  *
2762  * If request should be proxied, will:
2763  *   - Add request:Proxy-State
2764  *   - Strip the current username value of its realm (depending on config)
2765  *   - Create a CHAP-Challenge from the original request vector, if one doesn't already
2766  *     exist.
2767  *   - Call the pre-process section in the current server, or in the virtual server
2768  *     associated with the home server pool we're proxying to.
2769  *
2770  * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2771  *      specific function.
2772  *
2773  * @param request The #REQUEST to evaluate for proxying.
2774  * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2775  */
2776 static int request_will_proxy(REQUEST *request)
2777 {
2778         int rcode, pre_proxy_type = 0;
2779         char const *realmname = NULL;
2780         VALUE_PAIR *vp, *strippedname;
2781         home_server_t *home;
2782         REALM *realm = NULL;
2783         home_pool_t *pool = NULL;
2784
2785         VERIFY_REQUEST(request);
2786
2787         if (!request->root->proxy_requests) return 0;
2788         if (request->packet->dst_port == 0) return 0;
2789         if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2790         if (request->in_proxy_hash) return 0;
2791
2792         /*
2793          *      FIXME: for 3.0, allow this only for rejects?
2794          */
2795         if (request->reply->code != 0) return 0;
2796
2797         vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2798         if (vp) {
2799                 realm = realm_find2(vp->vp_strvalue);
2800                 if (!realm) {
2801                         REDEBUG2("Cannot proxy to unknown realm %s",
2802                                 vp->vp_strvalue);
2803                         return 0;
2804                 }
2805
2806                 realmname = vp->vp_strvalue;
2807
2808                 /*
2809                  *      Figure out which pool to use.
2810                  */
2811                 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2812                         pool = realm->auth_pool;
2813
2814 #ifdef WITH_ACCOUNTING
2815                 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2816                         pool = realm->acct_pool;
2817 #endif
2818
2819 #ifdef WITH_COA
2820                 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2821                            (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2822                         pool = realm->coa_pool;
2823 #endif
2824
2825                 } else {
2826                         return 0;
2827                 }
2828
2829         } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2830                 int pool_type;
2831
2832                 switch (request->packet->code) {
2833                 case PW_CODE_ACCESS_REQUEST:
2834                         pool_type = HOME_TYPE_AUTH;
2835                         break;
2836
2837 #ifdef WITH_ACCOUNTING
2838                 case PW_CODE_ACCOUNTING_REQUEST:
2839                         pool_type = HOME_TYPE_ACCT;
2840                         break;
2841 #endif
2842
2843 #ifdef WITH_COA
2844                 case PW_CODE_COA_REQUEST:
2845                 case PW_CODE_DISCONNECT_REQUEST:
2846                         pool_type = HOME_TYPE_COA;
2847                         break;
2848 #endif
2849
2850                 default:
2851                         return 0;
2852                 }
2853
2854                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2855
2856                 /*
2857                  *      Send it directly to a home server (i.e. NAS)
2858                  */
2859         } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2860                    ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2861                 uint16_t dst_port;
2862                 fr_ipaddr_t dst_ipaddr;
2863
2864                 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2865
2866                 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2867                         dst_ipaddr.af = AF_INET;
2868                         dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2869                         dst_ipaddr.prefix = 32;
2870                 } else {
2871                         dst_ipaddr.af = AF_INET6;
2872                         memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2873                         dst_ipaddr.prefix = 128;
2874                 }
2875
2876                 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2877                 if (!vp) {
2878                         if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2879                                 dst_port = PW_AUTH_UDP_PORT;
2880
2881 #ifdef WITH_ACCOUNTING
2882                         } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2883                                 dst_port = PW_ACCT_UDP_PORT;
2884 #endif
2885
2886 #ifdef WITH_COA
2887                         } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2888                                    (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2889                                 dst_port = PW_COA_UDP_PORT;
2890 #endif
2891                         } else { /* shouldn't happen for RADIUS... */
2892                                 return 0;
2893                         }
2894
2895                 } else {
2896                         dst_port = vp->vp_integer;
2897                 }
2898
2899                 /*
2900                  *      Nothing does CoA over TCP.
2901                  */
2902                 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2903                 if (!home) {
2904                         char buffer[256];
2905
2906                         WARN("No such home server %s port %u",
2907                              inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2908                              (unsigned int) dst_port);
2909                         return 0;
2910                 }
2911
2912                 /*
2913                  *      The home server is alive (or may be alive).
2914                  *      Send the packet to the IP.
2915                  */
2916                 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2917
2918                 /*
2919                  *      The home server is dead.  If you wanted
2920                  *      fail-over, you should have proxied to a pool.
2921                  *      Sucks to be you.
2922                  */
2923
2924                 return 0;
2925
2926         } else {
2927                 return 0;
2928         }
2929
2930         if (!pool) {
2931                 RWDEBUG2("Cancelling proxy as no home pool exists");
2932                 return 0;
2933         }
2934
2935         if (request->listener->synchronous) {
2936                 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2937                 return 0;
2938         }
2939
2940         request->home_pool = pool;
2941
2942         home = home_server_ldb(realmname, pool, request);
2943
2944         if (!home) {
2945                 REDEBUG2("Failed to find live home server: Cancelling proxy");
2946                 return 0;
2947         }
2948
2949 do_home:
2950         home_server_update_request(home, request);
2951
2952 #ifdef WITH_COA
2953         /*
2954          *      Once we've decided to proxy a request, we cannot send
2955          *      a CoA packet.  So we free up any CoA packet here.
2956          */
2957         if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2958 #endif
2959
2960         /*
2961          *      Remember that we sent the request to a Realm.
2962          */
2963         if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2964
2965         /*
2966          *      Strip the name, if told to.
2967          *
2968          *      Doing it here catches the case of proxied tunneled
2969          *      requests.
2970          */
2971         if (realm && (realm->strip_realm == true) &&
2972            (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2973                 /*
2974                  *      If there's a Stripped-User-Name attribute in
2975                  *      the request, then use THAT as the User-Name
2976                  *      for the proxied request, instead of the
2977                  *      original name.
2978                  *
2979                  *      This is done by making a copy of the
2980                  *      Stripped-User-Name attribute, turning it into
2981                  *      a User-Name attribute, deleting the
2982                  *      Stripped-User-Name and User-Name attributes
2983                  *      from the vps list, and making the new
2984                  *      User-Name the head of the vps list.
2985                  */
2986                 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2987                 if (!vp) {
2988                         vp_cursor_t cursor;
2989                         vp = radius_pair_create(NULL, NULL,
2990                                                PW_USER_NAME, 0);
2991                         rad_assert(vp != NULL); /* handled by above function */
2992                         /* Insert at the START of the list */
2993                         /* FIXME: Can't make assumptions about ordering */
2994                         fr_cursor_init(&cursor, &vp);
2995                         fr_cursor_merge(&cursor, request->proxy->vps);
2996                         request->proxy->vps = vp;
2997                 }
2998                 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
2999
3000                 /*
3001                  *      Do NOT delete Stripped-User-Name.
3002                  */
3003         }
3004
3005         /*
3006          *      If there is no PW_CHAP_CHALLENGE attribute but
3007          *      there is a PW_CHAP_PASSWORD we need to add it
3008          *      since we can't use the request authenticator
3009          *      anymore - we changed it.
3010          */
3011         if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
3012             fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
3013             fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
3014                 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
3015                 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
3016         }
3017
3018         /*
3019          *      The RFC's say we have to do this, but FreeRADIUS
3020          *      doesn't need it.
3021          */
3022         vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3023         fr_pair_value_sprintf(vp, "%u", request->packet->id);
3024
3025         /*
3026          *      Should be done BEFORE inserting into proxy hash, as
3027          *      pre-proxy may use this information, or change it.
3028          */
3029         request->proxy->code = request->packet->code;
3030
3031         /*
3032          *      Call the pre-proxy routines.
3033          */
3034         vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3035         if (vp) {
3036                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3037                 /* Must be a validation issue */
3038                 rad_assert(dval);
3039                 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3040                 pre_proxy_type = vp->vp_integer;
3041         }
3042
3043         /*
3044          *      home_pool may be NULL when originating CoA packets,
3045          *      because they go directly to an IP address.
3046          */
3047         if (request->home_pool && request->home_pool->virtual_server) {
3048                 char const *old_server = request->server;
3049
3050                 request->server = request->home_pool->virtual_server;
3051
3052                 RDEBUG2("server %s {", request->server);
3053                 RINDENT();
3054                 rcode = process_pre_proxy(pre_proxy_type, request);
3055                 REXDENT();
3056                 RDEBUG2("}");
3057
3058                 request->server = old_server;
3059         } else {
3060                 char buffer[128];
3061
3062                 RDEBUG2("Starting proxy to home server %s port %d",
3063                         inet_ntop(request->proxy->dst_ipaddr.af,
3064                                   &request->proxy->dst_ipaddr.ipaddr,
3065                                   buffer, sizeof(buffer)),
3066                         request->proxy->dst_port);
3067
3068                 rcode = process_pre_proxy(pre_proxy_type, request);
3069         }
3070
3071         switch (rcode) {
3072         case RLM_MODULE_FAIL:
3073         case RLM_MODULE_INVALID:
3074         case RLM_MODULE_NOTFOUND:
3075         case RLM_MODULE_USERLOCK:
3076         default:
3077                 /* FIXME: debug print failed stuff */
3078                 return -1;
3079
3080         case RLM_MODULE_REJECT:
3081         case RLM_MODULE_HANDLED:
3082                 return 0;
3083
3084         /*
3085          *      Only proxy the packet if the pre-proxy code succeeded.
3086          */
3087         case RLM_MODULE_NOOP:
3088         case RLM_MODULE_OK:
3089         case RLM_MODULE_UPDATED:
3090                 return 1;
3091         }
3092 }
3093
3094 static int proxy_to_virtual_server(REQUEST *request)
3095 {
3096         REQUEST *fake;
3097
3098         if (request->packet->dst_port == 0) {
3099                 WARN("Cannot proxy an internal request");
3100                 return 0;
3101         }
3102
3103         DEBUG("Proxying to virtual server %s",
3104               request->home_server->server);
3105
3106         /*
3107          *      Packets to virtual servers don't get
3108          *      retransmissions sent to them.  And the virtual
3109          *      server is run ONLY if we have no child
3110          *      threads, or we're running in a child thread.
3111          */
3112         rad_assert(!spawn_flag || !we_are_master());
3113
3114         fake = request_alloc_fake(request);
3115
3116         fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3117         talloc_free(request->proxy);
3118
3119         fake->server = request->home_server->server;
3120         fake->handle = request->handle;
3121         fake->process = NULL; /* should never be run for anything */
3122
3123         /*
3124          *      Run the virtual server.
3125          */
3126         request_running(fake, FR_ACTION_RUN);
3127
3128         request->proxy = talloc_steal(request, fake->packet);
3129         fake->packet = NULL;
3130         request->proxy_reply = talloc_steal(request, fake->reply);
3131         fake->reply = NULL;
3132
3133         talloc_free(fake);
3134
3135         /*
3136          *      No reply code, toss the reply we have,
3137          *      and do post-proxy-type Fail.
3138          */
3139         if (!request->proxy_reply->code) {
3140                 TALLOC_FREE(request->proxy_reply);
3141                 setup_post_proxy_fail(request);
3142         }
3143
3144         /*
3145          *      Do the proxy reply (if any)
3146          */
3147         if (process_proxy_reply(request, request->proxy_reply)) {
3148                 request->handle(request);
3149         }
3150
3151         return -1;      /* so we call request_finish */
3152 }
3153
3154
3155 static int request_proxy(REQUEST *request)
3156 {
3157         char buffer[128];
3158
3159         VERIFY_REQUEST(request);
3160
3161         rad_assert(request->parent == NULL);
3162         rad_assert(request->home_server != NULL);
3163
3164         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3165
3166 #ifdef WITH_COA
3167         if (request->coa) {
3168                 RWDEBUG("Cannot proxy and originate CoA packets at the same time.  Cancelling CoA request");
3169                 request_done(request->coa, FR_ACTION_DONE);
3170         }
3171 #endif
3172
3173         /*
3174          *      The request may need sending to a virtual server.
3175          *      This code is more than a little screwed up.  The rest
3176          *      of the state machine doesn't handle parent / child
3177          *      relationships well.  i.e. if the child request takes
3178          *      too long, the core will mark the *parent* as "stop
3179          *      processing".  And the child will continue without
3180          *      knowing anything...
3181          *
3182          *      So, we have some horrible hacks to get around that.
3183          */
3184         if (request->home_server->server) return proxy_to_virtual_server(request);
3185
3186         /*
3187          *      We're actually sending a proxied packet.  Do that now.
3188          */
3189         if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3190                 RPROXY("Failed to insert request into the proxy list");
3191                 return -1;
3192         }
3193
3194         rad_assert(request->proxy->id >= 0);
3195
3196         if (rad_debug_lvl) {
3197                 struct timeval *response_window;
3198
3199                 response_window = request_response_window(request);
3200
3201 #ifdef WITH_TLS
3202                 if (request->home_server->tls) {
3203                         RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3204                                 inet_ntop(request->proxy->dst_ipaddr.af,
3205                                           &request->proxy->dst_ipaddr.ipaddr,
3206                                           buffer, sizeof(buffer)),
3207                                 request->proxy->dst_port,
3208                                 (int) response_window->tv_sec, (int) response_window->tv_usec);
3209                 } else
3210 #endif
3211                         RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3212                                 inet_ntop(request->proxy->dst_ipaddr.af,
3213                                           &request->proxy->dst_ipaddr.ipaddr,
3214                                           buffer, sizeof(buffer)),
3215                                 request->proxy->dst_port,
3216                                 (int) response_window->tv_sec, (int) response_window->tv_usec);
3217
3218
3219         }
3220
3221         gettimeofday(&request->proxy->timestamp, NULL);
3222         request->home_server->last_packet_sent = request->proxy->timestamp.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, since the LAST
3290          *      time we tried to retransmit this packet.
3291          */
3292         if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3293                 VALUE_PAIR *vp;
3294
3295                 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3296                 if (!vp) vp = radius_pair_create(request->proxy,
3297                                                 &request->proxy->vps,
3298                                                 PW_ACCT_DELAY_TIME, 0);
3299                 if (vp) {
3300                         struct timeval now;
3301
3302                         gettimeofday(&now, NULL);
3303                         vp->vp_integer += now.tv_sec - request->proxy->timestamp.tv_sec;
3304                 }
3305         }
3306 #endif
3307
3308         /*
3309          *      May have failed over to a "fallback" virtual server.
3310          *      If so, run that instead of doing proxying to a real
3311          *      server.
3312          */
3313         if (home->server) {
3314                 request->home_server = home;
3315                 TALLOC_FREE(request->proxy);
3316
3317                 (void) proxy_to_virtual_server(request);
3318                 return 0;
3319         }
3320
3321         home_server_update_request(home, request);
3322
3323         if (!insert_into_proxy_hash(request)) {
3324                 RPROXY("Failed to insert retransmission into the proxy list");
3325                 goto post_proxy_fail;
3326         }
3327
3328         /*
3329          *      Free the old packet, to force re-encoding
3330          */
3331         talloc_free(request->proxy->data);
3332         request->proxy->data = NULL;
3333         request->proxy->data_len = 0;
3334
3335         if (request_proxy(request) != 1) goto post_proxy_fail;
3336
3337         return 1;
3338 }
3339
3340
3341 /** Ping a home server.
3342  *
3343  */
3344 static void request_ping(REQUEST *request, int action)
3345 {
3346         home_server_t *home = request->home_server;
3347         char buffer[128];
3348
3349         VERIFY_REQUEST(request);
3350
3351         TRACE_STATE_MACHINE;
3352         ASSERT_MASTER;
3353
3354         switch (action) {
3355         case FR_ACTION_TIMER:
3356                 ERROR("No response to status check %d ID %u for home server %s port %d",
3357                        request->number,
3358                        request->proxy->id,
3359                        inet_ntop(request->proxy->dst_ipaddr.af,
3360                                  &request->proxy->dst_ipaddr.ipaddr,
3361                                  buffer, sizeof(buffer)),
3362                        request->proxy->dst_port);
3363                 break;
3364
3365         case FR_ACTION_PROXY_REPLY:
3366                 rad_assert(request->in_proxy_hash);
3367
3368                 request->home_server->num_received_pings++;
3369                 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3370                        request->number, request->proxy->id, home->num_received_pings);
3371
3372                 /*
3373                  *      Remove the request from any hashes
3374                  */
3375                 fr_event_delete(el, &request->ev);
3376                 remove_from_proxy_hash(request);
3377
3378                 /*
3379                  *      The control socket may have marked the home server as
3380                  *      alive.  OR, it may have suddenly started responding to
3381                  *      requests again.  If so, don't re-do the "make alive"
3382                  *      work.
3383                  */
3384                 if (home->state == HOME_STATE_ALIVE) break;
3385
3386                 /*
3387                  *      It's dead, and we haven't received enough ping
3388                  *      responses to mark it "alive".  Wait a bit.
3389                  *
3390                  *      If it's zombie, we mark it alive immediately.
3391                  */
3392                 if ((home->state == HOME_STATE_IS_DEAD) &&
3393                     (home->num_received_pings < home->num_pings_to_alive)) {
3394                         return;
3395                 }
3396
3397                 /*
3398                  *      Mark it alive and delete any outstanding
3399                  *      pings.
3400                  */
3401                 mark_home_server_alive(request, home);
3402                 break;
3403
3404         default:
3405                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3406                 break;
3407         }
3408
3409         rad_assert(!request->in_request_hash);
3410         rad_assert(request->ev == NULL);
3411         NO_CHILD_THREAD;
3412         request_done(request, FR_ACTION_DONE);
3413 }
3414
3415 /*
3416  *      Add +/- 2s of jitter, as suggested in RFC 3539
3417  *      and in RFC 5080.
3418  */
3419 static void add_jitter(struct timeval *when)
3420 {
3421         uint32_t jitter;
3422
3423         when->tv_sec -= 2;
3424
3425         jitter = fr_rand();
3426         jitter ^= (jitter >> 10);
3427         jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
3428
3429         /*
3430          *      Add in ~ (4 * USEC) of jitter.
3431          */
3432         tv_add(when, jitter);
3433 }
3434
3435 /*
3436  *      Called from start of zombie period, OR after control socket
3437  *      marks the home server dead.
3438  */
3439 static void ping_home_server(void *ctx)
3440 {
3441         home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3442         REQUEST *request;
3443         VALUE_PAIR *vp;
3444         struct timeval when, now;
3445
3446         if ((home->state == HOME_STATE_ALIVE) ||
3447             (home->ev != NULL)) {
3448                 return;
3449         }
3450
3451         gettimeofday(&now, NULL);
3452         ASSERT_MASTER;
3453
3454         /*
3455          *      We've run out of zombie time.  Mark it dead.
3456          */
3457         if (home->state == HOME_STATE_ZOMBIE) {
3458                 when = home->zombie_period_start;
3459                 when.tv_sec += home->zombie_period;
3460
3461                 if (timercmp(&when, &now, <)) {
3462                         DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3463                         mark_home_server_dead(home, &now);
3464                 }
3465         }
3466
3467         /*
3468          *      We're not supposed to be pinging it.  Just wake up
3469          *      when we're supposed to mark it dead.
3470          */
3471         if (home->ping_check == HOME_PING_CHECK_NONE) {
3472                 if (home->state == HOME_STATE_ZOMBIE) {
3473                         home->when = home->zombie_period_start;
3474                         home->when.tv_sec += home->zombie_period;
3475                         INSERT_EVENT(ping_home_server, home);
3476                 }
3477
3478                 /*
3479                  *      Else mark_home_server_dead will set a timer
3480                  *      for revive_interval.
3481                  */
3482                 return;
3483         }
3484
3485
3486         request = request_alloc(NULL);
3487         if (!request) return;
3488         request->number = request_num_counter++;
3489         NO_CHILD_THREAD;
3490
3491         request->proxy = rad_alloc(request, true);
3492         rad_assert(request->proxy != NULL);
3493
3494         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3495                 request->proxy->code = PW_CODE_STATUS_SERVER;
3496
3497                 fr_pair_make(request->proxy, &request->proxy->vps,
3498                          "Message-Authenticator", "0x00", T_OP_SET);
3499
3500         } else if ((home->type == HOME_TYPE_AUTH) ||
3501                    (home->type == HOME_TYPE_AUTH_ACCT)) {
3502                 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3503
3504                 fr_pair_make(request->proxy, &request->proxy->vps,
3505                          "User-Name", home->ping_user_name, T_OP_SET);
3506                 fr_pair_make(request->proxy, &request->proxy->vps,
3507                          "User-Password", home->ping_user_password, T_OP_SET);
3508                 fr_pair_make(request->proxy, &request->proxy->vps,
3509                          "Service-Type", "Authenticate-Only", T_OP_SET);
3510                 fr_pair_make(request->proxy, &request->proxy->vps,
3511                          "Message-Authenticator", "0x00", T_OP_SET);
3512
3513 #ifdef WITH_ACCOUNTING
3514         } else if (home->type == HOME_TYPE_ACCT) {
3515                 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3516
3517                 fr_pair_make(request->proxy, &request->proxy->vps,
3518                          "User-Name", home->ping_user_name, T_OP_SET);
3519                 fr_pair_make(request->proxy, &request->proxy->vps,
3520                          "Acct-Status-Type", "Stop", T_OP_SET);
3521                 fr_pair_make(request->proxy, &request->proxy->vps,
3522                          "Acct-Session-Id", "00000000", T_OP_SET);
3523                 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3524                               "Event-Timestamp", "0", T_OP_SET);
3525                 vp->vp_date = now.tv_sec;
3526 #endif
3527
3528         } else {
3529                 /*
3530                  *      Unkown home server type.
3531                  */
3532                 talloc_free(request);
3533                 return;
3534         }
3535
3536         vp = fr_pair_make(request->proxy, &request->proxy->vps,
3537                       "NAS-Identifier", "", T_OP_SET);
3538         if (vp) {
3539                 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3540                             home->num_sent_pings);
3541         }
3542
3543 #ifdef WITH_TCP
3544         request->proxy->proto = home->proto;
3545 #endif
3546         request->proxy->src_ipaddr = home->src_ipaddr;
3547         request->proxy->dst_ipaddr = home->ipaddr;
3548         request->proxy->dst_port = home->port;
3549         request->home_server = home;
3550 #ifdef DEBUG_STATE_MACHINE
3551         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3552                                child_state_names[request->child_state],
3553                                child_state_names[REQUEST_DONE]);
3554         if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3555 #endif
3556 #ifdef HAVE_PTHREAD_H
3557         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3558 #endif
3559         request->child_state = REQUEST_PROXIED;
3560         request->process = request_ping;
3561
3562         rad_assert(request->proxy_listener == NULL);
3563
3564         if (!insert_into_proxy_hash(request)) {
3565                 RPROXY("Failed to insert status check %d into proxy list.  Discarding it.",
3566                        request->number);
3567
3568                 rad_assert(!request->in_request_hash);
3569                 rad_assert(!request->in_proxy_hash);
3570                 rad_assert(request->ev == NULL);
3571                 talloc_free(request);
3572                 return;
3573         }
3574
3575         /*
3576          *      Set up the timer callback.
3577          */
3578         when = now;
3579         when.tv_sec += home->ping_timeout;
3580
3581         DEBUG("PING: Waiting %u seconds for response to ping",
3582               home->ping_timeout);
3583
3584         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3585         home->num_sent_pings++;
3586
3587         rad_assert(request->proxy_listener != NULL);
3588         debug_packet(request, request->proxy, false);
3589         request->proxy_listener->send(request->proxy_listener,
3590                                       request);
3591
3592         /*
3593          *      Add +/- 2s of jitter, as suggested in RFC 3539
3594          *      and in the Issues and Fixes draft.
3595          */
3596         home->when = now;
3597         home->when.tv_sec += home->ping_interval;
3598
3599         add_jitter(&home->when);
3600
3601         DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3602         INSERT_EVENT(ping_home_server, home);
3603 }
3604
3605 static void home_trigger(home_server_t *home, char const *trigger)
3606 {
3607         REQUEST *my_request;
3608         RADIUS_PACKET *my_packet;
3609
3610         my_request = talloc_zero(NULL, REQUEST);
3611         my_packet = talloc_zero(my_request, RADIUS_PACKET);
3612         my_request->proxy = my_packet;
3613         my_packet->dst_ipaddr = home->ipaddr;
3614         my_packet->src_ipaddr = home->src_ipaddr;
3615
3616         exec_trigger(my_request, home->cs, trigger, false);
3617         talloc_free(my_request);
3618 }
3619
3620 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3621 {
3622         time_t start;
3623         char buffer[128];
3624
3625         ASSERT_MASTER;
3626
3627         rad_assert((home->state == HOME_STATE_ALIVE) ||
3628                    (home->state == HOME_STATE_UNKNOWN));
3629
3630         /*
3631          *      We've received a real packet recently.  Don't mark the
3632          *      server as zombie until we've received NO packets for a
3633          *      while.  The "1/4" of zombie period was chosen rather
3634          *      arbitrarily.  It's a balance between too short, which
3635          *      gives quick fail-over and fail-back, or too long,
3636          *      where the proxy still sends packets to an unresponsive
3637          *      home server.
3638          */
3639         start = now->tv_sec - ((home->zombie_period + 3) / 4);
3640         if (home->last_packet_recv >= start) {
3641                 DEBUG("Received reply from home server %d seconds ago.  Might not be zombie.",
3642                       (int) (now->tv_sec - home->last_packet_recv));
3643                 return;
3644         }
3645
3646         home->state = HOME_STATE_ZOMBIE;
3647         home_trigger(home, "home_server.zombie");
3648
3649         /*
3650          *      Set the home server to "zombie", as of the time
3651          *      calculated above.
3652          */
3653         home->zombie_period_start.tv_sec = start;
3654         home->zombie_period_start.tv_usec = USEC / 2;
3655
3656         fr_event_delete(el, &home->ev);
3657
3658         home->num_sent_pings = 0;
3659         home->num_received_pings = 0;
3660
3661         PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3662                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3663                          buffer, sizeof(buffer)),
3664                home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3665
3666         ping_home_server(home);
3667 }
3668
3669
3670 void revive_home_server(void *ctx)
3671 {
3672         home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3673         char buffer[128];
3674
3675         home->state = HOME_STATE_ALIVE;
3676         home->response_timeouts = 0;
3677         home_trigger(home, "home_server.alive");
3678         home->currently_outstanding = 0;
3679         gettimeofday(&home->revive_time, NULL);
3680
3681         /*
3682          *      Delete any outstanding events.
3683          */
3684         ASSERT_MASTER;
3685         if (home->ev) fr_event_delete(el, &home->ev);
3686
3687         PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3688                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3689                          buffer, sizeof(buffer)),
3690                home->port);
3691 }
3692
3693 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3694 {
3695         int previous_state = home->state;
3696         char buffer[128];
3697
3698         PROXY( "Marking home server %s port %d as dead.",
3699                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3700                          buffer, sizeof(buffer)),
3701                home->port);
3702
3703         home->state = HOME_STATE_IS_DEAD;
3704         home_trigger(home, "home_server.dead");
3705
3706         if (home->ping_check != HOME_PING_CHECK_NONE) {
3707                 /*
3708                  *      If the control socket marks us dead, start
3709                  *      pinging.  Otherwise, we already started
3710                  *      pinging when it was marked "zombie".
3711                  */
3712                 if (previous_state == HOME_STATE_ALIVE) {
3713                         ping_home_server(home);
3714                 } else {
3715                         DEBUG("PING: Already pinging home server %s", home->log_name);
3716                 }
3717
3718         } else {
3719                 /*
3720                  *      Revive it after a fixed period of time.  This
3721                  *      is very, very, bad.
3722                  */
3723                 home->when = *when;
3724                 home->when.tv_sec += home->revive_interval;
3725
3726                 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3727                 ASSERT_MASTER;
3728                 INSERT_EVENT(revive_home_server, home);
3729         }
3730 }
3731
3732 /** Wait for a reply after proxying a request.
3733  *
3734  *  Retransmit the proxied packet, or time out and go to
3735  *  proxy_no_reply.  Mark the home server unresponsive, etc.
3736  *
3737  *  If we do receive a reply, we transition to proxy_running.
3738  *
3739  *  \dot
3740  *      digraph proxy_wait_for_reply {
3741  *              proxy_wait_for_reply;
3742  *
3743  *              proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3744  *              proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3745  *              proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3746  *              proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3747  *              proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3748  *      }
3749  *  \enddot
3750  */
3751 static void proxy_wait_for_reply(REQUEST *request, int action)
3752 {
3753         struct timeval now, when;
3754         struct timeval *response_window = NULL;
3755         home_server_t *home = request->home_server;
3756         char buffer[128];
3757
3758         VERIFY_REQUEST(request);
3759
3760         TRACE_STATE_MACHINE;
3761         CHECK_FOR_STOP;
3762
3763         rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3764         rad_assert(request->home_server != NULL);
3765
3766         gettimeofday(&now, NULL);
3767
3768         switch (action) {
3769         case FR_ACTION_DUP:
3770                 /*
3771                  *      We have a reply, ignore the retransmit.
3772                  */
3773                 if (request->proxy_reply) return;
3774
3775                 /*
3776                  *      The request was proxied to a virtual server.
3777                  *      Ignore the retransmit.
3778                  */
3779                 if (request->home_server->server) return;
3780
3781                 /*
3782                  *      Use a new connection when the home server is
3783                  *      dead, or when there's no proxy listener, or
3784                  *      when the listener is failed or dead.
3785                  *
3786                  *      If the listener is known or frozen, use it for
3787                  *      retransmits.
3788                  */
3789                 if ((home->state == HOME_STATE_IS_DEAD) ||
3790                     !request->proxy_listener ||
3791                     (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3792                         request_proxy_anew(request);
3793                         return;
3794                 }
3795
3796 #ifdef WITH_TCP
3797                 /*
3798                  *      The home server is still alive, but TCP.  We
3799                  *      rely on TCP to get the request and reply back.
3800                  *      So there's no need to retransmit.
3801                  */
3802                 if (home->proto == IPPROTO_TCP) {
3803                         DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3804                                inet_ntop(request->proxy->dst_ipaddr.af,
3805                                          &request->proxy->dst_ipaddr.ipaddr,
3806                                          buffer, sizeof(buffer)),
3807                                request->proxy->dst_port,
3808                                request->proxy->id);
3809                         return;
3810                 }
3811 #endif
3812
3813                 /*
3814                  *      More than one retransmit a second is stupid,
3815                  *      and should be suppressed by the proxy.
3816                  */
3817                 when = request->proxy->timestamp;
3818                 when.tv_sec++;
3819
3820                 if (timercmp(&now, &when, <)) {
3821                         DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3822                                inet_ntop(request->proxy->dst_ipaddr.af,
3823                                          &request->proxy->dst_ipaddr.ipaddr,
3824                                          buffer, sizeof(buffer)),
3825                                request->proxy->dst_port,
3826                                request->proxy->id);
3827                         return;
3828                 }
3829
3830 #ifdef WITH_ACCOUNTING
3831                 /*
3832                  *      If we update the Acct-Delay-Time, we need to
3833                  *      get a new ID.
3834                  */
3835                 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3836                     fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3837                         request_proxy_anew(request);
3838                         return;
3839                 }
3840 #endif
3841
3842                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3843                         inet_ntop(request->proxy->dst_ipaddr.af,
3844                                   &request->proxy->dst_ipaddr.ipaddr,
3845                                   buffer, sizeof(buffer)),
3846                         request->proxy->dst_port,
3847                         request->proxy->id);
3848                 request->num_proxied_requests++;
3849
3850                 rad_assert(request->proxy_listener != NULL);
3851                 FR_STATS_TYPE_INC(home->stats.total_requests);
3852                 home->last_packet_sent = now.tv_sec;
3853                 request->proxy->timestamp = now;
3854                 debug_packet(request, request->proxy, false);
3855                 request->proxy_listener->send(request->proxy_listener, request);
3856                 break;
3857
3858         case FR_ACTION_TIMER:
3859                 response_window = request_response_window(request);
3860
3861 #ifdef WITH_TCP
3862                 if (!request->proxy_listener ||
3863                     (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3864                         remove_from_proxy_hash(request);
3865
3866                         when = request->packet->timestamp;
3867                         when.tv_sec += request->root->max_request_time;
3868
3869                         if (timercmp(&when, &now, >)) {
3870                                 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3871                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3872                                 return;
3873                         }
3874                 } else
3875 #endif
3876                 {
3877                         /*
3878                          *      Wake up "response_window" time in the future.
3879                          *      i.e. when MY packet hasn't received a response.
3880                          *
3881                          *      Note that we DO NOT mark the home server as
3882                          *      zombie if it doesn't respond to us.  It may be
3883                          *      responding to other (better looking) packets.
3884                          */
3885                         when = request->proxy->timestamp;
3886                         timeradd(&when, response_window, &when);
3887
3888                         /*
3889                          *      Not at the response window.  Set the timer for
3890                          *      that.
3891                          */
3892                         if (timercmp(&when, &now, >)) {
3893                                 struct timeval diff;
3894                                 timersub(&when, &now, &diff);
3895
3896                                 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3897                                        (int) diff.tv_sec, (int) diff.tv_usec);
3898                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3899                                 return;
3900                         }
3901                 }
3902
3903                 RDEBUG("No proxy response, giving up on request and marking it done");
3904
3905                 /*
3906                  *      If we haven't received any packets for
3907                  *      "response_window", then mark the home server
3908                  *      as zombie.
3909                  *
3910                  *      This check should really be part of a home
3911                  *      server state machine.
3912                  */
3913                 if (((home->state == HOME_STATE_ALIVE) ||
3914                      (home->state == HOME_STATE_UNKNOWN))
3915                         ) {
3916                         home->response_timeouts++;
3917                         if (home->response_timeouts >= home->max_response_timeouts)
3918                                 mark_home_server_zombie(home, &now, response_window);
3919                 }
3920
3921                 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3922                 if (home->type == HOME_TYPE_AUTH) {
3923                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3924                         FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3925                 }
3926 #ifdef WITH_ACCT
3927                 else if (home->type == HOME_TYPE_ACCT) {
3928                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3929                         FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3930                 }
3931 #endif
3932 #ifdef WITH_COA
3933                 else if (home->type == HOME_TYPE_COA) {
3934                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3935
3936                         if (request->packet->code == PW_CODE_COA_REQUEST) {
3937                                 FR_STATS_TYPE_INC(proxy_coa_stats.total_timeouts);
3938                         } else {
3939                                 FR_STATS_TYPE_INC(proxy_dsc_stats.total_timeouts);
3940                         }
3941                 }
3942 #endif
3943
3944                 /*
3945                  *      There was no response within the window.  Stop
3946                  *      the request.  If the client retransmitted, it
3947                  *      may have failed over to another home server.
3948                  *      But that one may be dead, too.
3949                  *
3950                  *      The extra verbose message if we have a username,
3951                  *      is extremely useful if the proxy is part of a chain
3952                  *      and the final home server, is not the one we're
3953                  *      proxying to.
3954                  */
3955                 if (request->username) {
3956                         RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3957                                "server %s port %d",
3958                                request->username->vp_strvalue,
3959                                inet_ntop(request->proxy->dst_ipaddr.af,
3960                                          &request->proxy->dst_ipaddr.ipaddr,
3961                                          buffer, sizeof(buffer)),
3962                                request->proxy->dst_port);
3963                 } else {
3964                         RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3965                                inet_ntop(request->proxy->dst_ipaddr.af,
3966                                          &request->proxy->dst_ipaddr.ipaddr,
3967                                          buffer, sizeof(buffer)),
3968                                request->proxy->dst_port);
3969                 }
3970
3971                 if (setup_post_proxy_fail(request)) {
3972                         request_queue_or_run(request, proxy_no_reply);
3973                 } else {
3974                         gettimeofday(&request->reply->timestamp, NULL);
3975                         request_cleanup_delay_init(request);
3976                 }
3977                 break;
3978
3979                 /*
3980                  *      We received a new reply.  Go process it.
3981                  */
3982         case FR_ACTION_PROXY_REPLY:
3983                 request_queue_or_run(request, proxy_running);
3984                 break;
3985
3986         default:
3987                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3988                 break;
3989         }
3990 }
3991 #endif  /* WITH_PROXY */
3992
3993
3994 /***********************************************************************
3995  *
3996  *  CoA code
3997  *
3998  ***********************************************************************/
3999 #ifdef WITH_COA
4000 static int null_handler(UNUSED REQUEST *request)
4001 {
4002         return 0;
4003 }
4004
4005 /*
4006  *      See if we need to originate a CoA request.
4007  */
4008 static void request_coa_originate(REQUEST *request)
4009 {
4010         int rcode, pre_proxy_type = 0;
4011         VALUE_PAIR *vp;
4012         REQUEST *coa;
4013         fr_ipaddr_t ipaddr;
4014         char buffer[256];
4015
4016         VERIFY_REQUEST(request);
4017
4018         rad_assert(request->coa != NULL);
4019         rad_assert(request->proxy == NULL);
4020         rad_assert(!request->in_proxy_hash);
4021         rad_assert(request->proxy_reply == NULL);
4022
4023         /*
4024          *      Check whether we want to originate one, or cancel one.
4025          */
4026         vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4027         if (!vp) {
4028                 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4029         }
4030
4031         if (vp) {
4032                 if (vp->vp_integer == 0) {
4033                 fail:
4034                         TALLOC_FREE(request->coa);
4035                         return;
4036                 }
4037         }
4038
4039         if (!main_config.proxy_requests) {
4040                 RWDEBUG("Cannot originate CoA packets unless 'proxy_requests = yes'");
4041                         TALLOC_FREE(request->coa);
4042                 return;
4043         }
4044
4045         coa = request->coa;
4046
4047         /*
4048          *      src_ipaddr will be set up in proxy_encode.
4049          */
4050         memset(&ipaddr, 0, sizeof(ipaddr));
4051         vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4052         if (vp) {
4053                 ipaddr.af = AF_INET;
4054                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4055                 ipaddr.prefix = 32;
4056         } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4057                 ipaddr.af = AF_INET6;
4058                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4059                 ipaddr.prefix = 128;
4060         } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4061                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4062                                                   HOME_TYPE_COA);
4063                 if (!coa->home_pool) {
4064                         RWDEBUG2("No such home_server_pool %s",
4065                                vp->vp_strvalue);
4066                         goto fail;
4067                 }
4068
4069                 /*
4070                  *      Prefer the pool to one server
4071                  */
4072         } else if (request->client->coa_pool) {
4073                 coa->home_pool = request->client->coa_pool;
4074
4075         } else if (request->client->coa_server) {
4076                 coa->home_server = request->client->coa_server;
4077
4078         } else {
4079                 /*
4080                  *      If all else fails, send it to the client that
4081                  *      originated this request.
4082                  */
4083                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4084         }
4085
4086         /*
4087          *      Use the pool, if it exists.
4088          */
4089         if (coa->home_pool) {
4090                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4091                 if (!coa->home_server) {
4092                         RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4093                         goto fail;
4094                 }
4095                 home_server_update_request(coa->home_server, coa);
4096
4097         } else if (!coa->home_server) {
4098                 uint16_t port = PW_COA_UDP_PORT;
4099
4100                 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4101                 if (vp) port = vp->vp_integer;
4102
4103                 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4104                 if (!coa->home_server) {
4105                         RWDEBUG2("Unknown destination %s:%d for CoA request.",
4106                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4107                                          buffer, sizeof(buffer)), port);
4108                         goto fail;
4109                 }
4110         }
4111
4112         vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4113         if (vp) {
4114                 switch (vp->vp_integer) {
4115                 case PW_CODE_COA_REQUEST:
4116                 case PW_CODE_DISCONNECT_REQUEST:
4117                         coa->proxy->code = vp->vp_integer;
4118                         break;
4119
4120                 default:
4121                         DEBUG("Cannot set CoA Packet-Type to code %d",
4122                               vp->vp_integer);
4123                         goto fail;
4124                 }
4125         }
4126
4127         if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4128
4129         /*
4130          *      The rest of the server code assumes that
4131          *      request->packet && request->reply exist.  Copy them
4132          *      from the original request.
4133          */
4134         rad_assert(coa->packet != NULL);
4135         rad_assert(coa->packet->vps == NULL);
4136
4137         coa->packet = rad_copy_packet(coa, request->packet);
4138         coa->reply = rad_copy_packet(coa, request->reply);
4139
4140         coa->config = fr_pair_list_copy(coa, request->config);
4141         coa->num_coa_requests = 0;
4142         coa->handle = null_handler;
4143         coa->number = request->number; /* it's associated with the same request */
4144
4145         /*
4146          *      Call the pre-proxy routines.
4147          */
4148         vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4149         if (vp) {
4150                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4151                 /* Must be a validation issue */
4152                 rad_assert(dval);
4153                 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4154                 pre_proxy_type = vp->vp_integer;
4155         }
4156
4157         if (coa->home_pool && coa->home_pool->virtual_server) {
4158                 char const *old_server = coa->server;
4159
4160                 coa->server = coa->home_pool->virtual_server;
4161                 RDEBUG2("server %s {", coa->server);
4162                 RINDENT();
4163                 rcode = process_pre_proxy(pre_proxy_type, coa);
4164                 REXDENT();
4165                 RDEBUG2("}");
4166                 coa->server = old_server;
4167         } else {
4168                 rcode = process_pre_proxy(pre_proxy_type, coa);
4169         }
4170         switch (rcode) {
4171         default:
4172                 goto fail;
4173
4174         /*
4175          *      Only send the CoA packet if the pre-proxy code succeeded.
4176          */
4177         case RLM_MODULE_NOOP:
4178         case RLM_MODULE_OK:
4179         case RLM_MODULE_UPDATED:
4180                 break;
4181         }
4182
4183         /*
4184          *      Source IP / port is set when the proxy socket
4185          *      is chosen.
4186          */
4187         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4188         coa->proxy->dst_port = coa->home_server->port;
4189
4190         if (!insert_into_proxy_hash(coa)) {
4191                 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4192                 goto fail;
4193         }
4194
4195         /*
4196          *      We CANNOT divorce the CoA request from the parent
4197          *      request.  This function is running in a child thread,
4198          *      and we need access to the main event loop in order to
4199          *      to add the timers for the CoA packet.
4200          *
4201          *      Instead, we wait for the timer on the parent request
4202          *      to fire.
4203          */
4204         gettimeofday(&coa->proxy->timestamp, NULL);
4205         coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4206         coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4207         coa->delay = 0;         /* need to calculate a new delay */
4208
4209         /*
4210          *      If requested, put a State attribute into the packet,
4211          *      and cache the VPS.
4212          */
4213         fr_state_put_vps(coa, NULL, coa->packet);
4214
4215         /*
4216          *      Encode the packet before we do anything else.
4217          */
4218         coa->proxy_listener->encode(coa->proxy_listener, coa);
4219         debug_packet(coa, coa->proxy, false);
4220
4221 #ifdef DEBUG_STATE_MACHINE
4222         if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4223                                child_state_names[request->child_state],
4224                                child_state_names[REQUEST_PROXIED]);
4225 #endif
4226
4227         /*
4228          *      Set the state function, then the state, no child, and
4229          *      send the packet.
4230          */
4231         coa->process = coa_wait_for_reply;
4232         coa->child_state = REQUEST_PROXIED;
4233
4234 #ifdef HAVE_PTHREAD_H
4235         coa->child_pid = NO_SUCH_CHILD_PID;
4236 #endif
4237
4238         if (we_are_master()) coa_separate(request->coa);
4239
4240         /*
4241          *      And send the packet.
4242          */
4243         coa->proxy_listener->send(coa->proxy_listener, coa);
4244 }
4245
4246
4247 static void coa_retransmit(REQUEST *request)
4248 {
4249         uint32_t delay, frac;
4250         struct timeval now, when, mrd;
4251         char buffer[128];
4252
4253         VERIFY_REQUEST(request);
4254
4255         fr_event_now(el, &now);
4256
4257         if (request->delay == 0) {
4258                 /*
4259                  *      Implement re-transmit algorithm as per RFC 5080
4260                  *      Section 2.2.1.
4261                  *
4262                  *      We want IRT + RAND*IRT
4263                  *      or 0.9 IRT + rand(0,.2) IRT
4264                  *
4265                  *      2^20 ~ USEC, and we want 2.
4266                  *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4267                  */
4268                 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4269                 request->delay = delay * request->home_server->coa_irt;
4270                 delay = request->home_server->coa_irt * USEC;
4271                 delay -= delay / 10;
4272                 delay += request->delay;
4273                 request->delay = delay;
4274
4275                 when = request->proxy->timestamp;
4276                 tv_add(&when, delay);
4277
4278                 if (timercmp(&when, &now, >)) {
4279                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4280                         return;
4281                 }
4282         }
4283
4284         /*
4285          *      Retransmit CoA request.
4286          */
4287
4288         /*
4289          *      Cap count at MRC, if it is non-zero.
4290          */
4291         if (request->home_server->coa_mrc &&
4292             (request->num_coa_requests >= request->home_server->coa_mrc)) {
4293                 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4294                        request->proxy->id,
4295                                inet_ntop(request->proxy->dst_ipaddr.af,
4296                                          &request->proxy->dst_ipaddr.ipaddr,
4297                                          buffer, sizeof(buffer)),
4298                                request->proxy->dst_port);
4299
4300                 if (setup_post_proxy_fail(request)) {
4301                         request_queue_or_run(request, coa_no_reply);
4302                 } else {
4303                         request_done(request, FR_ACTION_DONE);
4304                 }
4305                 return;
4306         }
4307
4308         /*
4309          *      RFC 5080 Section 2.2.1
4310          *
4311          *      RT = 2*RTprev + RAND*RTprev
4312          *         = 1.9 * RTprev + rand(0,.2) * RTprev
4313          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4314          */
4315         delay = fr_rand();
4316         delay ^= (delay >> 16);
4317         delay &= 0xffff;
4318         frac = request->delay / 5;
4319         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4320
4321         delay += (2 * request->delay) - (request->delay / 10);
4322
4323         /*
4324          *      Cap delay at MRT, if MRT is non-zero.
4325          */
4326         if (request->home_server->coa_mrt &&
4327             (delay > (request->home_server->coa_mrt * USEC))) {
4328                 int mrt_usec = request->home_server->coa_mrt * USEC;
4329
4330                 /*
4331                  *      delay = MRT + RAND * MRT
4332                  *            = 0.9 MRT + rand(0,.2)  * MRT
4333                  */
4334                 delay = fr_rand();
4335                 delay ^= (delay >> 15);
4336                 delay &= 0x1ffff;
4337                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4338                 delay += mrt_usec - (mrt_usec / 10);
4339         }
4340
4341         request->delay = delay;
4342         when = now;
4343         tv_add(&when, request->delay);
4344         mrd = request->proxy->timestamp;
4345         mrd.tv_sec += request->home_server->coa_mrd;
4346
4347         /*
4348          *      Cap duration at MRD.
4349          */
4350         if (timercmp(&mrd, &when, <)) {
4351                 when = mrd;
4352         }
4353         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4354
4355         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4356
4357         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4358
4359         RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4360                 inet_ntop(request->proxy->dst_ipaddr.af,
4361                           &request->proxy->dst_ipaddr.ipaddr,
4362                           buffer, sizeof(buffer)),
4363                 request->proxy->dst_port,
4364                 request->proxy->id);
4365
4366         request->proxy_listener->send(request->proxy_listener,
4367                                       request);
4368 }
4369
4370
4371 /** Wait for a reply after originating a CoA a request.
4372  *
4373  *  Retransmit the proxied packet, or time out and go to
4374  *  coa_no_reply.  Mark the home server unresponsive, etc.
4375  *
4376  *  If we do receive a reply, we transition to coa_running.
4377  *
4378  *  \dot
4379  *      digraph coa_wait_for_reply {
4380  *              coa_wait_for_reply;
4381  *
4382  *              coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4383  *              coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4384  *              coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4385  *              coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4386  *      }
4387  *  \enddot
4388  */
4389 static void coa_wait_for_reply(REQUEST *request, int action)
4390 {
4391         VERIFY_REQUEST(request);
4392
4393         TRACE_STATE_MACHINE;
4394         ASSERT_MASTER;
4395         CHECK_FOR_STOP;
4396
4397         if (request->parent) coa_separate(request);
4398
4399         switch (action) {
4400         case FR_ACTION_TIMER:
4401                 if (request_max_time(request)) break;
4402
4403                 /*
4404                  *      Don't do fail-over.  This is a 3.1 feature.
4405                  */
4406                 if (!request->home_server ||
4407                     (request->home_server->state == HOME_STATE_IS_DEAD) ||
4408                     !request->proxy_listener ||
4409                     (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
4410                         request_done(request, FR_ACTION_DONE);
4411                         break;
4412                 }
4413
4414                 coa_retransmit(request);
4415                 break;
4416
4417         case FR_ACTION_PROXY_REPLY:
4418                 request_queue_or_run(request, coa_running);
4419                 break;
4420
4421         default:
4422                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4423                 break;
4424         }
4425 }
4426
4427 static void coa_separate(REQUEST *request)
4428 {
4429         VERIFY_REQUEST(request);
4430 #ifdef DEBUG_STATE_MACHINE
4431         int action = FR_ACTION_TIMER;
4432 #endif
4433
4434         TRACE_STATE_MACHINE;
4435         ASSERT_MASTER;
4436
4437         rad_assert(request->parent != NULL);
4438         rad_assert(request->parent->coa == request);
4439         rad_assert(request->ev == NULL);
4440         rad_assert(!request->in_request_hash);
4441         rad_assert(request->coa == NULL);
4442
4443         rad_assert(request->proxy_reply || request->proxy_listener);
4444
4445         (void) talloc_steal(NULL, request);
4446         request->parent->coa = NULL;
4447         request->parent = NULL;
4448
4449         if (we_are_master()) {
4450                 request->delay = 0;
4451                 coa_retransmit(request);
4452         }
4453 }
4454
4455
4456 /** Process a request after the CoA has timed out.
4457  *
4458  *  Run the packet through Post-Proxy-Type Fail
4459  *
4460  *  \dot
4461  *      digraph coa_no_reply {
4462  *              coa_no_reply;
4463  *
4464  *              coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4465  *              coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4466  *              coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4467  *              coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4468  *              coa_no_reply -> done [ label = "TIMER >= timeout" ];
4469  *      }
4470  *  \enddot
4471  */
4472 static void coa_no_reply(REQUEST *request, int action)
4473 {
4474         char buffer[128];
4475
4476         VERIFY_REQUEST(request);
4477
4478         TRACE_STATE_MACHINE;
4479         CHECK_FOR_STOP;
4480
4481         switch (action) {
4482         case FR_ACTION_TIMER:
4483                 (void) request_max_time(request);
4484                 break;
4485
4486         case FR_ACTION_PROXY_REPLY: /* too late! */
4487                 RDEBUG2("Reply from CoA server %s port %d  - ID: %d arrived too late.",
4488                         inet_ntop(request->proxy->src_ipaddr.af,
4489                                   &request->proxy->src_ipaddr.ipaddr,
4490                                   buffer, sizeof(buffer)),
4491                         request->proxy->dst_port, request->proxy->id);
4492                 break;
4493
4494         case FR_ACTION_RUN:
4495                 if (process_proxy_reply(request, NULL)) {
4496                         request->handle(request);
4497                 }
4498                 request_done(request, FR_ACTION_DONE);
4499                 break;
4500
4501         default:
4502                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4503                 break;
4504         }
4505 }
4506
4507
4508 /** Process the request after receiving a coa reply.
4509  *
4510  *  Throught the post-proxy section, and the through the handler
4511  *  function.
4512  *
4513  *  \dot
4514  *      digraph coa_running {
4515  *              coa_running;
4516  *
4517  *              coa_running -> timer [ label = "TIMER < max_request_time" ];
4518  *              coa_running -> process_proxy_reply [ label = "RUN" ];
4519  *              coa_running -> done [ label = "TIMER >= timeout" ];
4520  *      }
4521  *  \enddot
4522  */
4523 static void coa_running(REQUEST *request, int action)
4524 {
4525         VERIFY_REQUEST(request);
4526
4527         TRACE_STATE_MACHINE;
4528         CHECK_FOR_STOP;
4529
4530         switch (action) {
4531         case FR_ACTION_TIMER:
4532                 (void) request_max_time(request);
4533                 break;
4534
4535         case FR_ACTION_RUN:
4536                 if (process_proxy_reply(request, request->proxy_reply)) {
4537                         request->handle(request);
4538                 }
4539                 request_done(request, FR_ACTION_DONE);
4540                 break;
4541
4542         default:
4543                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4544                 break;
4545         }
4546 }
4547 #endif  /* WITH_COA */
4548
4549 /***********************************************************************
4550  *
4551  *  End of the State machine.  Start of additional helper code.
4552  *
4553  ***********************************************************************/
4554
4555 /***********************************************************************
4556  *
4557  *      Event handlers.
4558  *
4559  ***********************************************************************/
4560 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4561 {
4562         rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4563
4564         rad_assert(xel == el);
4565
4566         if ((listener->fd < 0)
4567 #ifdef WITH_DETAIL
4568 #ifndef WITH_DETAIL_THREAD
4569             && (listener->type != RAD_LISTEN_DETAIL)
4570 #endif
4571 #endif
4572                 ) {
4573                 char buffer[256];
4574
4575                 listener->print(listener, buffer, sizeof(buffer));
4576                 ERROR("FATAL: Asked to read from closed socket: %s",
4577                        buffer);
4578
4579                 rad_panic("Socket was closed on us!");
4580                 fr_exit_now(1);
4581         }
4582
4583         listener->recv(listener);
4584 }
4585
4586 #ifdef WITH_DETAIL
4587 #ifdef WITH_DETAIL_THREAD
4588 #else
4589 /*
4590  *      This function is called periodically to see if this detail
4591  *      file is available for reading.
4592  */
4593 static void event_poll_detail(void *ctx)
4594 {
4595         int delay;
4596         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4597         struct timeval when, now;
4598         listen_detail_t *detail = this->data;
4599
4600         rad_assert(this->type == RAD_LISTEN_DETAIL);
4601
4602  redo:
4603         event_socket_handler(el, this->fd, this);
4604
4605         fr_event_now(el, &now);
4606         when = now;
4607
4608         /*
4609          *      Backdoor API to get the delay until the next poll
4610          *      time.
4611          */
4612         delay = this->encode(this, NULL);
4613         if (delay == 0) goto redo;
4614
4615         tv_add(&when, delay);
4616
4617         ASSERT_MASTER;
4618         if (!fr_event_insert(el, event_poll_detail, this,
4619                              &when, &detail->ev)) {
4620                 ERROR("Failed creating handler");
4621                 fr_exit(1);
4622         }
4623 }
4624 #endif  /* WITH_DETAIL_THREAD */
4625 #endif  /* WITH_DETAIL */
4626
4627 static void event_status(struct timeval *wake)
4628 {
4629 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4630         int argval;
4631 #endif
4632
4633         if (rad_debug_lvl == 0) {
4634                 if (just_started) {
4635                         INFO("Ready to process requests");
4636                         just_started = false;
4637                 }
4638                 return;
4639         }
4640
4641         if (!wake) {
4642                 INFO("Ready to process requests");
4643
4644         } else if ((wake->tv_sec != 0) ||
4645                    (wake->tv_usec >= 100000)) {
4646                 DEBUG("Waking up in %d.%01u seconds.",
4647                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4648         }
4649
4650
4651         /*
4652          *      FIXME: Put this somewhere else, where it isn't called
4653          *      all of the time...
4654          */
4655
4656 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4657         /*
4658          *      If there are no child threads, then there may
4659          *      be child processes.  In that case, wait for
4660          *      their exit status, and throw that exit status
4661          *      away.  This helps get rid of zxombie children.
4662          */
4663         while (waitpid(-1, &argval, WNOHANG) > 0) {
4664                 /* do nothing */
4665         }
4666 #endif
4667
4668 }
4669
4670 #ifdef WITH_TCP
4671 static void listener_free_cb(void *ctx)
4672 {
4673         rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4674         char buffer[1024];
4675
4676         if (this->count > 0) {
4677                 struct timeval when;
4678                 listen_socket_t *sock = this->data;
4679
4680                 fr_event_now(el, &when);
4681                 when.tv_sec += 3;
4682
4683                 ASSERT_MASTER;
4684                 if (!fr_event_insert(el, listener_free_cb, this, &when,
4685                                      &(sock->ev))) {
4686                         rad_panic("Failed to insert event");
4687                 }
4688
4689                 return;
4690         }
4691
4692         /*
4693          *      It's all free, close the socket.
4694          */
4695
4696         this->print(this, buffer, sizeof(buffer));
4697         DEBUG("... cleaning up socket %s", buffer);
4698         rad_assert(this->next == NULL);
4699         talloc_free(this);
4700 }
4701
4702 #ifdef WITH_PROXY
4703 static int proxy_eol_cb(void *ctx, void *data)
4704 {
4705         struct timeval when;
4706         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4707
4708         if (request->proxy_listener != ctx) return 0;
4709
4710         /*
4711          *      We don't care if it's being processed in a child thread.
4712          */
4713
4714 #ifdef WITH_ACCOUNTING
4715         /*
4716          *      Accounting packets should be deleted immediately.
4717          *      They will never be retransmitted by the client.
4718          */
4719         if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4720                 RDEBUG("Stopping request due to failed connection to home server");
4721                 request->master_state = REQUEST_STOP_PROCESSING;
4722         }
4723 #endif
4724
4725         /*
4726          *      Reset the timer to be now, so that the request is
4727          *      quickly updated.  But spread the requests randomly
4728          *      over the next second, so that we don't overload the
4729          *      server.
4730          */
4731         fr_event_now(el, &when);
4732         tv_add(&when, fr_rand() % USEC);
4733         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4734
4735         /*
4736          *      Don't delete it from the list.
4737          */
4738         return 0;
4739 }
4740 #endif  /* WITH_PROXY */
4741 #endif  /* WITH_TCP */
4742
4743 static int event_new_fd(rad_listen_t *this)
4744 {
4745         char buffer[1024];
4746
4747         ASSERT_MASTER;
4748
4749         if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4750
4751         this->print(this, buffer, sizeof(buffer));
4752
4753         if (this->status == RAD_LISTEN_STATUS_INIT) {
4754                 listen_socket_t *sock = this->data;
4755
4756                 rad_assert(sock != NULL);
4757                 if (just_started) {
4758                         DEBUG("Listening on %s", buffer);
4759                 } else {
4760                         INFO(" ... adding new socket %s", buffer);
4761                 }
4762
4763 #ifdef WITH_PROXY
4764                 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4765                         home_server_t *home;
4766                         
4767                         home = sock->home;
4768                         if (!home || !home->limit.max_connections) {
4769                                 INFO(" ... adding new socket %s", buffer);
4770                         } else {
4771                                 INFO(" ... adding new socket %s (%u of %u)", buffer,
4772                                      home->limit.num_connections, home->limit.max_connections);
4773                         }
4774
4775 #endif
4776                 }
4777
4778                 switch (this->type) {
4779 #ifdef WITH_DETAIL
4780                 /*
4781                  *      Detail files are always known, and aren't
4782                  *      put into the socket event loop.
4783                  */
4784                 case RAD_LISTEN_DETAIL:
4785                         this->status = RAD_LISTEN_STATUS_KNOWN;
4786
4787 #ifndef WITH_DETAIL_THREAD
4788                         /*
4789                          *      Set up the first poll interval.
4790                          */
4791                         event_poll_detail(this);
4792                         return 1;
4793 #else
4794                         break;  /* add the FD to the list */
4795 #endif
4796 #endif  /* WITH_DETAIL */
4797
4798 #ifdef WITH_PROXY
4799                 /*
4800                  *      Add it to the list of sockets we can use.
4801                  *      Server sockets (i.e. auth/acct) are never
4802                  *      added to the packet list.
4803                  */
4804                 case RAD_LISTEN_PROXY:
4805 #ifdef WITH_TCP
4806                         rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4807
4808                         /*
4809                          *      Add timers to outgoing child sockets, if necessary.
4810                          */
4811                         if (sock->proto == IPPROTO_TCP && sock->opened &&
4812                             (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4813                                 struct timeval when;
4814
4815                                 when.tv_sec = sock->opened + 1;
4816                                 when.tv_usec = 0;
4817
4818                                 ASSERT_MASTER;
4819                                 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4820                                                      &(sock->ev))) {
4821                                         rad_panic("Failed to insert event");
4822                                 }
4823                         }
4824 #endif  /* WITH_TCP */
4825                         break;
4826 #endif  /* WITH_PROXY */
4827
4828                         /*
4829                          *      FIXME: put idle timers on command sockets.
4830                          */
4831
4832                 default:
4833 #ifdef WITH_TCP
4834                         /*
4835                          *      Add timers to incoming child sockets, if necessary.
4836                          */
4837                         if (sock->proto == IPPROTO_TCP && sock->opened &&
4838                             (sock->limit.lifetime || sock->limit.idle_timeout)) {
4839                                 struct timeval when;
4840
4841                                 when.tv_sec = sock->opened + 1;
4842                                 when.tv_usec = 0;
4843
4844                                 ASSERT_MASTER;
4845                                 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4846                                                      &(sock->ev))) {
4847                                         ERROR("Failed adding timer for socket: %s", fr_strerror());
4848                                         fr_exit(1);
4849                                 }
4850                         }
4851 #endif  /* WITH_TCP */
4852                         break;
4853                 } /* switch over listener types */
4854
4855                 /*
4856                  *      All sockets: add the FD to the event handler.
4857                  */
4858                 if (!fr_event_fd_insert(el, 0, this->fd,
4859                                         event_socket_handler, this)) {
4860                         ERROR("Failed adding event handler for socket: %s", fr_strerror());
4861                         fr_exit(1);
4862                 }
4863
4864                 this->status = RAD_LISTEN_STATUS_KNOWN;
4865                 return 1;
4866         } /* end of INIT */
4867
4868 #ifdef WITH_TCP
4869         /*
4870          *      The socket has reached a timeout.  Try to close it.
4871          */
4872         if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4873                 /*
4874                  *      Requests are still using the socket.  Wait for
4875                  *      them to finish.
4876                  */
4877                 if (this->count > 0) {
4878                         struct timeval when;
4879                         listen_socket_t *sock = this->data;
4880
4881                         /*
4882                          *      Try again to clean up the socket in 30
4883                          *      seconds.
4884                          */
4885                         gettimeofday(&when, NULL);
4886                         when.tv_sec += 30;
4887
4888                         ASSERT_MASTER;
4889                         if (!fr_event_insert(el,
4890                                              (fr_event_callback_t) event_new_fd,
4891                                              this, &when, &sock->ev)) {
4892                                 rad_panic("Failed to insert event");
4893                         }
4894
4895                         return 1;
4896                 }
4897
4898                 fr_event_fd_delete(el, 0, this->fd);
4899                 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4900         }
4901
4902         /*
4903          *      The socket has had a catastrophic error.  Close it.
4904          */
4905         if (this->status == RAD_LISTEN_STATUS_EOL) {
4906                 /*
4907                  *      Remove it from the list of live FD's.
4908                  */
4909                 fr_event_fd_delete(el, 0, this->fd);
4910
4911 #ifdef WITH_PROXY
4912                 /*
4913                  *      Tell all requests using this socket that the socket is dead.
4914                  */
4915                 if (this->type == RAD_LISTEN_PROXY) {
4916                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
4917                         if (!fr_packet_list_socket_freeze(proxy_list,
4918                                                           this->fd)) {
4919                                 ERROR("Fatal error freezing socket: %s", fr_strerror());
4920                                 fr_exit(1);
4921                         }
4922
4923                         if (this->count > 0) {
4924                                 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4925                         }
4926                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4927                 }
4928 #endif  /* WITH_PROXY */
4929
4930                 /*
4931                  *      Requests are still using the socket.  Wait for
4932                  *      them to finish.
4933                  */
4934                 if (this->count > 0) {
4935                         struct timeval when;
4936                         listen_socket_t *sock = this->data;
4937
4938                         /*
4939                          *      Try again to clean up the socket in 30
4940                          *      seconds.
4941                          */
4942                         gettimeofday(&when, NULL);
4943                         when.tv_sec += 30;
4944
4945                         ASSERT_MASTER;
4946                         if (!fr_event_insert(el,
4947                                              (fr_event_callback_t) event_new_fd,
4948                                              this, &when, &sock->ev)) {
4949                                 rad_panic("Failed to insert event");
4950                         }
4951
4952                         return 1;
4953                 }
4954
4955                 /*
4956                  *      No one is using the socket.  We can remove it now.
4957                  */
4958                 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4959         } /* socket is at EOL */
4960 #endif    /* WITH_TCP */
4961
4962         /*
4963          *      Nuke the socket.
4964          */
4965         if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4966                 int devnull;
4967 #ifdef WITH_TCP
4968                 listen_socket_t *sock = this->data;
4969                 struct timeval when;
4970 #endif
4971
4972                 /*
4973                  *      Re-open the socket, pointing it to /dev/null.
4974                  *      This means that all writes proceed without
4975                  *      blocking, and all reads return "no data".
4976                  *
4977                  *      This leaves the socket active, so any child
4978                  *      threads won't go insane.  But it means that
4979                  *      they cannot send or receive any packets.
4980                  *
4981                  *      This is EXTRA work in the normal case, when
4982                  *      sockets are closed without error.  But it lets
4983                  *      us have one simple processing method for all
4984                  *      sockets.
4985                  */
4986                 devnull = open("/dev/null", O_RDWR);
4987                 if (devnull < 0) {
4988                         ERROR("FATAL failure opening /dev/null: %s",
4989                                fr_syserror(errno));
4990                         fr_exit(1);
4991                 }
4992                 if (dup2(devnull, this->fd) < 0) {
4993                         ERROR("FATAL failure closing socket: %s",
4994                                fr_syserror(errno));
4995                         fr_exit(1);
4996                 }
4997                 close(devnull);
4998
4999 #ifdef WITH_DETAIL
5000                 rad_assert(this->type != RAD_LISTEN_DETAIL);
5001 #endif
5002
5003 #ifdef WITH_TCP
5004 #ifdef WITH_PROXY
5005                 /*
5006                  *      The socket is dead.  Force all proxied packets
5007                  *      to stop using it.  And then remove it from the
5008                  *      list of outgoing sockets.
5009                  */
5010                 if (this->type == RAD_LISTEN_PROXY) {
5011                         home_server_t *home;
5012
5013                         home = sock->home;
5014                         if (!home || !home->limit.max_connections) {
5015                                 INFO(" ... shutting down socket %s", buffer);
5016                         } else {
5017                                 INFO(" ... shutting down socket %s (%u of %u)", buffer,
5018                                      home->limit.num_connections, home->limit.max_connections);
5019                         }
5020
5021                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
5022                         fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
5023
5024                         if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
5025                                 ERROR("Fatal error removing socket %s: %s",
5026                                       buffer, fr_strerror());
5027                                 fr_exit(1);
5028                         }
5029                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
5030                 } else
5031 #endif  /* WITH_PROXY */
5032                 {
5033                         INFO(" ... shutting down socket %s", buffer);
5034
5035                         /*
5036                          *      EOL all requests using this socket.
5037                          */
5038                         rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
5039                 }
5040
5041                 /*
5042                  *      No child threads, clean it up now.
5043                  */
5044                 if (!spawn_flag) {
5045                         ASSERT_MASTER;
5046                         if (sock->ev) fr_event_delete(el, &sock->ev);
5047                         listen_free(&this);
5048                         return 1;
5049                 }
5050
5051                 /*
5052                  *      Wait until all requests using this socket are done.
5053                  */
5054                 gettimeofday(&when, NULL);
5055                 when.tv_sec += 3;
5056
5057                 ASSERT_MASTER;
5058                 if (!fr_event_insert(el, listener_free_cb, this, &when,
5059                                      &(sock->ev))) {
5060                         rad_panic("Failed to insert event");
5061                 }
5062 #endif  /* WITH_TCP */
5063         }
5064
5065         return 1;
5066 }
5067
5068 /***********************************************************************
5069  *
5070  *      Signal handlers.
5071  *
5072  ***********************************************************************/
5073
5074 static void handle_signal_self(int flag)
5075 {
5076         ASSERT_MASTER;
5077
5078         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5079                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5080                         INFO("Signalled to exit");
5081                         fr_event_loop_exit(el, 1);
5082                 } else {
5083                         INFO("Signalled to terminate");
5084                         fr_event_loop_exit(el, 2);
5085                 }
5086
5087                 return;
5088         } /* else exit/term flags weren't set */
5089
5090         /*
5091          *      Tell the even loop to stop processing.
5092          */
5093         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5094                 time_t when;
5095                 static time_t last_hup = 0;
5096
5097                 when = time(NULL);
5098                 if ((int) (when - last_hup) < 5) {
5099                         INFO("Ignoring HUP (less than 5s since last one)");
5100                         return;
5101                 }
5102
5103                 INFO("Received HUP signal");
5104
5105                 last_hup = when;
5106
5107                 exec_trigger(NULL, NULL, "server.signal.hup", true);
5108                 fr_event_loop_exit(el, 0x80);
5109         }
5110
5111 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5112         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5113                 rad_listen_t *this;
5114
5115                 /*
5116                  *      FIXME: O(N) loops suck.
5117                  */
5118                 for (this = main_config.listen;
5119                      this != NULL;
5120                      this = this->next) {
5121                         if (this->type != RAD_LISTEN_DETAIL) continue;
5122
5123                         /*
5124                          *      This one didn't send the signal, skip
5125                          *      it.
5126                          */
5127                         if (!this->decode(this, NULL)) continue;
5128
5129                         /*
5130                          *      Go service the interrupt.
5131                          */
5132                         event_poll_detail(this);
5133                 }
5134         }
5135 #endif
5136
5137 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5138         /*
5139          *      There are new listeners in the list.  Run
5140          *      event_new_fd() on them.
5141          */
5142         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5143                 rad_listen_t *this, *next;
5144
5145                 FD_MUTEX_LOCK(&fd_mutex);
5146
5147                 /*
5148                  *      FIXME: unlock the mutex before calling
5149                  *      event_new_fd()?
5150                  */
5151                 for (this = new_listeners; this != NULL; this = next) {
5152                         next = this->next;
5153                         this->next = NULL;
5154
5155                         event_new_fd(this);
5156                 }
5157
5158                 new_listeners = NULL;
5159                 FD_MUTEX_UNLOCK(&fd_mutex);
5160         }
5161 #endif
5162 }
5163
5164 #ifndef HAVE_PTHREAD_H
5165 void radius_signal_self(int flag)
5166 {
5167         return handle_signal_self(flag);
5168 }
5169
5170 #else
5171 static int self_pipe[2] = { -1, -1 };
5172
5173 /*
5174  *      Inform ourselves that we received a signal.
5175  */
5176 void radius_signal_self(int flag)
5177 {
5178         ssize_t rcode;
5179         uint8_t buffer[16];
5180
5181         /*
5182          *      The read MUST be non-blocking for this to work.
5183          */
5184         rcode = read(self_pipe[0], buffer, sizeof(buffer));
5185         if (rcode > 0) {
5186                 ssize_t i;
5187
5188                 for (i = 0; i < rcode; i++) {
5189                         buffer[0] |= buffer[i];
5190                 }
5191         } else {
5192                 buffer[0] = 0;
5193         }
5194
5195         buffer[0] |= flag;
5196
5197         if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5198 }
5199
5200
5201 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5202                                  UNUSED int fd, UNUSED void *ctx)
5203 {
5204         ssize_t i, rcode;
5205         uint8_t buffer[32];
5206
5207         rcode = read(self_pipe[0], buffer, sizeof(buffer));
5208         if (rcode <= 0) return;
5209
5210         /*
5211          *      Merge pending signals.
5212          */
5213         for (i = 0; i < rcode; i++) {
5214                 buffer[0] |= buffer[i];
5215         }
5216
5217         handle_signal_self(buffer[0]);
5218 }
5219 #endif  /* HAVE_PTHREAD_H */
5220
5221 /***********************************************************************
5222  *
5223  *      Bootstrapping code.
5224  *
5225  ***********************************************************************/
5226
5227 /*
5228  *      Externally-visibly functions.
5229  */
5230 int radius_event_init(TALLOC_CTX *ctx) {
5231         el = fr_event_list_create(ctx, event_status);
5232         if (!el) return 0;
5233
5234         return 1;
5235 }
5236
5237 static int packet_entry_cmp(void const *one, void const *two)
5238 {
5239         RADIUS_PACKET const * const *a = one;
5240         RADIUS_PACKET const * const *b = two;
5241
5242         return fr_packet_cmp(*a, *b);
5243 }
5244
5245 #ifdef WITH_PROXY
5246 /*
5247  *      They haven't defined a proxy listener.  Automatically
5248  *      add one for them, with the correct address family.
5249  */
5250 static void create_default_proxy_listener(int af)
5251 {
5252         uint16_t        port = 0;
5253         home_server_t   home;
5254         listen_socket_t *sock;
5255         rad_listen_t    *this;
5256
5257         memset(&home, 0, sizeof(home));
5258
5259         /*
5260          *      Open a default UDP port
5261          */
5262         home.proto = IPPROTO_UDP;
5263         port = 0;
5264
5265         /*
5266          *      Set the address family.
5267          */
5268         home.src_ipaddr.af = af;
5269         home.ipaddr.af = af;
5270
5271         /*
5272          *      Get the correct listener.
5273          */
5274         this = proxy_new_listener(proxy_ctx, &home, port);
5275         if (!this) {
5276                 fr_exit_now(1);
5277         }
5278
5279         sock = this->data;
5280         if (!fr_packet_list_socket_add(proxy_list, this->fd,
5281                                        sock->proto,
5282                                        &sock->other_ipaddr, sock->other_port,
5283                                        this)) {
5284                 ERROR("Failed adding proxy socket");
5285                 fr_exit_now(1);
5286         }
5287
5288         /*
5289          *      Insert the FD into list of FDs to listen on.
5290          */
5291         radius_update_listener(this);
5292 }
5293
5294 /*
5295  *      See if we automatically need to open a proxy socket.
5296  */
5297 static void check_proxy(rad_listen_t *head)
5298 {
5299         bool            defined_proxy;
5300         bool            has_v4, has_v6;
5301         rad_listen_t    *this;
5302
5303         if (check_config) return;
5304         if (!main_config.proxy_requests) return;
5305         if (!head) return;
5306         if (!home_servers_udp) return;
5307
5308         /*
5309          *      We passed "-i" on the command line.  Use that address
5310          *      family for the proxy socket.
5311          */
5312         if (main_config.myip.af != AF_UNSPEC) {
5313                 create_default_proxy_listener(main_config.myip.af);
5314                 return;
5315         }
5316
5317         defined_proxy = has_v4 = has_v6 = false;
5318
5319         /*
5320          *      Figure out if we need to open a proxy socket, and if
5321          *      so, which one.
5322          */
5323         for (this = head; this != NULL; this = this->next) {
5324                 listen_socket_t *sock;
5325
5326                 switch (this->type) {
5327                 case RAD_LISTEN_PROXY:
5328                         defined_proxy = true;
5329                         break;
5330
5331                 case RAD_LISTEN_AUTH:
5332 #ifdef WITH_ACCT
5333                 case RAD_LISTEN_ACCT:
5334 #endif
5335 #ifdef WITH_COA
5336                 case RAD_LISTEN_COA:
5337 #endif
5338                         sock = this->data;
5339                         if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5340                         if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5341                         break;
5342                         
5343                 default:
5344                         break;
5345                 }
5346         }
5347
5348         /*
5349          *      Assume they know what they're doing.
5350          */
5351         if (defined_proxy) return;
5352
5353         if (has_v4) create_default_proxy_listener(AF_INET);
5354
5355         if (has_v6) create_default_proxy_listener(AF_INET6);
5356 }
5357 #endif
5358
5359 int radius_event_start(CONF_SECTION *cs, bool have_children)
5360 {
5361         rad_listen_t *head = NULL;
5362
5363         if (fr_start_time != (time_t)-1) return 0;
5364
5365         time(&fr_start_time);
5366
5367         if (!check_config) {
5368                 /*
5369                  *  radius_event_init() must be called first
5370                  */
5371                 rad_assert(el);
5372
5373                 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5374                 if (!pl) return 0;      /* leak el */
5375         }
5376
5377         request_num_counter = 0;
5378
5379 #ifdef WITH_PROXY
5380         if (main_config.proxy_requests && !check_config) {
5381                 /*
5382                  *      Create the tree for managing proxied requests and
5383                  *      responses.
5384                  */
5385                 proxy_list = fr_packet_list_create(1);
5386                 if (!proxy_list) return 0;
5387
5388 #ifdef HAVE_PTHREAD_H
5389                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5390                         ERROR("FATAL: Failed to initialize proxy mutex: %s",
5391                                fr_syserror(errno));
5392                         fr_exit(1);
5393                 }
5394 #endif
5395
5396                 /*
5397                  *      The "init_delay" is set to "response_window".
5398                  *      Reset it to half of "response_window" in order
5399                  *      to give the event loop enough time to service
5400                  *      the event before hitting "response_window".
5401                  */
5402                 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5403                 main_config.init_delay.tv_usec >>= 1;
5404                 main_config.init_delay.tv_sec >>= 1;
5405
5406                 proxy_ctx = talloc_init("proxy");
5407         }
5408 #endif
5409
5410         /*
5411          *      Move all of the thread calls to this file?
5412          *
5413          *      It may be best for the mutexes to be in this file...
5414          */
5415         spawn_flag = have_children;
5416
5417 #ifdef HAVE_PTHREAD_H
5418         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5419
5420         /*
5421          *      Initialize the threads ONLY if we're spawning, AND
5422          *      we're running normally.
5423          */
5424         if (have_children && !check_config &&
5425             (thread_pool_init(cs, &spawn_flag) < 0)) {
5426                 fr_exit(1);
5427         }
5428 #endif
5429
5430         if (check_config) {
5431                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5432                        main_config.name);
5433                 if (listen_init(cs, &head, spawn_flag) < 0) {
5434                         fflush(NULL);
5435                         fr_exit(1);
5436                 }
5437                 return 1;
5438         }
5439
5440 #ifdef HAVE_PTHREAD_H
5441         /*
5442          *      Child threads need a pipe to signal us, as do the
5443          *      signal handlers.
5444          */
5445         if (pipe(self_pipe) < 0) {
5446                 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5447                 fr_exit(1);
5448         }
5449         if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5450             (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5451                 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5452                 fr_exit(1);
5453         }
5454         if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5455             (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5456                 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5457                 fr_exit(1);
5458         }
5459         DEBUG4("Created signal pipe.  Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5460
5461         if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5462                 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5463                 fr_exit(1);
5464         }
5465 #endif
5466
5467         DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5468
5469         /*
5470          *      The server temporarily switches to an unprivileged
5471          *      user very early in the bootstrapping process.
5472          *      However, some sockets MAY require privileged access
5473          *      (bind to device, or to port < 1024, or to raw
5474          *      sockets).  Those sockets need to call suid up/down
5475          *      themselves around the functions that need a privileged
5476          *      uid.
5477          */
5478         if (listen_init(cs, &head, spawn_flag) < 0) {
5479                 fr_exit_now(1);
5480         }
5481
5482         main_config.listen = head;
5483
5484 #ifdef WITH_PROXY
5485         check_proxy(head);
5486 #endif
5487
5488         /*
5489          *      At this point, no one has any business *ever* going
5490          *      back to root uid.
5491          */
5492         rad_suid_down_permanent();
5493
5494         return 1;
5495 }
5496
5497
5498 #ifdef WITH_PROXY
5499 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5500 {
5501         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5502
5503         VERIFY_REQUEST(request);
5504
5505         request->master_state = REQUEST_STOP_PROCESSING;
5506
5507 #ifdef HAVE_PTHREAD_H
5508         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5509 #endif
5510
5511         /*
5512          *      If it's queued we can't delete it from the queue.
5513          *
5514          *      Otherwise, it's OK to delete it.  Even RUNNING, because
5515          *      that will get caught by the check above.
5516          */
5517         if (request->child_state == REQUEST_QUEUED) return 0;
5518
5519         request->in_proxy_hash = false;
5520
5521         if (!request->in_request_hash) {
5522                 request_done(request, FR_ACTION_DONE);
5523         }
5524
5525         /*
5526          *      Delete it from the list.
5527          */
5528         return 2;
5529 }
5530 #endif
5531
5532
5533 static int request_delete_cb(UNUSED void *ctx, void *data)
5534 {
5535         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5536
5537         VERIFY_REQUEST(request);
5538
5539         request->master_state = REQUEST_STOP_PROCESSING;
5540
5541         /*
5542          *      Not done, or the child thread is still processing it.
5543          */
5544         if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5545
5546 #ifdef HAVE_PTHREAD_H
5547         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5548 #endif
5549
5550 #ifdef WITH_PROXY
5551         rad_assert(request->in_proxy_hash == false);
5552 #endif
5553
5554         request->in_request_hash = false;
5555         ASSERT_MASTER;
5556         if (request->ev) fr_event_delete(el, &request->ev);
5557
5558         if (main_config.memory_report) {
5559                 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5560                         request->packet->id,
5561                         (unsigned int) (request->timestamp - fr_start_time));
5562         }
5563
5564 #ifdef WITH_COA
5565         if (request->coa) {
5566                 rad_assert(!request->coa->in_proxy_hash);
5567         }
5568 #endif
5569
5570         request_free(request);
5571
5572         /*
5573          *      Delete it from the list, and continue;
5574          */
5575         return 2;
5576 }
5577
5578
5579 void radius_event_free(void)
5580 {
5581         ASSERT_MASTER;
5582
5583 #ifdef WITH_PROXY
5584         /*
5585          *      There are requests in the proxy hash that aren't
5586          *      referenced from anywhere else.  Remove them first.
5587          */
5588         if (proxy_list) {
5589                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5590         }
5591 #endif
5592
5593         rbtree_walk(pl, RBTREE_DELETE_ORDER,  request_delete_cb, NULL);
5594
5595         if (spawn_flag) {
5596                 /*
5597                  *      Now that all requests have been marked "please stop",
5598                  *      ensure that all of the threads have exited.
5599                  */
5600 #ifdef HAVE_PTHREAD_H
5601                 thread_pool_stop();
5602 #endif
5603
5604                 /*
5605                  *      Walk the lists again, ensuring that all
5606                  *      requests are done.
5607                  */
5608                 if (main_config.memory_report) {
5609                         int num;
5610
5611 #ifdef WITH_PROXY
5612                         if (proxy_list) {
5613                                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5614                                 num = fr_packet_list_num_elements(proxy_list);
5615                                 if (num > 0) {
5616                                         ERROR("Proxy list has %d requests still in it.", num);
5617                                 }
5618                         }
5619 #endif
5620
5621                         rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5622                         num = rbtree_num_elements(pl);
5623                         if (num > 0) {
5624                                 ERROR("Request list has %d requests still in it.", num);
5625                         }
5626                 }
5627         }
5628
5629         rbtree_free(pl);
5630         pl = NULL;
5631
5632 #ifdef WITH_PROXY
5633         fr_packet_list_free(proxy_list);
5634         proxy_list = NULL;
5635
5636         if (proxy_ctx) talloc_free(proxy_ctx);
5637 #endif
5638
5639         TALLOC_FREE(el);
5640
5641         if (debug_condition) talloc_free(debug_condition);
5642 }
5643
5644 int radius_event_process(void)
5645 {
5646         if (!el) return 0;
5647
5648         return fr_event_loop(el);
5649 }