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