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