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 (debug_flag) do { \
75 struct timeval debug_tv; \
76 gettimeofday(&debug_tv, NULL); \
77 debug_tv.tv_sec -= fr_start_time; \
78 printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79 request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80 __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81 child_state_names[request->child_state]); \
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 /** Declare a state in the state machine
107 * Expands to the start of a function definition for a given state.
109 * @param _x the name of the state.
111 #define STATE_MACHINE_DECL(_x) static void CC_HINT(nonnull) _x(REQUEST *request, int action)
113 static void request_timer(void *ctx);
115 /** Insert #REQUEST back into the event heap, to continue executing at a future time
117 * @param request to set add the timer event for.
118 * @param when the event should fine.
119 * @param action to perform when we resume processing the request.
121 static inline void state_machine_timer(REQUEST *request, struct timeval *when, fr_state_action_t *action)
123 request->timer_action = action;
124 fr_event_insert(el, request_timer, request, when, &request->ev);
127 /** @copybrief state_machine_timer
129 * @param _x the action to perform when we resume processing the request.
131 #define STATE_MACHINE_TIMER(_x) state_machine_timer(request, &when, _x)
134 * We need a different VERIFY_REQUEST macro in process.c
135 * To avoid the race conditions with the master thread
136 * checking the REQUEST whilst it's being worked on by
139 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
140 # undef VERIFY_REQUEST
141 # define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
145 * @section request_timeline
147 * Time sequence of a request
150 * RQ-----------------P=============================Y-J-C
151 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
154 * - R: received. Duplicate detection is done, and request is
157 * - Q: Request is placed onto a queue for child threads to pick up.
158 * If there are no child threads, the request goes immediately
161 * - P: Processing the request through the modules.
163 * - Y: Reply is ready. Rejects MAY be delayed here. All other
164 * replies are sent immediately.
166 * - J: Reject is sent "response_delay" after the reply is ready.
168 * - C: For Access-Requests, After "cleanup_delay", the request is
169 * deleted. Accounting-Request packets go directly from Y to C.
171 * - M: Max request time. If the request hits this timer, it is
174 * Other considerations include duplicate and conflicting
175 * packets. When a dupicate packet is received, it is ignored
176 * until we've reached Y, as no response is ready. If the reply
177 * is a reject, duplicates are ignored until J, when we're ready
178 * to send the reply. In between the reply being sent (Y or J),
179 * and C, the server responds to duplicates by sending the cached
182 * Conflicting packets are sent in 2 situations.
184 * The first is in between R and Y. In that case, we consider
185 * it as a hint that we're taking too long, and the NAS has given
186 * up on the request. We then behave just as if the M timer was
187 * reached, and we discard the current request. This allows us
188 * to process the new one.
190 * The second case is when we're at Y, but we haven't yet
191 * finished processing the request. This is a race condition in
192 * the threading code (avoiding locks is faster). It means that
193 * a thread has actually encoded and sent the reply, and that the
194 * NAS has responded with a new packet. The server can then
195 * safely mark the current request as "OK to delete", and behaves
196 * just as if the M timer was reached. This usually happens only
197 * in high-load situations.
199 * Duplicate packets are sent when the NAS thinks we're taking
200 * too long, and wants a reply. From R-Y, duplicates are
201 * ignored. From Y-J (for Access-Rejects), duplicates are also
202 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
203 * they cause the "cleanup_delay" time to be extended. This
204 * extension means that we're more likely to send a duplicate
205 * reply (if we have one), or to suppress processing the packet
206 * twice if we didn't reply to it.
208 * All functions in this file should be thread-safe, and should
209 * assume thet the REQUEST structure is being accessed
210 * simultaneously by the main thread, and by the child worker
211 * threads. This means that timers, etc. cannot be updated in
214 * Instead, the master thread periodically calls request->process
215 * with action TIMER. It's up to the individual functions to
216 * determine how to handle that. They need to check if they're
217 * being called from a child thread or the master, and then do
218 * different things based on that.
221 static fr_packet_list_t *proxy_list = NULL;
222 static TALLOC_CTX *proxy_ctx = NULL;
225 #ifdef HAVE_PTHREAD_H
227 static pthread_mutex_t proxy_mutex;
228 static bool proxy_no_new_sockets = false;
231 # define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
232 # define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
234 static pthread_t NO_SUCH_CHILD_PID;
235 # define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
239 * This is easier than ifdef's throughout the code.
241 # define PTHREAD_MUTEX_LOCK(_x)
242 # define PTHREAD_MUTEX_UNLOCK(_x)
243 # define NO_CHILD_THREAD
246 #ifdef HAVE_PTHREAD_H
247 static bool we_are_master(void)
250 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
258 * Assertions are debug checks.
261 # define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
266 * No threads: we're always master.
268 # define we_are_master(_x) (1)
269 #endif /* HAVE_PTHREAD_H */
271 #ifndef ASSERT_MASTER
272 # define ASSERT_MASTER
275 static int event_new_fd(rad_listen_t *this);
278 * We need mutexes around the event FD list *only* in certain
281 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
282 static rad_listen_t *new_listeners = NULL;
284 static pthread_mutex_t fd_mutex;
285 # define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
286 # define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
288 void radius_update_listener(rad_listen_t *this)
291 * Just do it ourselves.
293 if (we_are_master()) {
298 FD_MUTEX_LOCK(&fd_mutex);
301 * If it's already in the list, don't add it again.
304 FD_MUTEX_UNLOCK(&fd_mutex);
309 * Otherwise, add it to the list
311 this->next = new_listeners;
312 new_listeners = this;
313 FD_MUTEX_UNLOCK(&fd_mutex);
314 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
317 void radius_update_listener(rad_listen_t *this)
320 * No threads. Just insert it.
325 * This is easier than ifdef's throughout the code.
327 # define FD_MUTEX_LOCK(_x)
328 # define FD_MUTEX_UNLOCK(_x)
331 static int request_num_counter = 1;
333 static int request_will_proxy(REQUEST *request);
334 static int request_proxy(REQUEST *request, int retransmit);
335 STATE_MACHINE_DECL(proxy_wait_for_reply);
336 STATE_MACHINE_DECL(proxy_no_reply);
337 STATE_MACHINE_DECL(proxy_running);
338 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply);
339 static void remove_from_proxy_hash(REQUEST *request);
340 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank);
341 static int insert_into_proxy_hash(REQUEST *request);
344 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
345 RADCLIENT *client, RAD_REQUEST_FUNP fun);
347 STATE_MACHINE_DECL(request_response_delay);
348 STATE_MACHINE_DECL(request_cleanup_delay);
349 STATE_MACHINE_DECL(request_running);
351 static void request_coa_originate(REQUEST *request);
352 STATE_MACHINE_DECL(coa_running);
353 STATE_MACHINE_DECL(coa_wait_for_reply);
354 STATE_MACHINE_DECL(coa_no_reply);
355 static void coa_separate(REQUEST *request);
356 #define COA_SEPARATE if (request->coa) coa_separate(request->coa);
361 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
364 #define USEC (1000000)
366 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
368 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
370 ERROR("[%s:%d] %s", file, line, msg);
377 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
379 static void tv_add(struct timeval *tv, int usec_delay)
381 if (usec_delay >= USEC) {
382 tv->tv_sec += usec_delay / USEC;
385 tv->tv_usec += usec_delay;
387 if (tv->tv_usec >= USEC) {
388 tv->tv_sec += tv->tv_usec / USEC;
394 * Debug the packet if requested.
396 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
398 char src_ipaddr[128];
399 char dst_ipaddr[128];
402 if (!RDEBUG_ENABLED) return;
405 * Client-specific debugging re-prints the input
406 * packet into the client log.
408 * This really belongs in a utility library
410 if (is_radius_code(packet->code)) {
411 RDEBUG("%s %s Id %i from %s:%i to %s:%i length %zu",
412 received ? "Received" : "Sent",
413 fr_packet_codes[packet->code],
415 inet_ntop(packet->src_ipaddr.af,
416 &packet->src_ipaddr.ipaddr,
417 src_ipaddr, sizeof(src_ipaddr)),
419 inet_ntop(packet->dst_ipaddr.af,
420 &packet->dst_ipaddr.ipaddr,
421 dst_ipaddr, sizeof(dst_ipaddr)),
425 RDEBUG("%s code %i Id %i from %s:%i to %s:%i length %zu",
426 received ? "Received" : "Sent",
429 inet_ntop(packet->src_ipaddr.af,
430 &packet->src_ipaddr.ipaddr,
431 src_ipaddr, sizeof(src_ipaddr)),
433 inet_ntop(packet->dst_ipaddr.af,
434 &packet->dst_ipaddr.ipaddr,
435 dst_ipaddr, sizeof(dst_ipaddr)),
441 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
443 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
448 /***********************************************************************
450 * Start of RADIUS server state machine.
452 ***********************************************************************/
454 static struct timeval *request_response_window(REQUEST *request)
456 VERIFY_REQUEST(request);
458 if (request->client) {
460 * The client hasn't set the response window. Return
461 * either the home server one, if set, or the global one.
463 if (!timerisset(&request->client->response_window)) {
464 return &request->home_server->response_window;
467 if (timercmp(&request->client->response_window,
468 &request->home_server->response_window, <)) {
469 return &request->client->response_window;
473 rad_assert(request->home_server != NULL);
474 return &request->home_server->response_window;
478 * Determine initial request processing delay.
480 static int request_init_delay(REQUEST *request)
482 struct timeval half_response_window;
484 VERIFY_REQUEST(request);
486 /* Allow client response window to lower initial delay */
487 if (timerisset(&request->client->response_window)) {
488 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
489 half_response_window.tv_usec =
490 ((request->client->response_window.tv_sec & 1) * USEC +
491 request->client->response_window.tv_usec) >> 1;
492 if (timercmp(&half_response_window, &request->root->init_delay, <))
493 return (int)half_response_window.tv_sec * USEC +
494 (int)half_response_window.tv_usec;
497 return (int)request->root->init_delay.tv_sec * USEC +
498 (int)request->root->init_delay.tv_usec;
502 * Callback for ALL timer events related to the request.
504 static void request_timer(void *ctx)
506 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
509 action = request->timer_action;
513 request->process(request, action);
517 * Wrapper for talloc pools. If there's no parent, just free the
518 * request. If there is a parent, free the parent INSTEAD of the
521 static void request_free(REQUEST *request)
525 rad_assert(request->ev == NULL);
526 rad_assert(!request->in_request_hash);
527 rad_assert(!request->in_proxy_hash);
529 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
530 talloc_free(request);
534 ptr = talloc_parent(request);
535 rad_assert(ptr != NULL);
541 static void proxy_reply_too_late(REQUEST *request)
545 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
546 inet_ntop(request->proxy->dst_ipaddr.af,
547 &request->proxy->dst_ipaddr.ipaddr,
548 buffer, sizeof(buffer)),
549 request->proxy->dst_port, request->proxy->id);
555 * Only ever called from the master thread.
557 STATE_MACHINE_DECL(request_done)
559 struct timeval now, when;
561 VERIFY_REQUEST(request);
566 * Force this no matter what.
568 request->process = request_done;
572 * Tell the detail listener that we're done.
574 if (request->listener &&
575 (request->listener->type == RAD_LISTEN_DETAIL) &&
576 (request->simul_max != 1)) {
577 request->simul_max = 1;
578 request->listener->send(request->listener,
583 #ifdef HAVE_PTHREAD_H
585 * If called from a child thread, mark ourselves as done,
586 * and wait for the master thread timer to clean us up.
588 if (!we_are_master()) {
590 request->child_state = REQUEST_DONE;
596 * Mark the request as STOP.
598 request->master_state = REQUEST_STOP_PROCESSING;
602 * Move the CoA request to its own handler.
605 coa_separate(request->coa);
606 } else if (request->parent && (request->parent->coa == request)) {
607 coa_separate(request);
612 * It doesn't hurt to send duplicate replies. All other
613 * signals are ignored, as the request will be cleaned up
619 rad_assert(request->listener != NULL);
621 if (request->reply->code != 0) {
622 request->listener->send(request->listener, request);
625 RDEBUG("No reply. Ignoring retransmit");
630 * Mark the request as done.
633 #ifdef HAVE_PTHREAD_H
635 * If the child is still running, leave it alone.
637 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
642 #ifdef DEBUG_STATE_MACHINE
643 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
644 request->number, __FUNCTION__,
645 child_state_names[request->child_state],
646 child_state_names[REQUEST_DONE]);
648 request->child_state = REQUEST_DONE;
652 * Called when the child is taking too long to
653 * finish. We've already marked it "please
654 * stop", so we don't complain any more.
656 case FR_ACTION_TIMER:
660 case FR_ACTION_PROXY_REPLY:
661 proxy_reply_too_late(request);
670 * Remove it from the request hash.
672 if (request->in_request_hash) {
673 if (!rbtree_deletebydata(pl, &request->packet)) {
676 request->in_request_hash = false;
681 * Wait for the proxy ID to expire. This allows us to
682 * avoid re-use of proxy IDs for a while.
684 if (request->in_proxy_hash) {
685 rad_assert(request->proxy != NULL);
687 fr_event_now(el, &now);
688 when = request->proxy->timestamp;
691 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
692 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
693 (request->packet->code != request->proxy->code)) {
694 when.tv_sec += request->home_server->coa_mrd;
697 timeradd(&when, request_response_window(request), &when);
700 * We haven't received all responses, AND there's still
701 * time to wait. Do so.
703 if ((request->num_proxied_requests > request->num_proxied_responses) &&
705 (request->home_server->proto != IPPROTO_TCP) &&
707 timercmp(&now, &when, <)) {
708 RDEBUG("Waiting for more responses from the home server");
715 remove_from_proxy_hash(request);
719 #ifdef HAVE_PTHREAD_H
721 * If there's no children, we can mark the request as done.
723 if (!spawn_flag) request->child_state = REQUEST_DONE;
727 * If the child is still running, wait for it to be finished.
729 if (request->child_state <= REQUEST_RUNNING) {
730 gettimeofday(&now, NULL);
735 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
736 tv_add(&when, request->delay);
737 request->delay += request->delay >> 1;
738 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
740 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
744 #ifdef HAVE_PTHREAD_H
745 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
749 * @todo: do final states for TCP sockets, too?
751 request_stats_final(request);
753 if (request->listener) {
754 request->listener->count--;
757 * If we're the last one, remove the listener now.
759 if ((request->listener->count == 0) &&
760 (request->listener->status == RAD_LISTEN_STATUS_EOL)) {
761 request->listener->status = RAD_LISTEN_STATUS_REMOVE_NOW;
762 event_new_fd(request->listener);
767 if (request->packet) {
768 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
770 (unsigned int) (request->timestamp - fr_start_time));
771 } /* else don't print anything */
774 fr_event_delete(el, &request->ev);
775 request_free(request);
779 static void request_cleanup_delay_init(REQUEST *request)
781 struct timeval now, when;
783 VERIFY_REQUEST(request);
785 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
789 * If the packets are from the detail file, we can clean them up now.
791 if (request->listener->type == RAD_LISTEN_DETAIL) goto done;
794 if (!request->root->cleanup_delay) goto done;
796 gettimeofday(&now, NULL);
798 rad_assert(request->reply->timestamp.tv_sec != 0);
799 when = request->reply->timestamp;
801 request->delay = request->root->cleanup_delay;
802 when.tv_sec += request->delay;
805 * Set timer for when we need to clean it up.
807 if (timercmp(&when, &now, >)) {
808 #ifdef DEBUG_STATE_MACHINE
809 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
811 request->process = request_cleanup_delay;
812 request->child_state = REQUEST_CLEANUP_DELAY;
815 * Update this if we can, otherwise let the timers pick it up.
817 if (we_are_master()) {
818 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
826 * Otherwise just clean it up.
829 request_done(request, FR_ACTION_DONE);
834 * Enforce max_request_time.
836 static void request_max_time(REQUEST *request)
838 struct timeval now, when;
839 rad_assert(request->magic == REQUEST_MAGIC);
840 #ifdef DEBUG_STATE_MACHINE
841 int action = FR_ACTION_TIMER;
844 VERIFY_REQUEST(request);
850 * The child thread has acknowledged it's done.
851 * Transition to the DONE state.
853 * If the request was marked STOP, then the "check for
854 * stop" macro already took care of it.
856 if (request->child_state == REQUEST_DONE) {
858 request_done(request, FR_ACTION_DONE);
863 * The request is still running. Enforce max_request_time.
865 fr_event_now(el, &now);
866 when = request->packet->timestamp;
867 when.tv_sec += request->root->max_request_time;
870 * Taking too long: tell it to die.
872 if (timercmp(&now, &when, >=)) {
873 #ifdef HAVE_PTHREAD_H
875 * If there's a child thread processing it,
879 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
880 ERROR("Unresponsive child for request %u, in component %s module %s",
882 request->component ? request->component : "<core>",
883 request->module ? request->module : "<core>");
884 exec_trigger(request, NULL, "server.thread.unresponsive", true);
888 * Tell the request that it's done.
894 * Sleep for some more. We HOPE that the child will
895 * become responsive at some point in the future. We do
896 * this by adding 50% to the current timer.
899 tv_add(&when, request->delay);
900 request->delay += request->delay >> 1;
901 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
904 static void request_queue_or_run(REQUEST *request,
905 fr_request_process_t process)
907 #ifdef DEBUG_STATE_MACHINE
908 int action = FR_ACTION_TIMER;
911 VERIFY_REQUEST(request);
916 * Do this here so that fewer other functions need to do
919 if (request->master_state == REQUEST_STOP_PROCESSING) {
920 #ifdef DEBUG_STATE_MACHINE
921 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
922 request->number, __FUNCTION__,
923 master_state_names[request->master_state],
924 child_state_names[request->child_state],
925 child_state_names[REQUEST_DONE]);
927 request_done(request, FR_ACTION_DONE);
931 request->process = process;
933 if (we_are_master()) {
937 * (re) set the initial delay.
939 request->delay = request_init_delay(request);
940 if (request->delay > USEC) request->delay = USEC;
941 gettimeofday(&when, NULL);
942 tv_add(&when, request->delay);
943 request->delay += request->delay >> 1;
945 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
947 #ifdef HAVE_PTHREAD_H
950 * A child thread will eventually pick it up.
952 if (request_enqueue(request)) return;
955 * Otherwise we're not going to do anything with
958 request_done(request, FR_ACTION_DONE);
964 request->child_state = REQUEST_RUNNING;
965 request->process(request, FR_ACTION_RUN);
969 * Requests that care about child process exit
970 * codes have already either called
971 * rad_waitpid(), or they've given up.
973 while (waitpid(-1, NULL, WNOHANG) > 0);
978 static void request_dup(REQUEST *request)
980 ERROR("(%u) Ignoring duplicate packet from "
981 "client %s port %d - ID: %u due to unfinished request "
982 "in component %s module %s",
983 request->number, request->client->shortname,
984 request->packet->src_port,request->packet->id,
985 request->component, request->module);
988 STATE_MACHINE_DECL(request_cleanup_delay)
990 struct timeval when, now;
992 VERIFY_REQUEST(request);
1001 if (request->reply->code != 0) {
1002 request->listener->send(request->listener, request);
1004 RDEBUG("No reply. Ignoring retransmit");
1008 * Double the cleanup_delay to catch retransmits.
1010 when = request->reply->timestamp;
1011 request->delay += request->delay;
1012 when.tv_sec += request->delay;
1014 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1018 case FR_ACTION_PROXY_REPLY:
1019 proxy_reply_too_late(request);
1023 case FR_ACTION_TIMER:
1024 fr_event_now(el, &now);
1026 rad_assert(request->root->cleanup_delay > 0);
1028 when = request->reply->timestamp;
1029 when.tv_sec += request->root->cleanup_delay;
1031 if (timercmp(&when, &now, >)) {
1032 #ifdef DEBUG_STATE_MACHINE
1033 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1035 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1037 } /* else it's time to clean up */
1039 request_done(request, REQUEST_DONE);
1043 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1048 STATE_MACHINE_DECL(request_response_delay)
1050 struct timeval when, now;
1052 VERIFY_REQUEST(request);
1054 TRACE_STATE_MACHINE;
1061 ERROR("(%u) Discarding duplicate request from "
1062 "client %s port %d - ID: %u due to delayed response",
1063 request->number, request->client->shortname,
1064 request->packet->src_port,request->packet->id);
1068 case FR_ACTION_PROXY_REPLY:
1069 proxy_reply_too_late(request);
1073 case FR_ACTION_TIMER:
1074 fr_event_now(el, &now);
1076 rad_assert(request->response_delay.tv_sec > 0);
1079 * See if it's time to send the reply. If not,
1080 * we wait some more.
1082 when = request->reply->timestamp;
1084 tv_add(&when, request->response_delay.tv_sec * USEC);
1085 tv_add(&when, request->response_delay.tv_usec);
1087 if (timercmp(&when, &now, >)) {
1088 #ifdef DEBUG_STATE_MACHINE
1089 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1091 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1093 } /* else it's time to send the reject */
1095 RDEBUG2("Sending delayed response");
1096 debug_packet(request, request->reply, false);
1097 request->listener->send(request->listener, request);
1100 * Clean up the request.
1102 request_cleanup_delay_init(request);
1106 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1112 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1116 VERIFY_REQUEST(request);
1118 TRACE_STATE_MACHINE;
1120 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1123 * Don't decode the packet if it's an internal "fake"
1124 * request. Instead, just return so that the caller can
1127 if (request->packet->dst_port == 0) {
1128 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1129 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1133 if (!request->packet->vps) { /* FIXME: check for correct state */
1134 rcode = request->listener->decode(request->listener, request);
1137 if (debug_condition) {
1139 * Ignore parse errors.
1141 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1142 request->log.lvl = L_DBG_LVL_2;
1143 request->log.func = vradlog_request;
1148 debug_packet(request, request->packet, true);
1154 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1155 request->reply->offset = -2; /* bad authenticator */
1159 if (!request->username) {
1160 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1166 STATE_MACHINE_DECL(request_finish)
1170 VERIFY_REQUEST(request);
1172 TRACE_STATE_MACHINE;
1175 (void) action; /* -Wunused */
1179 * Don't do post-auth if we're a CoA request originated
1180 * from an Access-Request. See request_alloc_coa() for
1183 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1187 * Override the response code if a control:Response-Packet-Type attribute is present.
1189 vp = pairfind(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1191 if (vp->vp_integer == 256) {
1192 RDEBUG2("Not responding to request");
1193 request->reply->code = 0;
1195 request->reply->code = vp->vp_integer;
1199 * Catch Auth-Type := Reject BEFORE proxying the packet.
1201 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1202 if (request->reply->code == 0) {
1203 vp = pairfind(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1205 if (!vp || (vp->vp_integer != 5)) {
1206 RDEBUG2("There was no response configured: "
1207 "rejecting request");
1210 request->reply->code = PW_CODE_ACCESS_REJECT;
1215 * Copy Proxy-State from the request to the reply.
1217 vp = paircopy_by_num(request->reply, request->packet->vps,
1218 PW_PROXY_STATE, 0, TAG_ANY);
1219 if (vp) pairadd(&request->reply->vps, vp);
1222 * Call Post-Auth for Access-Request packets.
1224 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1225 rad_postauth(request);
1230 * Clean up. These are no longer needed.
1232 gettimeofday(&request->reply->timestamp, NULL);
1235 * Fake packets get marked as "done", and have the
1236 * proxy-reply section deal with the reply attributes.
1237 * We therefore don't free the reply attributes.
1239 if (request->packet->dst_port == 0) {
1240 RDEBUG("Finished internally proxied request.");
1242 request->child_state = REQUEST_DONE;
1248 * Always send the reply to the detail listener.
1250 if (request->listener->type == RAD_LISTEN_DETAIL) {
1251 request->simul_max = 1;
1252 request->listener->send(request->listener, request);
1254 * But only print the reply if there is one.
1256 if (request->reply->code != 0) {
1257 debug_packet(request, request->reply, false);
1264 * Ignore all "do not respond" packets.
1265 * Except for the detail ones, which need to ping
1266 * the detail file reader so that it will retransmit.
1268 if (!request->reply->code) {
1269 RDEBUG("Not sending reply to client.");
1274 * If it's not in the request hash, we MIGHT not want to
1277 * If duplicate packets are allowed, then then only
1278 * reason to NOT be in the request hash is because we
1279 * don't want to send a reply.
1281 * FIXME: this is crap. The rest of the state handling
1282 * should use a different field so that we don't have two
1285 * Otherwise duplicates are forbidden, and the request is
1286 * SUPPOSED to avoid the request hash.
1288 * In that case, we need to send a reply.
1290 if (!request->in_request_hash &&
1291 !request->listener->nodup) {
1292 RDEBUG("Suppressing reply to client.");
1297 * See if we need to delay an Access-Reject packet.
1299 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1300 (request->root->reject_delay.tv_sec > 0)) {
1301 request->response_delay = request->root->reject_delay;
1305 * If we timed out a proxy packet, don't delay
1306 * the reject any more.
1308 if (request->proxy && !request->proxy_reply) {
1309 request->response_delay.tv_sec = 0;
1310 request->response_delay.tv_usec = 0;
1318 if (request->response_delay.tv_sec == 0) {
1319 rad_assert(request->response_delay.tv_usec == 0);
1322 * Don't print a reply if there's none to send.
1324 if (request->reply->code != 0) {
1325 request->listener->send(request->listener, request);
1326 debug_packet(request, request->reply, false);
1330 RDEBUG2("Finished request");
1331 request->component = "<core>";
1332 request->module = "<done>";
1334 #ifdef WITH_ACCOUNTING
1336 * Accounting packets can be cleaned up now.
1338 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1340 request->child_state = REQUEST_DONE;
1347 * If the packets are from the detail file, we can clean them up now.
1349 if (request->listener->type == RAD_LISTEN_DETAIL) {
1351 request->child_state = REQUEST_DONE;
1358 * If we've originated this CoA request, it gets
1361 if (request->proxy &&
1362 ((request->proxy->code == PW_CODE_COA_REQUEST) ||
1363 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
1364 (request->packet->code != request->proxy->code)) {
1366 request->child_state = REQUEST_DONE;
1372 * Clean up the request.
1374 request_cleanup_delay_init(request);
1378 * Encode and sign it here, so that the master
1379 * thread can just send the encoded data, which
1380 * means it does less work.
1382 RDEBUG2("Delaying response for %d.%06d seconds",
1383 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1384 request->listener->encode(request->listener, request);
1385 request->component = "<core>";
1386 request->module = "<delay>";
1387 request->process = request_response_delay;
1389 request->child_state = REQUEST_RESPONSE_DELAY;
1393 STATE_MACHINE_DECL(request_running)
1395 VERIFY_REQUEST(request);
1397 TRACE_STATE_MACHINE;
1401 case FR_ACTION_TIMER:
1403 request_max_time(request);
1407 request_dup(request);
1411 if (!request_pre_handler(request, action)) {
1412 #ifdef DEBUG_STATE_MACHINE
1413 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1414 request->number, __FUNCTION__,
1415 child_state_names[request->child_state],
1416 child_state_names[REQUEST_DONE]);
1420 request->child_state = REQUEST_DONE;
1424 rad_assert(request->handle != NULL);
1425 request->handle(request);
1429 * We may need to send a proxied request.
1431 if ((action == FR_ACTION_RUN) &&
1432 request_will_proxy(request)) {
1433 #ifdef DEBUG_STATE_MACHINE
1434 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1438 * takes care of setting
1439 * up the post proxy fail
1442 if (request_proxy(request, 0) < 0) goto req_finished;
1446 #ifdef DEBUG_STATE_MACHINE
1447 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1452 * Maybe originate a CoA request.
1454 if ((action == FR_ACTION_RUN) && request->coa) {
1455 request_coa_originate(request);
1462 request_finish(request, action);
1467 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1472 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1473 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1476 RADIUS_PACKET **packet_p;
1477 REQUEST *request = NULL;
1479 listen_socket_t *sock = NULL;
1481 VERIFY_PACKET(packet);
1484 * Set the last packet received.
1486 gettimeofday(&now, NULL);
1488 packet->timestamp = now;
1490 #ifdef WITH_ACCOUNTING
1491 if (listener->type != RAD_LISTEN_DETAIL)
1494 sock = listener->data;
1495 sock->last_packet = now.tv_sec;
1499 * Skip everything if required.
1501 if (listener->nodup) goto skip_dup;
1503 packet_p = rbtree_finddata(pl, &packet);
1505 rad_child_state_t child_state;
1507 request = fr_packet2myptr(REQUEST, packet, packet_p);
1508 rad_assert(request->in_request_hash);
1509 child_state = request->child_state;
1512 * Same src/dst ip/port, length, and
1513 * authentication vector: must be a duplicate.
1515 if ((request->packet->data_len == packet->data_len) &&
1516 (memcmp(request->packet->vector, packet->vector,
1517 sizeof(packet->vector)) == 0)) {
1520 switch (packet->code) {
1521 case PW_CODE_ACCESS_REQUEST:
1522 FR_STATS_INC(auth, total_dup_requests);
1525 #ifdef WITH_ACCOUNTING
1526 case PW_CODE_ACCOUNTING_REQUEST:
1527 FR_STATS_INC(acct, total_dup_requests);
1531 case PW_CODE_COA_REQUEST:
1532 FR_STATS_INC(coa, total_dup_requests);
1535 case PW_CODE_DISCONNECT_REQUEST:
1536 FR_STATS_INC(dsc, total_dup_requests);
1543 #endif /* WITH_STATS */
1546 * Tell the state machine that there's a
1547 * duplicate request.
1549 request->process(request, FR_ACTION_DUP);
1550 return 0; /* duplicate of live request */
1554 * Mark the request as done ASAP, and before we
1555 * log anything. The child may stop processing
1556 * the request just as we're logging the
1559 request_done(request, FR_ACTION_DONE);
1563 * It's a new request, not a duplicate. If the
1564 * old one is done, then we can clean it up.
1566 if (child_state <= REQUEST_RUNNING) {
1568 * The request is still QUEUED or RUNNING. That's a problem.
1570 ERROR("Received conflicting packet from "
1571 "client %s port %d - ID: %u due to "
1572 "unfinished request. Giving up on old request.",
1574 packet->src_port, packet->id);
1578 * Mark the old request as done. If there's no
1579 * child, the request will be cleaned up
1580 * immediately. If there is a child, we'll set a
1581 * timer to go clean up the request.
1583 } /* else the new packet is unique */
1586 * Quench maximum number of outstanding requests.
1588 if (main_config.max_requests &&
1589 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1590 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1592 packet->src_port, packet->id);
1593 WARN("Please check the configuration file.\n"
1594 "\tThe value for 'max_requests' is probably set too low.\n"));
1596 exec_trigger(NULL, NULL, "server.max_requests", true);
1602 * Rate-limit the incoming packets
1604 if (sock && sock->max_rate) {
1607 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1608 if (pps > sock->max_rate) {
1609 DEBUG("Dropping request due to rate limiting");
1612 sock->rate_pps_now++;
1616 * Allocate a pool for the request.
1619 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1623 * The packet is still allocated from a different
1624 * context, but oh well.
1626 (void) talloc_steal(ctx, packet);
1629 request = request_setup(ctx, listener, packet, client, fun);
1636 * Mark it as a "real" request with a context.
1638 request->options |= RAD_REQUEST_OPTION_CTX;
1641 * Remember the request in the list.
1643 if (!listener->nodup) {
1644 if (!rbtree_insert(pl, &request->packet)) {
1645 RERROR("Failed to insert request in the list of live requests: discarding it");
1646 request_done(request, FR_ACTION_DONE);
1650 request->in_request_hash = true;
1654 * Process it. Send a response, and free it.
1656 if (listener->synchronous) {
1658 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1661 request->listener->decode(request->listener, request);
1662 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1663 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1667 if (request->reply->code != 0) {
1668 request->listener->send(request->listener, request);
1670 RDEBUG("Not sending reply");
1674 * Don't do delayed reject. Oh well.
1676 request_free(request);
1681 * Otherwise, insert it into the state machine.
1682 * The child threads will take care of processing it.
1684 request_queue_or_run(request, request_running);
1690 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1691 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1696 * Create and initialize the new request.
1698 request = request_alloc(ctx);
1703 request->reply = rad_alloc(request, false);
1704 if (!request->reply) {
1706 talloc_free(request);
1710 request->listener = listener;
1711 request->client = client;
1712 request->packet = talloc_steal(request, packet);
1713 request->number = request_num_counter++;
1714 request->priority = listener->type;
1715 request->master_state = REQUEST_ACTIVE;
1716 request->child_state = REQUEST_RUNNING;
1717 #ifdef DEBUG_STATE_MACHINE
1718 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1719 request->number, __FUNCTION__,
1720 child_state_names[request->child_state],
1721 child_state_names[REQUEST_RUNNING]);
1723 #ifdef HAVE_PTHREAD_H
1724 request->child_pid = NO_SUCH_CHILD_PID;
1726 request->handle = fun;
1730 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1731 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1732 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1733 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1734 #ifdef WITH_ACCOUNTING
1735 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1736 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1737 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1740 #endif /* WITH_STATS */
1743 * Status-Server packets go to the head of the queue.
1745 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1748 * Set virtual server identity
1750 if (client->server) {
1751 request->server = client->server;
1752 } else if (listener->server) {
1753 request->server = listener->server;
1755 request->server = NULL;
1758 request->root = &main_config;
1760 request->listener->count++;
1764 * The request passes many of our sanity checks.
1765 * From here on in, if anything goes wrong, we
1766 * send a reject message, instead of dropping the
1771 * Build the reply template from the request.
1774 request->reply->sockfd = request->packet->sockfd;
1775 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1776 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1777 request->reply->dst_port = request->packet->src_port;
1778 request->reply->src_port = request->packet->dst_port;
1779 request->reply->id = request->packet->id;
1780 request->reply->code = 0; /* UNKNOWN code */
1781 memcpy(request->reply->vector, request->packet->vector,
1782 sizeof(request->reply->vector));
1783 request->reply->vps = NULL;
1784 request->reply->data = NULL;
1785 request->reply->data_len = 0;
1791 /***********************************************************************
1795 ***********************************************************************/
1798 * Timer function for all TCP sockets.
1800 static void tcp_socket_timer(void *ctx)
1802 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1803 listen_socket_t *sock = listener->data;
1804 struct timeval end, now;
1806 fr_socket_limit_t *limit;
1810 fr_event_now(el, &now);
1812 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1814 switch (listener->type) {
1816 case RAD_LISTEN_PROXY:
1817 limit = &sock->home->limit;
1821 case RAD_LISTEN_AUTH:
1822 #ifdef WITH_ACCOUNTING
1823 case RAD_LISTEN_ACCT:
1825 limit = &sock->limit;
1833 * If we enforce a lifetime, do it now.
1835 if (limit->lifetime > 0) {
1836 end.tv_sec = sock->opened + limit->lifetime;
1839 if (timercmp(&end, &now, <=)) {
1840 listener->print(listener, buffer, sizeof(buffer));
1841 DEBUG("Reached maximum lifetime on socket %s", buffer);
1845 listener->status = RAD_LISTEN_STATUS_EOL;
1846 event_new_fd(listener);
1855 * Enforce an idle timeout.
1857 if (limit->idle_timeout > 0) {
1858 struct timeval idle;
1860 rad_assert(sock->last_packet != 0);
1861 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1864 if (timercmp(&idle, &now, <=)) {
1865 listener->print(listener, buffer, sizeof(buffer));
1866 DEBUG("Reached idle timeout on socket %s", buffer);
1871 * Enforce the minimum of idle timeout or lifetime.
1873 if (timercmp(&idle, &end, <)) {
1879 * Wake up at t + 0.5s. The code above checks if the timers
1880 * are <= t. This addition gives us a bit of leeway.
1882 end.tv_usec = USEC / 2;
1885 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1886 rad_panic("Failed to insert event");
1893 * Add +/- 2s of jitter, as suggested in RFC 3539
1896 static void add_jitter(struct timeval *when)
1903 jitter ^= (jitter >> 10);
1904 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1907 * Add in ~ (4 * USEC) of jitter.
1909 tv_add(when, jitter);
1913 * Called by socket_del to remove requests with this socket
1915 static int eol_proxy_listener(void *ctx, void *data)
1917 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
1918 RADIUS_PACKET **proxy_p = data;
1921 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1922 if (request->proxy_listener != this) return 0;
1925 * The normal "remove_from_proxy_hash" tries to grab the
1926 * proxy mutex. We already have it held, so grabbing it
1927 * again will cause a deadlock. Instead, call the "no
1928 * lock" version of the function.
1930 rad_assert(request->in_proxy_hash == true);
1931 remove_from_proxy_hash_nl(request, false);
1934 * Don't mark it as DONE. The client can retransmit, and
1935 * the packet SHOULD be re-proxied somewhere else.
1937 * Return "2" means that the rbtree code will remove it
1938 * from the tree, and we don't need to do it ourselves.
1942 #endif /* WITH_PROXY */
1944 static int eol_listener(void *ctx, void *data)
1946 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
1947 RADIUS_PACKET **packet_p = data;
1950 request = fr_packet2myptr(REQUEST, packet, packet_p);
1951 if (request->listener != this) return 0;
1953 request->master_state = REQUEST_STOP_PROCESSING;
1954 request->process = request_done;
1958 #endif /* WITH_TCP */
1961 /***********************************************************************
1963 * Proxy handlers for the state machine.
1965 ***********************************************************************/
1968 * Called with the proxy mutex held
1970 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1972 VERIFY_REQUEST(request);
1974 if (!request->in_proxy_hash) return;
1976 fr_packet_list_id_free(proxy_list, request->proxy, yank);
1977 request->in_proxy_hash = false;
1980 * On the FIRST reply, decrement the count of outstanding
1981 * requests. Note that this is NOT the count of sent
1982 * packets, but whether or not the home server has
1985 if (request->home_server &&
1986 request->home_server->currently_outstanding) {
1987 request->home_server->currently_outstanding--;
1990 * If we're NOT sending it packets, AND it's been
1991 * a while since we got a response, then we don't
1992 * know if it's alive or dead.
1994 if ((request->home_server->currently_outstanding == 0) &&
1995 (request->home_server->state == HOME_STATE_ALIVE)) {
1996 struct timeval when, now;
1998 when.tv_sec = request->home_server->last_packet_recv ;
2001 timeradd(&when, request_response_window(request), &when);
2002 gettimeofday(&now, NULL);
2005 * last_packet + response_window
2007 * We *administratively* mark the home
2008 * server as "unknown" state, because we
2009 * haven't seen a packet for a while.
2011 if (timercmp(&now, &when, >)) {
2012 request->home_server->state = HOME_STATE_UNKNOWN;
2013 request->home_server->last_packet_sent = 0;
2014 request->home_server->last_packet_recv = 0;
2020 rad_assert(request->proxy_listener != NULL);
2021 request->proxy_listener->count--;
2023 request->proxy_listener = NULL;
2026 * Got from YES in hash, to NO, not in hash while we hold
2027 * the mutex. This guarantees that when another thread
2028 * grabs the mutex, the "not in hash" flag is correct.
2030 RDEBUG3("proxy: request is no longer in proxy hash");
2033 static void remove_from_proxy_hash(REQUEST *request)
2035 VERIFY_REQUEST(request);
2038 * Check this without grabbing the mutex because it's a
2039 * lot faster that way.
2041 if (!request->in_proxy_hash) return;
2044 * The "not in hash" flag is definitive. However, if the
2045 * flag says that it IS in the hash, there might still be
2046 * a race condition where it isn't.
2048 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2050 if (!request->in_proxy_hash) {
2051 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2055 remove_from_proxy_hash_nl(request, true);
2057 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2060 static int insert_into_proxy_hash(REQUEST *request)
2064 bool success = false;
2065 void *proxy_listener;
2067 VERIFY_REQUEST(request);
2069 rad_assert(request->proxy != NULL);
2070 rad_assert(request->home_server != NULL);
2071 rad_assert(proxy_list != NULL);
2074 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2075 proxy_listener = NULL;
2076 request->num_proxied_requests = 1;
2077 request->num_proxied_responses = 0;
2079 for (tries = 0; tries < 2; tries++) {
2081 listen_socket_t *sock;
2083 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2084 success = fr_packet_list_id_alloc(proxy_list,
2085 request->home_server->proto,
2086 &request->proxy, &proxy_listener);
2089 if (tries > 0) continue; /* try opening new socket only once */
2091 #ifdef HAVE_PTHREAD_H
2092 if (proxy_no_new_sockets) break;
2095 RDEBUG3("proxy: Trying to open a new listener to the home server");
2096 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2098 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2102 request->proxy->src_port = 0; /* Use any new socket */
2103 proxy_listener = this;
2106 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2108 &sock->other_ipaddr, sock->other_port,
2111 #ifdef HAVE_PTHREAD_H
2112 proxy_no_new_sockets = true;
2114 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2117 * This is bad. However, the
2118 * packet list now supports 256
2119 * open sockets, which should
2120 * minimize this problem.
2122 ERROR("Failed adding proxy socket: %s",
2128 * Add it to the event loop. Ensure that we have
2129 * only one mutex locked at a time.
2131 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2132 radius_update_listener(this);
2133 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2136 if (!proxy_listener || !success) {
2137 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2138 REDEBUG2("proxy: Failed allocating Id for proxied request");
2140 request->proxy_listener = NULL;
2141 request->in_proxy_hash = false;
2145 rad_assert(request->proxy->id >= 0);
2147 request->proxy_listener = proxy_listener;
2148 request->in_proxy_hash = true;
2149 RDEBUG3("proxy: request is now in proxy hash");
2152 * Keep track of maximum outstanding requests to a
2153 * particular home server. 'max_outstanding' is
2154 * enforced in home_server_ldb(), in realms.c.
2156 request->home_server->currently_outstanding++;
2159 request->proxy_listener->count++;
2162 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2164 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2165 inet_ntop(request->proxy->dst_ipaddr.af,
2166 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2167 request->proxy->dst_port,
2168 request->proxy->id);
2173 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2176 int post_proxy_type = 0;
2179 VERIFY_REQUEST(request);
2182 * There may be a proxy reply, but it may be too late.
2184 if (!request->home_server->server && !request->proxy_listener) return 0;
2187 * Delete any reply we had accumulated until now.
2189 RDEBUG2("Clearing existing &reply: attributes");
2190 pairfree(&request->reply->vps);
2193 * Run the packet through the post-proxy stage,
2194 * BEFORE playing games with the attributes.
2196 vp = pairfind(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2198 post_proxy_type = vp->vp_integer;
2200 * If we have a proxy_reply, and it was a reject, or a NAK
2201 * setup Post-Proxy <type>.
2203 * If the <type> doesn't have a section, then the Post-Proxy
2204 * section is ignored.
2207 DICT_VALUE *dval = NULL;
2209 switch (reply->code) {
2210 case PW_CODE_ACCESS_REJECT:
2211 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2212 if (dval) post_proxy_type = dval->value;
2215 case PW_CODE_DISCONNECT_NAK:
2216 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2217 if (dval) post_proxy_type = dval->value;
2220 case PW_CODE_COA_NAK:
2221 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2222 if (dval) post_proxy_type = dval->value;
2230 * Create config:Post-Proxy-Type
2233 vp = radius_paircreate(request, &request->config, PW_POST_PROXY_TYPE, 0);
2234 vp->vp_integer = dval->value;
2238 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2239 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2242 VERIFY_PACKET(reply);
2245 * Decode the packet if required.
2247 if (request->proxy_listener) {
2248 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2249 debug_packet(request, reply, true);
2252 * Pro-actively remove it from the proxy hash.
2253 * This is later than in 2.1.x, but it means that
2254 * the replies are authenticated before being
2255 * removed from the hash.
2258 (request->num_proxied_requests <= request->num_proxied_responses)) {
2259 remove_from_proxy_hash(request);
2262 rad_assert(!request->in_proxy_hash);
2264 } else if (request->in_proxy_hash) {
2265 remove_from_proxy_hash(request);
2268 if (request->home_pool && request->home_pool->virtual_server) {
2269 char const *old_server = request->server;
2271 request->server = request->home_pool->virtual_server;
2272 RDEBUG2("server %s {", request->server);
2274 rcode = process_post_proxy(post_proxy_type, request);
2277 request->server = old_server;
2279 rcode = process_post_proxy(post_proxy_type, request);
2283 if (request->packet->code == request->proxy->code)
2285 * Don't run the next bit if we originated a CoA
2286 * packet, after receiving an Access-Request or
2287 * Accounting-Request.
2292 * There may NOT be a proxy reply, as we may be
2293 * running Post-Proxy-Type = Fail.
2296 pairadd(&request->reply->vps, paircopy(request->reply, reply->vps));
2299 * Delete the Proxy-State Attributes from
2300 * the reply. These include Proxy-State
2301 * attributes from us and remote server.
2303 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2307 default: /* Don't do anything */
2309 case RLM_MODULE_FAIL:
2312 case RLM_MODULE_HANDLED:
2319 int request_proxy_reply(RADIUS_PACKET *packet)
2321 RADIUS_PACKET **proxy_p;
2326 VERIFY_PACKET(packet);
2328 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2329 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2332 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2333 PROXY("No outstanding request was found for reply from host %s port %d - ID %u",
2334 inet_ntop(packet->src_ipaddr.af,
2335 &packet->src_ipaddr.ipaddr,
2336 buffer, sizeof(buffer)),
2337 packet->src_port, packet->id);
2341 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2342 request->num_proxied_responses++; /* needs to be protected by lock */
2344 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2347 * No reply, BUT the current packet fails verification:
2348 * ignore it. This does the MD5 calculations in the
2349 * server core, but I guess we can fix that later.
2351 if (!request->proxy_reply &&
2352 (rad_verify(packet, request->proxy,
2353 request->home_server->secret) != 0)) {
2354 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2359 * The home server sent us a packet which doesn't match
2360 * something we have: ignore it. This is done only to
2361 * catch the case of broken systems.
2363 if (request->proxy_reply &&
2364 (memcmp(request->proxy_reply->vector,
2366 sizeof(request->proxy_reply->vector)) != 0)) {
2367 RDEBUG2("Ignoring conflicting proxy reply");
2371 gettimeofday(&now, NULL);
2374 * Status-Server packets don't count as real packets.
2376 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2377 listen_socket_t *sock = request->proxy_listener->data;
2379 request->home_server->last_packet_recv = now.tv_sec;
2380 sock->last_packet = now.tv_sec;
2384 * If we have previously seen a reply, ignore the
2387 if (request->proxy_reply) {
2388 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2389 inet_ntop(packet->src_ipaddr.af,
2390 &packet->src_ipaddr.ipaddr,
2391 buffer, sizeof(buffer)),
2392 packet->src_port, packet->id);
2397 * Call the state machine to do something useful with the
2400 request->proxy_reply = talloc_steal(request, packet);
2401 packet->timestamp = now;
2402 request->priority = RAD_LISTEN_PROXY;
2406 * Update the proxy listener stats here, because only one
2407 * thread accesses that at a time. The home_server and
2408 * main proxy_*_stats structures are updated once the
2409 * request is cleaned up.
2411 request->proxy_listener->stats.total_responses++;
2413 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2414 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2416 switch (request->proxy->code) {
2417 case PW_CODE_ACCESS_REQUEST:
2418 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2420 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2421 request->proxy_listener->stats.total_access_accepts++;
2423 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2424 request->proxy_listener->stats.total_access_rejects++;
2426 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2427 request->proxy_listener->stats.total_access_challenges++;
2431 #ifdef WITH_ACCOUNTING
2432 case PW_CODE_ACCOUNTING_REQUEST:
2433 request->proxy_listener->stats.total_responses++;
2434 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2440 case PW_CODE_COA_REQUEST:
2441 request->proxy_listener->stats.total_responses++;
2442 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2445 case PW_CODE_DISCONNECT_REQUEST:
2446 request->proxy_listener->stats.total_responses++;
2447 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2457 * We've received a reply. If we hadn't been sending it
2458 * packets for a while, just mark it alive.
2460 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2461 request->home_server->state = HOME_STATE_ALIVE;
2462 request->home_server->response_timeouts = 0;
2466 * Tell the request state machine that we have a proxy
2467 * reply. Depending on the function, this should either
2468 * ignore it, or process it.
2470 request->process(request, FR_ACTION_PROXY_REPLY);
2476 static int setup_post_proxy_fail(REQUEST *request)
2478 DICT_VALUE const *dval = NULL;
2481 VERIFY_REQUEST(request);
2483 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2484 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2485 "Fail-Authentication");
2487 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2488 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2491 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2492 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2494 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2495 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2498 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2502 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2505 pairdelete(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2509 vp = pairfind(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2510 if (!vp) vp = radius_paircreate(request, &request->config,
2511 PW_POST_PROXY_TYPE, 0);
2512 vp->vp_integer = dval->value;
2517 STATE_MACHINE_DECL(proxy_no_reply)
2519 VERIFY_REQUEST(request);
2521 TRACE_STATE_MACHINE;
2526 request_dup(request);
2529 case FR_ACTION_TIMER:
2530 request_max_time(request);
2533 case FR_ACTION_PROXY_REPLY:
2534 proxy_reply_too_late(request);
2538 if (process_proxy_reply(request, NULL)) {
2539 request->handle(request);
2541 request_finish(request, action);
2545 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2550 STATE_MACHINE_DECL(proxy_running)
2552 VERIFY_REQUEST(request);
2554 TRACE_STATE_MACHINE;
2559 request_dup(request);
2562 case FR_ACTION_TIMER:
2563 request_max_time(request);
2567 if (process_proxy_reply(request, request->proxy_reply)) {
2568 request->handle(request);
2570 request_finish(request, action);
2573 default: /* duplicate proxy replies are suppressed */
2574 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2579 static int request_will_proxy(REQUEST *request)
2581 int rcode, pre_proxy_type = 0;
2582 char const *realmname = NULL;
2583 VALUE_PAIR *vp, *strippedname;
2584 home_server_t *home;
2585 REALM *realm = NULL;
2586 home_pool_t *pool = NULL;
2588 VERIFY_REQUEST(request);
2590 if (!request->root->proxy_requests) return 0;
2591 if (request->packet->dst_port == 0) return 0;
2592 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2593 if (request->in_proxy_hash) return 0;
2596 * FIXME: for 3.0, allow this only for rejects?
2598 if (request->reply->code != 0) return 0;
2600 vp = pairfind(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2602 realm = realm_find2(vp->vp_strvalue);
2604 REDEBUG2("Cannot proxy to unknown realm %s",
2609 realmname = vp->vp_strvalue;
2612 * Figure out which pool to use.
2614 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2615 pool = realm->auth_pool;
2617 #ifdef WITH_ACCOUNTING
2618 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2619 pool = realm->acct_pool;
2623 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2624 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2625 pool = realm->coa_pool;
2632 } else if ((vp = pairfind(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2635 switch (request->packet->code) {
2636 case PW_CODE_ACCESS_REQUEST:
2637 pool_type = HOME_TYPE_AUTH;
2640 #ifdef WITH_ACCOUNTING
2641 case PW_CODE_ACCOUNTING_REQUEST:
2642 pool_type = HOME_TYPE_ACCT;
2647 case PW_CODE_COA_REQUEST:
2648 case PW_CODE_DISCONNECT_REQUEST:
2649 pool_type = HOME_TYPE_COA;
2657 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2660 * Send it directly to a home server (i.e. NAS)
2662 } else if (((vp = pairfind(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2663 ((vp = pairfind(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2666 fr_ipaddr_t dst_ipaddr;
2668 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2670 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2671 dst_ipaddr.af = AF_INET;
2672 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2673 dst_ipaddr.prefix = 32;
2675 dst_ipaddr.af = AF_INET6;
2676 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2677 dst_ipaddr.prefix = 128;
2680 port = pairfind(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2682 dst_port = PW_COA_UDP_PORT;
2684 dst_port = vp->vp_integer;
2688 * Nothing does CoA over TCP.
2690 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2694 WARN("No such CoA home server %s port %u",
2695 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2696 (unsigned int) dst_port);
2707 RWDEBUG2("Cancelling proxy as no home pool exists");
2711 if (request->listener->synchronous) {
2712 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2716 request->home_pool = pool;
2718 home = home_server_ldb(realmname, pool, request);
2721 REDEBUG2("Failed to find live home server: Cancelling proxy");
2726 home_server_update_request(home, request);
2730 * Once we've decided to proxy a request, we cannot send
2731 * a CoA packet. So we free up any CoA packet here.
2733 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2737 * Remember that we sent the request to a Realm.
2739 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2742 * Strip the name, if told to.
2744 * Doing it here catches the case of proxied tunneled
2747 if (realm && (realm->strip_realm == true) &&
2748 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2750 * If there's a Stripped-User-Name attribute in
2751 * the request, then use THAT as the User-Name
2752 * for the proxied request, instead of the
2755 * This is done by making a copy of the
2756 * Stripped-User-Name attribute, turning it into
2757 * a User-Name attribute, deleting the
2758 * Stripped-User-Name and User-Name attributes
2759 * from the vps list, and making the new
2760 * User-Name the head of the vps list.
2762 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2765 vp = radius_paircreate(NULL, NULL,
2767 rad_assert(vp != NULL); /* handled by above function */
2768 /* Insert at the START of the list */
2769 /* FIXME: Can't make assumptions about ordering */
2770 fr_cursor_init(&cursor, &vp);
2771 fr_cursor_merge(&cursor, request->proxy->vps);
2772 request->proxy->vps = vp;
2774 pairstrcpy(vp, strippedname->vp_strvalue);
2777 * Do NOT delete Stripped-User-Name.
2782 * If there is no PW_CHAP_CHALLENGE attribute but
2783 * there is a PW_CHAP_PASSWORD we need to add it
2784 * since we can't use the request authenticator
2785 * anymore - we changed it.
2787 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2788 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2789 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2790 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2791 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2795 * The RFC's say we have to do this, but FreeRADIUS
2798 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2799 pairsprintf(vp, "%u", request->packet->id);
2802 * Should be done BEFORE inserting into proxy hash, as
2803 * pre-proxy may use this information, or change it.
2805 request->proxy->code = request->packet->code;
2808 * Call the pre-proxy routines.
2810 vp = pairfind(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2812 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2813 /* Must be a validation issue */
2815 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2816 pre_proxy_type = vp->vp_integer;
2820 * home_pool may be NULL when originating CoA packets,
2821 * because they go directly to an IP address.
2823 if (request->home_pool && request->home_pool->virtual_server) {
2824 char const *old_server = request->server;
2826 request->server = request->home_pool->virtual_server;
2828 RDEBUG2("server %s {", request->server);
2830 rcode = process_pre_proxy(pre_proxy_type, request);
2834 request->server = old_server;
2836 rcode = process_pre_proxy(pre_proxy_type, request);
2839 case RLM_MODULE_FAIL:
2840 case RLM_MODULE_INVALID:
2841 case RLM_MODULE_NOTFOUND:
2842 case RLM_MODULE_USERLOCK:
2844 /* FIXME: debug print failed stuff */
2847 case RLM_MODULE_REJECT:
2848 case RLM_MODULE_HANDLED:
2852 * Only proxy the packet if the pre-proxy code succeeded.
2854 case RLM_MODULE_NOOP:
2856 case RLM_MODULE_UPDATED:
2863 static int request_proxy(REQUEST *request, int retransmit)
2867 VERIFY_REQUEST(request);
2869 rad_assert(request->parent == NULL);
2870 rad_assert(request->home_server != NULL);
2872 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2876 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2877 request_done(request->coa, FR_ACTION_DONE);
2882 * The request may need sending to a virtual server.
2883 * This code is more than a little screwed up. The rest
2884 * of the state machine doesn't handle parent / child
2885 * relationships well. i.e. if the child request takes
2886 * too long, the core will mark the *parent* as "stop
2887 * processing". And the child will continue without
2888 * knowing anything...
2890 * So, we have some horrible hacks to get around that.
2892 if (request->home_server->server) {
2895 if (request->packet->dst_port == 0) {
2896 WARN("Cannot proxy an internal request");
2900 DEBUG("Proxying to virtual server %s",
2901 request->home_server->server);
2904 * Packets to virtual serrers don't get
2905 * retransmissions sent to them. And the virtual
2906 * server is run ONLY if we have no child
2907 * threads, or we're running in a child thread.
2909 rad_assert(retransmit == 0);
2910 rad_assert(!spawn_flag || !we_are_master());
2912 fake = request_alloc_fake(request);
2914 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
2915 talloc_free(request->proxy);
2917 fake->server = request->home_server->server;
2918 fake->handle = request->handle;
2919 fake->process = NULL; /* should never be run for anything */
2922 * Run the virtual server.
2924 request_running(fake, FR_ACTION_RUN);
2926 request->proxy = talloc_steal(request, fake->packet);
2927 fake->packet = NULL;
2928 request->proxy_reply = talloc_steal(request, fake->reply);
2934 * No reply code, toss the reply we have,
2935 * and do post-proxy-type Fail.
2937 if (!request->proxy_reply->code) {
2938 TALLOC_FREE(request->proxy_reply);
2939 setup_post_proxy_fail(request);
2943 * Just do the work here, rather than trying to
2944 * run the "decode proxy reply" stuff...
2946 process_proxy_reply(request, request->proxy_reply);
2949 * If we have a reply, run it through the handler.
2951 if (request->proxy_reply) {
2952 request->handle(request); /* to do more post-proxy stuff */
2955 return -1; /* so we call request_finish */
2959 * We're actually sending a proxied packet. Do that now.
2961 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2962 ERROR("Failed to insert request into the proxy list");
2966 rad_assert(request->proxy->id >= 0);
2969 struct timeval *response_window;
2971 response_window = request_response_window(request);
2974 if (request->home_server->tls) {
2975 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
2976 inet_ntop(request->proxy->dst_ipaddr.af,
2977 &request->proxy->dst_ipaddr.ipaddr,
2978 buffer, sizeof(buffer)),
2979 request->proxy->dst_port,
2980 (int) response_window->tv_sec, (int) response_window->tv_usec);
2983 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
2984 inet_ntop(request->proxy->dst_ipaddr.af,
2985 &request->proxy->dst_ipaddr.ipaddr,
2986 buffer, sizeof(buffer)),
2987 request->proxy->dst_port,
2988 (int) response_window->tv_sec, (int) response_window->tv_usec);
2993 gettimeofday(&request->proxy_retransmit, NULL);
2995 request->proxy->timestamp = request->proxy_retransmit;
2997 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3000 * Encode the packet before we do anything else.
3002 request->proxy_listener->encode(request->proxy_listener, request);
3003 debug_packet(request, request->proxy, false);
3006 * Set the state function, then the state, no child, and
3009 request->process = proxy_wait_for_reply;
3010 request->child_state = REQUEST_PROXIED;
3014 * And send the packet.
3016 request->proxy_listener->send(request->proxy_listener, request);
3021 * Proxy the packet as if it was new.
3023 static int request_proxy_anew(REQUEST *request)
3025 home_server_t *home;
3027 VERIFY_REQUEST(request);
3030 * Delete the request from the proxy list.
3032 * The packet list code takes care of ensuring that IDs
3033 * aren't reused until all 256 IDs have been used. So
3034 * there's a 1/256 chance of re-using the same ID when
3035 * we're sending to the same home server. Which is
3038 remove_from_proxy_hash(request);
3041 * Find a live home server for the request.
3043 home = home_server_ldb(NULL, request->home_pool, request);
3045 REDEBUG2("Failed to find live home server for request");
3047 if (setup_post_proxy_fail(request)) {
3048 request_queue_or_run(request, proxy_running);
3050 gettimeofday(&request->reply->timestamp, NULL);
3051 request_cleanup_delay_init(request);
3055 home_server_update_request(home, request);
3057 if (!insert_into_proxy_hash(request)) {
3058 RPROXY("Failed to insert retransmission into the proxy list");
3059 goto post_proxy_fail;
3063 * Free the old packet, to force re-encoding
3065 talloc_free(request->proxy->data);
3066 request->proxy->data = NULL;
3067 request->proxy->data_len = 0;
3069 #ifdef WITH_ACCOUNTING
3071 * Update the Acct-Delay-Time attribute.
3073 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3076 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3077 if (!vp) vp = radius_paircreate(request->proxy,
3078 &request->proxy->vps,
3079 PW_ACCT_DELAY_TIME, 0);
3083 gettimeofday(&now, NULL);
3084 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3089 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3094 STATE_MACHINE_DECL(request_ping)
3096 home_server_t *home = request->home_server;
3099 VERIFY_REQUEST(request);
3101 TRACE_STATE_MACHINE;
3105 case FR_ACTION_TIMER:
3106 ERROR("No response to status check %d for home server %s port %d",
3108 inet_ntop(request->proxy->dst_ipaddr.af,
3109 &request->proxy->dst_ipaddr.ipaddr,
3110 buffer, sizeof(buffer)),
3111 request->proxy->dst_port);
3114 case FR_ACTION_PROXY_REPLY:
3115 rad_assert(request->in_proxy_hash);
3117 request->home_server->num_received_pings++;
3118 RPROXY("Received response to status check %d (%d in current sequence)",
3119 request->number, home->num_received_pings);
3122 * Remove the request from any hashes
3124 fr_event_delete(el, &request->ev);
3125 remove_from_proxy_hash(request);
3128 * The control socket may have marked the home server as
3129 * alive. OR, it may have suddenly started responding to
3130 * requests again. If so, don't re-do the "make alive"
3133 if (home->state == HOME_STATE_ALIVE) break;
3136 * It's dead, and we haven't received enough ping
3137 * responses to mark it "alive". Wait a bit.
3139 * If it's zombie, we mark it alive immediately.
3141 if ((home->state == HOME_STATE_IS_DEAD) &&
3142 (home->num_received_pings < home->num_pings_to_alive)) {
3147 * Mark it alive and delete any outstanding
3150 home->state = HOME_STATE_ALIVE;
3151 home->response_timeouts = 0;
3152 exec_trigger(request, home->cs, "home_server.alive", false);
3153 home->currently_outstanding = 0;
3154 home->num_sent_pings = 0;
3155 home->num_received_pings = 0;
3156 gettimeofday(&home->revive_time, NULL);
3158 fr_event_delete(el, &home->ev);
3160 RPROXY("Marking home server %s port %d alive",
3161 inet_ntop(request->proxy->dst_ipaddr.af,
3162 &request->proxy->dst_ipaddr.ipaddr,
3163 buffer, sizeof(buffer)),
3164 request->proxy->dst_port);
3168 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3172 rad_assert(!request->in_request_hash);
3173 rad_assert(request->ev == NULL);
3175 request_done(request, FR_ACTION_DONE);
3179 * Called from start of zombie period, OR after control socket
3180 * marks the home server dead.
3182 static void ping_home_server(void *ctx)
3184 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3187 struct timeval when, now;
3189 if ((home->state == HOME_STATE_ALIVE) ||
3191 (home->proto == IPPROTO_TCP) ||
3193 (home->ev != NULL)) {
3197 gettimeofday(&now, NULL);
3201 * We've run out of zombie time. Mark it dead.
3203 if (home->state == HOME_STATE_ZOMBIE) {
3204 when = home->zombie_period_start;
3205 when.tv_sec += home->zombie_period;
3207 if (timercmp(&when, &now, <)) {
3208 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3209 mark_home_server_dead(home, &now);
3214 * We're not supposed to be pinging it. Just wake up
3215 * when we're supposed to mark it dead.
3217 if (home->ping_check == HOME_PING_CHECK_NONE) {
3218 if (home->state == HOME_STATE_ZOMBIE) {
3219 when = home->zombie_period_start;
3220 when.tv_sec += home->zombie_period;
3221 INSERT_EVENT(ping_home_server, home);
3225 * Else mark_home_server_dead will set a timer
3226 * for revive_interval.
3232 request = request_alloc(NULL);
3233 if (!request) return;
3234 request->number = request_num_counter++;
3237 request->proxy = rad_alloc(request, true);
3238 rad_assert(request->proxy != NULL);
3240 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3241 request->proxy->code = PW_CODE_STATUS_SERVER;
3243 pairmake(request->proxy, &request->proxy->vps,
3244 "Message-Authenticator", "0x00", T_OP_SET);
3246 } else if (home->type == HOME_TYPE_AUTH) {
3247 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3249 pairmake(request->proxy, &request->proxy->vps,
3250 "User-Name", home->ping_user_name, T_OP_SET);
3251 pairmake(request->proxy, &request->proxy->vps,
3252 "User-Password", home->ping_user_password, T_OP_SET);
3253 pairmake(request->proxy, &request->proxy->vps,
3254 "Service-Type", "Authenticate-Only", T_OP_SET);
3255 pairmake(request->proxy, &request->proxy->vps,
3256 "Message-Authenticator", "0x00", T_OP_SET);
3259 #ifdef WITH_ACCOUNTING
3260 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3262 pairmake(request->proxy, &request->proxy->vps,
3263 "User-Name", home->ping_user_name, T_OP_SET);
3264 pairmake(request->proxy, &request->proxy->vps,
3265 "Acct-Status-Type", "Stop", T_OP_SET);
3266 pairmake(request->proxy, &request->proxy->vps,
3267 "Acct-Session-Id", "00000000", T_OP_SET);
3268 vp = pairmake(request->proxy, &request->proxy->vps,
3269 "Event-Timestamp", "0", T_OP_SET);
3270 vp->vp_date = now.tv_sec;
3272 rad_assert("Internal sanity check failed");
3276 vp = pairmake(request->proxy, &request->proxy->vps,
3277 "NAS-Identifier", "", T_OP_SET);
3279 pairsprintf(vp, "Status Check %u. Are you alive?",
3280 home->num_sent_pings);
3283 request->proxy->src_ipaddr = home->src_ipaddr;
3284 request->proxy->dst_ipaddr = home->ipaddr;
3285 request->proxy->dst_port = home->port;
3286 request->home_server = home;
3287 #ifdef DEBUG_STATE_MACHINE
3288 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3289 child_state_names[request->child_state],
3290 child_state_names[REQUEST_DONE]);
3291 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3293 #ifdef HAVE_PTHREAD_H
3294 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3296 request->child_state = REQUEST_PROXIED;
3297 request->process = request_ping;
3299 rad_assert(request->proxy_listener == NULL);
3301 if (!insert_into_proxy_hash(request)) {
3302 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3305 rad_assert(!request->in_request_hash);
3306 rad_assert(!request->in_proxy_hash);
3307 rad_assert(request->ev == NULL);
3308 talloc_free(request);
3313 * Set up the timer callback.
3316 when.tv_sec += home->ping_timeout;
3318 DEBUG("PING: Waiting %u seconds for response to ping",
3319 home->ping_timeout);
3321 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3322 home->num_sent_pings++;
3324 rad_assert(request->proxy_listener != NULL);
3325 request->proxy_listener->send(request->proxy_listener,
3329 * Add +/- 2s of jitter, as suggested in RFC 3539
3330 * and in the Issues and Fixes draft.
3333 home->when.tv_sec += home->ping_interval;
3335 add_jitter(&home->when);
3337 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3338 INSERT_EVENT(ping_home_server, home);
3341 static void home_trigger(home_server_t *home, char const *trigger)
3343 REQUEST *my_request;
3344 RADIUS_PACKET *my_packet;
3346 my_request = talloc_zero(NULL, REQUEST);
3347 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3348 my_request->proxy = my_packet;
3349 my_packet->dst_ipaddr = home->ipaddr;
3350 my_packet->src_ipaddr = home->src_ipaddr;
3352 exec_trigger(my_request, home->cs, trigger, false);
3353 talloc_free(my_request);
3356 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3363 rad_assert((home->state == HOME_STATE_ALIVE) ||
3364 (home->state == HOME_STATE_UNKNOWN));
3367 if (home->proto == IPPROTO_TCP) {
3368 WARN("Not marking TCP server %s zombie", home->log_name);
3374 * We've received a real packet recently. Don't mark the
3375 * server as zombie until we've received NO packets for a
3376 * while. The "1/4" of zombie period was chosen rather
3377 * arbitrarily. It's a balance between too short, which
3378 * gives quick fail-over and fail-back, or too long,
3379 * where the proxy still sends packets to an unresponsive
3382 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3383 if (home->last_packet_recv >= start) {
3384 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3385 (int) (now->tv_sec - home->last_packet_recv));
3389 home->state = HOME_STATE_ZOMBIE;
3390 home_trigger(home, "home_server.zombie");
3393 * Set the home server to "zombie", as of the time
3396 home->zombie_period_start.tv_sec = start;
3397 home->zombie_period_start.tv_usec = USEC / 2;
3399 fr_event_delete(el, &home->ev);
3401 home->num_sent_pings = 0;
3402 home->num_received_pings = 0;
3404 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3405 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3406 buffer, sizeof(buffer)),
3407 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3409 ping_home_server(home);
3413 void revive_home_server(void *ctx)
3415 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3419 rad_assert(home->proto != IPPROTO_TCP);
3422 home->state = HOME_STATE_ALIVE;
3423 home->response_timeouts = 0;
3424 home_trigger(home, "home_server.alive");
3425 home->currently_outstanding = 0;
3426 gettimeofday(&home->revive_time, NULL);
3429 * Delete any outstanding events.
3432 if (home->ev) fr_event_delete(el, &home->ev);
3434 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3435 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3436 buffer, sizeof(buffer)),
3440 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3442 int previous_state = home->state;
3446 if (home->proto == IPPROTO_TCP) {
3447 WARN("Not marking TCP server dead");
3452 PROXY( "Marking home server %s port %d as dead.",
3453 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3454 buffer, sizeof(buffer)),
3457 home->state = HOME_STATE_IS_DEAD;
3458 home_trigger(home, "home_server.dead");
3460 if (home->ping_check != HOME_PING_CHECK_NONE) {
3462 * If the control socket marks us dead, start
3463 * pinging. Otherwise, we already started
3464 * pinging when it was marked "zombie".
3466 if (previous_state == HOME_STATE_ALIVE) {
3467 ping_home_server(home);
3469 DEBUG("PING: Already pinging home server %s", home->log_name);
3474 * Revive it after a fixed period of time. This
3475 * is very, very, bad.
3478 home->when.tv_sec += home->revive_interval;
3480 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3482 INSERT_EVENT(revive_home_server, home);
3486 STATE_MACHINE_DECL(proxy_wait_for_reply)
3488 struct timeval now, when;
3489 struct timeval *response_window = NULL;
3490 home_server_t *home = request->home_server;
3493 VERIFY_REQUEST(request);
3495 TRACE_STATE_MACHINE;
3498 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3499 rad_assert(request->home_server != NULL);
3501 gettimeofday(&now, NULL);
3506 * We have a reply, ignore the retransmit.
3508 if (request->proxy_reply) return;
3511 * The request was proxied to a virtual server.
3512 * Ignore the retransmit.
3514 if (request->home_server->server) return;
3516 if ((home->state == HOME_STATE_IS_DEAD) ||
3517 !request->proxy_listener ||
3518 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3519 request_proxy_anew(request);
3524 if (home->proto == IPPROTO_TCP) {
3525 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3526 inet_ntop(request->proxy->dst_ipaddr.af,
3527 &request->proxy->dst_ipaddr.ipaddr,
3528 buffer, sizeof(buffer)),
3529 request->proxy->dst_port,
3530 request->proxy->id);
3536 * More than one retransmit a second is stupid,
3537 * and should be suppressed by the proxy.
3539 when = request->proxy_retransmit;
3542 if (timercmp(&now, &when, <)) {
3543 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3544 inet_ntop(request->proxy->dst_ipaddr.af,
3545 &request->proxy->dst_ipaddr.ipaddr,
3546 buffer, sizeof(buffer)),
3547 request->proxy->dst_port,
3548 request->proxy->id);
3552 #ifdef WITH_ACCOUNTING
3554 * If we update the Acct-Delay-Time, we need to
3557 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3558 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3559 request_proxy_anew(request);
3564 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3565 inet_ntop(request->proxy->dst_ipaddr.af,
3566 &request->proxy->dst_ipaddr.ipaddr,
3567 buffer, sizeof(buffer)),
3568 request->proxy->dst_port,
3569 request->proxy->id);
3570 request->num_proxied_requests++;
3572 rad_assert(request->proxy_listener != NULL);
3573 FR_STATS_TYPE_INC(home->stats.total_requests);
3574 home->last_packet_sent = now.tv_sec;
3575 request->proxy_retransmit = now;
3576 request->proxy_listener->send(request->proxy_listener, request);
3577 debug_packet(request, request->proxy, false);
3580 case FR_ACTION_TIMER:
3581 response_window = request_response_window(request);
3584 if (!request->proxy_listener ||
3585 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3586 remove_from_proxy_hash(request);
3588 when = request->packet->timestamp;
3589 when.tv_sec += request->root->max_request_time;
3591 if (timercmp(&when, &now, >)) {
3592 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3593 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3600 * Wake up "response_window" time in the future.
3601 * i.e. when MY packet hasn't received a response.
3603 * Note that we DO NOT mark the home server as
3604 * zombie if it doesn't respond to us. It may be
3605 * responding to other (better looking) packets.
3607 when = request->proxy->timestamp;
3608 timeradd(&when, response_window, &when);
3611 * Not at the response window. Set the timer for
3614 if (timercmp(&when, &now, >)) {
3615 struct timeval diff;
3616 timersub(&when, &now, &diff);
3618 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3619 (int) diff.tv_sec, (int) diff.tv_usec);
3620 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3625 RDEBUG("No proxy response, giving up on request and marking it done");
3628 * If we haven't received any packets for
3629 * "response_window", then mark the home server
3632 * If the connection is TCP, then another
3633 * "watchdog timer" function takes care of pings,
3634 * etc. So we don't need to do it here.
3636 * This check should really be part of a home
3637 * server state machine.
3639 if (((home->state == HOME_STATE_ALIVE) ||
3640 (home->state == HOME_STATE_UNKNOWN))
3642 && (home->proto != IPPROTO_TCP)
3645 home->response_timeouts++;
3646 if (home->response_timeouts >= home->max_response_timeouts)
3647 mark_home_server_zombie(home, &now, response_window);
3650 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3651 if (home->type == HOME_TYPE_AUTH) {
3652 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3653 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3656 else if (home->type == HOME_TYPE_ACCT) {
3657 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3658 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3663 * There was no response within the window. Stop
3664 * the request. If the client retransmitted, it
3665 * may have failed over to another home server.
3666 * But that one may be dead, too.
3668 * The extra verbose message if we have a username,
3669 * is extremely useful if the proxy is part of a chain
3670 * and the final home server, is not the one we're
3673 if (request->username) {
3674 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3675 "server %s port %d",
3676 request->username->vp_strvalue,
3677 inet_ntop(request->proxy->dst_ipaddr.af,
3678 &request->proxy->dst_ipaddr.ipaddr,
3679 buffer, sizeof(buffer)),
3680 request->proxy->dst_port);
3682 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3683 inet_ntop(request->proxy->dst_ipaddr.af,
3684 &request->proxy->dst_ipaddr.ipaddr,
3685 buffer, sizeof(buffer)),
3686 request->proxy->dst_port);
3689 if (setup_post_proxy_fail(request)) {
3690 request_queue_or_run(request, proxy_no_reply);
3692 gettimeofday(&request->reply->timestamp, NULL);
3693 request_cleanup_delay_init(request);
3698 * We received a new reply. Go process it.
3700 case FR_ACTION_PROXY_REPLY:
3701 request_queue_or_run(request, proxy_running);
3705 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3709 #endif /* WITH_PROXY */
3711 /***********************************************************************
3715 ***********************************************************************/
3717 static int null_handler(UNUSED REQUEST *request)
3723 * See if we need to originate a CoA request.
3725 static void request_coa_originate(REQUEST *request)
3727 int rcode, pre_proxy_type = 0;
3733 VERIFY_REQUEST(request);
3735 rad_assert(request->coa != NULL);
3736 rad_assert(request->proxy == NULL);
3737 rad_assert(!request->in_proxy_hash);
3738 rad_assert(request->proxy_reply == NULL);
3741 * Check whether we want to originate one, or cancel one.
3743 vp = pairfind(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3745 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3749 if (vp->vp_integer == 0) {
3751 TALLOC_FREE(request->coa);
3759 * src_ipaddr will be set up in proxy_encode.
3761 memset(&ipaddr, 0, sizeof(ipaddr));
3762 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3764 ipaddr.af = AF_INET;
3765 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3767 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3768 ipaddr.af = AF_INET6;
3769 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3770 ipaddr.prefix = 128;
3771 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3772 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3774 if (!coa->home_pool) {
3775 RWDEBUG2("No such home_server_pool %s",
3781 * Prefer the pool to one server
3783 } else if (request->client->coa_pool) {
3784 coa->home_pool = request->client->coa_pool;
3786 } else if (request->client->coa_server) {
3787 coa->home_server = request->client->coa_server;
3791 * If all else fails, send it to the client that
3792 * originated this request.
3794 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3798 * Use the pool, if it exists.
3800 if (coa->home_pool) {
3801 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3802 if (!coa->home_server) {
3803 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3806 home_server_update_request(coa->home_server, coa);
3808 } else if (!coa->home_server) {
3809 uint16_t port = PW_COA_UDP_PORT;
3811 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3812 if (vp) port = vp->vp_integer;
3814 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3815 if (!coa->home_server) {
3816 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3817 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3818 buffer, sizeof(buffer)), port);
3823 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3825 switch (vp->vp_integer) {
3826 case PW_CODE_COA_REQUEST:
3827 case PW_CODE_DISCONNECT_REQUEST:
3828 coa->proxy->code = vp->vp_integer;
3832 DEBUG("Cannot set CoA Packet-Type to code %d",
3838 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3841 * The rest of the server code assumes that
3842 * request->packet && request->reply exist. Copy them
3843 * from the original request.
3845 rad_assert(coa->packet != NULL);
3846 rad_assert(coa->packet->vps == NULL);
3848 coa->packet = rad_copy_packet(coa, request->packet);
3849 coa->reply = rad_copy_packet(coa, request->reply);
3851 coa->config = paircopy(coa, request->config);
3852 coa->num_coa_requests = 0;
3853 coa->handle = null_handler;
3854 coa->number = request->number; /* it's associated with the same request */
3857 * Call the pre-proxy routines.
3859 vp = pairfind(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3861 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3862 /* Must be a validation issue */
3864 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3865 pre_proxy_type = vp->vp_integer;
3868 if (coa->home_pool && coa->home_pool->virtual_server) {
3869 char const *old_server = coa->server;
3871 coa->server = coa->home_pool->virtual_server;
3872 RDEBUG2("server %s {", coa->server);
3874 rcode = process_pre_proxy(pre_proxy_type, coa);
3877 coa->server = old_server;
3879 rcode = process_pre_proxy(pre_proxy_type, coa);
3886 * Only send the CoA packet if the pre-proxy code succeeded.
3888 case RLM_MODULE_NOOP:
3890 case RLM_MODULE_UPDATED:
3895 * Source IP / port is set when the proxy socket
3898 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3899 coa->proxy->dst_port = coa->home_server->port;
3901 if (!insert_into_proxy_hash(coa)) {
3902 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
3907 * We CANNOT divorce the CoA request from the parent
3908 * request. This function is running in a child thread,
3909 * and we need access to the main event loop in order to
3910 * to add the timers for the CoA packet.
3912 * Instead, we wait for the timer on the parent request
3915 gettimeofday(&coa->proxy->timestamp, NULL);
3916 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3917 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3918 coa->delay = 0; /* need to calculate a new delay */
3921 * If requested, put a State attribute into the packet,
3922 * and cache the VPS.
3924 fr_state_put_vps(coa, NULL, coa->packet);
3927 * Encode the packet before we do anything else.
3929 coa->proxy_listener->encode(coa->proxy_listener, coa);
3930 debug_packet(coa, coa->proxy, false);
3932 #ifdef DEBUG_STATE_MACHINE
3933 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3934 child_state_names[request->child_state],
3935 child_state_names[REQUEST_PROXIED]);
3939 * Set the state function, then the state, no child, and
3942 coa->process = coa_wait_for_reply;
3943 coa->child_state = REQUEST_PROXIED;
3945 #ifdef HAVE_PTHREAD_H
3946 coa->child_pid = NO_SUCH_CHILD_PID;
3950 * And send the packet.
3952 coa->proxy_listener->send(coa->proxy_listener, coa);
3956 static void coa_retransmit(REQUEST *request)
3958 uint32_t delay, frac;
3959 struct timeval now, when, mrd;
3961 VERIFY_REQUEST(request);
3963 fr_event_now(el, &now);
3966 * FIXME: Enforce max_request_time
3969 if (request->delay == 0) {
3971 * Implement re-transmit algorithm as per RFC 5080
3974 * We want IRT + RAND*IRT
3975 * or 0.9 IRT + rand(0,.2) IRT
3977 * 2^20 ~ USEC, and we want 2.
3978 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3980 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3981 request->delay = delay * request->home_server->coa_irt;
3982 delay = request->home_server->coa_irt * USEC;
3983 delay -= delay / 10;
3984 delay += request->delay;
3985 request->delay = delay;
3987 when = request->proxy->timestamp;
3988 tv_add(&when, delay);
3990 if (timercmp(&when, &now, >)) {
3991 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3997 * Retransmit CoA request.
4001 * Cap count at MRC, if it is non-zero.
4003 if (request->home_server->coa_mrc &&
4004 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4007 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4009 inet_ntop(request->proxy->dst_ipaddr.af,
4010 &request->proxy->dst_ipaddr.ipaddr,
4011 buffer, sizeof(buffer)),
4012 request->proxy->dst_port);
4014 if (setup_post_proxy_fail(request)) {
4015 request_queue_or_run(request, coa_no_reply);
4017 request_done(request, FR_ACTION_DONE);
4023 * RFC 5080 Section 2.2.1
4025 * RT = 2*RTprev + RAND*RTprev
4026 * = 1.9 * RTprev + rand(0,.2) * RTprev
4027 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4030 delay ^= (delay >> 16);
4032 frac = request->delay / 5;
4033 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4035 delay += (2 * request->delay) - (request->delay / 10);
4038 * Cap delay at MRT, if MRT is non-zero.
4040 if (request->home_server->coa_mrt &&
4041 (delay > (request->home_server->coa_mrt * USEC))) {
4042 int mrt_usec = request->home_server->coa_mrt * USEC;
4045 * delay = MRT + RAND * MRT
4046 * = 0.9 MRT + rand(0,.2) * MRT
4049 delay ^= (delay >> 15);
4051 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4052 delay += mrt_usec - (mrt_usec / 10);
4055 request->delay = delay;
4057 tv_add(&when, request->delay);
4058 mrd = request->proxy->timestamp;
4059 mrd.tv_sec += request->home_server->coa_mrd;
4062 * Cap duration at MRD.
4064 if (timercmp(&mrd, &when, <)) {
4067 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4069 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4071 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4073 request->proxy_listener->send(request->proxy_listener,
4077 STATE_MACHINE_DECL(coa_wait_for_reply)
4079 VERIFY_REQUEST(request);
4081 TRACE_STATE_MACHINE;
4086 case FR_ACTION_TIMER:
4087 if (request->parent) coa_separate(request);
4089 coa_retransmit(request);
4092 case FR_ACTION_PROXY_REPLY:
4093 if (request->parent) coa_separate(request);
4095 request_queue_or_run(request, coa_running);
4099 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4104 static void coa_separate(REQUEST *request)
4106 VERIFY_REQUEST(request);
4107 #ifdef DEBUG_STATE_MACHINE
4108 int action = FR_ACTION_TIMER;
4111 TRACE_STATE_MACHINE;
4114 rad_assert(request->parent != NULL);
4115 rad_assert(request->parent->coa == request);
4116 rad_assert(request->ev == NULL);
4117 rad_assert(!request->in_request_hash);
4118 rad_assert(request->coa == NULL);
4120 rad_assert(request->proxy_reply || request->proxy_listener);
4122 (void) talloc_steal(NULL, request);
4123 request->parent->coa = NULL;
4124 request->parent = NULL;
4127 STATE_MACHINE_DECL(coa_no_reply)
4131 VERIFY_REQUEST(request);
4133 TRACE_STATE_MACHINE;
4137 case FR_ACTION_TIMER:
4138 request_max_time(request);
4141 case FR_ACTION_PROXY_REPLY: /* too late! */
4142 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4143 inet_ntop(request->proxy->src_ipaddr.af,
4144 &request->proxy->src_ipaddr.ipaddr,
4145 buffer, sizeof(buffer)),
4146 request->proxy->dst_port, request->proxy->id);
4150 if (process_proxy_reply(request, NULL)) {
4151 request->handle(request);
4153 request_done(request, FR_ACTION_DONE);
4157 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4162 STATE_MACHINE_DECL(coa_running)
4164 VERIFY_REQUEST(request);
4166 TRACE_STATE_MACHINE;
4170 case FR_ACTION_TIMER:
4171 request_max_time(request);
4175 if (process_proxy_reply(request, request->proxy_reply)) {
4176 request->handle(request);
4178 request_done(request, FR_ACTION_DONE);
4182 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4186 #endif /* WITH_COA */
4188 /***********************************************************************
4190 * End of the State machine. Start of additional helper code.
4192 ***********************************************************************/
4194 /***********************************************************************
4198 ***********************************************************************/
4199 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4201 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4203 rad_assert(xel == el);
4205 if ((listener->fd < 0)
4207 #ifndef WITH_DETAIL_THREAD
4208 && (listener->type != RAD_LISTEN_DETAIL)
4214 listener->print(listener, buffer, sizeof(buffer));
4215 ERROR("FATAL: Asked to read from closed socket: %s",
4218 rad_panic("Socket was closed on us!");
4222 listener->recv(listener);
4226 #ifdef WITH_DETAIL_THREAD
4229 * This function is called periodically to see if this detail
4230 * file is available for reading.
4232 static void event_poll_detail(void *ctx)
4235 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4236 struct timeval when, now;
4237 listen_detail_t *detail = this->data;
4239 rad_assert(this->type == RAD_LISTEN_DETAIL);
4242 event_socket_handler(el, this->fd, this);
4244 fr_event_now(el, &now);
4248 * Backdoor API to get the delay until the next poll
4251 delay = this->encode(this, NULL);
4252 if (delay == 0) goto redo;
4254 tv_add(&when, delay);
4257 if (!fr_event_insert(el, event_poll_detail, this,
4258 &when, &detail->ev)) {
4259 ERROR("Failed creating handler");
4263 #endif /* WITH_DETAIL_THREAD */
4264 #endif /* WITH_DETAIL */
4266 static void event_status(struct timeval *wake)
4268 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4272 if (debug_flag == 0) {
4274 INFO("Ready to process requests");
4275 just_started = false;
4281 INFO("Ready to process requests");
4283 } else if ((wake->tv_sec != 0) ||
4284 (wake->tv_usec >= 100000)) {
4285 DEBUG("Waking up in %d.%01u seconds.",
4286 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4291 * FIXME: Put this somewhere else, where it isn't called
4292 * all of the time...
4295 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4297 * If there are no child threads, then there may
4298 * be child processes. In that case, wait for
4299 * their exit status, and throw that exit status
4300 * away. This helps get rid of zxombie children.
4302 while (waitpid(-1, &argval, WNOHANG) > 0) {
4310 static void listener_free_cb(void *ctx)
4312 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4315 if (this->count > 0) {
4316 struct timeval when;
4317 listen_socket_t *sock = this->data;
4319 fr_event_now(el, &when);
4323 if (!fr_event_insert(el, listener_free_cb, this, &when,
4325 rad_panic("Failed to insert event");
4332 * It's all free, close the socket.
4335 this->print(this, buffer, sizeof(buffer));
4336 DEBUG("... cleaning up socket %s", buffer);
4337 rad_assert(this->next == NULL);
4343 static int proxy_eol_cb(void *ctx, void *data)
4345 struct timeval when;
4346 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4348 if (request->proxy_listener != ctx) return 0;
4351 * We don't care if it's being processed in a child thread.
4354 #ifdef WITH_ACCOUNTING
4356 * Accounting packets should be deleted immediately.
4357 * They will never be retransmitted by the client.
4359 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4360 RDEBUG("Stopping request due to failed connection to home server");
4361 request->master_state = REQUEST_STOP_PROCESSING;
4366 * Reset the timer to be now, so that the request is
4367 * quickly updated. But spread the requests randomly
4368 * over the next second, so that we don't overload the
4371 fr_event_now(el, &when);
4372 tv_add(&when, fr_rand() % USEC);
4373 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4376 * Don't delete it from the list.
4382 static int event_new_fd(rad_listen_t *this)
4388 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4390 this->print(this, buffer, sizeof(buffer));
4392 if (this->status == RAD_LISTEN_STATUS_INIT) {
4393 listen_socket_t *sock = this->data;
4395 rad_assert(sock != NULL);
4397 DEBUG("Listening on %s", buffer);
4400 } else if (this->type == RAD_LISTEN_PROXY) {
4401 home_server_t *home;
4404 if (!home || !home->limit.max_connections) {
4405 INFO(" ... adding new socket %s", buffer);
4407 INFO(" ... adding new socket %s (%u of %u)", buffer,
4408 home->limit.num_connections, home->limit.max_connections);
4413 INFO(" ... adding new socket %s", buffer);
4416 switch (this->type) {
4419 * Detail files are always known, and aren't
4420 * put into the socket event loop.
4422 case RAD_LISTEN_DETAIL:
4423 this->status = RAD_LISTEN_STATUS_KNOWN;
4425 #ifndef WITH_DETAIL_THREAD
4427 * Set up the first poll interval.
4429 event_poll_detail(this);
4432 break; /* add the FD to the list */
4434 #endif /* WITH_DETAIL */
4438 * Add it to the list of sockets we can use.
4439 * Server sockets (i.e. auth/acct) are never
4440 * added to the packet list.
4442 case RAD_LISTEN_PROXY:
4444 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4447 * Add timers to outgoing child sockets, if necessary.
4449 if (sock->proto == IPPROTO_TCP && sock->opened &&
4450 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4451 struct timeval when;
4453 when.tv_sec = sock->opened + 1;
4457 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4459 rad_panic("Failed to insert event");
4464 #endif /* WITH_PROXY */
4467 * FIXME: put idle timers on command sockets.
4473 * Add timers to incoming child sockets, if necessary.
4475 if (sock->proto == IPPROTO_TCP && sock->opened &&
4476 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4477 struct timeval when;
4479 when.tv_sec = sock->opened + 1;
4483 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4485 ERROR("Failed adding timer for socket: %s", fr_strerror());
4491 } /* switch over listener types */
4494 * All sockets: add the FD to the event handler.
4496 if (!fr_event_fd_insert(el, 0, this->fd,
4497 event_socket_handler, this)) {
4498 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4502 this->status = RAD_LISTEN_STATUS_KNOWN;
4508 * Stop using this socket, if at all possible.
4510 if (this->status == RAD_LISTEN_STATUS_EOL) {
4512 * Remove it from the list of live FD's.
4514 fr_event_fd_delete(el, 0, this->fd);
4518 * Proxy sockets get frozen, so that we don't use
4519 * them for new requests. But we do keep them
4520 * open to listen for replies to requests we had
4523 if (this->type == RAD_LISTEN_PROXY) {
4524 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4525 if (!fr_packet_list_socket_freeze(proxy_list,
4527 ERROR("Fatal error freezing socket: %s", fr_strerror());
4531 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4532 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4537 * Requests are still using the socket. Wait for
4540 if (this->count > 0) {
4541 struct timeval when;
4542 listen_socket_t *sock = this->data;
4545 * Try again to clean up the socket in 30
4548 gettimeofday(&when, NULL);
4552 if (!fr_event_insert(el,
4553 (fr_event_callback_t) event_new_fd,
4554 this, &when, &sock->ev)) {
4555 rad_panic("Failed to insert event");
4562 * No one is using the socket. We can remove it now.
4564 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4565 } /* socket is at EOL */
4571 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4574 listen_socket_t *sock = this->data;
4576 struct timeval when;
4579 * Re-open the socket, pointing it to /dev/null.
4580 * This means that all writes proceed without
4581 * blocking, and all reads return "no data".
4583 * This leaves the socket active, so any child
4584 * threads won't go insane. But it means that
4585 * they cannot send or receive any packets.
4587 * This is EXTRA work in the normal case, when
4588 * sockets are closed without error. But it lets
4589 * us have one simple processing method for all
4592 devnull = open("/dev/null", O_RDWR);
4594 ERROR("FATAL failure opening /dev/null: %s",
4595 fr_syserror(errno));
4598 if (dup2(devnull, this->fd) < 0) {
4599 ERROR("FATAL failure closing socket: %s",
4600 fr_syserror(errno));
4606 rad_assert(this->type != RAD_LISTEN_DETAIL);
4612 * The socket is dead. Force all proxied packets
4613 * to stop using it. And then remove it from the
4614 * list of outgoing sockets.
4616 if (this->type == RAD_LISTEN_PROXY) {
4617 home_server_t *home;
4620 if (!home || !home->limit.max_connections) {
4621 INFO(" ... shutting down socket %s", buffer);
4623 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4624 home->limit.num_connections, home->limit.max_connections);
4627 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4628 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4630 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4631 ERROR("Fatal error removing socket %s: %s",
4632 buffer, fr_strerror());
4635 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4639 INFO(" ... shutting down socket %s", buffer);
4642 * EOL all requests using this socket.
4644 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4648 * No child threads, clean it up now.
4652 if (sock->ev) fr_event_delete(el, &sock->ev);
4658 * Wait until all requests using this socket are done.
4660 gettimeofday(&when, NULL);
4664 if (!fr_event_insert(el, listener_free_cb, this, &when,
4666 rad_panic("Failed to insert event");
4669 #endif /* WITH_TCP */
4674 /***********************************************************************
4678 ***********************************************************************/
4680 static void handle_signal_self(int flag)
4684 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4685 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4686 INFO("Signalled to exit");
4687 fr_event_loop_exit(el, 1);
4689 INFO("Signalled to terminate");
4690 fr_event_loop_exit(el, 2);
4694 } /* else exit/term flags weren't set */
4697 * Tell the even loop to stop processing.
4699 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4701 static time_t last_hup = 0;
4704 if ((int) (when - last_hup) < 5) {
4705 INFO("Ignoring HUP (less than 5s since last one)");
4709 INFO("Received HUP signal");
4713 exec_trigger(NULL, NULL, "server.signal.hup", true);
4714 fr_event_loop_exit(el, 0x80);
4717 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
4718 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4722 * FIXME: O(N) loops suck.
4724 for (this = main_config.listen;
4726 this = this->next) {
4727 if (this->type != RAD_LISTEN_DETAIL) continue;
4730 * This one didn't send the signal, skip
4733 if (!this->decode(this, NULL)) continue;
4736 * Go service the interrupt.
4738 event_poll_detail(this);
4743 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
4745 * There are new listeners in the list. Run
4746 * event_new_fd() on them.
4748 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4749 rad_listen_t *this, *next;
4751 FD_MUTEX_LOCK(&fd_mutex);
4754 * FIXME: unlock the mutex before calling
4757 for (this = new_listeners; this != NULL; this = next) {
4764 new_listeners = NULL;
4765 FD_MUTEX_UNLOCK(&fd_mutex);
4770 #ifndef HAVE_PTHREAD_H
4771 void radius_signal_self(int flag)
4773 return handle_signal_self(flag);
4777 static int self_pipe[2] = { -1, -1 };
4780 * Inform ourselves that we received a signal.
4782 void radius_signal_self(int flag)
4788 * The read MUST be non-blocking for this to work.
4790 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4794 for (i = 0; i < rcode; i++) {
4795 buffer[0] |= buffer[i];
4803 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4807 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4808 UNUSED int fd, UNUSED void *ctx)
4813 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4814 if (rcode <= 0) return;
4817 * Merge pending signals.
4819 for (i = 0; i < rcode; i++) {
4820 buffer[0] |= buffer[i];
4823 handle_signal_self(buffer[0]);
4825 #endif /* HAVE_PTHREAD_H */
4827 /***********************************************************************
4829 * Bootstrapping code.
4831 ***********************************************************************/
4834 * Externally-visibly functions.
4836 int radius_event_init(TALLOC_CTX *ctx) {
4837 el = fr_event_list_create(ctx, event_status);
4843 static int packet_entry_cmp(void const *one, void const *two)
4845 RADIUS_PACKET const * const *a = one;
4846 RADIUS_PACKET const * const *b = two;
4848 return fr_packet_cmp(*a, *b);
4852 int radius_event_start(CONF_SECTION *cs, bool have_children)
4854 rad_listen_t *head = NULL;
4856 if (fr_start_time != (time_t)-1) return 0;
4858 time(&fr_start_time);
4860 if (!check_config) {
4862 * radius_event_init() must be called first
4866 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
4867 if (!pl) return 0; /* leak el */
4870 request_num_counter = 0;
4873 if (main_config.proxy_requests) {
4875 * Create the tree for managing proxied requests and
4878 proxy_list = fr_packet_list_create(1);
4879 if (!proxy_list) return 0;
4881 #ifdef HAVE_PTHREAD_H
4882 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4883 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4884 fr_syserror(errno));
4890 * The "init_delay" is set to "response_window".
4891 * Reset it to half of "response_window" in order
4892 * to give the event loop enough time to service
4893 * the event before hitting "response_window".
4895 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
4896 main_config.init_delay.tv_usec >>= 1;
4897 main_config.init_delay.tv_sec >>= 1;
4899 proxy_ctx = talloc_init("proxy");
4904 * Move all of the thread calls to this file?
4906 * It may be best for the mutexes to be in this file...
4908 spawn_flag = have_children;
4910 #ifdef HAVE_PTHREAD_H
4911 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4914 * Initialize the threads ONLY if we're spawning, AND
4915 * we're running normally.
4917 if (have_children && !check_config &&
4918 (thread_pool_init(cs, &spawn_flag) < 0)) {
4924 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4926 if (listen_init(cs, &head, spawn_flag) < 0) {
4933 #ifdef HAVE_PTHREAD_H
4935 * Child threads need a pipe to signal us, as do the
4938 if (pipe(self_pipe) < 0) {
4939 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
4942 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4943 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4944 ERROR("Error setting internal flags: %s", fr_syserror(errno));
4947 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4948 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4949 ERROR("Error setting internal flags: %s", fr_syserror(errno));
4952 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
4954 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
4955 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
4960 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
4963 * The server temporarily switches to an unprivileged
4964 * user very early in the bootstrapping process.
4965 * However, some sockets MAY require privileged access
4966 * (bind to device, or to port < 1024, or to raw
4967 * sockets). Those sockets need to call suid up/down
4968 * themselves around the functions that need a privileged
4971 if (listen_init(cs, &head, spawn_flag) < 0) {
4975 main_config.listen = head;
4978 * At this point, no one has any business *ever* going
4981 rad_suid_down_permanent();
4988 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4990 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4992 VERIFY_REQUEST(request);
4994 request->master_state = REQUEST_STOP_PROCESSING;
4996 #ifdef HAVE_PTHREAD_H
4997 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5001 * If it's queued we can't delete it from the queue.
5003 * Otherwise, it's OK to delete it. Even RUNNING, because
5004 * that will get caught by the check above.
5006 if (request->child_state == REQUEST_QUEUED) return 0;
5008 request->in_proxy_hash = false;
5010 if (!request->in_request_hash) {
5011 request_done(request, FR_ACTION_DONE);
5015 * Delete it from the list.
5022 static int request_delete_cb(UNUSED void *ctx, void *data)
5024 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5026 VERIFY_REQUEST(request);
5028 request->master_state = REQUEST_STOP_PROCESSING;
5031 * Not done, or the child thread is still processing it.
5033 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5035 #ifdef HAVE_PTHREAD_H
5036 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5040 rad_assert(request->in_proxy_hash == false);
5043 request->in_request_hash = false;
5045 if (request->ev) fr_event_delete(el, &request->ev);
5047 if (main_config.memory_report) {
5048 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5049 request->packet->id,
5050 (unsigned int) (request->timestamp - fr_start_time));
5055 rad_assert(!request->coa->in_proxy_hash);
5059 request_free(request);
5062 * Delete it from the list, and continue;
5068 void radius_event_free(void)
5074 * There are requests in the proxy hash that aren't
5075 * referenced from anywhere else. Remove them first.
5078 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5082 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5086 * Now that all requests have been marked "please stop",
5087 * ensure that all of the threads have exited.
5089 #ifdef HAVE_PTHREAD_H
5094 * Walk the lists again, ensuring that all
5095 * requests are done.
5097 if (main_config.memory_report) {
5102 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5103 num = fr_packet_list_num_elements(proxy_list);
5105 ERROR("Proxy list has %d requests still in it.", num);
5110 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5111 num = rbtree_num_elements(pl);
5113 ERROR("Request list has %d requests still in it.", num);
5122 fr_packet_list_free(proxy_list);
5125 if (proxy_ctx) talloc_free(proxy_ctx);
5130 if (debug_condition) talloc_free(debug_condition);
5133 int radius_event_process(void)
5137 return fr_event_loop(el);