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