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.
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.
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
21 * @brief Defines the state machines that control how requests are processed.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
34 #include <freeradius-devel/rad_assert.h>
37 #include <freeradius-devel/detail.h>
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
47 extern pid_t radius_pid;
48 extern fr_cond_t *debug_condition;
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;
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. */
61 static char const *action_codes[] = {
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]); \
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
102 # define TRACE_STATE_MACHINE {}
105 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
107 ERROR("%s[%u]: %s", file, line, msg);
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
113 /** Declare a state in the state machine
115 * Expands to the start of a function definition for a given state.
117 * @param _x the name of the state.
119 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
121 static void request_timer(void *ctx);
123 /** Insert #REQUEST back into the event heap, to continue executing at a future time
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.
131 static inline void state_machine_timer(char const *file, int line, REQUEST *request,
132 struct timeval *when, fr_state_action_t action)
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");
140 /** @copybrief state_machine_timer
142 * @param _x the action to perform when we resume processing the request.
144 #define STATE_MACHINE_TIMER(_x) state_machine_timer(__FILE__, __LINE__, request, &when, _x)
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
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)
158 * @section request_timeline
160 * Time sequence of a request
163 * RQ-----------------P=============================Y-J-C
164 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
167 * - R: received. Duplicate detection is done, and request is
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
174 * - P: Processing the request through the modules.
176 * - Y: Reply is ready. Rejects MAY be delayed here. All other
177 * replies are sent immediately.
179 * - J: Reject is sent "response_delay" after the reply is ready.
181 * - C: For Access-Requests, After "cleanup_delay", the request is
182 * deleted. Accounting-Request packets go directly from Y to C.
184 * - M: Max request time. If the request hits this timer, it is
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
195 * Conflicting packets are sent in 2 situations.
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.
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.
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.
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
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.
234 static fr_packet_list_t *proxy_list = NULL;
235 static TALLOC_CTX *proxy_ctx = NULL;
238 #ifdef HAVE_PTHREAD_H
240 static pthread_mutex_t proxy_mutex;
241 static bool proxy_no_new_sockets = false;
244 # define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
245 # define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
247 static pthread_t NO_SUCH_CHILD_PID;
248 # define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
252 * This is easier than ifdef's throughout the code.
254 # define PTHREAD_MUTEX_LOCK(_x)
255 # define PTHREAD_MUTEX_UNLOCK(_x)
256 # define NO_CHILD_THREAD
259 #ifdef HAVE_PTHREAD_H
260 static bool we_are_master(void)
263 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
271 * Assertions are debug checks.
274 # define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
279 * No threads: we're always master.
281 # define we_are_master(_x) (1)
282 #endif /* HAVE_PTHREAD_H */
284 #ifndef ASSERT_MASTER
285 # define ASSERT_MASTER
289 * Make state transitions simpler.
291 #define FINAL_STATE(_x) NO_CHILD_THREAD; request->component = "<" #_x ">"; request->module = ""; request->child_state = _x
294 static int event_new_fd(rad_listen_t *this);
297 * We need mutexes around the event FD list *only* in certain
300 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
301 static rad_listen_t *new_listeners = NULL;
303 static pthread_mutex_t fd_mutex;
304 # define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
305 # define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
307 void radius_update_listener(rad_listen_t *this)
310 * Just do it ourselves.
312 if (we_are_master()) {
317 FD_MUTEX_LOCK(&fd_mutex);
320 * If it's already in the list, don't add it again.
323 FD_MUTEX_UNLOCK(&fd_mutex);
328 * Otherwise, add it to the list
330 this->next = new_listeners;
331 new_listeners = this;
332 FD_MUTEX_UNLOCK(&fd_mutex);
333 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
336 void radius_update_listener(rad_listen_t *this)
339 * No threads. Just insert it.
344 * This is easier than ifdef's throughout the code.
346 # define FD_MUTEX_LOCK(_x)
347 # define FD_MUTEX_UNLOCK(_x)
350 static int request_num_counter = 1;
352 static int request_will_proxy(REQUEST *request) CC_HINT(nonnull);
353 static int request_proxy(REQUEST *request) CC_HINT(nonnull);
354 STATE_MACHINE_DECL(request_ping) CC_HINT(nonnull);
356 STATE_MACHINE_DECL(request_response_delay) CC_HINT(nonnull);
357 STATE_MACHINE_DECL(request_cleanup_delay) CC_HINT(nonnull);
358 STATE_MACHINE_DECL(request_running) CC_HINT(nonnull);
359 STATE_MACHINE_DECL(request_done) CC_HINT(nonnull);
361 STATE_MACHINE_DECL(proxy_no_reply) CC_HINT(nonnull);
362 STATE_MACHINE_DECL(proxy_running) CC_HINT(nonnull);
363 STATE_MACHINE_DECL(proxy_wait_for_reply) CC_HINT(nonnull);
365 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply) CC_HINT(nonnull (1));
366 static void remove_from_proxy_hash(REQUEST *request) CC_HINT(nonnull);
367 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank) CC_HINT(nonnull);
368 static int insert_into_proxy_hash(REQUEST *request) CC_HINT(nonnull);
371 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
372 RADCLIENT *client, RAD_REQUEST_FUNP fun);
373 static int request_pre_handler(REQUEST *request, UNUSED int action) CC_HINT(nonnull);
376 static void request_coa_originate(REQUEST *request) CC_HINT(nonnull);
377 STATE_MACHINE_DECL(coa_wait_for_reply) CC_HINT(nonnull);
378 STATE_MACHINE_DECL(coa_no_reply) CC_HINT(nonnull);
379 STATE_MACHINE_DECL(coa_running) CC_HINT(nonnull);
380 static void coa_separate(REQUEST *request) CC_HINT(nonnull);
381 # define COA_SEPARATE if (request->coa) coa_separate(request->coa);
383 # define COA_SEPARATE
386 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
389 #define USEC (1000000)
391 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
393 static void tv_add(struct timeval *tv, int usec_delay)
395 if (usec_delay >= USEC) {
396 tv->tv_sec += usec_delay / USEC;
399 tv->tv_usec += usec_delay;
401 if (tv->tv_usec >= USEC) {
402 tv->tv_sec += tv->tv_usec / USEC;
408 * Debug the packet if requested.
410 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
412 char src_ipaddr[128];
413 char dst_ipaddr[128];
416 if (!RDEBUG_ENABLED) return;
420 * Don't print IP addresses for detail files.
422 if (request->listener &&
423 (request->listener->type == RAD_LISTEN_DETAIL)) return;
427 * Client-specific debugging re-prints the input
428 * packet into the client log.
430 * This really belongs in a utility library
432 if (is_radius_code(packet->code)) {
433 RDEBUG("%s %s Id %i from %s%s%s:%i to %s%s%s:%i length %zu",
434 received ? "Received" : "Sent",
435 fr_packet_codes[packet->code],
437 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
438 inet_ntop(packet->src_ipaddr.af,
439 &packet->src_ipaddr.ipaddr,
440 src_ipaddr, sizeof(src_ipaddr)),
441 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
443 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
444 inet_ntop(packet->dst_ipaddr.af,
445 &packet->dst_ipaddr.ipaddr,
446 dst_ipaddr, sizeof(dst_ipaddr)),
447 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
451 RDEBUG("%s code %u Id %i from %s%s%s:%i to %s%s%s:%i length %zu\n",
452 received ? "Received" : "Sent",
455 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
456 inet_ntop(packet->src_ipaddr.af,
457 &packet->src_ipaddr.ipaddr,
458 src_ipaddr, sizeof(src_ipaddr)),
459 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
461 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
462 inet_ntop(packet->dst_ipaddr.af,
463 &packet->dst_ipaddr.ipaddr,
464 dst_ipaddr, sizeof(dst_ipaddr)),
465 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
471 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
473 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
478 /***********************************************************************
480 * Start of RADIUS server state machine.
482 ***********************************************************************/
484 static struct timeval *request_response_window(REQUEST *request)
486 VERIFY_REQUEST(request);
488 rad_assert(request->home_server != NULL);
490 if (request->client) {
492 * The client hasn't set the response window. Return
493 * either the home server one, if set, or the global one.
495 if (!timerisset(&request->client->response_window)) {
496 return &request->home_server->response_window;
499 if (timercmp(&request->client->response_window,
500 &request->home_server->response_window, <)) {
501 return &request->client->response_window;
505 return &request->home_server->response_window;
509 * Determine initial request processing delay.
511 static int request_init_delay(REQUEST *request)
513 struct timeval half_response_window;
515 VERIFY_REQUEST(request);
517 /* Allow client response window to lower initial delay */
518 if (timerisset(&request->client->response_window)) {
519 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
520 half_response_window.tv_usec =
521 ((request->client->response_window.tv_sec & 1) * USEC +
522 request->client->response_window.tv_usec) >> 1;
523 if (timercmp(&half_response_window, &request->root->init_delay, <))
524 return (int)half_response_window.tv_sec * USEC +
525 (int)half_response_window.tv_usec;
528 return (int)request->root->init_delay.tv_sec * USEC +
529 (int)request->root->init_delay.tv_usec;
533 * Callback for ALL timer events related to the request.
535 static void request_timer(void *ctx)
537 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
540 action = request->timer_action;
544 request->process(request, action);
548 * Wrapper for talloc pools. If there's no parent, just free the
549 * request. If there is a parent, free the parent INSTEAD of the
552 static void request_free(REQUEST *request)
556 rad_assert(request->ev == NULL);
557 rad_assert(!request->in_request_hash);
558 rad_assert(!request->in_proxy_hash);
560 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
561 talloc_free(request);
565 ptr = talloc_parent(request);
566 rad_assert(ptr != NULL);
572 static void proxy_reply_too_late(REQUEST *request)
576 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
577 inet_ntop(request->proxy->dst_ipaddr.af,
578 &request->proxy->dst_ipaddr.ipaddr,
579 buffer, sizeof(buffer)),
580 request->proxy->dst_port, request->proxy->id);
585 /** Mark a request DONE and clean it up.
587 * When a request is DONE, it can have ties to a number of other
588 * portions of the server. The request hash, proxy hash, events,
589 * child threads, etc. This function takes care of either cleaning
590 * up the request, or managing the timers to wait for the ties to be
595 * done -> done [ label = "still running" ];
599 static void request_done(REQUEST *request, int action)
601 struct timeval now, when;
603 VERIFY_REQUEST(request);
608 * Force this no matter what.
610 request->process = request_done;
614 * Tell the detail listener that we're done.
616 if (request->listener &&
617 (request->listener->type == RAD_LISTEN_DETAIL) &&
618 (request->simul_max != 1)) {
619 request->simul_max = 1;
620 request->listener->send(request->listener,
625 #ifdef HAVE_PTHREAD_H
627 * If called from a child thread, mark ourselves as done,
628 * and wait for the master thread timer to clean us up.
630 if (!we_are_master()) {
631 FINAL_STATE(REQUEST_DONE);
637 * Mark the request as STOP.
639 request->master_state = REQUEST_STOP_PROCESSING;
643 * Move the CoA request to its own handler.
646 coa_separate(request->coa);
647 } else if (request->parent && (request->parent->coa == request)) {
648 coa_separate(request);
653 * It doesn't hurt to send duplicate replies. All other
654 * signals are ignored, as the request will be cleaned up
660 rad_assert(request->listener != NULL);
662 if (request->reply->code != 0) {
663 request->listener->send(request->listener, request);
666 RDEBUG("No reply. Ignoring retransmit");
671 * Mark the request as done.
674 #ifdef HAVE_PTHREAD_H
676 * If the child is still running, leave it alone.
678 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
683 #ifdef DEBUG_STATE_MACHINE
684 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
685 request->number, __FUNCTION__,
686 child_state_names[request->child_state],
687 child_state_names[REQUEST_DONE]);
689 request->child_state = REQUEST_DONE;
693 * Called when the child is taking too long to
694 * finish. We've already marked it "please
695 * stop", so we don't complain any more.
697 case FR_ACTION_TIMER:
701 case FR_ACTION_PROXY_REPLY:
702 proxy_reply_too_late(request);
711 * Remove it from the request hash.
713 if (request->in_request_hash) {
714 if (!rbtree_deletebydata(pl, &request->packet)) {
717 request->in_request_hash = false;
722 * Wait for the proxy ID to expire. This allows us to
723 * avoid re-use of proxy IDs for a while.
725 if (request->in_proxy_hash) {
726 rad_assert(request->proxy != NULL);
728 fr_event_now(el, &now);
729 when = request->proxy->timestamp;
732 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
733 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
734 (request->packet->code != request->proxy->code)) {
735 when.tv_sec += request->home_server->coa_mrd;
738 timeradd(&when, request_response_window(request), &when);
741 * We haven't received all responses, AND there's still
742 * time to wait. Do so.
744 if ((request->num_proxied_requests > request->num_proxied_responses) &&
746 (request->home_server->proto != IPPROTO_TCP) &&
748 timercmp(&now, &when, <)) {
749 RDEBUG("Waiting for more responses from the home server");
756 remove_from_proxy_hash(request);
760 #ifdef HAVE_PTHREAD_H
762 * If there's no children, we can mark the request as done.
764 if (!spawn_flag) request->child_state = REQUEST_DONE;
768 * If the child is still running, wait for it to be finished.
770 if (request->child_state <= REQUEST_RUNNING) {
771 gettimeofday(&now, NULL);
776 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
777 tv_add(&when, request->delay);
778 request->delay += request->delay >> 1;
779 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
781 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
785 #ifdef HAVE_PTHREAD_H
786 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
790 * @todo: do final states for TCP sockets, too?
792 request_stats_final(request);
794 if (request->listener) {
795 request->listener->count--;
798 * If we're the last one, remove the listener now.
800 if ((request->listener->count == 0) &&
801 (request->listener->status >= RAD_LISTEN_STATUS_FROZEN)) {
802 event_new_fd(request->listener);
807 if (request->packet) {
808 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
810 (unsigned int) (request->timestamp - fr_start_time));
811 } /* else don't print anything */
814 fr_event_delete(el, &request->ev);
815 request_free(request);
819 static void request_cleanup_delay_init(REQUEST *request)
821 struct timeval now, when;
823 VERIFY_REQUEST(request);
826 * Do cleanup delay ONLY for RADIUS packets from a real
827 * client. Everything else just gets cleaned up
830 if (request->packet->dst_port == 0) goto done;
833 * Accounting packets shouldn't be retransmitted. They
834 * should always be updated with Acct-Delay-Time.
836 #ifdef WITH_ACCOUNTING
837 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
841 if (request->listener->type == RAD_LISTEN_DHCP) goto done;
845 if (request->listener->type == RAD_LISTEN_VQP) goto done;
848 if (!request->root->cleanup_delay) goto done;
850 gettimeofday(&now, NULL);
852 rad_assert(request->reply->timestamp.tv_sec != 0);
853 when = request->reply->timestamp;
855 request->delay = request->root->cleanup_delay;
856 when.tv_sec += request->delay;
859 * Set timer for when we need to clean it up.
861 if (timercmp(&when, &now, >)) {
862 #ifdef DEBUG_STATE_MACHINE
863 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
865 request->process = request_cleanup_delay;
867 if (!we_are_master()) {
868 FINAL_STATE(REQUEST_CLEANUP_DELAY);
873 * Update this if we can, otherwise let the timers pick it up.
875 request->child_state = REQUEST_CLEANUP_DELAY;
876 #ifdef HAVE_PTHREAD_H
877 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
879 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
884 * Otherwise just clean it up.
887 request_done(request, FR_ACTION_DONE);
892 * Enforce max_request_time.
894 static bool request_max_time(REQUEST *request)
896 struct timeval now, when;
897 rad_assert(request->magic == REQUEST_MAGIC);
898 #ifdef DEBUG_STATE_MACHINE
899 int action = FR_ACTION_TIMER;
902 VERIFY_REQUEST(request);
908 * The child thread has acknowledged it's done.
909 * Transition to the DONE state.
911 * If the request was marked STOP, then the "check for
912 * stop" macro already took care of it.
914 if (request->child_state == REQUEST_DONE) {
916 request_done(request, FR_ACTION_DONE);
921 * The request is still running. Enforce max_request_time.
923 fr_event_now(el, &now);
924 when = request->packet->timestamp;
925 when.tv_sec += request->root->max_request_time;
928 * Taking too long: tell it to die.
930 if (timercmp(&now, &when, >=)) {
931 #ifdef HAVE_PTHREAD_H
933 * If there's a child thread processing it,
937 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
938 ERROR("Unresponsive child for request %u, in component %s module %s",
940 request->component ? request->component : "<core>",
941 request->module ? request->module : "<core>");
942 exec_trigger(request, NULL, "server.thread.unresponsive", true);
946 * Tell the request that it's done.
952 * Sleep for some more. We HOPE that the child will
953 * become responsive at some point in the future. We do
954 * this by adding 50% to the current timer.
957 tv_add(&when, request->delay);
958 request->delay += request->delay >> 1;
959 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
963 static void request_queue_or_run(REQUEST *request,
964 fr_request_process_t process)
966 #ifdef DEBUG_STATE_MACHINE
967 int action = FR_ACTION_TIMER;
970 VERIFY_REQUEST(request);
975 * Do this here so that fewer other functions need to do
978 if (request->master_state == REQUEST_STOP_PROCESSING) {
979 #ifdef DEBUG_STATE_MACHINE
980 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
981 request->number, __FUNCTION__,
982 master_state_names[request->master_state],
983 child_state_names[request->child_state],
984 child_state_names[REQUEST_DONE]);
986 request_done(request, FR_ACTION_DONE);
990 request->process = process;
992 if (we_are_master()) {
996 * (re) set the initial delay.
998 request->delay = request_init_delay(request);
999 if (request->delay > USEC) request->delay = USEC;
1000 gettimeofday(&when, NULL);
1001 tv_add(&when, request->delay);
1002 request->delay += request->delay >> 1;
1004 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1006 #ifdef HAVE_PTHREAD_H
1009 * A child thread will eventually pick it up.
1011 if (request_enqueue(request)) return;
1014 * Otherwise we're not going to do anything with
1017 request_done(request, FR_ACTION_DONE);
1023 request->child_state = REQUEST_RUNNING;
1024 request->process(request, FR_ACTION_RUN);
1028 * Requests that care about child process exit
1029 * codes have already either called
1030 * rad_waitpid(), or they've given up.
1032 while (waitpid(-1, NULL, WNOHANG) > 0);
1037 static void request_dup(REQUEST *request)
1039 ERROR("(%u) Ignoring duplicate packet from "
1040 "client %s port %d - ID: %u due to unfinished request "
1041 "in component %s module %s",
1042 request->number, request->client->shortname,
1043 request->packet->src_port,request->packet->id,
1044 request->component, request->module);
1048 /** Sit on a request until it's time to clean it up.
1050 * A NAS may not see a response from the server. When the NAS
1051 * retransmits, we want to be able to send a cached reply back. The
1052 * alternative is to re-process the packet, which does bad things for
1053 * EAP, among others.
1055 * IF we do see a NAS retransmit, we extend the cleanup delay,
1056 * because the NAS might miss our cached reply.
1058 * Otherwise, once we reach cleanup_delay, we transition to DONE.
1061 * digraph cleanup_delay {
1063 * send_reply [ label = "send_reply\nincrease cleanup delay" ];
1065 * cleanup_delay -> send_reply [ label = "DUP" ];
1066 * send_reply -> cleanup_delay;
1067 * cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1068 * cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
1069 * cleanup_delay -> done [ label = "TIMER >= timeout" ];
1073 static void request_cleanup_delay(REQUEST *request, int action)
1075 struct timeval when, now;
1077 VERIFY_REQUEST(request);
1079 TRACE_STATE_MACHINE;
1086 if (request->reply->code != 0) {
1087 request->listener->send(request->listener, request);
1089 RDEBUG("No reply. Ignoring retransmit");
1093 * Double the cleanup_delay to catch retransmits.
1095 when = request->reply->timestamp;
1096 request->delay += request->delay;
1097 when.tv_sec += request->delay;
1099 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1103 case FR_ACTION_PROXY_REPLY:
1104 proxy_reply_too_late(request);
1108 case FR_ACTION_TIMER:
1109 fr_event_now(el, &now);
1111 rad_assert(request->root->cleanup_delay > 0);
1113 when = request->reply->timestamp;
1114 when.tv_sec += request->root->cleanup_delay;
1116 if (timercmp(&when, &now, >)) {
1117 #ifdef DEBUG_STATE_MACHINE
1118 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1120 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1122 } /* else it's time to clean up */
1124 request_done(request, FR_ACTION_DONE);
1128 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1134 /** Sit on a request until it's time to respond to it.
1136 * For security reasons, rejects (and maybe some other) packets are
1137 * delayed for a while before we respond. This delay means that
1138 * badly behaved NASes don't hammer the server with authentication
1141 * Otherwise, once we reach response_delay, we send the reply, and
1142 * transition to cleanup_delay.
1145 * digraph response_delay {
1146 * response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1147 * response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1148 * response_delay -> send_reply [ label = "TIMER >= timeout" ];
1149 * send_reply -> cleanup_delay;
1153 static void request_response_delay(REQUEST *request, int action)
1155 struct timeval when, now;
1157 VERIFY_REQUEST(request);
1159 TRACE_STATE_MACHINE;
1166 RDEBUG("(%u) Discarding duplicate request from "
1167 "client %s port %d - ID: %u due to delayed response",
1168 request->number, request->client->shortname,
1169 request->packet->src_port,request->packet->id);
1173 case FR_ACTION_PROXY_REPLY:
1174 proxy_reply_too_late(request);
1178 case FR_ACTION_TIMER:
1179 fr_event_now(el, &now);
1182 * See if it's time to send the reply. If not,
1183 * we wait some more.
1185 when = request->reply->timestamp;
1187 tv_add(&when, request->response_delay.tv_sec * USEC);
1188 tv_add(&when, request->response_delay.tv_usec);
1190 if (timercmp(&when, &now, >)) {
1191 #ifdef DEBUG_STATE_MACHINE
1192 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1194 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1196 } /* else it's time to send the reject */
1198 RDEBUG2("Sending delayed response");
1199 debug_packet(request, request->reply, false);
1200 request->listener->send(request->listener, request);
1203 * Clean up the request.
1205 request_cleanup_delay_init(request);
1209 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1215 static int request_pre_handler(REQUEST *request, UNUSED int action)
1219 VERIFY_REQUEST(request);
1221 TRACE_STATE_MACHINE;
1223 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1226 * Don't decode the packet if it's an internal "fake"
1227 * request. Instead, just return so that the caller can
1230 if (request->packet->dst_port == 0) {
1231 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1232 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1236 if (!request->packet->vps) { /* FIXME: check for correct state */
1237 rcode = request->listener->decode(request->listener, request);
1240 if (debug_condition) {
1242 * Ignore parse errors.
1244 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1245 request->log.lvl = L_DBG_LVL_2;
1246 request->log.func = vradlog_request;
1251 debug_packet(request, request->packet, true);
1257 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1258 request->reply->offset = -2; /* bad authenticator */
1262 if (!request->username) {
1263 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1270 /** Do the final processing of a request before we reply to the NAS.
1272 * Various cleanups, suppress responses, copy Proxy-State, and set
1273 * response_delay or cleanup_delay;
1275 static void request_finish(REQUEST *request, int action)
1279 VERIFY_REQUEST(request);
1281 TRACE_STATE_MACHINE;
1284 (void) action; /* -Wunused */
1288 * Don't do post-auth if we're a CoA request originated
1289 * from an Access-Request. See request_alloc_coa() for
1292 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1296 * Override the response code if a control:Response-Packet-Type attribute is present.
1298 vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1300 if (vp->vp_integer == 256) {
1301 RDEBUG2("Not responding to request");
1302 request->reply->code = 0;
1304 request->reply->code = vp->vp_integer;
1308 * Catch Auth-Type := Reject BEFORE proxying the packet.
1310 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1311 if (request->reply->code == 0) {
1312 vp = fr_pair_find_by_num(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1313 if (!vp || (vp->vp_integer != 5)) {
1314 RDEBUG2("There was no response configured: "
1315 "rejecting request");
1318 request->reply->code = PW_CODE_ACCESS_REJECT;
1323 * Copy Proxy-State from the request to the reply.
1325 vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps,
1326 PW_PROXY_STATE, 0, TAG_ANY);
1327 if (vp) fr_pair_add(&request->reply->vps, vp);
1330 * Call Post-Auth for Access-Request packets.
1332 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1333 rad_postauth(request);
1338 * Maybe originate a CoA request.
1340 if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1341 request_coa_originate(request);
1346 * Clean up. These are no longer needed.
1348 gettimeofday(&request->reply->timestamp, NULL);
1351 * Fake packets get marked as "done", and have the
1352 * proxy-reply section deal with the reply attributes.
1353 * We therefore don't free the reply attributes.
1355 if (request->packet->dst_port == 0) {
1356 RDEBUG("Finished internally proxied request.");
1357 FINAL_STATE(REQUEST_DONE);
1363 * Always send the reply to the detail listener.
1365 if (request->listener->type == RAD_LISTEN_DETAIL) {
1366 request->simul_max = 1;
1369 * But only print the reply if there is one.
1371 if (request->reply->code != 0) {
1372 debug_packet(request, request->reply, false);
1375 request->listener->send(request->listener, request);
1381 * Ignore all "do not respond" packets.
1382 * Except for the detail ones, which need to ping
1383 * the detail file reader so that it will retransmit.
1385 if (!request->reply->code) {
1386 RDEBUG("Not sending reply to client.");
1391 * If it's not in the request hash, we MIGHT not want to
1394 * If duplicate packets are allowed, then then only
1395 * reason to NOT be in the request hash is because we
1396 * don't want to send a reply.
1398 * FIXME: this is crap. The rest of the state handling
1399 * should use a different field so that we don't have two
1402 * Otherwise duplicates are forbidden, and the request is
1403 * SUPPOSED to avoid the request hash.
1405 * In that case, we need to send a reply.
1407 if (!request->in_request_hash &&
1408 !request->listener->nodup) {
1409 RDEBUG("Suppressing reply to client.");
1414 * See if we need to delay an Access-Reject packet.
1416 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1417 (request->root->reject_delay.tv_sec > 0)) {
1418 request->response_delay = request->root->reject_delay;
1420 vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY, 0, TAG_ANY);
1422 if (vp->vp_integer <= 10) {
1423 request->response_delay.tv_sec = vp->vp_integer;
1425 request->response_delay.tv_sec = 10;
1427 request->response_delay.tv_usec = 0;
1429 vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY_USEC, 0, TAG_ANY);
1431 if (vp->vp_integer <= 10 * USEC) {
1432 request->response_delay.tv_sec = vp->vp_integer / USEC;
1433 request->response_delay.tv_usec = vp->vp_integer % USEC;
1435 request->response_delay.tv_sec = 10;
1436 request->response_delay.tv_usec = 0;
1443 * If we timed out a proxy packet, don't delay
1444 * the reject any more.
1446 if (request->proxy && !request->proxy_reply) {
1447 request->response_delay.tv_sec = 0;
1448 request->response_delay.tv_usec = 0;
1456 if ((request->response_delay.tv_sec == 0) &&
1457 (request->response_delay.tv_usec == 0)) {
1460 * Don't print a reply if there's none to send.
1462 if (request->reply->code != 0) {
1463 if (rad_debug_lvl && request->state &&
1464 (request->reply->code == PW_CODE_ACCESS_ACCEPT)) {
1465 if (!fr_pair_find_by_num(request->packet->vps, PW_STATE, 0, TAG_ANY)) {
1466 RWDEBUG2("Unused attributes found in &session-state:");
1470 debug_packet(request, request->reply, false);
1471 request->listener->send(request->listener, request);
1475 RDEBUG2("Finished request");
1476 request_cleanup_delay_init(request);
1480 * Encode and sign it here, so that the master
1481 * thread can just send the encoded data, which
1482 * means it does less work.
1484 RDEBUG2("Delaying response for %d.%06d seconds",
1485 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1486 request->listener->encode(request->listener, request);
1487 request->process = request_response_delay;
1489 FINAL_STATE(REQUEST_RESPONSE_DELAY);
1493 /** Process a request from a client.
1495 * The outcome might be that the request is proxied.
1499 * running -> running [ label = "TIMER < max_request_time" ];
1500 * running -> done [ label = "TIMER >= max_request_time" ];
1501 * running -> proxy [ label = "proxied" ];
1502 * running -> dup [ label = "DUP", arrowhead = "none" ];
1506 static void request_running(REQUEST *request, int action)
1508 VERIFY_REQUEST(request);
1510 TRACE_STATE_MACHINE;
1514 case FR_ACTION_TIMER:
1516 (void) request_max_time(request);
1520 request_dup(request);
1524 if (!request_pre_handler(request, action)) {
1525 #ifdef DEBUG_STATE_MACHINE
1526 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1527 request->number, __FUNCTION__,
1528 child_state_names[request->child_state],
1529 child_state_names[REQUEST_DONE]);
1531 FINAL_STATE(REQUEST_DONE);
1535 rad_assert(request->handle != NULL);
1536 request->handle(request);
1540 * We may need to send a proxied request.
1542 if ((action == FR_ACTION_RUN) &&
1543 request_will_proxy(request)) {
1544 #ifdef DEBUG_STATE_MACHINE
1545 if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1549 * takes care of setting
1550 * up the post proxy fail
1553 if (request_proxy(request) < 0) goto req_finished;
1557 #ifdef DEBUG_STATE_MACHINE
1558 if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1564 request_finish(request, action);
1569 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1574 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1575 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1578 RADIUS_PACKET **packet_p;
1579 REQUEST *request = NULL;
1581 listen_socket_t *sock = NULL;
1583 VERIFY_PACKET(packet);
1586 * Set the last packet received.
1588 gettimeofday(&now, NULL);
1590 packet->timestamp = now;
1592 #ifdef WITH_ACCOUNTING
1593 if (listener->type != RAD_LISTEN_DETAIL)
1598 sock = listener->data;
1599 sock->last_packet = now.tv_sec;
1601 packet->proto = sock->proto;
1606 * Skip everything if required.
1608 if (listener->nodup) goto skip_dup;
1610 packet_p = rbtree_finddata(pl, &packet);
1612 rad_child_state_t child_state;
1614 request = fr_packet2myptr(REQUEST, packet, packet_p);
1615 rad_assert(request->in_request_hash);
1616 child_state = request->child_state;
1619 * Same src/dst ip/port, length, and
1620 * authentication vector: must be a duplicate.
1622 if ((request->packet->data_len == packet->data_len) &&
1623 (memcmp(request->packet->vector, packet->vector,
1624 sizeof(packet->vector)) == 0)) {
1627 switch (packet->code) {
1628 case PW_CODE_ACCESS_REQUEST:
1629 FR_STATS_INC(auth, total_dup_requests);
1632 #ifdef WITH_ACCOUNTING
1633 case PW_CODE_ACCOUNTING_REQUEST:
1634 FR_STATS_INC(acct, total_dup_requests);
1638 case PW_CODE_COA_REQUEST:
1639 FR_STATS_INC(coa, total_dup_requests);
1642 case PW_CODE_DISCONNECT_REQUEST:
1643 FR_STATS_INC(dsc, total_dup_requests);
1650 #endif /* WITH_STATS */
1653 * Tell the state machine that there's a
1654 * duplicate request.
1656 request->process(request, FR_ACTION_DUP);
1657 return 0; /* duplicate of live request */
1661 * Mark the request as done ASAP, and before we
1662 * log anything. The child may stop processing
1663 * the request just as we're logging the
1666 request_done(request, FR_ACTION_DONE);
1670 * It's a new request, not a duplicate. If the
1671 * old one is done, then we can clean it up.
1673 if (child_state <= REQUEST_RUNNING) {
1675 * The request is still QUEUED or RUNNING. That's a problem.
1677 ERROR("Received conflicting packet from "
1678 "client %s port %d - ID: %u due to "
1679 "unfinished request. Giving up on old request.",
1681 packet->src_port, packet->id);
1685 * Mark the old request as done. If there's no
1686 * child, the request will be cleaned up
1687 * immediately. If there is a child, we'll set a
1688 * timer to go clean up the request.
1690 } /* else the new packet is unique */
1693 * Quench maximum number of outstanding requests.
1695 if (main_config.max_requests &&
1696 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1697 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1699 packet->src_port, packet->id);
1700 WARN("Please check the configuration file.\n"
1701 "\tThe value for 'max_requests' is probably set too low.\n"));
1703 exec_trigger(NULL, NULL, "server.max_requests", true);
1709 * Rate-limit the incoming packets
1711 if (sock && sock->max_rate) {
1714 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1715 if (pps > sock->max_rate) {
1716 DEBUG("Dropping request due to rate limiting");
1719 sock->rate_pps_now++;
1723 * Allocate a pool for the request.
1726 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1728 talloc_set_name_const(ctx, "request_receive_pool");
1731 * The packet is still allocated from a different
1732 * context, but oh well.
1734 (void) talloc_steal(ctx, packet);
1737 request = request_setup(ctx, listener, packet, client, fun);
1744 * Mark it as a "real" request with a context.
1746 request->options |= RAD_REQUEST_OPTION_CTX;
1749 * Remember the request in the list.
1751 if (!listener->nodup) {
1752 if (!rbtree_insert(pl, &request->packet)) {
1753 RERROR("Failed to insert request in the list of live requests: discarding it");
1754 request_done(request, FR_ACTION_DONE);
1758 request->in_request_hash = true;
1762 * Process it. Send a response, and free it.
1764 if (listener->synchronous) {
1766 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1769 request->listener->decode(request->listener, request);
1770 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1771 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1775 if (request->reply->code != 0) {
1776 request->listener->send(request->listener, request);
1778 RDEBUG("Not sending reply");
1782 * Don't do delayed reject. Oh well.
1784 request_free(request);
1789 * Otherwise, insert it into the state machine.
1790 * The child threads will take care of processing it.
1792 request_queue_or_run(request, request_running);
1798 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1799 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1804 * Create and initialize the new request.
1806 request = request_alloc(ctx);
1811 request->reply = rad_alloc_reply(request, packet);
1812 if (!request->reply) {
1814 talloc_free(request);
1818 request->listener = listener;
1819 request->client = client;
1820 request->packet = talloc_steal(request, packet);
1821 request->number = request_num_counter++;
1822 request->priority = listener->type;
1823 request->master_state = REQUEST_ACTIVE;
1824 request->child_state = REQUEST_RUNNING;
1825 #ifdef DEBUG_STATE_MACHINE
1826 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1827 request->number, __FUNCTION__,
1828 child_state_names[request->child_state],
1829 child_state_names[REQUEST_RUNNING]);
1831 request->handle = fun;
1835 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1836 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1837 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1838 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1839 #ifdef WITH_ACCOUNTING
1840 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1841 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1842 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1845 #endif /* WITH_STATS */
1848 * Status-Server packets go to the head of the queue.
1850 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1853 * Set virtual server identity
1855 if (client->server) {
1856 request->server = client->server;
1857 } else if (listener->server) {
1858 request->server = listener->server;
1860 request->server = NULL;
1863 request->root = &main_config;
1865 request->listener->count++;
1869 * The request passes many of our sanity checks.
1870 * From here on in, if anything goes wrong, we
1871 * send a reject message, instead of dropping the
1876 * Build the reply template from the request.
1879 request->reply->sockfd = request->packet->sockfd;
1880 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1881 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1882 request->reply->dst_port = request->packet->src_port;
1883 request->reply->src_port = request->packet->dst_port;
1884 request->reply->id = request->packet->id;
1885 request->reply->code = 0; /* UNKNOWN code */
1886 memcpy(request->reply->vector, request->packet->vector,
1887 sizeof(request->reply->vector));
1888 request->reply->vps = NULL;
1889 request->reply->data = NULL;
1890 request->reply->data_len = 0;
1896 /***********************************************************************
1900 ***********************************************************************/
1903 * Timer function for all TCP sockets.
1905 static void tcp_socket_timer(void *ctx)
1907 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1908 listen_socket_t *sock = listener->data;
1909 struct timeval end, now;
1911 fr_socket_limit_t *limit;
1915 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1917 fr_event_now(el, &now);
1919 switch (listener->type) {
1921 case RAD_LISTEN_PROXY:
1922 limit = &sock->home->limit;
1926 case RAD_LISTEN_AUTH:
1927 #ifdef WITH_ACCOUNTING
1928 case RAD_LISTEN_ACCT:
1930 limit = &sock->limit;
1938 * If we enforce a lifetime, do it now.
1940 if (limit->lifetime > 0) {
1941 end.tv_sec = sock->opened + limit->lifetime;
1944 if (timercmp(&end, &now, <=)) {
1945 listener->print(listener, buffer, sizeof(buffer));
1946 DEBUG("Reached maximum lifetime on socket %s", buffer);
1952 * Proxy sockets get frozen, so that we don't use
1953 * them for new requests. But we do keep them
1954 * open to listen for replies to requests we had
1957 if (listener->type == RAD_LISTEN_PROXY) {
1958 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1959 if (!fr_packet_list_socket_freeze(proxy_list,
1961 ERROR("Fatal error freezing socket: %s", fr_strerror());
1964 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1969 * Mark the socket as "don't use if at all possible".
1971 listener->status = RAD_LISTEN_STATUS_FROZEN;
1972 event_new_fd(listener);
1981 * Enforce an idle timeout.
1983 if (limit->idle_timeout > 0) {
1984 struct timeval idle;
1986 rad_assert(sock->last_packet != 0);
1987 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1990 if (timercmp(&idle, &now, <=)) {
1991 listener->print(listener, buffer, sizeof(buffer));
1992 DEBUG("Reached idle timeout on socket %s", buffer);
1997 * Enforce the minimum of idle timeout or lifetime.
1999 if (timercmp(&idle, &end, <)) {
2005 * Wake up at t + 0.5s. The code above checks if the timers
2006 * are <= t. This addition gives us a bit of leeway.
2008 end.tv_usec = USEC / 2;
2011 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
2012 rad_panic("Failed to insert event");
2019 * Called by socket_del to remove requests with this socket
2021 static int eol_proxy_listener(void *ctx, void *data)
2023 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2024 RADIUS_PACKET **proxy_p = data;
2027 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2028 if (request->proxy_listener != this) return 0;
2031 * The normal "remove_from_proxy_hash" tries to grab the
2032 * proxy mutex. We already have it held, so grabbing it
2033 * again will cause a deadlock. Instead, call the "no
2034 * lock" version of the function.
2036 rad_assert(request->in_proxy_hash == true);
2037 remove_from_proxy_hash_nl(request, false);
2040 * Don't mark it as DONE. The client can retransmit, and
2041 * the packet SHOULD be re-proxied somewhere else.
2043 * Return "2" means that the rbtree code will remove it
2044 * from the tree, and we don't need to do it ourselves.
2048 #endif /* WITH_PROXY */
2050 static int eol_listener(void *ctx, void *data)
2052 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2053 RADIUS_PACKET **packet_p = data;
2056 request = fr_packet2myptr(REQUEST, packet, packet_p);
2057 if (request->listener != this) return 0;
2059 request->master_state = REQUEST_STOP_PROCESSING;
2060 request->process = request_done;
2064 #endif /* WITH_TCP */
2067 /***********************************************************************
2069 * Proxy handlers for the state machine.
2071 ***********************************************************************/
2074 * Called with the proxy mutex held
2076 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2078 VERIFY_REQUEST(request);
2080 if (!request->in_proxy_hash) return;
2082 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2083 request->in_proxy_hash = false;
2086 * On the FIRST reply, decrement the count of outstanding
2087 * requests. Note that this is NOT the count of sent
2088 * packets, but whether or not the home server has
2091 if (request->home_server &&
2092 request->home_server->currently_outstanding) {
2093 request->home_server->currently_outstanding--;
2096 * If we're NOT sending it packets, AND it's been
2097 * a while since we got a response, then we don't
2098 * know if it's alive or dead.
2100 if ((request->home_server->currently_outstanding == 0) &&
2101 (request->home_server->state == HOME_STATE_ALIVE)) {
2102 struct timeval when, now;
2104 when.tv_sec = request->home_server->last_packet_recv ;
2107 timeradd(&when, request_response_window(request), &when);
2108 gettimeofday(&now, NULL);
2111 * last_packet + response_window
2113 * We *administratively* mark the home
2114 * server as "unknown" state, because we
2115 * haven't seen a packet for a while.
2117 if (timercmp(&now, &when, >)) {
2118 request->home_server->state = HOME_STATE_UNKNOWN;
2119 request->home_server->last_packet_sent = 0;
2120 request->home_server->last_packet_recv = 0;
2126 if (request->proxy_listener) {
2127 request->proxy_listener->count--;
2130 request->proxy_listener = NULL;
2133 * Got from YES in hash, to NO, not in hash while we hold
2134 * the mutex. This guarantees that when another thread
2135 * grabs the mutex, the "not in hash" flag is correct.
2139 static void remove_from_proxy_hash(REQUEST *request)
2141 VERIFY_REQUEST(request);
2144 * Check this without grabbing the mutex because it's a
2145 * lot faster that way.
2147 if (!request->in_proxy_hash) return;
2150 * The "not in hash" flag is definitive. However, if the
2151 * flag says that it IS in the hash, there might still be
2152 * a race condition where it isn't.
2154 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2156 if (!request->in_proxy_hash) {
2157 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2161 remove_from_proxy_hash_nl(request, true);
2163 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2166 static int insert_into_proxy_hash(REQUEST *request)
2170 bool success = false;
2171 void *proxy_listener;
2173 VERIFY_REQUEST(request);
2175 rad_assert(request->proxy != NULL);
2176 rad_assert(request->home_server != NULL);
2177 rad_assert(proxy_list != NULL);
2180 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2181 proxy_listener = NULL;
2182 request->num_proxied_requests = 1;
2183 request->num_proxied_responses = 0;
2185 for (tries = 0; tries < 2; tries++) {
2187 listen_socket_t *sock;
2189 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2190 success = fr_packet_list_id_alloc(proxy_list,
2191 request->home_server->proto,
2192 &request->proxy, &proxy_listener);
2195 if (tries > 0) continue; /* try opening new socket only once */
2197 #ifdef HAVE_PTHREAD_H
2198 if (proxy_no_new_sockets) break;
2201 RDEBUG3("proxy: Trying to open a new listener to the home server");
2202 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2204 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2208 request->proxy->src_port = 0; /* Use any new socket */
2209 proxy_listener = this;
2212 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2214 &sock->other_ipaddr, sock->other_port,
2217 #ifdef HAVE_PTHREAD_H
2218 proxy_no_new_sockets = true;
2220 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2223 * This is bad. However, the
2224 * packet list now supports 256
2225 * open sockets, which should
2226 * minimize this problem.
2228 ERROR("Failed adding proxy socket: %s",
2234 * Add it to the event loop. Ensure that we have
2235 * only one mutex locked at a time.
2237 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2238 radius_update_listener(this);
2239 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2242 if (!proxy_listener || !success) {
2243 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2244 REDEBUG2("proxy: Failed allocating Id for proxied request");
2246 request->proxy_listener = NULL;
2247 request->in_proxy_hash = false;
2251 rad_assert(request->proxy->id >= 0);
2253 request->proxy_listener = proxy_listener;
2254 request->in_proxy_hash = true;
2255 RDEBUG3("proxy: request is now in proxy hash");
2258 * Keep track of maximum outstanding requests to a
2259 * particular home server. 'max_outstanding' is
2260 * enforced in home_server_ldb(), in realms.c.
2262 request->home_server->currently_outstanding++;
2265 request->proxy_listener->count++;
2268 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2270 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2271 inet_ntop(request->proxy->dst_ipaddr.af,
2272 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2273 request->proxy->dst_port,
2274 request->proxy->id);
2279 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2282 int post_proxy_type = 0;
2285 VERIFY_REQUEST(request);
2288 * There may be a proxy reply, but it may be too late.
2290 if (!request->home_server->server && !request->proxy_listener) return 0;
2293 * Delete any reply we had accumulated until now.
2295 RDEBUG2("Clearing existing &reply: attributes");
2296 fr_pair_list_free(&request->reply->vps);
2299 * Run the packet through the post-proxy stage,
2300 * BEFORE playing games with the attributes.
2302 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2304 post_proxy_type = vp->vp_integer;
2306 * If we have a proxy_reply, and it was a reject, or a NAK
2307 * setup Post-Proxy <type>.
2309 * If the <type> doesn't have a section, then the Post-Proxy
2310 * section is ignored.
2313 DICT_VALUE *dval = NULL;
2315 switch (reply->code) {
2316 case PW_CODE_ACCESS_REJECT:
2317 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2318 if (dval) post_proxy_type = dval->value;
2321 case PW_CODE_DISCONNECT_NAK:
2322 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2323 if (dval) post_proxy_type = dval->value;
2326 case PW_CODE_COA_NAK:
2327 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2328 if (dval) post_proxy_type = dval->value;
2336 * Create config:Post-Proxy-Type
2339 vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2340 vp->vp_integer = dval->value;
2344 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2345 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2348 VERIFY_PACKET(reply);
2351 * Decode the packet if required.
2353 if (request->proxy_listener) {
2354 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2355 debug_packet(request, reply, true);
2358 * Pro-actively remove it from the proxy hash.
2359 * This is later than in 2.1.x, but it means that
2360 * the replies are authenticated before being
2361 * removed from the hash.
2364 (request->num_proxied_requests <= request->num_proxied_responses)) {
2365 remove_from_proxy_hash(request);
2368 rad_assert(!request->in_proxy_hash);
2370 } else if (request->in_proxy_hash) {
2371 remove_from_proxy_hash(request);
2374 if (request->home_pool && request->home_pool->virtual_server) {
2375 char const *old_server = request->server;
2377 request->server = request->home_pool->virtual_server;
2378 RDEBUG2("server %s {", request->server);
2380 rcode = process_post_proxy(post_proxy_type, request);
2383 request->server = old_server;
2385 rcode = process_post_proxy(post_proxy_type, request);
2389 if (request->packet->code == request->proxy->code) {
2391 * Don't run the next bit if we originated a CoA
2392 * packet, after receiving an Access-Request or
2393 * Accounting-Request.
2398 * There may NOT be a proxy reply, as we may be
2399 * running Post-Proxy-Type = Fail.
2402 fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2405 * Delete the Proxy-State Attributes from
2406 * the reply. These include Proxy-State
2407 * attributes from us and remote server.
2409 fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2412 vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
2413 if (vp && (vp->vp_integer != 256)) {
2414 request->proxy_reply = rad_alloc_reply(request, request->proxy);
2415 request->proxy_reply->code = vp->vp_integer;
2422 default: /* Don't do anything */
2424 case RLM_MODULE_FAIL:
2427 case RLM_MODULE_HANDLED:
2434 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2438 home->state = HOME_STATE_ALIVE;
2439 home->response_timeouts = 0;
2440 exec_trigger(request, home->cs, "home_server.alive", false);
2441 home->currently_outstanding = 0;
2442 home->num_sent_pings = 0;
2443 home->num_received_pings = 0;
2444 gettimeofday(&home->revive_time, NULL);
2446 fr_event_delete(el, &home->ev);
2448 RPROXY("Marking home server %s port %d alive",
2449 inet_ntop(request->proxy->dst_ipaddr.af,
2450 &request->proxy->dst_ipaddr.ipaddr,
2451 buffer, sizeof(buffer)),
2452 request->proxy->dst_port);
2456 int request_proxy_reply(RADIUS_PACKET *packet)
2458 RADIUS_PACKET **proxy_p;
2463 VERIFY_PACKET(packet);
2465 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2466 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2469 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2470 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2471 fr_packet_codes[packet->code],
2472 inet_ntop(packet->src_ipaddr.af,
2473 &packet->src_ipaddr.ipaddr,
2474 buffer, sizeof(buffer)),
2475 packet->src_port, packet->id);
2479 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2481 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2484 * No reply, BUT the current packet fails verification:
2485 * ignore it. This does the MD5 calculations in the
2486 * server core, but I guess we can fix that later.
2488 if (!request->proxy_reply &&
2489 (rad_verify(packet, request->proxy,
2490 request->home_server->secret) != 0)) {
2491 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2496 * The home server sent us a packet which doesn't match
2497 * something we have: ignore it. This is done only to
2498 * catch the case of broken systems.
2500 if (request->proxy_reply &&
2501 (memcmp(request->proxy_reply->vector,
2503 sizeof(request->proxy_reply->vector)) != 0)) {
2504 RDEBUG2("Ignoring conflicting proxy reply");
2508 gettimeofday(&now, NULL);
2511 * Status-Server packets don't count as real packets.
2513 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2515 listen_socket_t *sock = request->proxy_listener->data;
2517 sock->last_packet = now.tv_sec;
2519 request->home_server->last_packet_recv = now.tv_sec;
2522 request->num_proxied_responses++;
2525 * If we have previously seen a reply, ignore the
2528 if (request->proxy_reply) {
2529 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2530 inet_ntop(packet->src_ipaddr.af,
2531 &packet->src_ipaddr.ipaddr,
2532 buffer, sizeof(buffer)),
2533 packet->src_port, packet->id);
2538 * Call the state machine to do something useful with the
2541 request->proxy_reply = talloc_steal(request, packet);
2542 packet->timestamp = now;
2543 request->priority = RAD_LISTEN_PROXY;
2547 * Update the proxy listener stats here, because only one
2548 * thread accesses that at a time. The home_server and
2549 * main proxy_*_stats structures are updated once the
2550 * request is cleaned up.
2552 request->proxy_listener->stats.total_responses++;
2554 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2555 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2557 switch (request->proxy->code) {
2558 case PW_CODE_ACCESS_REQUEST:
2559 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2561 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2562 request->proxy_listener->stats.total_access_accepts++;
2564 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2565 request->proxy_listener->stats.total_access_rejects++;
2567 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2568 request->proxy_listener->stats.total_access_challenges++;
2572 #ifdef WITH_ACCOUNTING
2573 case PW_CODE_ACCOUNTING_REQUEST:
2574 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2576 request->proxy_listener->stats.total_responses++;
2577 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2583 case PW_CODE_COA_REQUEST:
2584 request->proxy_listener->stats.total_responses++;
2585 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2588 case PW_CODE_DISCONNECT_REQUEST:
2589 request->proxy_listener->stats.total_responses++;
2590 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2600 * If we hadn't been sending the home server packets for
2601 * a while, just mark it alive. Or, if it was zombie,
2602 * it's now responded, and is therefore alive.
2604 if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2605 (request->home_server->state == HOME_STATE_ZOMBIE)) {
2606 mark_home_server_alive(request, request->home_server);
2610 * Tell the request state machine that we have a proxy
2611 * reply. Depending on the function, this should either
2612 * ignore it, or process it.
2614 request->process(request, FR_ACTION_PROXY_REPLY);
2620 static int setup_post_proxy_fail(REQUEST *request)
2622 DICT_VALUE const *dval = NULL;
2625 VERIFY_REQUEST(request);
2627 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2628 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2629 "Fail-Authentication");
2630 #ifdef WITH_ACCOUNTING
2631 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2632 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2637 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2638 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2640 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2641 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2644 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2648 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2651 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2655 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2656 if (!vp) vp = radius_pair_create(request, &request->config,
2657 PW_POST_PROXY_TYPE, 0);
2658 vp->vp_integer = dval->value;
2664 /** Process a request after the proxy has timed out.
2666 * Run the packet through Post-Proxy-Type Fail
2669 * digraph proxy_no_reply {
2672 * proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2673 * proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2674 * proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2675 * proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2676 * proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2680 static void proxy_no_reply(REQUEST *request, int action)
2682 VERIFY_REQUEST(request);
2684 TRACE_STATE_MACHINE;
2689 request_dup(request);
2692 case FR_ACTION_TIMER:
2693 (void) request_max_time(request);
2696 case FR_ACTION_PROXY_REPLY:
2697 proxy_reply_too_late(request);
2701 if (process_proxy_reply(request, NULL)) {
2702 request->handle(request);
2704 request_finish(request, action);
2708 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2713 /** Process the request after receiving a proxy reply.
2715 * Throught the post-proxy section, and the through the handler
2719 * digraph proxy_running {
2722 * proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2723 * proxy_running -> timer [ label = "TIMER < max_request_time" ];
2724 * proxy_running -> process_proxy_reply [ label = "RUN" ];
2725 * proxy_running -> done [ label = "TIMER >= timeout" ];
2729 static void proxy_running(REQUEST *request, int action)
2731 VERIFY_REQUEST(request);
2733 TRACE_STATE_MACHINE;
2738 request_dup(request);
2741 case FR_ACTION_TIMER:
2742 (void) request_max_time(request);
2746 if (process_proxy_reply(request, request->proxy_reply)) {
2747 request->handle(request);
2749 request_finish(request, action);
2752 default: /* duplicate proxy replies are suppressed */
2753 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2758 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2760 * Whether a request will be proxied is determined by the attributes present
2761 * in request->config. If any of the following attributes are found, the
2762 * request may be proxied.
2764 * The key attributes are:
2765 * - PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2766 * - PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2767 * - PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2768 * - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2770 * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2772 * If request should be proxied, will:
2773 * - Add request:Proxy-State
2774 * - Strip the current username value of its realm (depending on config)
2775 * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2777 * - Call the pre-process section in the current server, or in the virtual server
2778 * associated with the home server pool we're proxying to.
2780 * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2781 * specific function.
2783 * @param request The #REQUEST to evaluate for proxying.
2784 * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2786 static int request_will_proxy(REQUEST *request)
2788 int rcode, pre_proxy_type = 0;
2789 char const *realmname = NULL;
2790 VALUE_PAIR *vp, *strippedname;
2791 home_server_t *home;
2792 REALM *realm = NULL;
2793 home_pool_t *pool = NULL;
2795 VERIFY_REQUEST(request);
2797 if (!request->root->proxy_requests) return 0;
2798 if (request->packet->dst_port == 0) return 0;
2799 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2800 if (request->in_proxy_hash) return 0;
2803 * FIXME: for 3.0, allow this only for rejects?
2805 if (request->reply->code != 0) return 0;
2807 vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2809 realm = realm_find2(vp->vp_strvalue);
2811 REDEBUG2("Cannot proxy to unknown realm %s",
2816 realmname = vp->vp_strvalue;
2819 * Figure out which pool to use.
2821 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2822 pool = realm->auth_pool;
2824 #ifdef WITH_ACCOUNTING
2825 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2826 pool = realm->acct_pool;
2830 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2831 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2832 pool = realm->coa_pool;
2839 } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2842 switch (request->packet->code) {
2843 case PW_CODE_ACCESS_REQUEST:
2844 pool_type = HOME_TYPE_AUTH;
2847 #ifdef WITH_ACCOUNTING
2848 case PW_CODE_ACCOUNTING_REQUEST:
2849 pool_type = HOME_TYPE_ACCT;
2854 case PW_CODE_COA_REQUEST:
2855 case PW_CODE_DISCONNECT_REQUEST:
2856 pool_type = HOME_TYPE_COA;
2864 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2867 * Send it directly to a home server (i.e. NAS)
2869 } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2870 ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2872 fr_ipaddr_t dst_ipaddr;
2874 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2876 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2877 dst_ipaddr.af = AF_INET;
2878 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2879 dst_ipaddr.prefix = 32;
2881 dst_ipaddr.af = AF_INET6;
2882 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2883 dst_ipaddr.prefix = 128;
2886 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2888 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2889 dst_port = PW_AUTH_UDP_PORT;
2891 #ifdef WITH_ACCOUNTING
2892 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2893 dst_port = PW_ACCT_UDP_PORT;
2897 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2898 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2899 dst_port = PW_COA_UDP_PORT;
2901 } else { /* shouldn't happen for RADIUS... */
2906 dst_port = vp->vp_integer;
2910 * Nothing does CoA over TCP.
2912 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2916 WARN("No such home server %s port %u",
2917 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2918 (unsigned int) dst_port);
2923 * The home server is alive (or may be alive).
2924 * Send the packet to the IP.
2926 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2929 * The home server is dead. If you wanted
2930 * fail-over, you should have proxied to a pool.
2941 RWDEBUG2("Cancelling proxy as no home pool exists");
2945 if (request->listener->synchronous) {
2946 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2950 request->home_pool = pool;
2952 home = home_server_ldb(realmname, pool, request);
2955 REDEBUG2("Failed to find live home server: Cancelling proxy");
2960 home_server_update_request(home, request);
2964 * Once we've decided to proxy a request, we cannot send
2965 * a CoA packet. So we free up any CoA packet here.
2967 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2971 * Remember that we sent the request to a Realm.
2973 if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2976 * Strip the name, if told to.
2978 * Doing it here catches the case of proxied tunneled
2981 if (realm && (realm->strip_realm == true) &&
2982 (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2984 * If there's a Stripped-User-Name attribute in
2985 * the request, then use THAT as the User-Name
2986 * for the proxied request, instead of the
2989 * This is done by making a copy of the
2990 * Stripped-User-Name attribute, turning it into
2991 * a User-Name attribute, deleting the
2992 * Stripped-User-Name and User-Name attributes
2993 * from the vps list, and making the new
2994 * User-Name the head of the vps list.
2996 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2999 vp = radius_pair_create(NULL, NULL,
3001 rad_assert(vp != NULL); /* handled by above function */
3002 /* Insert at the START of the list */
3003 /* FIXME: Can't make assumptions about ordering */
3004 fr_cursor_init(&cursor, &vp);
3005 fr_cursor_merge(&cursor, request->proxy->vps);
3006 request->proxy->vps = vp;
3008 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
3011 * Do NOT delete Stripped-User-Name.
3016 * If there is no PW_CHAP_CHALLENGE attribute but
3017 * there is a PW_CHAP_PASSWORD we need to add it
3018 * since we can't use the request authenticator
3019 * anymore - we changed it.
3021 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
3022 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
3023 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
3024 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
3025 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
3029 * The RFC's say we have to do this, but FreeRADIUS
3032 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3033 fr_pair_value_sprintf(vp, "%u", request->packet->id);
3036 * Should be done BEFORE inserting into proxy hash, as
3037 * pre-proxy may use this information, or change it.
3039 request->proxy->code = request->packet->code;
3042 * Call the pre-proxy routines.
3044 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3046 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3047 /* Must be a validation issue */
3049 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3050 pre_proxy_type = vp->vp_integer;
3054 * home_pool may be NULL when originating CoA packets,
3055 * because they go directly to an IP address.
3057 if (request->home_pool && request->home_pool->virtual_server) {
3058 char const *old_server = request->server;
3060 request->server = request->home_pool->virtual_server;
3062 RDEBUG2("server %s {", request->server);
3064 rcode = process_pre_proxy(pre_proxy_type, request);
3068 request->server = old_server;
3072 RDEBUG2("Starting proxy to home server %s port %d",
3073 inet_ntop(request->proxy->dst_ipaddr.af,
3074 &request->proxy->dst_ipaddr.ipaddr,
3075 buffer, sizeof(buffer)),
3076 request->proxy->dst_port);
3078 rcode = process_pre_proxy(pre_proxy_type, request);
3082 case RLM_MODULE_FAIL:
3083 case RLM_MODULE_INVALID:
3084 case RLM_MODULE_NOTFOUND:
3085 case RLM_MODULE_USERLOCK:
3087 /* FIXME: debug print failed stuff */
3090 case RLM_MODULE_REJECT:
3091 case RLM_MODULE_HANDLED:
3095 * Only proxy the packet if the pre-proxy code succeeded.
3097 case RLM_MODULE_NOOP:
3099 case RLM_MODULE_UPDATED:
3104 static int proxy_to_virtual_server(REQUEST *request)
3108 if (request->packet->dst_port == 0) {
3109 WARN("Cannot proxy an internal request");
3113 DEBUG("Proxying to virtual server %s",
3114 request->home_server->server);
3117 * Packets to virtual servers don't get
3118 * retransmissions sent to them. And the virtual
3119 * server is run ONLY if we have no child
3120 * threads, or we're running in a child thread.
3122 rad_assert(!spawn_flag || !we_are_master());
3124 fake = request_alloc_fake(request);
3126 fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3127 talloc_free(request->proxy);
3129 fake->server = request->home_server->server;
3130 fake->handle = request->handle;
3131 fake->process = NULL; /* should never be run for anything */
3134 * Run the virtual server.
3136 request_running(fake, FR_ACTION_RUN);
3138 request->proxy = talloc_steal(request, fake->packet);
3139 fake->packet = NULL;
3140 request->proxy_reply = talloc_steal(request, fake->reply);
3146 * No reply code, toss the reply we have,
3147 * and do post-proxy-type Fail.
3149 if (!request->proxy_reply->code) {
3150 TALLOC_FREE(request->proxy_reply);
3151 setup_post_proxy_fail(request);
3155 * Do the proxy reply (if any)
3157 if (process_proxy_reply(request, request->proxy_reply)) {
3158 request->handle(request);
3161 return -1; /* so we call request_finish */
3165 static int request_proxy(REQUEST *request)
3169 VERIFY_REQUEST(request);
3171 rad_assert(request->parent == NULL);
3172 rad_assert(request->home_server != NULL);
3174 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3178 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
3179 request_done(request->coa, FR_ACTION_DONE);
3184 * The request may need sending to a virtual server.
3185 * This code is more than a little screwed up. The rest
3186 * of the state machine doesn't handle parent / child
3187 * relationships well. i.e. if the child request takes
3188 * too long, the core will mark the *parent* as "stop
3189 * processing". And the child will continue without
3190 * knowing anything...
3192 * So, we have some horrible hacks to get around that.
3194 if (request->home_server->server) return proxy_to_virtual_server(request);
3197 * We're actually sending a proxied packet. Do that now.
3199 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3200 RPROXY("Failed to insert request into the proxy list");
3204 rad_assert(request->proxy->id >= 0);
3206 if (rad_debug_lvl) {
3207 struct timeval *response_window;
3209 response_window = request_response_window(request);
3212 if (request->home_server->tls) {
3213 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3214 inet_ntop(request->proxy->dst_ipaddr.af,
3215 &request->proxy->dst_ipaddr.ipaddr,
3216 buffer, sizeof(buffer)),
3217 request->proxy->dst_port,
3218 (int) response_window->tv_sec, (int) response_window->tv_usec);
3221 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3222 inet_ntop(request->proxy->dst_ipaddr.af,
3223 &request->proxy->dst_ipaddr.ipaddr,
3224 buffer, sizeof(buffer)),
3225 request->proxy->dst_port,
3226 (int) response_window->tv_sec, (int) response_window->tv_usec);
3231 gettimeofday(&request->proxy->timestamp, NULL);
3232 request->home_server->last_packet_sent = request->proxy->timestamp.tv_sec;
3235 * Encode the packet before we do anything else.
3237 request->proxy_listener->encode(request->proxy_listener, request);
3238 debug_packet(request, request->proxy, false);
3241 * Set the state function, then the state, no child, and
3244 * The order here is different from other state changes
3245 * due to race conditions with replies from the home
3248 request->process = proxy_wait_for_reply;
3249 request->child_state = REQUEST_PROXIED;
3250 request->component = "<REQUEST_PROXIED>";
3251 request->module = "";
3255 * And send the packet.
3257 request->proxy_listener->send(request->proxy_listener, request);
3262 * Proxy the packet as if it was new.
3264 static int request_proxy_anew(REQUEST *request)
3266 home_server_t *home;
3268 VERIFY_REQUEST(request);
3271 * Delete the request from the proxy list.
3273 * The packet list code takes care of ensuring that IDs
3274 * aren't reused until all 256 IDs have been used. So
3275 * there's a 1/256 chance of re-using the same ID when
3276 * we're sending to the same home server. Which is
3279 remove_from_proxy_hash(request);
3282 * Find a live home server for the request.
3284 home = home_server_ldb(NULL, request->home_pool, request);
3286 REDEBUG2("Failed to find live home server for request");
3288 if (setup_post_proxy_fail(request)) {
3289 request_queue_or_run(request, proxy_running);
3291 gettimeofday(&request->reply->timestamp, NULL);
3292 request_cleanup_delay_init(request);
3297 #ifdef WITH_ACCOUNTING
3299 * Update the Acct-Delay-Time attribute, since the LAST
3300 * time we tried to retransmit this packet.
3302 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3305 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3306 if (!vp) vp = radius_pair_create(request->proxy,
3307 &request->proxy->vps,
3308 PW_ACCT_DELAY_TIME, 0);
3312 gettimeofday(&now, NULL);
3313 vp->vp_integer += now.tv_sec - request->proxy->timestamp.tv_sec;
3319 * May have failed over to a "fallback" virtual server.
3320 * If so, run that instead of doing proxying to a real
3324 request->home_server = home;
3325 TALLOC_FREE(request->proxy);
3327 (void) proxy_to_virtual_server(request);
3331 home_server_update_request(home, request);
3333 if (!insert_into_proxy_hash(request)) {
3334 RPROXY("Failed to insert retransmission into the proxy list");
3335 goto post_proxy_fail;
3339 * Free the old packet, to force re-encoding
3341 talloc_free(request->proxy->data);
3342 request->proxy->data = NULL;
3343 request->proxy->data_len = 0;
3345 if (request_proxy(request) != 1) goto post_proxy_fail;
3351 /** Ping a home server.
3354 static void request_ping(REQUEST *request, int action)
3356 home_server_t *home = request->home_server;
3359 VERIFY_REQUEST(request);
3361 TRACE_STATE_MACHINE;
3365 case FR_ACTION_TIMER:
3366 ERROR("No response to status check %d ID %u for home server %s port %d",
3369 inet_ntop(request->proxy->dst_ipaddr.af,
3370 &request->proxy->dst_ipaddr.ipaddr,
3371 buffer, sizeof(buffer)),
3372 request->proxy->dst_port);
3373 remove_from_proxy_hash(request);
3376 case FR_ACTION_PROXY_REPLY:
3377 rad_assert(request->in_proxy_hash);
3379 request->home_server->num_received_pings++;
3380 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3381 request->number, request->proxy->id, home->num_received_pings);
3384 * Remove the request from any hashes
3386 fr_event_delete(el, &request->ev);
3387 remove_from_proxy_hash(request);
3390 * The control socket may have marked the home server as
3391 * alive. OR, it may have suddenly started responding to
3392 * requests again. If so, don't re-do the "make alive"
3395 if (home->state == HOME_STATE_ALIVE) break;
3398 * It's dead, and we haven't received enough ping
3399 * responses to mark it "alive". Wait a bit.
3401 * If it's zombie, we mark it alive immediately.
3403 if ((home->state == HOME_STATE_IS_DEAD) &&
3404 (home->num_received_pings < home->num_pings_to_alive)) {
3409 * Mark it alive and delete any outstanding
3412 mark_home_server_alive(request, home);
3416 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3420 rad_assert(!request->in_request_hash);
3421 rad_assert(!request->in_proxy_hash);
3422 rad_assert(request->ev == NULL);
3424 request_done(request, FR_ACTION_DONE);
3428 * Add +/- 2s of jitter, as suggested in RFC 3539
3431 static void add_jitter(struct timeval *when)
3438 jitter ^= (jitter >> 10);
3439 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
3442 * Add in ~ (4 * USEC) of jitter.
3444 tv_add(when, jitter);
3448 * Called from start of zombie period, OR after control socket
3449 * marks the home server dead.
3451 static void ping_home_server(void *ctx)
3453 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3456 struct timeval when, now;
3458 if ((home->state == HOME_STATE_ALIVE) ||
3459 (home->ev != NULL)) {
3463 gettimeofday(&now, NULL);
3467 * We've run out of zombie time. Mark it dead.
3469 if (home->state == HOME_STATE_ZOMBIE) {
3470 when = home->zombie_period_start;
3471 when.tv_sec += home->zombie_period;
3473 if (timercmp(&when, &now, <)) {
3474 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3475 mark_home_server_dead(home, &now);
3480 * We're not supposed to be pinging it. Just wake up
3481 * when we're supposed to mark it dead.
3483 if (home->ping_check == HOME_PING_CHECK_NONE) {
3484 if (home->state == HOME_STATE_ZOMBIE) {
3485 home->when = home->zombie_period_start;
3486 home->when.tv_sec += home->zombie_period;
3487 INSERT_EVENT(ping_home_server, home);
3491 * Else mark_home_server_dead will set a timer
3492 * for revive_interval.
3498 request = request_alloc(NULL);
3499 if (!request) return;
3500 request->number = request_num_counter++;
3503 request->proxy = rad_alloc(request, true);
3504 rad_assert(request->proxy != NULL);
3506 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3507 request->proxy->code = PW_CODE_STATUS_SERVER;
3509 fr_pair_make(request->proxy, &request->proxy->vps,
3510 "Message-Authenticator", "0x00", T_OP_SET);
3512 } else if ((home->type == HOME_TYPE_AUTH) ||
3513 (home->type == HOME_TYPE_AUTH_ACCT)) {
3514 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3516 fr_pair_make(request->proxy, &request->proxy->vps,
3517 "User-Name", home->ping_user_name, T_OP_SET);
3518 fr_pair_make(request->proxy, &request->proxy->vps,
3519 "User-Password", home->ping_user_password, T_OP_SET);
3520 fr_pair_make(request->proxy, &request->proxy->vps,
3521 "Service-Type", "Authenticate-Only", T_OP_SET);
3522 fr_pair_make(request->proxy, &request->proxy->vps,
3523 "Message-Authenticator", "0x00", T_OP_SET);
3525 #ifdef WITH_ACCOUNTING
3526 } else if (home->type == HOME_TYPE_ACCT) {
3527 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3529 fr_pair_make(request->proxy, &request->proxy->vps,
3530 "User-Name", home->ping_user_name, T_OP_SET);
3531 fr_pair_make(request->proxy, &request->proxy->vps,
3532 "Acct-Status-Type", "Stop", T_OP_SET);
3533 fr_pair_make(request->proxy, &request->proxy->vps,
3534 "Acct-Session-Id", "00000000", T_OP_SET);
3535 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3536 "Event-Timestamp", "0", T_OP_SET);
3537 vp->vp_date = now.tv_sec;
3542 * Unkown home server type.
3544 talloc_free(request);
3548 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3549 "NAS-Identifier", "", T_OP_SET);
3551 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3552 home->num_sent_pings);
3556 request->proxy->proto = home->proto;
3558 request->proxy->src_ipaddr = home->src_ipaddr;
3559 request->proxy->dst_ipaddr = home->ipaddr;
3560 request->proxy->dst_port = home->port;
3561 request->home_server = home;
3562 #ifdef DEBUG_STATE_MACHINE
3563 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3564 child_state_names[request->child_state],
3565 child_state_names[REQUEST_DONE]);
3566 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3568 #ifdef HAVE_PTHREAD_H
3569 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3571 request->child_state = REQUEST_PROXIED;
3572 request->process = request_ping;
3574 rad_assert(request->proxy_listener == NULL);
3576 if (!insert_into_proxy_hash(request)) {
3577 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3580 rad_assert(!request->in_request_hash);
3581 rad_assert(!request->in_proxy_hash);
3582 rad_assert(request->ev == NULL);
3583 talloc_free(request);
3588 * Set up the timer callback.
3591 when.tv_sec += home->ping_timeout;
3593 DEBUG("PING: Waiting %u seconds for response to ping",
3594 home->ping_timeout);
3596 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3597 home->num_sent_pings++;
3599 rad_assert(request->proxy_listener != NULL);
3600 debug_packet(request, request->proxy, false);
3601 request->proxy_listener->send(request->proxy_listener,
3605 * Add +/- 2s of jitter, as suggested in RFC 3539
3606 * and in the Issues and Fixes draft.
3609 home->when.tv_sec += home->ping_interval;
3611 add_jitter(&home->when);
3613 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3614 INSERT_EVENT(ping_home_server, home);
3617 static void home_trigger(home_server_t *home, char const *trigger)
3619 REQUEST *my_request;
3620 RADIUS_PACKET *my_packet;
3622 my_request = talloc_zero(NULL, REQUEST);
3623 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3624 my_request->proxy = my_packet;
3625 my_packet->dst_ipaddr = home->ipaddr;
3626 my_packet->src_ipaddr = home->src_ipaddr;
3628 exec_trigger(my_request, home->cs, trigger, false);
3629 talloc_free(my_request);
3632 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3639 rad_assert((home->state == HOME_STATE_ALIVE) ||
3640 (home->state == HOME_STATE_UNKNOWN));
3643 * We've received a real packet recently. Don't mark the
3644 * server as zombie until we've received NO packets for a
3645 * while. The "1/4" of zombie period was chosen rather
3646 * arbitrarily. It's a balance between too short, which
3647 * gives quick fail-over and fail-back, or too long,
3648 * where the proxy still sends packets to an unresponsive
3651 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3652 if (home->last_packet_recv >= start) {
3653 DEBUG("Received reply from home server %d seconds ago. Might not be zombie.",
3654 (int) (now->tv_sec - home->last_packet_recv));
3658 home->state = HOME_STATE_ZOMBIE;
3659 home_trigger(home, "home_server.zombie");
3662 * Set the home server to "zombie", as of the time
3665 home->zombie_period_start.tv_sec = start;
3666 home->zombie_period_start.tv_usec = USEC / 2;
3668 fr_event_delete(el, &home->ev);
3670 home->num_sent_pings = 0;
3671 home->num_received_pings = 0;
3673 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3674 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3675 buffer, sizeof(buffer)),
3676 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3678 ping_home_server(home);
3682 void revive_home_server(void *ctx)
3684 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3687 home->state = HOME_STATE_ALIVE;
3688 home->response_timeouts = 0;
3689 home_trigger(home, "home_server.alive");
3690 home->currently_outstanding = 0;
3691 gettimeofday(&home->revive_time, NULL);
3694 * Delete any outstanding events.
3697 if (home->ev) fr_event_delete(el, &home->ev);
3699 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3700 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3701 buffer, sizeof(buffer)),
3705 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3707 int previous_state = home->state;
3710 PROXY( "Marking home server %s port %d as dead.",
3711 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3712 buffer, sizeof(buffer)),
3715 home->state = HOME_STATE_IS_DEAD;
3716 home_trigger(home, "home_server.dead");
3718 if (home->ping_check != HOME_PING_CHECK_NONE) {
3720 * If the control socket marks us dead, start
3721 * pinging. Otherwise, we already started
3722 * pinging when it was marked "zombie".
3724 if (previous_state == HOME_STATE_ALIVE) {
3725 ping_home_server(home);
3727 DEBUG("PING: Already pinging home server %s", home->log_name);
3732 * Revive it after a fixed period of time. This
3733 * is very, very, bad.
3736 home->when.tv_sec += home->revive_interval;
3738 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3740 INSERT_EVENT(revive_home_server, home);
3744 /** Wait for a reply after proxying a request.
3746 * Retransmit the proxied packet, or time out and go to
3747 * proxy_no_reply. Mark the home server unresponsive, etc.
3749 * If we do receive a reply, we transition to proxy_running.
3752 * digraph proxy_wait_for_reply {
3753 * proxy_wait_for_reply;
3755 * proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3756 * proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3757 * proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3758 * proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3759 * proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3763 static void proxy_wait_for_reply(REQUEST *request, int action)
3765 struct timeval now, when;
3766 struct timeval *response_window = NULL;
3767 home_server_t *home = request->home_server;
3770 VERIFY_REQUEST(request);
3772 TRACE_STATE_MACHINE;
3775 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3776 rad_assert(request->home_server != NULL);
3778 gettimeofday(&now, NULL);
3783 * We have a reply, ignore the retransmit.
3785 if (request->proxy_reply) return;
3788 * The request was proxied to a virtual server.
3789 * Ignore the retransmit.
3791 if (request->home_server->server) return;
3794 * Use a new connection when the home server is
3795 * dead, or when there's no proxy listener, or
3796 * when the listener is failed or dead.
3798 * If the listener is known or frozen, use it for
3801 if ((home->state == HOME_STATE_IS_DEAD) ||
3802 !request->proxy_listener ||
3803 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3804 request_proxy_anew(request);
3810 * The home server is still alive, but TCP. We
3811 * rely on TCP to get the request and reply back.
3812 * So there's no need to retransmit.
3814 if (home->proto == IPPROTO_TCP) {
3815 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3816 inet_ntop(request->proxy->dst_ipaddr.af,
3817 &request->proxy->dst_ipaddr.ipaddr,
3818 buffer, sizeof(buffer)),
3819 request->proxy->dst_port,
3820 request->proxy->id);
3826 * More than one retransmit a second is stupid,
3827 * and should be suppressed by the proxy.
3829 when = request->proxy->timestamp;
3832 if (timercmp(&now, &when, <)) {
3833 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3834 inet_ntop(request->proxy->dst_ipaddr.af,
3835 &request->proxy->dst_ipaddr.ipaddr,
3836 buffer, sizeof(buffer)),
3837 request->proxy->dst_port,
3838 request->proxy->id);
3842 #ifdef WITH_ACCOUNTING
3844 * If we update the Acct-Delay-Time, we need to
3847 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3848 fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3849 request_proxy_anew(request);
3854 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3855 inet_ntop(request->proxy->dst_ipaddr.af,
3856 &request->proxy->dst_ipaddr.ipaddr,
3857 buffer, sizeof(buffer)),
3858 request->proxy->dst_port,
3859 request->proxy->id);
3860 request->num_proxied_requests++;
3862 rad_assert(request->proxy_listener != NULL);
3863 FR_STATS_TYPE_INC(home->stats.total_requests);
3864 home->last_packet_sent = now.tv_sec;
3865 request->proxy->timestamp = now;
3866 debug_packet(request, request->proxy, false);
3867 request->proxy_listener->send(request->proxy_listener, request);
3870 case FR_ACTION_TIMER:
3871 response_window = request_response_window(request);
3874 if (!request->proxy_listener ||
3875 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3876 remove_from_proxy_hash(request);
3878 when = request->packet->timestamp;
3879 when.tv_sec += request->root->max_request_time;
3881 if (timercmp(&when, &now, >)) {
3882 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3883 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3890 * Wake up "response_window" time in the future.
3891 * i.e. when MY packet hasn't received a response.
3893 * Note that we DO NOT mark the home server as
3894 * zombie if it doesn't respond to us. It may be
3895 * responding to other (better looking) packets.
3897 when = request->proxy->timestamp;
3898 timeradd(&when, response_window, &when);
3901 * Not at the response window. Set the timer for
3904 if (timercmp(&when, &now, >)) {
3905 struct timeval diff;
3906 timersub(&when, &now, &diff);
3908 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3909 (int) diff.tv_sec, (int) diff.tv_usec);
3910 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3915 RDEBUG("No proxy response, giving up on request and marking it done");
3918 * If we haven't received any packets for
3919 * "response_window", then mark the home server
3922 * This check should really be part of a home
3923 * server state machine.
3925 if (((home->state == HOME_STATE_ALIVE) ||
3926 (home->state == HOME_STATE_UNKNOWN))
3928 home->response_timeouts++;
3929 if (home->response_timeouts >= home->max_response_timeouts)
3930 mark_home_server_zombie(home, &now, response_window);
3933 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3934 if (home->type == HOME_TYPE_AUTH) {
3935 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3936 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3939 else if (home->type == HOME_TYPE_ACCT) {
3940 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3941 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3945 else if (home->type == HOME_TYPE_COA) {
3946 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3948 if (request->packet->code == PW_CODE_COA_REQUEST) {
3949 FR_STATS_TYPE_INC(proxy_coa_stats.total_timeouts);
3951 FR_STATS_TYPE_INC(proxy_dsc_stats.total_timeouts);
3957 * There was no response within the window. Stop
3958 * the request. If the client retransmitted, it
3959 * may have failed over to another home server.
3960 * But that one may be dead, too.
3962 * The extra verbose message if we have a username,
3963 * is extremely useful if the proxy is part of a chain
3964 * and the final home server, is not the one we're
3967 if (request->username) {
3968 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3969 "server %s port %d",
3970 request->username->vp_strvalue,
3971 inet_ntop(request->proxy->dst_ipaddr.af,
3972 &request->proxy->dst_ipaddr.ipaddr,
3973 buffer, sizeof(buffer)),
3974 request->proxy->dst_port);
3976 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3977 inet_ntop(request->proxy->dst_ipaddr.af,
3978 &request->proxy->dst_ipaddr.ipaddr,
3979 buffer, sizeof(buffer)),
3980 request->proxy->dst_port);
3983 if (setup_post_proxy_fail(request)) {
3984 request_queue_or_run(request, proxy_no_reply);
3986 gettimeofday(&request->reply->timestamp, NULL);
3987 request_cleanup_delay_init(request);
3992 * We received a new reply. Go process it.
3994 case FR_ACTION_PROXY_REPLY:
3995 request_queue_or_run(request, proxy_running);
3999 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4003 #endif /* WITH_PROXY */
4006 /***********************************************************************
4010 ***********************************************************************/
4012 static int null_handler(UNUSED REQUEST *request)
4018 * See if we need to originate a CoA request.
4020 static void request_coa_originate(REQUEST *request)
4022 int rcode, pre_proxy_type = 0;
4028 VERIFY_REQUEST(request);
4030 rad_assert(request->coa != NULL);
4031 rad_assert(request->proxy == NULL);
4032 rad_assert(!request->in_proxy_hash);
4033 rad_assert(request->proxy_reply == NULL);
4036 * Check whether we want to originate one, or cancel one.
4038 vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4040 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4044 if (vp->vp_integer == 0) {
4046 TALLOC_FREE(request->coa);
4051 if (!main_config.proxy_requests) {
4052 RWDEBUG("Cannot originate CoA packets unless 'proxy_requests = yes'");
4053 TALLOC_FREE(request->coa);
4060 * src_ipaddr will be set up in proxy_encode.
4062 memset(&ipaddr, 0, sizeof(ipaddr));
4063 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4065 ipaddr.af = AF_INET;
4066 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4068 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4069 ipaddr.af = AF_INET6;
4070 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4071 ipaddr.prefix = 128;
4072 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4073 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4075 if (!coa->home_pool) {
4076 RWDEBUG2("No such home_server_pool %s",
4082 * Prefer the pool to one server
4084 } else if (request->client->coa_pool) {
4085 coa->home_pool = request->client->coa_pool;
4087 } else if (request->client->coa_server) {
4088 coa->home_server = request->client->coa_server;
4092 * If all else fails, send it to the client that
4093 * originated this request.
4095 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4099 * Use the pool, if it exists.
4101 if (coa->home_pool) {
4102 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4103 if (!coa->home_server) {
4104 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4107 home_server_update_request(coa->home_server, coa);
4109 } else if (!coa->home_server) {
4110 uint16_t port = PW_COA_UDP_PORT;
4112 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4113 if (vp) port = vp->vp_integer;
4115 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4116 if (!coa->home_server) {
4117 RWDEBUG2("Unknown destination %s:%d for CoA request.",
4118 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4119 buffer, sizeof(buffer)), port);
4124 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4126 switch (vp->vp_integer) {
4127 case PW_CODE_COA_REQUEST:
4128 case PW_CODE_DISCONNECT_REQUEST:
4129 coa->proxy->code = vp->vp_integer;
4133 DEBUG("Cannot set CoA Packet-Type to code %d",
4139 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4142 * The rest of the server code assumes that
4143 * request->packet && request->reply exist. Copy them
4144 * from the original request.
4146 rad_assert(coa->packet != NULL);
4147 rad_assert(coa->packet->vps == NULL);
4149 coa->packet = rad_copy_packet(coa, request->packet);
4150 coa->reply = rad_copy_packet(coa, request->reply);
4152 coa->config = fr_pair_list_copy(coa, request->config);
4153 coa->num_coa_requests = 0;
4154 coa->handle = null_handler;
4155 coa->number = request->number; /* it's associated with the same request */
4158 * Call the pre-proxy routines.
4160 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4162 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4163 /* Must be a validation issue */
4165 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4166 pre_proxy_type = vp->vp_integer;
4169 if (coa->home_pool && coa->home_pool->virtual_server) {
4170 char const *old_server = coa->server;
4172 coa->server = coa->home_pool->virtual_server;
4173 RDEBUG2("server %s {", coa->server);
4175 rcode = process_pre_proxy(pre_proxy_type, coa);
4178 coa->server = old_server;
4180 rcode = process_pre_proxy(pre_proxy_type, coa);
4187 * Only send the CoA packet if the pre-proxy code succeeded.
4189 case RLM_MODULE_NOOP:
4191 case RLM_MODULE_UPDATED:
4196 * Source IP / port is set when the proxy socket
4199 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4200 coa->proxy->dst_port = coa->home_server->port;
4202 if (!insert_into_proxy_hash(coa)) {
4203 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4208 * We CANNOT divorce the CoA request from the parent
4209 * request. This function is running in a child thread,
4210 * and we need access to the main event loop in order to
4211 * to add the timers for the CoA packet.
4213 * Instead, we wait for the timer on the parent request
4216 gettimeofday(&coa->proxy->timestamp, NULL);
4217 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4218 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4219 coa->delay = 0; /* need to calculate a new delay */
4222 * If requested, put a State attribute into the packet,
4223 * and cache the VPS.
4225 fr_state_put_vps(coa, NULL, coa->packet);
4228 * Encode the packet before we do anything else.
4230 coa->proxy_listener->encode(coa->proxy_listener, coa);
4231 debug_packet(coa, coa->proxy, false);
4233 #ifdef DEBUG_STATE_MACHINE
4234 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4235 child_state_names[request->child_state],
4236 child_state_names[REQUEST_PROXIED]);
4240 * Set the state function, then the state, no child, and
4243 coa->process = coa_wait_for_reply;
4244 coa->child_state = REQUEST_PROXIED;
4246 #ifdef HAVE_PTHREAD_H
4247 coa->child_pid = NO_SUCH_CHILD_PID;
4250 if (we_are_master()) coa_separate(request->coa);
4253 * And send the packet.
4255 coa->proxy_listener->send(coa->proxy_listener, coa);
4259 static void coa_retransmit(REQUEST *request)
4261 uint32_t delay, frac;
4262 struct timeval now, when, mrd;
4265 VERIFY_REQUEST(request);
4267 fr_event_now(el, &now);
4269 if (request->delay == 0) {
4271 * Implement re-transmit algorithm as per RFC 5080
4274 * We want IRT + RAND*IRT
4275 * or 0.9 IRT + rand(0,.2) IRT
4277 * 2^20 ~ USEC, and we want 2.
4278 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4280 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4281 request->delay = delay * request->home_server->coa_irt;
4282 delay = request->home_server->coa_irt * USEC;
4283 delay -= delay / 10;
4284 delay += request->delay;
4285 request->delay = delay;
4287 when = request->proxy->timestamp;
4288 tv_add(&when, delay);
4290 if (timercmp(&when, &now, >)) {
4291 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4297 * Retransmit CoA request.
4301 * Cap count at MRC, if it is non-zero.
4303 if (request->home_server->coa_mrc &&
4304 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4305 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4307 inet_ntop(request->proxy->dst_ipaddr.af,
4308 &request->proxy->dst_ipaddr.ipaddr,
4309 buffer, sizeof(buffer)),
4310 request->proxy->dst_port);
4312 if (setup_post_proxy_fail(request)) {
4313 request_queue_or_run(request, coa_no_reply);
4315 request_done(request, FR_ACTION_DONE);
4321 * RFC 5080 Section 2.2.1
4323 * RT = 2*RTprev + RAND*RTprev
4324 * = 1.9 * RTprev + rand(0,.2) * RTprev
4325 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4328 delay ^= (delay >> 16);
4330 frac = request->delay / 5;
4331 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4333 delay += (2 * request->delay) - (request->delay / 10);
4336 * Cap delay at MRT, if MRT is non-zero.
4338 if (request->home_server->coa_mrt &&
4339 (delay > (request->home_server->coa_mrt * USEC))) {
4340 int mrt_usec = request->home_server->coa_mrt * USEC;
4343 * delay = MRT + RAND * MRT
4344 * = 0.9 MRT + rand(0,.2) * MRT
4347 delay ^= (delay >> 15);
4349 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4350 delay += mrt_usec - (mrt_usec / 10);
4353 request->delay = delay;
4355 tv_add(&when, request->delay);
4356 mrd = request->proxy->timestamp;
4357 mrd.tv_sec += request->home_server->coa_mrd;
4360 * Cap duration at MRD.
4362 if (timercmp(&mrd, &when, <)) {
4365 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4367 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4369 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4371 RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4372 inet_ntop(request->proxy->dst_ipaddr.af,
4373 &request->proxy->dst_ipaddr.ipaddr,
4374 buffer, sizeof(buffer)),
4375 request->proxy->dst_port,
4376 request->proxy->id);
4378 request->proxy_listener->send(request->proxy_listener,
4383 /** Wait for a reply after originating a CoA a request.
4385 * Retransmit the proxied packet, or time out and go to
4386 * coa_no_reply. Mark the home server unresponsive, etc.
4388 * If we do receive a reply, we transition to coa_running.
4391 * digraph coa_wait_for_reply {
4392 * coa_wait_for_reply;
4394 * coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4395 * coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4396 * coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4397 * coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4401 static void coa_wait_for_reply(REQUEST *request, int action)
4403 VERIFY_REQUEST(request);
4405 TRACE_STATE_MACHINE;
4409 if (request->parent) coa_separate(request);
4412 case FR_ACTION_TIMER:
4413 if (request_max_time(request)) break;
4416 * Don't do fail-over. This is a 3.1 feature.
4418 if (!request->home_server ||
4419 (request->home_server->state == HOME_STATE_IS_DEAD) ||
4420 !request->proxy_listener ||
4421 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
4422 request_done(request, FR_ACTION_DONE);
4426 coa_retransmit(request);
4429 case FR_ACTION_PROXY_REPLY:
4430 request_queue_or_run(request, coa_running);
4434 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4439 static void coa_separate(REQUEST *request)
4441 VERIFY_REQUEST(request);
4442 #ifdef DEBUG_STATE_MACHINE
4443 int action = FR_ACTION_TIMER;
4446 TRACE_STATE_MACHINE;
4449 rad_assert(request->parent != NULL);
4450 rad_assert(request->parent->coa == request);
4451 rad_assert(request->ev == NULL);
4452 rad_assert(!request->in_request_hash);
4453 rad_assert(request->coa == NULL);
4455 rad_assert(request->proxy_reply || request->proxy_listener);
4457 (void) talloc_steal(NULL, request);
4458 request->parent->coa = NULL;
4459 request->parent = NULL;
4461 if (we_are_master()) {
4463 coa_retransmit(request);
4468 /** Process a request after the CoA has timed out.
4470 * Run the packet through Post-Proxy-Type Fail
4473 * digraph coa_no_reply {
4476 * coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4477 * coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4478 * coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4479 * coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4480 * coa_no_reply -> done [ label = "TIMER >= timeout" ];
4484 static void coa_no_reply(REQUEST *request, int action)
4488 VERIFY_REQUEST(request);
4490 TRACE_STATE_MACHINE;
4494 case FR_ACTION_TIMER:
4495 (void) request_max_time(request);
4498 case FR_ACTION_PROXY_REPLY: /* too late! */
4499 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4500 inet_ntop(request->proxy->src_ipaddr.af,
4501 &request->proxy->src_ipaddr.ipaddr,
4502 buffer, sizeof(buffer)),
4503 request->proxy->dst_port, request->proxy->id);
4507 if (process_proxy_reply(request, NULL)) {
4508 request->handle(request);
4510 request_done(request, FR_ACTION_DONE);
4514 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4520 /** Process the request after receiving a coa reply.
4522 * Throught the post-proxy section, and the through the handler
4526 * digraph coa_running {
4529 * coa_running -> timer [ label = "TIMER < max_request_time" ];
4530 * coa_running -> process_proxy_reply [ label = "RUN" ];
4531 * coa_running -> done [ label = "TIMER >= timeout" ];
4535 static void coa_running(REQUEST *request, int action)
4537 VERIFY_REQUEST(request);
4539 TRACE_STATE_MACHINE;
4543 case FR_ACTION_TIMER:
4544 (void) request_max_time(request);
4548 if (process_proxy_reply(request, request->proxy_reply)) {
4549 request->handle(request);
4551 request_done(request, FR_ACTION_DONE);
4555 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4559 #endif /* WITH_COA */
4561 /***********************************************************************
4563 * End of the State machine. Start of additional helper code.
4565 ***********************************************************************/
4567 /***********************************************************************
4571 ***********************************************************************/
4572 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4574 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4576 rad_assert(xel == el);
4578 if ((listener->fd < 0)
4580 #ifndef WITH_DETAIL_THREAD
4581 && (listener->type != RAD_LISTEN_DETAIL)
4587 listener->print(listener, buffer, sizeof(buffer));
4588 ERROR("FATAL: Asked to read from closed socket: %s",
4591 rad_panic("Socket was closed on us!");
4595 listener->recv(listener);
4599 #ifdef WITH_DETAIL_THREAD
4602 * This function is called periodically to see if this detail
4603 * file is available for reading.
4605 static void event_poll_detail(void *ctx)
4608 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4609 struct timeval when, now;
4610 listen_detail_t *detail = this->data;
4612 rad_assert(this->type == RAD_LISTEN_DETAIL);
4615 event_socket_handler(el, this->fd, this);
4617 fr_event_now(el, &now);
4621 * Backdoor API to get the delay until the next poll
4624 delay = this->encode(this, NULL);
4625 if (delay == 0) goto redo;
4627 tv_add(&when, delay);
4630 if (!fr_event_insert(el, event_poll_detail, this,
4631 &when, &detail->ev)) {
4632 ERROR("Failed creating handler");
4636 #endif /* WITH_DETAIL_THREAD */
4637 #endif /* WITH_DETAIL */
4639 static void event_status(struct timeval *wake)
4641 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4645 if (rad_debug_lvl == 0) {
4647 INFO("Ready to process requests");
4648 just_started = false;
4654 INFO("Ready to process requests");
4656 } else if ((wake->tv_sec != 0) ||
4657 (wake->tv_usec >= 100000)) {
4658 DEBUG("Waking up in %d.%01u seconds.",
4659 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4664 * FIXME: Put this somewhere else, where it isn't called
4665 * all of the time...
4668 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4670 * If there are no child threads, then there may
4671 * be child processes. In that case, wait for
4672 * their exit status, and throw that exit status
4673 * away. This helps get rid of zxombie children.
4675 while (waitpid(-1, &argval, WNOHANG) > 0) {
4683 static void listener_free_cb(void *ctx)
4685 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4688 if (this->count > 0) {
4689 struct timeval when;
4690 listen_socket_t *sock = this->data;
4692 fr_event_now(el, &when);
4696 if (!fr_event_insert(el, listener_free_cb, this, &when,
4698 rad_panic("Failed to insert event");
4705 * It's all free, close the socket.
4708 this->print(this, buffer, sizeof(buffer));
4709 DEBUG("... cleaning up socket %s", buffer);
4710 rad_assert(this->next == NULL);
4715 static int proxy_eol_cb(void *ctx, void *data)
4717 struct timeval when;
4718 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4720 if (request->proxy_listener != ctx) return 0;
4723 * We don't care if it's being processed in a child thread.
4726 #ifdef WITH_ACCOUNTING
4728 * Accounting packets should be deleted immediately.
4729 * They will never be retransmitted by the client.
4731 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4732 RDEBUG("Stopping request due to failed connection to home server");
4733 request->master_state = REQUEST_STOP_PROCESSING;
4738 * Reset the timer to be now, so that the request is
4739 * quickly updated. But spread the requests randomly
4740 * over the next second, so that we don't overload the
4743 fr_event_now(el, &when);
4744 tv_add(&when, fr_rand() % USEC);
4745 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4748 * Don't delete it from the list.
4752 #endif /* WITH_PROXY */
4753 #endif /* WITH_TCP */
4755 static int event_new_fd(rad_listen_t *this)
4761 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4763 this->print(this, buffer, sizeof(buffer));
4765 if (this->status == RAD_LISTEN_STATUS_INIT) {
4766 listen_socket_t *sock = this->data;
4768 rad_assert(sock != NULL);
4770 DEBUG("Listening on %s", buffer);
4772 INFO(" ... adding new socket %s", buffer);
4776 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4777 home_server_t *home;
4780 if (!home || !home->limit.max_connections) {
4781 INFO(" ... adding new socket %s", buffer);
4783 INFO(" ... adding new socket %s (%u of %u)", buffer,
4784 home->limit.num_connections, home->limit.max_connections);
4790 switch (this->type) {
4793 * Detail files are always known, and aren't
4794 * put into the socket event loop.
4796 case RAD_LISTEN_DETAIL:
4797 this->status = RAD_LISTEN_STATUS_KNOWN;
4799 #ifndef WITH_DETAIL_THREAD
4801 * Set up the first poll interval.
4803 event_poll_detail(this);
4806 break; /* add the FD to the list */
4808 #endif /* WITH_DETAIL */
4812 * Add it to the list of sockets we can use.
4813 * Server sockets (i.e. auth/acct) are never
4814 * added to the packet list.
4816 case RAD_LISTEN_PROXY:
4818 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4821 * Add timers to outgoing child sockets, if necessary.
4823 if (sock->proto == IPPROTO_TCP && sock->opened &&
4824 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4825 struct timeval when;
4827 when.tv_sec = sock->opened + 1;
4831 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4833 rad_panic("Failed to insert event");
4836 #endif /* WITH_TCP */
4838 #endif /* WITH_PROXY */
4841 * FIXME: put idle timers on command sockets.
4847 * Add timers to incoming child sockets, if necessary.
4849 if (sock->proto == IPPROTO_TCP && sock->opened &&
4850 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4851 struct timeval when;
4853 when.tv_sec = sock->opened + 1;
4857 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4859 ERROR("Failed adding timer for socket: %s", fr_strerror());
4863 #endif /* WITH_TCP */
4865 } /* switch over listener types */
4868 * All sockets: add the FD to the event handler.
4870 if (!fr_event_fd_insert(el, 0, this->fd,
4871 event_socket_handler, this)) {
4872 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4876 this->status = RAD_LISTEN_STATUS_KNOWN;
4882 * The socket has reached a timeout. Try to close it.
4884 if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4886 * Requests are still using the socket. Wait for
4889 if (this->count > 0) {
4890 struct timeval when;
4891 listen_socket_t *sock = this->data;
4894 * Try again to clean up the socket in 30
4897 gettimeofday(&when, NULL);
4901 if (!fr_event_insert(el,
4902 (fr_event_callback_t) event_new_fd,
4903 this, &when, &sock->ev)) {
4904 rad_panic("Failed to insert event");
4910 fr_event_fd_delete(el, 0, this->fd);
4911 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4915 * The socket has had a catastrophic error. Close it.
4917 if (this->status == RAD_LISTEN_STATUS_EOL) {
4919 * Remove it from the list of live FD's.
4921 fr_event_fd_delete(el, 0, this->fd);
4925 * Tell all requests using this socket that the socket is dead.
4927 if (this->type == RAD_LISTEN_PROXY) {
4928 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4929 if (!fr_packet_list_socket_freeze(proxy_list,
4931 ERROR("Fatal error freezing socket: %s", fr_strerror());
4935 if (this->count > 0) {
4936 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4938 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4940 #endif /* WITH_PROXY */
4943 * Requests are still using the socket. Wait for
4946 if (this->count > 0) {
4947 struct timeval when;
4948 listen_socket_t *sock = this->data;
4951 * Try again to clean up the socket in 30
4954 gettimeofday(&when, NULL);
4958 if (!fr_event_insert(el,
4959 (fr_event_callback_t) event_new_fd,
4960 this, &when, &sock->ev)) {
4961 rad_panic("Failed to insert event");
4968 * No one is using the socket. We can remove it now.
4970 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4971 } /* socket is at EOL */
4972 #endif /* WITH_TCP */
4977 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4980 listen_socket_t *sock = this->data;
4981 struct timeval when;
4985 * Re-open the socket, pointing it to /dev/null.
4986 * This means that all writes proceed without
4987 * blocking, and all reads return "no data".
4989 * This leaves the socket active, so any child
4990 * threads won't go insane. But it means that
4991 * they cannot send or receive any packets.
4993 * This is EXTRA work in the normal case, when
4994 * sockets are closed without error. But it lets
4995 * us have one simple processing method for all
4998 devnull = open("/dev/null", O_RDWR);
5000 ERROR("FATAL failure opening /dev/null: %s",
5001 fr_syserror(errno));
5004 if (dup2(devnull, this->fd) < 0) {
5005 ERROR("FATAL failure closing socket: %s",
5006 fr_syserror(errno));
5012 rad_assert(this->type != RAD_LISTEN_DETAIL);
5018 * The socket is dead. Force all proxied packets
5019 * to stop using it. And then remove it from the
5020 * list of outgoing sockets.
5022 if (this->type == RAD_LISTEN_PROXY) {
5023 home_server_t *home;
5026 if (!home || !home->limit.max_connections) {
5027 INFO(" ... shutting down socket %s", buffer);
5029 INFO(" ... shutting down socket %s (%u of %u)", buffer,
5030 home->limit.num_connections, home->limit.max_connections);
5033 PTHREAD_MUTEX_LOCK(&proxy_mutex);
5034 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
5036 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
5037 ERROR("Fatal error removing socket %s: %s",
5038 buffer, fr_strerror());
5041 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
5043 #endif /* WITH_PROXY */
5045 INFO(" ... shutting down socket %s", buffer);
5048 * EOL all requests using this socket.
5050 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
5054 * No child threads, clean it up now.
5058 if (sock->ev) fr_event_delete(el, &sock->ev);
5064 * Wait until all requests using this socket are done.
5066 gettimeofday(&when, NULL);
5070 if (!fr_event_insert(el, listener_free_cb, this, &when,
5072 rad_panic("Failed to insert event");
5074 #endif /* WITH_TCP */
5080 /***********************************************************************
5084 ***********************************************************************/
5086 static void handle_signal_self(int flag)
5090 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5091 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5092 INFO("Signalled to exit");
5093 fr_event_loop_exit(el, 1);
5095 INFO("Signalled to terminate");
5096 fr_event_loop_exit(el, 2);
5100 } /* else exit/term flags weren't set */
5103 * Tell the even loop to stop processing.
5105 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5107 static time_t last_hup = 0;
5110 if ((int) (when - last_hup) < 5) {
5111 INFO("Ignoring HUP (less than 5s since last one)");
5115 INFO("Received HUP signal");
5119 exec_trigger(NULL, NULL, "server.signal.hup", true);
5120 fr_event_loop_exit(el, 0x80);
5123 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5124 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5128 * FIXME: O(N) loops suck.
5130 for (this = main_config.listen;
5132 this = this->next) {
5133 if (this->type != RAD_LISTEN_DETAIL) continue;
5136 * This one didn't send the signal, skip
5139 if (!this->decode(this, NULL)) continue;
5142 * Go service the interrupt.
5144 event_poll_detail(this);
5149 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5151 * There are new listeners in the list. Run
5152 * event_new_fd() on them.
5154 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5155 rad_listen_t *this, *next;
5157 FD_MUTEX_LOCK(&fd_mutex);
5160 * FIXME: unlock the mutex before calling
5163 for (this = new_listeners; this != NULL; this = next) {
5170 new_listeners = NULL;
5171 FD_MUTEX_UNLOCK(&fd_mutex);
5176 #ifndef HAVE_PTHREAD_H
5177 void radius_signal_self(int flag)
5179 if (flag == RADIUS_SIGNAL_SELF_TERM) {
5180 main_config.exiting = true;
5183 return handle_signal_self(flag);
5187 static int self_pipe[2] = { -1, -1 };
5190 * Inform ourselves that we received a signal.
5192 void radius_signal_self(int flag)
5197 if (flag == RADIUS_SIGNAL_SELF_TERM) {
5198 main_config.exiting = true;
5202 * The read MUST be non-blocking for this to work.
5204 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5208 for (i = 0; i < rcode; i++) {
5209 buffer[0] |= buffer[i];
5217 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5221 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5222 UNUSED int fd, UNUSED void *ctx)
5227 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5228 if (rcode <= 0) return;
5231 * Merge pending signals.
5233 for (i = 0; i < rcode; i++) {
5234 buffer[0] |= buffer[i];
5237 handle_signal_self(buffer[0]);
5239 #endif /* HAVE_PTHREAD_H */
5241 /***********************************************************************
5243 * Bootstrapping code.
5245 ***********************************************************************/
5248 * Externally-visibly functions.
5250 int radius_event_init(TALLOC_CTX *ctx) {
5251 el = fr_event_list_create(ctx, event_status);
5257 static int packet_entry_cmp(void const *one, void const *two)
5259 RADIUS_PACKET const * const *a = one;
5260 RADIUS_PACKET const * const *b = two;
5262 return fr_packet_cmp(*a, *b);
5267 * They haven't defined a proxy listener. Automatically
5268 * add one for them, with the correct address family.
5270 static void create_default_proxy_listener(int af)
5274 listen_socket_t *sock;
5277 memset(&home, 0, sizeof(home));
5280 * Open a default UDP port
5282 home.proto = IPPROTO_UDP;
5286 * Set the address family.
5288 home.src_ipaddr.af = af;
5289 home.ipaddr.af = af;
5292 * Get the correct listener.
5294 this = proxy_new_listener(proxy_ctx, &home, port);
5300 if (!fr_packet_list_socket_add(proxy_list, this->fd,
5302 &sock->other_ipaddr, sock->other_port,
5304 ERROR("Failed adding proxy socket");
5309 * Insert the FD into list of FDs to listen on.
5311 radius_update_listener(this);
5315 * See if we automatically need to open a proxy socket.
5317 static void check_proxy(rad_listen_t *head)
5320 bool has_v4, has_v6;
5323 if (check_config) return;
5324 if (!main_config.proxy_requests) return;
5326 if (!home_servers_udp) return;
5329 * We passed "-i" on the command line. Use that address
5330 * family for the proxy socket.
5332 if (main_config.myip.af != AF_UNSPEC) {
5333 create_default_proxy_listener(main_config.myip.af);
5337 defined_proxy = has_v4 = has_v6 = false;
5340 * Figure out if we need to open a proxy socket, and if
5343 for (this = head; this != NULL; this = this->next) {
5344 listen_socket_t *sock;
5346 switch (this->type) {
5347 case RAD_LISTEN_PROXY:
5348 defined_proxy = true;
5351 case RAD_LISTEN_AUTH:
5353 case RAD_LISTEN_ACCT:
5356 case RAD_LISTEN_COA:
5359 if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5360 if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5369 * Assume they know what they're doing.
5371 if (defined_proxy) return;
5373 if (has_v4) create_default_proxy_listener(AF_INET);
5375 if (has_v6) create_default_proxy_listener(AF_INET6);
5379 int radius_event_start(CONF_SECTION *cs, bool have_children)
5381 rad_listen_t *head = NULL;
5383 if (fr_start_time != (time_t)-1) return 0;
5385 time(&fr_start_time);
5387 if (!check_config) {
5389 * radius_event_init() must be called first
5393 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5394 if (!pl) return 0; /* leak el */
5397 request_num_counter = 0;
5400 if (main_config.proxy_requests && !check_config) {
5402 * Create the tree for managing proxied requests and
5405 proxy_list = fr_packet_list_create(1);
5406 if (!proxy_list) return 0;
5408 #ifdef HAVE_PTHREAD_H
5409 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5410 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5411 fr_syserror(errno));
5417 * The "init_delay" is set to "response_window".
5418 * Reset it to half of "response_window" in order
5419 * to give the event loop enough time to service
5420 * the event before hitting "response_window".
5422 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5423 main_config.init_delay.tv_usec >>= 1;
5424 main_config.init_delay.tv_sec >>= 1;
5426 proxy_ctx = talloc_init("proxy");
5431 * Move all of the thread calls to this file?
5433 * It may be best for the mutexes to be in this file...
5435 spawn_flag = have_children;
5437 #ifdef HAVE_PTHREAD_H
5438 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5441 * Initialize the threads ONLY if we're spawning, AND
5442 * we're running normally.
5444 if (have_children && !check_config &&
5445 (thread_pool_init(cs, &spawn_flag) < 0)) {
5451 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5453 if (listen_init(cs, &head, spawn_flag) < 0) {
5460 #ifdef HAVE_PTHREAD_H
5462 * Child threads need a pipe to signal us, as do the
5465 if (pipe(self_pipe) < 0) {
5466 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5469 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5470 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5471 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5474 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5475 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5476 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5479 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5481 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5482 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5487 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5490 * The server temporarily switches to an unprivileged
5491 * user very early in the bootstrapping process.
5492 * However, some sockets MAY require privileged access
5493 * (bind to device, or to port < 1024, or to raw
5494 * sockets). Those sockets need to call suid up/down
5495 * themselves around the functions that need a privileged
5498 if (listen_init(cs, &head, spawn_flag) < 0) {
5502 main_config.listen = head;
5509 * At this point, no one has any business *ever* going
5512 rad_suid_down_permanent();
5519 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5521 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5523 VERIFY_REQUEST(request);
5525 request->master_state = REQUEST_STOP_PROCESSING;
5527 #ifdef HAVE_PTHREAD_H
5528 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5532 * If it's queued we can't delete it from the queue.
5534 * Otherwise, it's OK to delete it. Even RUNNING, because
5535 * that will get caught by the check above.
5537 if (request->child_state == REQUEST_QUEUED) return 0;
5539 request->in_proxy_hash = false;
5541 if (!request->in_request_hash) {
5542 request_done(request, FR_ACTION_DONE);
5546 * Delete it from the list.
5553 static int request_delete_cb(UNUSED void *ctx, void *data)
5555 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5557 VERIFY_REQUEST(request);
5559 request->master_state = REQUEST_STOP_PROCESSING;
5562 * Not done, or the child thread is still processing it.
5564 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5566 #ifdef HAVE_PTHREAD_H
5567 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5571 rad_assert(request->in_proxy_hash == false);
5574 request->in_request_hash = false;
5576 if (request->ev) fr_event_delete(el, &request->ev);
5578 if (main_config.memory_report) {
5579 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5580 request->packet->id,
5581 (unsigned int) (request->timestamp - fr_start_time));
5586 rad_assert(!request->coa->in_proxy_hash);
5590 request_free(request);
5593 * Delete it from the list, and continue;
5599 void radius_event_free(void)
5605 * There are requests in the proxy hash that aren't
5606 * referenced from anywhere else. Remove them first.
5609 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5613 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5617 * Now that all requests have been marked "please stop",
5618 * ensure that all of the threads have exited.
5620 #ifdef HAVE_PTHREAD_H
5625 * Walk the lists again, ensuring that all
5626 * requests are done.
5628 if (main_config.memory_report) {
5633 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5634 num = fr_packet_list_num_elements(proxy_list);
5636 ERROR("Proxy list has %d requests still in it.", num);
5641 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5642 num = rbtree_num_elements(pl);
5644 ERROR("Request list has %d requests still in it.", num);
5653 fr_packet_list_free(proxy_list);
5656 if (proxy_ctx) talloc_free(proxy_ctx);
5661 if (debug_condition) talloc_free(debug_condition);
5664 int radius_event_process(void)
5668 return fr_event_loop(el);