2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Defines the state machines that control how requests are processed.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
34 #include <freeradius-devel/rad_assert.h>
37 #include <freeradius-devel/detail.h>
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
47 extern pid_t radius_pid;
48 extern fr_cond_t *debug_condition;
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static rbtree_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57 /* Currently we do not run a second event loop for modules. */
61 static char const *action_codes[] = {
72 #ifdef DEBUG_STATE_MACHINE
73 # define TRACE_STATE_MACHINE \
74 if (rad_debug_lvl) do { \
75 struct timeval debug_tv; \
76 gettimeofday(&debug_tv, NULL); \
77 debug_tv.tv_sec -= fr_start_time; \
78 printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79 request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80 __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81 child_state_names[request->child_state]); \
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
102 # define TRACE_STATE_MACHINE {}
105 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
107 ERROR("%s[%u]: %s", file, line, msg);
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
113 /** Declare a state in the state machine
115 * Expands to the start of a function definition for a given state.
117 * @param _x the name of the state.
119 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
121 static void request_timer(void *ctx);
123 /** Insert #REQUEST back into the event heap, to continue executing at a future time
125 * @param file the state machine timer call occurred in.
126 * @param line the state machine timer call occurred on.
127 * @param request to set add the timer event for.
128 * @param when the event should fine.
129 * @param action to perform when we resume processing the request.
131 static inline void state_machine_timer(char const *file, int line, REQUEST *request,
132 struct timeval *when, fr_state_action_t action)
134 request->timer_action = action;
135 if (!fr_event_insert(el, request_timer, request, when, &request->ev)) {
136 _rad_panic(file, line, "Failed to insert event");
140 /** @copybrief state_machine_timer
142 * @param _x the action to perform when we resume processing the request.
144 #define STATE_MACHINE_TIMER(_x) state_machine_timer(__FILE__, __LINE__, request, &when, _x)
147 * We need a different VERIFY_REQUEST macro in process.c
148 * To avoid the race conditions with the master thread
149 * checking the REQUEST whilst it's being worked on by
152 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
153 # undef VERIFY_REQUEST
154 # define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
158 * @section request_timeline
160 * Time sequence of a request
163 * RQ-----------------P=============================Y-J-C
164 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
167 * - R: received. Duplicate detection is done, and request is
170 * - Q: Request is placed onto a queue for child threads to pick up.
171 * If there are no child threads, the request goes immediately
174 * - P: Processing the request through the modules.
176 * - Y: Reply is ready. Rejects MAY be delayed here. All other
177 * replies are sent immediately.
179 * - J: Reject is sent "response_delay" after the reply is ready.
181 * - C: For Access-Requests, After "cleanup_delay", the request is
182 * deleted. Accounting-Request packets go directly from Y to C.
184 * - M: Max request time. If the request hits this timer, it is
187 * Other considerations include duplicate and conflicting
188 * packets. When a dupicate packet is received, it is ignored
189 * until we've reached Y, as no response is ready. If the reply
190 * is a reject, duplicates are ignored until J, when we're ready
191 * to send the reply. In between the reply being sent (Y or J),
192 * and C, the server responds to duplicates by sending the cached
195 * Conflicting packets are sent in 2 situations.
197 * The first is in between R and Y. In that case, we consider
198 * it as a hint that we're taking too long, and the NAS has given
199 * up on the request. We then behave just as if the M timer was
200 * reached, and we discard the current request. This allows us
201 * to process the new one.
203 * The second case is when we're at Y, but we haven't yet
204 * finished processing the request. This is a race condition in
205 * the threading code (avoiding locks is faster). It means that
206 * a thread has actually encoded and sent the reply, and that the
207 * NAS has responded with a new packet. The server can then
208 * safely mark the current request as "OK to delete", and behaves
209 * just as if the M timer was reached. This usually happens only
210 * in high-load situations.
212 * Duplicate packets are sent when the NAS thinks we're taking
213 * too long, and wants a reply. From R-Y, duplicates are
214 * ignored. From Y-J (for Access-Rejects), duplicates are also
215 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
216 * they cause the "cleanup_delay" time to be extended. This
217 * extension means that we're more likely to send a duplicate
218 * reply (if we have one), or to suppress processing the packet
219 * twice if we didn't reply to it.
221 * All functions in this file should be thread-safe, and should
222 * assume thet the REQUEST structure is being accessed
223 * simultaneously by the main thread, and by the child worker
224 * threads. This means that timers, etc. cannot be updated in
227 * Instead, the master thread periodically calls request->process
228 * with action TIMER. It's up to the individual functions to
229 * determine how to handle that. They need to check if they're
230 * being called from a child thread or the master, and then do
231 * different things based on that.
234 static fr_packet_list_t *proxy_list = NULL;
235 static TALLOC_CTX *proxy_ctx = NULL;
238 #ifdef HAVE_PTHREAD_H
240 static pthread_mutex_t proxy_mutex;
241 static bool proxy_no_new_sockets = false;
244 # define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
245 # define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
247 static pthread_t NO_SUCH_CHILD_PID;
248 # define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
252 * This is easier than ifdef's throughout the code.
254 # define PTHREAD_MUTEX_LOCK(_x)
255 # define PTHREAD_MUTEX_UNLOCK(_x)
256 # define NO_CHILD_THREAD
259 #ifdef HAVE_PTHREAD_H
260 static bool we_are_master(void)
263 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
271 * Assertions are debug checks.
274 # define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
279 * No threads: we're always master.
281 # define we_are_master(_x) (1)
282 #endif /* HAVE_PTHREAD_H */
284 #ifndef ASSERT_MASTER
285 # define ASSERT_MASTER
288 static int event_new_fd(rad_listen_t *this);
291 * We need mutexes around the event FD list *only* in certain
294 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
295 static rad_listen_t *new_listeners = NULL;
297 static pthread_mutex_t fd_mutex;
298 # define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
299 # define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
301 void radius_update_listener(rad_listen_t *this)
304 * Just do it ourselves.
306 if (we_are_master()) {
311 FD_MUTEX_LOCK(&fd_mutex);
314 * If it's already in the list, don't add it again.
317 FD_MUTEX_UNLOCK(&fd_mutex);
322 * Otherwise, add it to the list
324 this->next = new_listeners;
325 new_listeners = this;
326 FD_MUTEX_UNLOCK(&fd_mutex);
327 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
330 void radius_update_listener(rad_listen_t *this)
333 * No threads. Just insert it.
338 * This is easier than ifdef's throughout the code.
340 # define FD_MUTEX_LOCK(_x)
341 # define FD_MUTEX_UNLOCK(_x)
344 static int request_num_counter = 1;
346 static int request_will_proxy(REQUEST *request) CC_HINT(nonnull);
347 static int request_proxy(REQUEST *request, int retransmit) CC_HINT(nonnull);
348 STATE_MACHINE_DECL(request_ping) CC_HINT(nonnull);
350 STATE_MACHINE_DECL(request_response_delay) CC_HINT(nonnull);
351 STATE_MACHINE_DECL(request_cleanup_delay) CC_HINT(nonnull);
352 STATE_MACHINE_DECL(request_running) CC_HINT(nonnull);
353 STATE_MACHINE_DECL(request_done) CC_HINT(nonnull);
355 STATE_MACHINE_DECL(proxy_no_reply) CC_HINT(nonnull);
356 STATE_MACHINE_DECL(proxy_running) CC_HINT(nonnull);
357 STATE_MACHINE_DECL(proxy_wait_for_reply) CC_HINT(nonnull);
359 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply) CC_HINT(nonnull (1));
360 static void remove_from_proxy_hash(REQUEST *request) CC_HINT(nonnull);
361 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank) CC_HINT(nonnull);
362 static int insert_into_proxy_hash(REQUEST *request) CC_HINT(nonnull);
365 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
366 RADCLIENT *client, RAD_REQUEST_FUNP fun);
367 static int request_pre_handler(REQUEST *request, UNUSED int action) CC_HINT(nonnull);
370 static void request_coa_originate(REQUEST *request) CC_HINT(nonnull);
371 STATE_MACHINE_DECL(coa_wait_for_reply) CC_HINT(nonnull);
372 STATE_MACHINE_DECL(coa_no_reply) CC_HINT(nonnull);
373 STATE_MACHINE_DECL(coa_running) CC_HINT(nonnull);
374 static void coa_separate(REQUEST *request) CC_HINT(nonnull);
375 # define COA_SEPARATE if (request->coa) coa_separate(request->coa);
377 # define COA_SEPARATE
380 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
383 #define USEC (1000000)
385 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
387 static void tv_add(struct timeval *tv, int usec_delay)
389 if (usec_delay >= USEC) {
390 tv->tv_sec += usec_delay / USEC;
393 tv->tv_usec += usec_delay;
395 if (tv->tv_usec >= USEC) {
396 tv->tv_sec += tv->tv_usec / USEC;
402 * Debug the packet if requested.
404 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
406 char src_ipaddr[128];
407 char dst_ipaddr[128];
410 if (!RDEBUG_ENABLED) return;
413 * Client-specific debugging re-prints the input
414 * packet into the client log.
416 * This really belongs in a utility library
418 if (is_radius_code(packet->code)) {
419 RDEBUG("%s %s Id %i from %s%s%s:%i to %s%s%s:%i length %zu",
420 received ? "Received" : "Sent",
421 fr_packet_codes[packet->code],
423 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
424 inet_ntop(packet->src_ipaddr.af,
425 &packet->src_ipaddr.ipaddr,
426 src_ipaddr, sizeof(src_ipaddr)),
427 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
429 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
430 inet_ntop(packet->dst_ipaddr.af,
431 &packet->dst_ipaddr.ipaddr,
432 dst_ipaddr, sizeof(dst_ipaddr)),
433 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
437 RDEBUG("%s code %u Id %i from %s%s%s:%i to %s%s%s:%i length %zu\n",
438 received ? "Received" : "Sent",
441 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
442 inet_ntop(packet->src_ipaddr.af,
443 &packet->src_ipaddr.ipaddr,
444 src_ipaddr, sizeof(src_ipaddr)),
445 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
447 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
448 inet_ntop(packet->dst_ipaddr.af,
449 &packet->dst_ipaddr.ipaddr,
450 dst_ipaddr, sizeof(dst_ipaddr)),
451 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
457 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
459 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
464 /***********************************************************************
466 * Start of RADIUS server state machine.
468 ***********************************************************************/
470 static struct timeval *request_response_window(REQUEST *request)
472 VERIFY_REQUEST(request);
474 if (request->client) {
476 * The client hasn't set the response window. Return
477 * either the home server one, if set, or the global one.
479 if (!timerisset(&request->client->response_window)) {
480 return &request->home_server->response_window;
483 if (timercmp(&request->client->response_window,
484 &request->home_server->response_window, <)) {
485 return &request->client->response_window;
489 rad_assert(request->home_server != NULL);
490 return &request->home_server->response_window;
494 * Determine initial request processing delay.
496 static int request_init_delay(REQUEST *request)
498 struct timeval half_response_window;
500 VERIFY_REQUEST(request);
502 /* Allow client response window to lower initial delay */
503 if (timerisset(&request->client->response_window)) {
504 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
505 half_response_window.tv_usec =
506 ((request->client->response_window.tv_sec & 1) * USEC +
507 request->client->response_window.tv_usec) >> 1;
508 if (timercmp(&half_response_window, &request->root->init_delay, <))
509 return (int)half_response_window.tv_sec * USEC +
510 (int)half_response_window.tv_usec;
513 return (int)request->root->init_delay.tv_sec * USEC +
514 (int)request->root->init_delay.tv_usec;
518 * Callback for ALL timer events related to the request.
520 static void request_timer(void *ctx)
522 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
525 action = request->timer_action;
529 request->process(request, action);
533 * Wrapper for talloc pools. If there's no parent, just free the
534 * request. If there is a parent, free the parent INSTEAD of the
537 static void request_free(REQUEST *request)
541 rad_assert(request->ev == NULL);
542 rad_assert(!request->in_request_hash);
543 rad_assert(!request->in_proxy_hash);
545 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
546 talloc_free(request);
550 ptr = talloc_parent(request);
551 rad_assert(ptr != NULL);
557 static void proxy_reply_too_late(REQUEST *request)
561 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
562 inet_ntop(request->proxy->dst_ipaddr.af,
563 &request->proxy->dst_ipaddr.ipaddr,
564 buffer, sizeof(buffer)),
565 request->proxy->dst_port, request->proxy->id);
570 /** Mark a request DONE and clean it up.
572 * When a request is DONE, it can have ties to a number of other
573 * portions of the server. The request hash, proxy hash, events,
574 * child threads, etc. This function takes care of either cleaning
575 * up the request, or managing the timers to wait for the ties to be
580 * done -> done [ label = "still running" ];
584 static void request_done(REQUEST *request, int action)
586 struct timeval now, when;
588 VERIFY_REQUEST(request);
593 * Force this no matter what.
595 request->process = request_done;
599 * Tell the detail listener that we're done.
601 if (request->listener &&
602 (request->listener->type == RAD_LISTEN_DETAIL) &&
603 (request->simul_max != 1)) {
604 request->simul_max = 1;
605 request->listener->send(request->listener,
610 #ifdef HAVE_PTHREAD_H
612 * If called from a child thread, mark ourselves as done,
613 * and wait for the master thread timer to clean us up.
615 if (!we_are_master()) {
617 request->child_state = REQUEST_DONE;
623 * Mark the request as STOP.
625 request->master_state = REQUEST_STOP_PROCESSING;
629 * Move the CoA request to its own handler.
632 coa_separate(request->coa);
633 } else if (request->parent && (request->parent->coa == request)) {
634 coa_separate(request);
639 * It doesn't hurt to send duplicate replies. All other
640 * signals are ignored, as the request will be cleaned up
646 rad_assert(request->listener != NULL);
648 if (request->reply->code != 0) {
649 request->listener->send(request->listener, request);
652 RDEBUG("No reply. Ignoring retransmit");
657 * Mark the request as done.
660 #ifdef HAVE_PTHREAD_H
662 * If the child is still running, leave it alone.
664 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
669 #ifdef DEBUG_STATE_MACHINE
670 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
671 request->number, __FUNCTION__,
672 child_state_names[request->child_state],
673 child_state_names[REQUEST_DONE]);
675 request->child_state = REQUEST_DONE;
679 * Called when the child is taking too long to
680 * finish. We've already marked it "please
681 * stop", so we don't complain any more.
683 case FR_ACTION_TIMER:
687 case FR_ACTION_PROXY_REPLY:
688 proxy_reply_too_late(request);
697 * Remove it from the request hash.
699 if (request->in_request_hash) {
700 if (!rbtree_deletebydata(pl, &request->packet)) {
703 request->in_request_hash = false;
708 * Wait for the proxy ID to expire. This allows us to
709 * avoid re-use of proxy IDs for a while.
711 if (request->in_proxy_hash) {
712 rad_assert(request->proxy != NULL);
714 fr_event_now(el, &now);
715 when = request->proxy->timestamp;
718 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
719 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
720 (request->packet->code != request->proxy->code)) {
721 when.tv_sec += request->home_server->coa_mrd;
724 timeradd(&when, request_response_window(request), &when);
727 * We haven't received all responses, AND there's still
728 * time to wait. Do so.
730 if ((request->num_proxied_requests > request->num_proxied_responses) &&
732 (request->home_server->proto != IPPROTO_TCP) &&
734 timercmp(&now, &when, <)) {
735 RDEBUG("Waiting for more responses from the home server");
742 remove_from_proxy_hash(request);
746 #ifdef HAVE_PTHREAD_H
748 * If there's no children, we can mark the request as done.
750 if (!spawn_flag) request->child_state = REQUEST_DONE;
754 * If the child is still running, wait for it to be finished.
756 if (request->child_state <= REQUEST_RUNNING) {
757 gettimeofday(&now, NULL);
762 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
763 tv_add(&when, request->delay);
764 request->delay += request->delay >> 1;
765 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
767 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
771 #ifdef HAVE_PTHREAD_H
772 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
776 * @todo: do final states for TCP sockets, too?
778 request_stats_final(request);
780 if (request->listener) {
781 request->listener->count--;
784 * If we're the last one, remove the listener now.
786 if ((request->listener->count == 0) &&
787 (request->listener->status >= RAD_LISTEN_STATUS_FROZEN)) {
788 event_new_fd(request->listener);
793 if (request->packet) {
794 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
796 (unsigned int) (request->timestamp - fr_start_time));
797 } /* else don't print anything */
800 fr_event_delete(el, &request->ev);
801 request_free(request);
805 static void request_cleanup_delay_init(REQUEST *request)
807 struct timeval now, when;
809 VERIFY_REQUEST(request);
812 * Do cleanup delay ONLY for RADIUS packets from a real
813 * client. Everything else just gets cleaned up
816 if (request->packet->dst_port == 0) goto done;
819 * Accounting packets shouldn't be retransmitted. They
820 * should always be updated with Acct-Delay-Time.
822 #ifdef WITH_ACCOUNTING
823 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
827 if (request->listener->type == RAD_LISTEN_DHCP) goto done;
831 if (request->listener->type == RAD_LISTEN_VQP) goto done;
834 if (!request->root->cleanup_delay) goto done;
836 gettimeofday(&now, NULL);
838 rad_assert(request->reply->timestamp.tv_sec != 0);
839 when = request->reply->timestamp;
841 request->delay = request->root->cleanup_delay;
842 when.tv_sec += request->delay;
845 * Set timer for when we need to clean it up.
847 if (timercmp(&when, &now, >)) {
848 #ifdef DEBUG_STATE_MACHINE
849 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
851 request->process = request_cleanup_delay;
853 if (!we_are_master()) {
855 request->child_state = REQUEST_CLEANUP_DELAY;
860 * Update this if we can, otherwise let the timers pick it up.
862 request->child_state = REQUEST_CLEANUP_DELAY;
863 #ifdef HAVE_PTHREAD_H
864 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
866 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
871 * Otherwise just clean it up.
874 request_done(request, FR_ACTION_DONE);
879 * Enforce max_request_time.
881 static bool request_max_time(REQUEST *request)
883 struct timeval now, when;
884 rad_assert(request->magic == REQUEST_MAGIC);
885 #ifdef DEBUG_STATE_MACHINE
886 int action = FR_ACTION_TIMER;
889 VERIFY_REQUEST(request);
895 * The child thread has acknowledged it's done.
896 * Transition to the DONE state.
898 * If the request was marked STOP, then the "check for
899 * stop" macro already took care of it.
901 if (request->child_state == REQUEST_DONE) {
903 request_done(request, FR_ACTION_DONE);
908 * The request is still running. Enforce max_request_time.
910 fr_event_now(el, &now);
911 when = request->packet->timestamp;
912 when.tv_sec += request->root->max_request_time;
915 * Taking too long: tell it to die.
917 if (timercmp(&now, &when, >=)) {
918 #ifdef HAVE_PTHREAD_H
920 * If there's a child thread processing it,
924 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
925 ERROR("Unresponsive child for request %u, in component %s module %s",
927 request->component ? request->component : "<core>",
928 request->module ? request->module : "<core>");
929 exec_trigger(request, NULL, "server.thread.unresponsive", true);
933 * Tell the request that it's done.
939 * Sleep for some more. We HOPE that the child will
940 * become responsive at some point in the future. We do
941 * this by adding 50% to the current timer.
944 tv_add(&when, request->delay);
945 request->delay += request->delay >> 1;
946 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
950 static void request_queue_or_run(REQUEST *request,
951 fr_request_process_t process)
953 #ifdef DEBUG_STATE_MACHINE
954 int action = FR_ACTION_TIMER;
957 VERIFY_REQUEST(request);
962 * Do this here so that fewer other functions need to do
965 if (request->master_state == REQUEST_STOP_PROCESSING) {
966 #ifdef DEBUG_STATE_MACHINE
967 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
968 request->number, __FUNCTION__,
969 master_state_names[request->master_state],
970 child_state_names[request->child_state],
971 child_state_names[REQUEST_DONE]);
973 request_done(request, FR_ACTION_DONE);
977 request->process = process;
979 if (we_are_master()) {
983 * (re) set the initial delay.
985 request->delay = request_init_delay(request);
986 if (request->delay > USEC) request->delay = USEC;
987 gettimeofday(&when, NULL);
988 tv_add(&when, request->delay);
989 request->delay += request->delay >> 1;
991 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
993 #ifdef HAVE_PTHREAD_H
996 * A child thread will eventually pick it up.
998 if (request_enqueue(request)) return;
1001 * Otherwise we're not going to do anything with
1004 request_done(request, FR_ACTION_DONE);
1010 request->child_state = REQUEST_RUNNING;
1011 request->process(request, FR_ACTION_RUN);
1015 * Requests that care about child process exit
1016 * codes have already either called
1017 * rad_waitpid(), or they've given up.
1019 while (waitpid(-1, NULL, WNOHANG) > 0);
1024 static void request_dup(REQUEST *request)
1026 ERROR("(%u) Ignoring duplicate packet from "
1027 "client %s port %d - ID: %u due to unfinished request "
1028 "in component %s module %s",
1029 request->number, request->client->shortname,
1030 request->packet->src_port,request->packet->id,
1031 request->component, request->module);
1035 /** Sit on a request until it's time to clean it up.
1037 * A NAS may not see a response from the server. When the NAS
1038 * retransmits, we want to be able to send a cached reply back. The
1039 * alternative is to re-process the packet, which does bad things for
1040 * EAP, among others.
1042 * IF we do see a NAS retransmit, we extend the cleanup delay,
1043 * because the NAS might miss our cached reply.
1045 * Otherwise, once we reach cleanup_delay, we transition to DONE.
1048 * digraph cleanup_delay {
1050 * send_reply [ label = "send_reply\nincrease cleanup delay" ];
1052 * cleanup_delay -> send_reply [ label = "DUP" ];
1053 * send_reply -> cleanup_delay;
1054 * cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1055 * cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
1056 * cleanup_delay -> done [ label = "TIMER >= timeout" ];
1060 static void request_cleanup_delay(REQUEST *request, int action)
1062 struct timeval when, now;
1064 VERIFY_REQUEST(request);
1066 TRACE_STATE_MACHINE;
1073 if (request->reply->code != 0) {
1074 request->listener->send(request->listener, request);
1076 RDEBUG("No reply. Ignoring retransmit");
1080 * Double the cleanup_delay to catch retransmits.
1082 when = request->reply->timestamp;
1083 request->delay += request->delay;
1084 when.tv_sec += request->delay;
1086 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1090 case FR_ACTION_PROXY_REPLY:
1091 proxy_reply_too_late(request);
1095 case FR_ACTION_TIMER:
1096 fr_event_now(el, &now);
1098 rad_assert(request->root->cleanup_delay > 0);
1100 when = request->reply->timestamp;
1101 when.tv_sec += request->root->cleanup_delay;
1103 if (timercmp(&when, &now, >)) {
1104 #ifdef DEBUG_STATE_MACHINE
1105 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1107 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1109 } /* else it's time to clean up */
1111 request_done(request, REQUEST_DONE);
1115 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1121 /** Sit on a request until it's time to respond to it.
1123 * For security reasons, rejects (and maybe some other) packets are
1124 * delayed for a while before we respond. This delay means that
1125 * badly behaved NASes don't hammer the server with authentication
1128 * Otherwise, once we reach response_delay, we send the reply, and
1129 * transition to cleanup_delay.
1132 * digraph response_delay {
1133 * response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1134 * response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1135 * response_delay -> send_reply [ label = "TIMER >= timeout" ];
1136 * send_reply -> cleanup_delay;
1140 static void request_response_delay(REQUEST *request, int action)
1142 struct timeval when, now;
1144 VERIFY_REQUEST(request);
1146 TRACE_STATE_MACHINE;
1153 ERROR("(%u) Discarding duplicate request from "
1154 "client %s port %d - ID: %u due to delayed response",
1155 request->number, request->client->shortname,
1156 request->packet->src_port,request->packet->id);
1160 case FR_ACTION_PROXY_REPLY:
1161 proxy_reply_too_late(request);
1165 case FR_ACTION_TIMER:
1166 fr_event_now(el, &now);
1169 * See if it's time to send the reply. If not,
1170 * we wait some more.
1172 when = request->reply->timestamp;
1174 tv_add(&when, request->response_delay.tv_sec * USEC);
1175 tv_add(&when, request->response_delay.tv_usec);
1177 if (timercmp(&when, &now, >)) {
1178 #ifdef DEBUG_STATE_MACHINE
1179 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1181 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1183 } /* else it's time to send the reject */
1185 RDEBUG2("Sending delayed response");
1186 debug_packet(request, request->reply, false);
1187 request->listener->send(request->listener, request);
1190 * Clean up the request.
1192 request_cleanup_delay_init(request);
1196 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1202 static int request_pre_handler(REQUEST *request, UNUSED int action)
1206 VERIFY_REQUEST(request);
1208 TRACE_STATE_MACHINE;
1210 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1213 * Don't decode the packet if it's an internal "fake"
1214 * request. Instead, just return so that the caller can
1217 if (request->packet->dst_port == 0) {
1218 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1219 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1223 if (!request->packet->vps) { /* FIXME: check for correct state */
1224 rcode = request->listener->decode(request->listener, request);
1227 if (debug_condition) {
1229 * Ignore parse errors.
1231 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1232 request->log.lvl = L_DBG_LVL_2;
1233 request->log.func = vradlog_request;
1238 debug_packet(request, request->packet, true);
1244 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1245 request->reply->offset = -2; /* bad authenticator */
1249 if (!request->username) {
1250 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1257 /** Do the final processing of a request before we reply to the NAS.
1259 * Various cleanups, suppress responses, copy Proxy-State, and set
1260 * response_delay or cleanup_delay;
1262 static void request_finish(REQUEST *request, int action)
1266 VERIFY_REQUEST(request);
1268 TRACE_STATE_MACHINE;
1271 (void) action; /* -Wunused */
1275 * Don't do post-auth if we're a CoA request originated
1276 * from an Access-Request. See request_alloc_coa() for
1279 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1283 * Override the response code if a control:Response-Packet-Type attribute is present.
1285 vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1287 if (vp->vp_integer == 256) {
1288 RDEBUG2("Not responding to request");
1289 request->reply->code = 0;
1291 request->reply->code = vp->vp_integer;
1295 * Catch Auth-Type := Reject BEFORE proxying the packet.
1297 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1298 if (request->reply->code == 0) {
1299 vp = fr_pair_find_by_num(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1300 if (!vp || (vp->vp_integer != 5)) {
1301 RDEBUG2("There was no response configured: "
1302 "rejecting request");
1305 request->reply->code = PW_CODE_ACCESS_REJECT;
1310 * Copy Proxy-State from the request to the reply.
1312 vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps,
1313 PW_PROXY_STATE, 0, TAG_ANY);
1314 if (vp) fr_pair_add(&request->reply->vps, vp);
1317 * Call Post-Auth for Access-Request packets.
1319 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1320 rad_postauth(request);
1325 * Maybe originate a CoA request.
1327 if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1328 request_coa_originate(request);
1333 * Clean up. These are no longer needed.
1335 gettimeofday(&request->reply->timestamp, NULL);
1338 * Fake packets get marked as "done", and have the
1339 * proxy-reply section deal with the reply attributes.
1340 * We therefore don't free the reply attributes.
1342 if (request->packet->dst_port == 0) {
1343 RDEBUG("Finished internally proxied request.");
1345 request->child_state = REQUEST_DONE;
1351 * Always send the reply to the detail listener.
1353 if (request->listener->type == RAD_LISTEN_DETAIL) {
1354 request->simul_max = 1;
1357 * But only print the reply if there is one.
1359 if (request->reply->code != 0) {
1360 debug_packet(request, request->reply, false);
1363 request->listener->send(request->listener, request);
1369 * Ignore all "do not respond" packets.
1370 * Except for the detail ones, which need to ping
1371 * the detail file reader so that it will retransmit.
1373 if (!request->reply->code) {
1374 RDEBUG("Not sending reply to client.");
1379 * If it's not in the request hash, we MIGHT not want to
1382 * If duplicate packets are allowed, then then only
1383 * reason to NOT be in the request hash is because we
1384 * don't want to send a reply.
1386 * FIXME: this is crap. The rest of the state handling
1387 * should use a different field so that we don't have two
1390 * Otherwise duplicates are forbidden, and the request is
1391 * SUPPOSED to avoid the request hash.
1393 * In that case, we need to send a reply.
1395 if (!request->in_request_hash &&
1396 !request->listener->nodup) {
1397 RDEBUG("Suppressing reply to client.");
1402 * See if we need to delay an Access-Reject packet.
1404 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1405 (request->root->reject_delay.tv_sec > 0)) {
1406 request->response_delay = request->root->reject_delay;
1408 vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY, 0, TAG_ANY);
1410 if (vp->vp_integer <= 10) {
1411 request->response_delay.tv_sec = vp->vp_integer;
1413 request->response_delay.tv_sec = 10;
1415 request->response_delay.tv_usec = 0;
1417 vp = fr_pair_find_by_num(request->reply->vps, PW_FREERADIUS_RESPONSE_DELAY_USEC, 0, TAG_ANY);
1419 if (vp->vp_integer <= 10 * USEC) {
1420 request->response_delay.tv_sec = vp->vp_integer / USEC;
1421 request->response_delay.tv_usec = vp->vp_integer % USEC;
1423 request->response_delay.tv_sec = 10;
1424 request->response_delay.tv_usec = 0;
1431 * If we timed out a proxy packet, don't delay
1432 * the reject any more.
1434 if (request->proxy && !request->proxy_reply) {
1435 request->response_delay.tv_sec = 0;
1436 request->response_delay.tv_usec = 0;
1444 if ((request->response_delay.tv_sec == 0) &&
1445 (request->response_delay.tv_usec == 0)) {
1448 * Don't print a reply if there's none to send.
1450 if (request->reply->code != 0) {
1451 if (rad_debug_lvl && request->state &&
1452 (request->reply->code == PW_CODE_ACCESS_ACCEPT)) {
1453 if (!fr_pair_find_by_num(request->packet->vps, PW_STATE, 0, TAG_ANY)) {
1454 RWDEBUG2("Unused attributes found in &session-state:");
1458 debug_packet(request, request->reply, false);
1459 request->listener->send(request->listener, request);
1463 RDEBUG2("Finished request");
1464 request->component = "<core>";
1465 request->module = "<done>";
1467 request_cleanup_delay_init(request);
1471 * Encode and sign it here, so that the master
1472 * thread can just send the encoded data, which
1473 * means it does less work.
1475 RDEBUG2("Delaying response for %d.%06d seconds",
1476 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1477 request->listener->encode(request->listener, request);
1478 request->component = "<core>";
1479 request->module = "<delay>";
1480 request->process = request_response_delay;
1482 request->child_state = REQUEST_RESPONSE_DELAY;
1486 /** Process a request from a client.
1488 * The outcome might be that the request is proxied.
1492 * running -> running [ label = "TIMER < max_request_time" ];
1493 * running -> done [ label = "TIMER >= max_request_time" ];
1494 * running -> proxy [ label = "proxied" ];
1495 * running -> dup [ label = "DUP", arrowhead = "none" ];
1499 static void request_running(REQUEST *request, int action)
1501 VERIFY_REQUEST(request);
1503 TRACE_STATE_MACHINE;
1507 case FR_ACTION_TIMER:
1509 (void) request_max_time(request);
1513 request_dup(request);
1517 if (!request_pre_handler(request, action)) {
1518 #ifdef DEBUG_STATE_MACHINE
1519 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1520 request->number, __FUNCTION__,
1521 child_state_names[request->child_state],
1522 child_state_names[REQUEST_DONE]);
1526 request->child_state = REQUEST_DONE;
1530 rad_assert(request->handle != NULL);
1531 request->handle(request);
1535 * We may need to send a proxied request.
1537 if ((action == FR_ACTION_RUN) &&
1538 request_will_proxy(request)) {
1539 #ifdef DEBUG_STATE_MACHINE
1540 if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1544 * takes care of setting
1545 * up the post proxy fail
1548 if (request_proxy(request, 0) < 0) goto req_finished;
1552 #ifdef DEBUG_STATE_MACHINE
1553 if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1559 request_finish(request, action);
1564 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1569 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1570 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1573 RADIUS_PACKET **packet_p;
1574 REQUEST *request = NULL;
1576 listen_socket_t *sock = NULL;
1578 VERIFY_PACKET(packet);
1581 * Set the last packet received.
1583 gettimeofday(&now, NULL);
1585 packet->timestamp = now;
1587 #ifdef WITH_ACCOUNTING
1588 if (listener->type != RAD_LISTEN_DETAIL)
1591 sock = listener->data;
1592 sock->last_packet = now.tv_sec;
1595 packet->proto = sock->proto;
1600 * Skip everything if required.
1602 if (listener->nodup) goto skip_dup;
1604 packet_p = rbtree_finddata(pl, &packet);
1606 rad_child_state_t child_state;
1608 request = fr_packet2myptr(REQUEST, packet, packet_p);
1609 rad_assert(request->in_request_hash);
1610 child_state = request->child_state;
1613 * Same src/dst ip/port, length, and
1614 * authentication vector: must be a duplicate.
1616 if ((request->packet->data_len == packet->data_len) &&
1617 (memcmp(request->packet->vector, packet->vector,
1618 sizeof(packet->vector)) == 0)) {
1621 switch (packet->code) {
1622 case PW_CODE_ACCESS_REQUEST:
1623 FR_STATS_INC(auth, total_dup_requests);
1626 #ifdef WITH_ACCOUNTING
1627 case PW_CODE_ACCOUNTING_REQUEST:
1628 FR_STATS_INC(acct, total_dup_requests);
1632 case PW_CODE_COA_REQUEST:
1633 FR_STATS_INC(coa, total_dup_requests);
1636 case PW_CODE_DISCONNECT_REQUEST:
1637 FR_STATS_INC(dsc, total_dup_requests);
1644 #endif /* WITH_STATS */
1647 * Tell the state machine that there's a
1648 * duplicate request.
1650 request->process(request, FR_ACTION_DUP);
1651 return 0; /* duplicate of live request */
1655 * Mark the request as done ASAP, and before we
1656 * log anything. The child may stop processing
1657 * the request just as we're logging the
1660 request_done(request, FR_ACTION_DONE);
1664 * It's a new request, not a duplicate. If the
1665 * old one is done, then we can clean it up.
1667 if (child_state <= REQUEST_RUNNING) {
1669 * The request is still QUEUED or RUNNING. That's a problem.
1671 ERROR("Received conflicting packet from "
1672 "client %s port %d - ID: %u due to "
1673 "unfinished request. Giving up on old request.",
1675 packet->src_port, packet->id);
1679 * Mark the old request as done. If there's no
1680 * child, the request will be cleaned up
1681 * immediately. If there is a child, we'll set a
1682 * timer to go clean up the request.
1684 } /* else the new packet is unique */
1687 * Quench maximum number of outstanding requests.
1689 if (main_config.max_requests &&
1690 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1691 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1693 packet->src_port, packet->id);
1694 WARN("Please check the configuration file.\n"
1695 "\tThe value for 'max_requests' is probably set too low.\n"));
1697 exec_trigger(NULL, NULL, "server.max_requests", true);
1703 * Rate-limit the incoming packets
1705 if (sock && sock->max_rate) {
1708 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1709 if (pps > sock->max_rate) {
1710 DEBUG("Dropping request due to rate limiting");
1713 sock->rate_pps_now++;
1717 * Allocate a pool for the request.
1720 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1722 talloc_set_name_const(ctx, "request_receive_pool");
1725 * The packet is still allocated from a different
1726 * context, but oh well.
1728 (void) talloc_steal(ctx, packet);
1731 request = request_setup(ctx, listener, packet, client, fun);
1738 * Mark it as a "real" request with a context.
1740 request->options |= RAD_REQUEST_OPTION_CTX;
1743 * Remember the request in the list.
1745 if (!listener->nodup) {
1746 if (!rbtree_insert(pl, &request->packet)) {
1747 RERROR("Failed to insert request in the list of live requests: discarding it");
1748 request_done(request, FR_ACTION_DONE);
1752 request->in_request_hash = true;
1756 * Process it. Send a response, and free it.
1758 if (listener->synchronous) {
1760 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1763 request->listener->decode(request->listener, request);
1764 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1765 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1769 if (request->reply->code != 0) {
1770 request->listener->send(request->listener, request);
1772 RDEBUG("Not sending reply");
1776 * Don't do delayed reject. Oh well.
1778 request_free(request);
1783 * Otherwise, insert it into the state machine.
1784 * The child threads will take care of processing it.
1786 request_queue_or_run(request, request_running);
1792 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1793 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1798 * Create and initialize the new request.
1800 request = request_alloc(ctx);
1805 request->reply = rad_alloc(request, false);
1806 if (!request->reply) {
1808 talloc_free(request);
1812 request->listener = listener;
1813 request->client = client;
1814 request->packet = talloc_steal(request, packet);
1815 request->number = request_num_counter++;
1816 request->priority = listener->type;
1817 request->master_state = REQUEST_ACTIVE;
1818 request->child_state = REQUEST_RUNNING;
1819 #ifdef DEBUG_STATE_MACHINE
1820 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1821 request->number, __FUNCTION__,
1822 child_state_names[request->child_state],
1823 child_state_names[REQUEST_RUNNING]);
1825 #ifdef HAVE_PTHREAD_H
1826 request->child_pid = NO_SUCH_CHILD_PID;
1828 request->handle = fun;
1832 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1833 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1834 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1835 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1836 #ifdef WITH_ACCOUNTING
1837 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1838 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1839 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1842 #endif /* WITH_STATS */
1845 * Status-Server packets go to the head of the queue.
1847 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1850 * Set virtual server identity
1852 if (client->server) {
1853 request->server = client->server;
1854 } else if (listener->server) {
1855 request->server = listener->server;
1857 request->server = NULL;
1860 request->root = &main_config;
1862 request->listener->count++;
1866 * The request passes many of our sanity checks.
1867 * From here on in, if anything goes wrong, we
1868 * send a reject message, instead of dropping the
1873 * Build the reply template from the request.
1876 request->reply->sockfd = request->packet->sockfd;
1877 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1878 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1879 request->reply->dst_port = request->packet->src_port;
1880 request->reply->src_port = request->packet->dst_port;
1881 request->reply->id = request->packet->id;
1882 request->reply->code = 0; /* UNKNOWN code */
1883 memcpy(request->reply->vector, request->packet->vector,
1884 sizeof(request->reply->vector));
1885 request->reply->vps = NULL;
1886 request->reply->data = NULL;
1887 request->reply->data_len = 0;
1893 /***********************************************************************
1897 ***********************************************************************/
1900 * Timer function for all TCP sockets.
1902 static void tcp_socket_timer(void *ctx)
1904 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1905 listen_socket_t *sock = listener->data;
1906 struct timeval end, now;
1908 fr_socket_limit_t *limit;
1912 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1914 fr_event_now(el, &now);
1916 switch (listener->type) {
1918 case RAD_LISTEN_PROXY:
1919 limit = &sock->home->limit;
1923 case RAD_LISTEN_AUTH:
1924 #ifdef WITH_ACCOUNTING
1925 case RAD_LISTEN_ACCT:
1927 limit = &sock->limit;
1935 * If we enforce a lifetime, do it now.
1937 if (limit->lifetime > 0) {
1938 end.tv_sec = sock->opened + limit->lifetime;
1941 if (timercmp(&end, &now, <=)) {
1942 listener->print(listener, buffer, sizeof(buffer));
1943 DEBUG("Reached maximum lifetime on socket %s", buffer);
1949 * Proxy sockets get frozen, so that we don't use
1950 * them for new requests. But we do keep them
1951 * open to listen for replies to requests we had
1954 if (listener->type == RAD_LISTEN_PROXY) {
1955 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1956 if (!fr_packet_list_socket_freeze(proxy_list,
1958 ERROR("Fatal error freezing socket: %s", fr_strerror());
1961 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1966 * Mark the socket as "don't use if at all possible".
1968 listener->status = RAD_LISTEN_STATUS_FROZEN;
1969 event_new_fd(listener);
1978 * Enforce an idle timeout.
1980 if (limit->idle_timeout > 0) {
1981 struct timeval idle;
1983 rad_assert(sock->last_packet != 0);
1984 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1987 if (timercmp(&idle, &now, <=)) {
1988 listener->print(listener, buffer, sizeof(buffer));
1989 DEBUG("Reached idle timeout on socket %s", buffer);
1994 * Enforce the minimum of idle timeout or lifetime.
1996 if (timercmp(&idle, &end, <)) {
2002 * Wake up at t + 0.5s. The code above checks if the timers
2003 * are <= t. This addition gives us a bit of leeway.
2005 end.tv_usec = USEC / 2;
2008 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
2009 rad_panic("Failed to insert event");
2016 * Add +/- 2s of jitter, as suggested in RFC 3539
2019 static void add_jitter(struct timeval *when)
2026 jitter ^= (jitter >> 10);
2027 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
2030 * Add in ~ (4 * USEC) of jitter.
2032 tv_add(when, jitter);
2036 * Called by socket_del to remove requests with this socket
2038 static int eol_proxy_listener(void *ctx, void *data)
2040 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2041 RADIUS_PACKET **proxy_p = data;
2044 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2045 if (request->proxy_listener != this) return 0;
2048 * The normal "remove_from_proxy_hash" tries to grab the
2049 * proxy mutex. We already have it held, so grabbing it
2050 * again will cause a deadlock. Instead, call the "no
2051 * lock" version of the function.
2053 rad_assert(request->in_proxy_hash == true);
2054 remove_from_proxy_hash_nl(request, false);
2057 * Don't mark it as DONE. The client can retransmit, and
2058 * the packet SHOULD be re-proxied somewhere else.
2060 * Return "2" means that the rbtree code will remove it
2061 * from the tree, and we don't need to do it ourselves.
2065 #endif /* WITH_PROXY */
2067 static int eol_listener(void *ctx, void *data)
2069 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2070 RADIUS_PACKET **packet_p = data;
2073 request = fr_packet2myptr(REQUEST, packet, packet_p);
2074 if (request->listener != this) return 0;
2076 request->master_state = REQUEST_STOP_PROCESSING;
2077 request->process = request_done;
2081 #endif /* WITH_TCP */
2084 /***********************************************************************
2086 * Proxy handlers for the state machine.
2088 ***********************************************************************/
2091 * Called with the proxy mutex held
2093 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2095 VERIFY_REQUEST(request);
2097 if (!request->in_proxy_hash) return;
2099 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2100 request->in_proxy_hash = false;
2103 * On the FIRST reply, decrement the count of outstanding
2104 * requests. Note that this is NOT the count of sent
2105 * packets, but whether or not the home server has
2108 if (request->home_server &&
2109 request->home_server->currently_outstanding) {
2110 request->home_server->currently_outstanding--;
2113 * If we're NOT sending it packets, AND it's been
2114 * a while since we got a response, then we don't
2115 * know if it's alive or dead.
2117 if ((request->home_server->currently_outstanding == 0) &&
2118 (request->home_server->state == HOME_STATE_ALIVE)) {
2119 struct timeval when, now;
2121 when.tv_sec = request->home_server->last_packet_recv ;
2124 timeradd(&when, request_response_window(request), &when);
2125 gettimeofday(&now, NULL);
2128 * last_packet + response_window
2130 * We *administratively* mark the home
2131 * server as "unknown" state, because we
2132 * haven't seen a packet for a while.
2134 if (timercmp(&now, &when, >)) {
2135 request->home_server->state = HOME_STATE_UNKNOWN;
2136 request->home_server->last_packet_sent = 0;
2137 request->home_server->last_packet_recv = 0;
2143 rad_assert(request->proxy_listener != NULL);
2144 request->proxy_listener->count--;
2146 request->proxy_listener = NULL;
2149 * Got from YES in hash, to NO, not in hash while we hold
2150 * the mutex. This guarantees that when another thread
2151 * grabs the mutex, the "not in hash" flag is correct.
2155 static void remove_from_proxy_hash(REQUEST *request)
2157 VERIFY_REQUEST(request);
2160 * Check this without grabbing the mutex because it's a
2161 * lot faster that way.
2163 if (!request->in_proxy_hash) return;
2166 * The "not in hash" flag is definitive. However, if the
2167 * flag says that it IS in the hash, there might still be
2168 * a race condition where it isn't.
2170 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2172 if (!request->in_proxy_hash) {
2173 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2177 remove_from_proxy_hash_nl(request, true);
2179 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2182 static int insert_into_proxy_hash(REQUEST *request)
2186 bool success = false;
2187 void *proxy_listener;
2189 VERIFY_REQUEST(request);
2191 rad_assert(request->proxy != NULL);
2192 rad_assert(request->home_server != NULL);
2193 rad_assert(proxy_list != NULL);
2196 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2197 proxy_listener = NULL;
2198 request->num_proxied_requests = 1;
2199 request->num_proxied_responses = 0;
2201 for (tries = 0; tries < 2; tries++) {
2203 listen_socket_t *sock;
2205 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2206 success = fr_packet_list_id_alloc(proxy_list,
2207 request->home_server->proto,
2208 &request->proxy, &proxy_listener);
2211 if (tries > 0) continue; /* try opening new socket only once */
2213 #ifdef HAVE_PTHREAD_H
2214 if (proxy_no_new_sockets) break;
2217 RDEBUG3("proxy: Trying to open a new listener to the home server");
2218 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2220 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2224 request->proxy->src_port = 0; /* Use any new socket */
2225 proxy_listener = this;
2228 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2230 &sock->other_ipaddr, sock->other_port,
2233 #ifdef HAVE_PTHREAD_H
2234 proxy_no_new_sockets = true;
2236 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2239 * This is bad. However, the
2240 * packet list now supports 256
2241 * open sockets, which should
2242 * minimize this problem.
2244 ERROR("Failed adding proxy socket: %s",
2250 * Add it to the event loop. Ensure that we have
2251 * only one mutex locked at a time.
2253 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2254 radius_update_listener(this);
2255 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2258 if (!proxy_listener || !success) {
2259 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2260 REDEBUG2("proxy: Failed allocating Id for proxied request");
2262 request->proxy_listener = NULL;
2263 request->in_proxy_hash = false;
2267 rad_assert(request->proxy->id >= 0);
2269 request->proxy_listener = proxy_listener;
2270 request->in_proxy_hash = true;
2271 RDEBUG3("proxy: request is now in proxy hash");
2274 * Keep track of maximum outstanding requests to a
2275 * particular home server. 'max_outstanding' is
2276 * enforced in home_server_ldb(), in realms.c.
2278 request->home_server->currently_outstanding++;
2281 request->proxy_listener->count++;
2284 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2286 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2287 inet_ntop(request->proxy->dst_ipaddr.af,
2288 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2289 request->proxy->dst_port,
2290 request->proxy->id);
2295 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2298 int post_proxy_type = 0;
2301 VERIFY_REQUEST(request);
2304 * There may be a proxy reply, but it may be too late.
2306 if (!request->home_server->server && !request->proxy_listener) return 0;
2309 * Delete any reply we had accumulated until now.
2311 RDEBUG2("Clearing existing &reply: attributes");
2312 fr_pair_list_free(&request->reply->vps);
2315 * Run the packet through the post-proxy stage,
2316 * BEFORE playing games with the attributes.
2318 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2320 post_proxy_type = vp->vp_integer;
2322 * If we have a proxy_reply, and it was a reject, or a NAK
2323 * setup Post-Proxy <type>.
2325 * If the <type> doesn't have a section, then the Post-Proxy
2326 * section is ignored.
2329 DICT_VALUE *dval = NULL;
2331 switch (reply->code) {
2332 case PW_CODE_ACCESS_REJECT:
2333 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2334 if (dval) post_proxy_type = dval->value;
2337 case PW_CODE_DISCONNECT_NAK:
2338 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2339 if (dval) post_proxy_type = dval->value;
2342 case PW_CODE_COA_NAK:
2343 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2344 if (dval) post_proxy_type = dval->value;
2352 * Create config:Post-Proxy-Type
2355 vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2356 vp->vp_integer = dval->value;
2360 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2361 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2364 VERIFY_PACKET(reply);
2367 * Decode the packet if required.
2369 if (request->proxy_listener) {
2370 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2371 debug_packet(request, reply, true);
2374 * Pro-actively remove it from the proxy hash.
2375 * This is later than in 2.1.x, but it means that
2376 * the replies are authenticated before being
2377 * removed from the hash.
2380 (request->num_proxied_requests <= request->num_proxied_responses)) {
2381 remove_from_proxy_hash(request);
2384 rad_assert(!request->in_proxy_hash);
2386 } else if (request->in_proxy_hash) {
2387 remove_from_proxy_hash(request);
2390 if (request->home_pool && request->home_pool->virtual_server) {
2391 char const *old_server = request->server;
2393 request->server = request->home_pool->virtual_server;
2394 RDEBUG2("server %s {", request->server);
2396 rcode = process_post_proxy(post_proxy_type, request);
2399 request->server = old_server;
2401 rcode = process_post_proxy(post_proxy_type, request);
2405 if (request->packet->code == request->proxy->code)
2407 * Don't run the next bit if we originated a CoA
2408 * packet, after receiving an Access-Request or
2409 * Accounting-Request.
2414 * There may NOT be a proxy reply, as we may be
2415 * running Post-Proxy-Type = Fail.
2418 fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2421 * Delete the Proxy-State Attributes from
2422 * the reply. These include Proxy-State
2423 * attributes from us and remote server.
2425 fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2429 default: /* Don't do anything */
2431 case RLM_MODULE_FAIL:
2434 case RLM_MODULE_HANDLED:
2441 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2445 home->state = HOME_STATE_ALIVE;
2446 home->response_timeouts = 0;
2447 exec_trigger(request, home->cs, "home_server.alive", false);
2448 home->currently_outstanding = 0;
2449 home->num_sent_pings = 0;
2450 home->num_received_pings = 0;
2451 gettimeofday(&home->revive_time, NULL);
2453 fr_event_delete(el, &home->ev);
2455 RPROXY("Marking home server %s port %d alive",
2456 inet_ntop(request->proxy->dst_ipaddr.af,
2457 &request->proxy->dst_ipaddr.ipaddr,
2458 buffer, sizeof(buffer)),
2459 request->proxy->dst_port);
2463 int request_proxy_reply(RADIUS_PACKET *packet)
2465 RADIUS_PACKET **proxy_p;
2470 VERIFY_PACKET(packet);
2472 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2473 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2476 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2477 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2478 fr_packet_codes[packet->code],
2479 inet_ntop(packet->src_ipaddr.af,
2480 &packet->src_ipaddr.ipaddr,
2481 buffer, sizeof(buffer)),
2482 packet->src_port, packet->id);
2486 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2487 request->num_proxied_responses++; /* needs to be protected by lock */
2489 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2492 * No reply, BUT the current packet fails verification:
2493 * ignore it. This does the MD5 calculations in the
2494 * server core, but I guess we can fix that later.
2496 if (!request->proxy_reply &&
2497 (rad_verify(packet, request->proxy,
2498 request->home_server->secret) != 0)) {
2499 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2504 * The home server sent us a packet which doesn't match
2505 * something we have: ignore it. This is done only to
2506 * catch the case of broken systems.
2508 if (request->proxy_reply &&
2509 (memcmp(request->proxy_reply->vector,
2511 sizeof(request->proxy_reply->vector)) != 0)) {
2512 RDEBUG2("Ignoring conflicting proxy reply");
2516 gettimeofday(&now, NULL);
2519 * Status-Server packets don't count as real packets.
2521 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2522 listen_socket_t *sock = request->proxy_listener->data;
2524 request->home_server->last_packet_recv = now.tv_sec;
2525 sock->last_packet = now.tv_sec;
2529 * If we have previously seen a reply, ignore the
2532 if (request->proxy_reply) {
2533 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2534 inet_ntop(packet->src_ipaddr.af,
2535 &packet->src_ipaddr.ipaddr,
2536 buffer, sizeof(buffer)),
2537 packet->src_port, packet->id);
2542 * Call the state machine to do something useful with the
2545 request->proxy_reply = talloc_steal(request, packet);
2546 packet->timestamp = now;
2547 request->priority = RAD_LISTEN_PROXY;
2551 * Update the proxy listener stats here, because only one
2552 * thread accesses that at a time. The home_server and
2553 * main proxy_*_stats structures are updated once the
2554 * request is cleaned up.
2556 request->proxy_listener->stats.total_responses++;
2558 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2559 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2561 switch (request->proxy->code) {
2562 case PW_CODE_ACCESS_REQUEST:
2563 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2565 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2566 request->proxy_listener->stats.total_access_accepts++;
2568 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2569 request->proxy_listener->stats.total_access_rejects++;
2571 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2572 request->proxy_listener->stats.total_access_challenges++;
2576 #ifdef WITH_ACCOUNTING
2577 case PW_CODE_ACCOUNTING_REQUEST:
2578 request->proxy_listener->stats.total_responses++;
2579 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2585 case PW_CODE_COA_REQUEST:
2586 request->proxy_listener->stats.total_responses++;
2587 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2590 case PW_CODE_DISCONNECT_REQUEST:
2591 request->proxy_listener->stats.total_responses++;
2592 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2602 * If we hadn't been sending the home server packets for
2603 * a while, just mark it alive. Or, if it was zombie,
2604 * it's now responded, and is therefore alive.
2606 if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2607 (request->home_server->state == HOME_STATE_ZOMBIE)) {
2608 mark_home_server_alive(request, request->home_server);
2612 * Tell the request state machine that we have a proxy
2613 * reply. Depending on the function, this should either
2614 * ignore it, or process it.
2616 request->process(request, FR_ACTION_PROXY_REPLY);
2622 static int setup_post_proxy_fail(REQUEST *request)
2624 DICT_VALUE const *dval = NULL;
2627 VERIFY_REQUEST(request);
2629 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2630 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2631 "Fail-Authentication");
2632 #ifdef WITH_ACCOUNTING
2633 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2634 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2639 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2640 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2642 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2643 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2646 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2650 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2653 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2657 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2658 if (!vp) vp = radius_pair_create(request, &request->config,
2659 PW_POST_PROXY_TYPE, 0);
2660 vp->vp_integer = dval->value;
2666 /** Process a request after the proxy has timed out.
2668 * Run the packet through Post-Proxy-Type Fail
2671 * digraph proxy_no_reply {
2674 * proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2675 * proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2676 * proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2677 * proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2678 * proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2682 static void proxy_no_reply(REQUEST *request, int action)
2684 VERIFY_REQUEST(request);
2686 TRACE_STATE_MACHINE;
2691 request_dup(request);
2694 case FR_ACTION_TIMER:
2695 (void) request_max_time(request);
2698 case FR_ACTION_PROXY_REPLY:
2699 proxy_reply_too_late(request);
2703 if (process_proxy_reply(request, NULL)) {
2704 request->handle(request);
2706 request_finish(request, action);
2710 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2715 /** Process the request after receiving a proxy reply.
2717 * Throught the post-proxy section, and the through the handler
2721 * digraph proxy_running {
2724 * proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2725 * proxy_running -> timer [ label = "TIMER < max_request_time" ];
2726 * proxy_running -> process_proxy_reply [ label = "RUN" ];
2727 * proxy_running -> done [ label = "TIMER >= timeout" ];
2731 static void proxy_running(REQUEST *request, int action)
2733 VERIFY_REQUEST(request);
2735 TRACE_STATE_MACHINE;
2740 request_dup(request);
2743 case FR_ACTION_TIMER:
2744 (void) request_max_time(request);
2748 if (process_proxy_reply(request, request->proxy_reply)) {
2749 request->handle(request);
2751 request_finish(request, action);
2754 default: /* duplicate proxy replies are suppressed */
2755 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2760 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2762 * Whether a request will be proxied is determined by the attributes present
2763 * in request->config. If any of the following attributes are found, the
2764 * request may be proxied.
2766 * The key attributes are:
2767 * - PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2768 * - PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2769 * - PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2770 * - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2772 * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2774 * If request should be proxied, will:
2775 * - Add request:Proxy-State
2776 * - Strip the current username value of its realm (depending on config)
2777 * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2779 * - Call the pre-process section in the current server, or in the virtual server
2780 * associated with the home server pool we're proxying to.
2782 * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2783 * specific function.
2785 * @param request The #REQUEST to evaluate for proxying.
2786 * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2788 static int request_will_proxy(REQUEST *request)
2790 int rcode, pre_proxy_type = 0;
2791 char const *realmname = NULL;
2792 VALUE_PAIR *vp, *strippedname;
2793 home_server_t *home;
2794 REALM *realm = NULL;
2795 home_pool_t *pool = NULL;
2797 VERIFY_REQUEST(request);
2799 if (!request->root->proxy_requests) return 0;
2800 if (request->packet->dst_port == 0) return 0;
2801 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2802 if (request->in_proxy_hash) return 0;
2805 * FIXME: for 3.0, allow this only for rejects?
2807 if (request->reply->code != 0) return 0;
2809 vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2811 realm = realm_find2(vp->vp_strvalue);
2813 REDEBUG2("Cannot proxy to unknown realm %s",
2818 realmname = vp->vp_strvalue;
2821 * Figure out which pool to use.
2823 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2824 pool = realm->auth_pool;
2826 #ifdef WITH_ACCOUNTING
2827 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2828 pool = realm->acct_pool;
2832 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2833 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2834 pool = realm->coa_pool;
2841 } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2844 switch (request->packet->code) {
2845 case PW_CODE_ACCESS_REQUEST:
2846 pool_type = HOME_TYPE_AUTH;
2849 #ifdef WITH_ACCOUNTING
2850 case PW_CODE_ACCOUNTING_REQUEST:
2851 pool_type = HOME_TYPE_ACCT;
2856 case PW_CODE_COA_REQUEST:
2857 case PW_CODE_DISCONNECT_REQUEST:
2858 pool_type = HOME_TYPE_COA;
2866 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2869 * Send it directly to a home server (i.e. NAS)
2871 } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2872 ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2874 fr_ipaddr_t dst_ipaddr;
2876 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2878 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2879 dst_ipaddr.af = AF_INET;
2880 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2881 dst_ipaddr.prefix = 32;
2883 dst_ipaddr.af = AF_INET6;
2884 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2885 dst_ipaddr.prefix = 128;
2888 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2890 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2891 dst_port = PW_AUTH_UDP_PORT;
2893 #ifdef WITH_ACCOUNTING
2894 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2895 dst_port = PW_ACCT_UDP_PORT;
2899 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2900 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2901 dst_port = PW_COA_UDP_PORT;
2903 } else { /* shouldn't happen for RADIUS... */
2908 dst_port = vp->vp_integer;
2912 * Nothing does CoA over TCP.
2914 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2918 WARN("No such home server %s port %u",
2919 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2920 (unsigned int) dst_port);
2925 * The home server is alive (or may be alive).
2926 * Send the packet to the IP.
2928 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2931 * The home server is dead. If you wanted
2932 * fail-over, you should have proxied to a pool.
2943 RWDEBUG2("Cancelling proxy as no home pool exists");
2947 if (request->listener->synchronous) {
2948 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2952 request->home_pool = pool;
2954 home = home_server_ldb(realmname, pool, request);
2957 REDEBUG2("Failed to find live home server: Cancelling proxy");
2962 home_server_update_request(home, request);
2966 * Once we've decided to proxy a request, we cannot send
2967 * a CoA packet. So we free up any CoA packet here.
2969 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2973 * Remember that we sent the request to a Realm.
2975 if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2978 * Strip the name, if told to.
2980 * Doing it here catches the case of proxied tunneled
2983 if (realm && (realm->strip_realm == true) &&
2984 (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2986 * If there's a Stripped-User-Name attribute in
2987 * the request, then use THAT as the User-Name
2988 * for the proxied request, instead of the
2991 * This is done by making a copy of the
2992 * Stripped-User-Name attribute, turning it into
2993 * a User-Name attribute, deleting the
2994 * Stripped-User-Name and User-Name attributes
2995 * from the vps list, and making the new
2996 * User-Name the head of the vps list.
2998 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
3001 vp = radius_pair_create(NULL, NULL,
3003 rad_assert(vp != NULL); /* handled by above function */
3004 /* Insert at the START of the list */
3005 /* FIXME: Can't make assumptions about ordering */
3006 fr_cursor_init(&cursor, &vp);
3007 fr_cursor_merge(&cursor, request->proxy->vps);
3008 request->proxy->vps = vp;
3010 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
3013 * Do NOT delete Stripped-User-Name.
3018 * If there is no PW_CHAP_CHALLENGE attribute but
3019 * there is a PW_CHAP_PASSWORD we need to add it
3020 * since we can't use the request authenticator
3021 * anymore - we changed it.
3023 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
3024 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
3025 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
3026 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
3027 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
3031 * The RFC's say we have to do this, but FreeRADIUS
3034 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3035 fr_pair_value_sprintf(vp, "%u", request->packet->id);
3038 * Should be done BEFORE inserting into proxy hash, as
3039 * pre-proxy may use this information, or change it.
3041 request->proxy->code = request->packet->code;
3044 * Call the pre-proxy routines.
3046 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3048 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3049 /* Must be a validation issue */
3051 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3052 pre_proxy_type = vp->vp_integer;
3056 * home_pool may be NULL when originating CoA packets,
3057 * because they go directly to an IP address.
3059 if (request->home_pool && request->home_pool->virtual_server) {
3060 char const *old_server = request->server;
3062 request->server = request->home_pool->virtual_server;
3064 RDEBUG2("server %s {", request->server);
3066 rcode = process_pre_proxy(pre_proxy_type, request);
3070 request->server = old_server;
3072 rcode = process_pre_proxy(pre_proxy_type, request);
3076 case RLM_MODULE_FAIL:
3077 case RLM_MODULE_INVALID:
3078 case RLM_MODULE_NOTFOUND:
3079 case RLM_MODULE_USERLOCK:
3081 /* FIXME: debug print failed stuff */
3084 case RLM_MODULE_REJECT:
3085 case RLM_MODULE_HANDLED:
3089 * Only proxy the packet if the pre-proxy code succeeded.
3091 case RLM_MODULE_NOOP:
3093 case RLM_MODULE_UPDATED:
3098 static int proxy_to_virtual_server(REQUEST *request)
3102 if (request->packet->dst_port == 0) {
3103 WARN("Cannot proxy an internal request");
3107 DEBUG("Proxying to virtual server %s",
3108 request->home_server->server);
3111 * Packets to virtual servers don't get
3112 * retransmissions sent to them. And the virtual
3113 * server is run ONLY if we have no child
3114 * threads, or we're running in a child thread.
3116 rad_assert(!spawn_flag || !we_are_master());
3118 fake = request_alloc_fake(request);
3120 fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3121 talloc_free(request->proxy);
3123 fake->server = request->home_server->server;
3124 fake->handle = request->handle;
3125 fake->process = NULL; /* should never be run for anything */
3128 * Run the virtual server.
3130 request_running(fake, FR_ACTION_RUN);
3132 request->proxy = talloc_steal(request, fake->packet);
3133 fake->packet = NULL;
3134 request->proxy_reply = talloc_steal(request, fake->reply);
3140 * No reply code, toss the reply we have,
3141 * and do post-proxy-type Fail.
3143 if (!request->proxy_reply->code) {
3144 TALLOC_FREE(request->proxy_reply);
3145 setup_post_proxy_fail(request);
3149 * Do the proxy reply (if any)
3151 if (process_proxy_reply(request, request->proxy_reply)) {
3152 request->handle(request);
3155 return -1; /* so we call request_finish */
3159 static int request_proxy(REQUEST *request, int retransmit)
3163 VERIFY_REQUEST(request);
3165 rad_assert(request->parent == NULL);
3166 rad_assert(request->home_server != NULL);
3168 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3172 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
3173 request_done(request->coa, FR_ACTION_DONE);
3178 * The request may need sending to a virtual server.
3179 * This code is more than a little screwed up. The rest
3180 * of the state machine doesn't handle parent / child
3181 * relationships well. i.e. if the child request takes
3182 * too long, the core will mark the *parent* as "stop
3183 * processing". And the child will continue without
3184 * knowing anything...
3186 * So, we have some horrible hacks to get around that.
3188 if (request->home_server->server) return proxy_to_virtual_server(request);
3191 * We're actually sending a proxied packet. Do that now.
3193 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3194 RPROXY("Failed to insert request into the proxy list");
3198 rad_assert(request->proxy->id >= 0);
3200 if (rad_debug_lvl) {
3201 struct timeval *response_window;
3203 response_window = request_response_window(request);
3206 if (request->home_server->tls) {
3207 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3208 inet_ntop(request->proxy->dst_ipaddr.af,
3209 &request->proxy->dst_ipaddr.ipaddr,
3210 buffer, sizeof(buffer)),
3211 request->proxy->dst_port,
3212 (int) response_window->tv_sec, (int) response_window->tv_usec);
3215 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3216 inet_ntop(request->proxy->dst_ipaddr.af,
3217 &request->proxy->dst_ipaddr.ipaddr,
3218 buffer, sizeof(buffer)),
3219 request->proxy->dst_port,
3220 (int) response_window->tv_sec, (int) response_window->tv_usec);
3225 gettimeofday(&request->proxy_retransmit, NULL);
3227 request->proxy->timestamp = request->proxy_retransmit;
3229 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3232 * Encode the packet before we do anything else.
3234 request->proxy_listener->encode(request->proxy_listener, request);
3235 debug_packet(request, request->proxy, false);
3238 * Set the state function, then the state, no child, and
3241 request->process = proxy_wait_for_reply;
3242 request->child_state = REQUEST_PROXIED;
3246 * And send the packet.
3248 request->proxy_listener->send(request->proxy_listener, request);
3253 * Proxy the packet as if it was new.
3255 static int request_proxy_anew(REQUEST *request)
3257 home_server_t *home;
3259 VERIFY_REQUEST(request);
3262 * Delete the request from the proxy list.
3264 * The packet list code takes care of ensuring that IDs
3265 * aren't reused until all 256 IDs have been used. So
3266 * there's a 1/256 chance of re-using the same ID when
3267 * we're sending to the same home server. Which is
3270 remove_from_proxy_hash(request);
3273 * Find a live home server for the request.
3275 home = home_server_ldb(NULL, request->home_pool, request);
3277 REDEBUG2("Failed to find live home server for request");
3279 if (setup_post_proxy_fail(request)) {
3280 request_queue_or_run(request, proxy_running);
3282 gettimeofday(&request->reply->timestamp, NULL);
3283 request_cleanup_delay_init(request);
3288 #ifdef WITH_ACCOUNTING
3290 * Update the Acct-Delay-Time attribute.
3292 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3295 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3296 if (!vp) vp = radius_pair_create(request->proxy,
3297 &request->proxy->vps,
3298 PW_ACCT_DELAY_TIME, 0);
3302 gettimeofday(&now, NULL);
3303 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3309 * May have failed over to a "fallback" virtual server.
3310 * If so, run that instead of doing proxying to a real
3314 request->home_server = home;
3315 TALLOC_FREE(request->proxy);
3317 (void) proxy_to_virtual_server(request);
3321 home_server_update_request(home, request);
3323 if (!insert_into_proxy_hash(request)) {
3324 RPROXY("Failed to insert retransmission into the proxy list");
3325 goto post_proxy_fail;
3329 * Free the old packet, to force re-encoding
3331 talloc_free(request->proxy->data);
3332 request->proxy->data = NULL;
3333 request->proxy->data_len = 0;
3335 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3341 /** Ping a home server.
3344 static void request_ping(REQUEST *request, int action)
3346 home_server_t *home = request->home_server;
3349 VERIFY_REQUEST(request);
3351 TRACE_STATE_MACHINE;
3355 case FR_ACTION_TIMER:
3356 ERROR("No response to status check %d ID %u for home server %s port %d",
3359 inet_ntop(request->proxy->dst_ipaddr.af,
3360 &request->proxy->dst_ipaddr.ipaddr,
3361 buffer, sizeof(buffer)),
3362 request->proxy->dst_port);
3365 case FR_ACTION_PROXY_REPLY:
3366 rad_assert(request->in_proxy_hash);
3368 request->home_server->num_received_pings++;
3369 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3370 request->number, request->proxy->id, home->num_received_pings);
3373 * Remove the request from any hashes
3375 fr_event_delete(el, &request->ev);
3376 remove_from_proxy_hash(request);
3379 * The control socket may have marked the home server as
3380 * alive. OR, it may have suddenly started responding to
3381 * requests again. If so, don't re-do the "make alive"
3384 if (home->state == HOME_STATE_ALIVE) break;
3387 * It's dead, and we haven't received enough ping
3388 * responses to mark it "alive". Wait a bit.
3390 * If it's zombie, we mark it alive immediately.
3392 if ((home->state == HOME_STATE_IS_DEAD) &&
3393 (home->num_received_pings < home->num_pings_to_alive)) {
3398 * Mark it alive and delete any outstanding
3401 mark_home_server_alive(request, home);
3405 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3409 rad_assert(!request->in_request_hash);
3410 rad_assert(request->ev == NULL);
3412 request_done(request, FR_ACTION_DONE);
3416 * Called from start of zombie period, OR after control socket
3417 * marks the home server dead.
3419 static void ping_home_server(void *ctx)
3421 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3424 struct timeval when, now;
3426 if ((home->state == HOME_STATE_ALIVE) ||
3428 (home->proto == IPPROTO_TCP) ||
3430 (home->ev != NULL)) {
3434 gettimeofday(&now, NULL);
3438 * We've run out of zombie time. Mark it dead.
3440 if (home->state == HOME_STATE_ZOMBIE) {
3441 when = home->zombie_period_start;
3442 when.tv_sec += home->zombie_period;
3444 if (timercmp(&when, &now, <)) {
3445 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3446 mark_home_server_dead(home, &now);
3451 * We're not supposed to be pinging it. Just wake up
3452 * when we're supposed to mark it dead.
3454 if (home->ping_check == HOME_PING_CHECK_NONE) {
3455 if (home->state == HOME_STATE_ZOMBIE) {
3456 home->when = home->zombie_period_start;
3457 home->when.tv_sec += home->zombie_period;
3458 INSERT_EVENT(ping_home_server, home);
3462 * Else mark_home_server_dead will set a timer
3463 * for revive_interval.
3469 request = request_alloc(NULL);
3470 if (!request) return;
3471 request->number = request_num_counter++;
3474 request->proxy = rad_alloc(request, true);
3475 rad_assert(request->proxy != NULL);
3477 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3478 request->proxy->code = PW_CODE_STATUS_SERVER;
3480 fr_pair_make(request->proxy, &request->proxy->vps,
3481 "Message-Authenticator", "0x00", T_OP_SET);
3483 } else if (home->type == HOME_TYPE_AUTH) {
3484 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3486 fr_pair_make(request->proxy, &request->proxy->vps,
3487 "User-Name", home->ping_user_name, T_OP_SET);
3488 fr_pair_make(request->proxy, &request->proxy->vps,
3489 "User-Password", home->ping_user_password, T_OP_SET);
3490 fr_pair_make(request->proxy, &request->proxy->vps,
3491 "Service-Type", "Authenticate-Only", T_OP_SET);
3492 fr_pair_make(request->proxy, &request->proxy->vps,
3493 "Message-Authenticator", "0x00", T_OP_SET);
3496 #ifdef WITH_ACCOUNTING
3497 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3499 fr_pair_make(request->proxy, &request->proxy->vps,
3500 "User-Name", home->ping_user_name, T_OP_SET);
3501 fr_pair_make(request->proxy, &request->proxy->vps,
3502 "Acct-Status-Type", "Stop", T_OP_SET);
3503 fr_pair_make(request->proxy, &request->proxy->vps,
3504 "Acct-Session-Id", "00000000", T_OP_SET);
3505 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3506 "Event-Timestamp", "0", T_OP_SET);
3507 vp->vp_date = now.tv_sec;
3509 rad_assert("Internal sanity check failed");
3513 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3514 "NAS-Identifier", "", T_OP_SET);
3516 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3517 home->num_sent_pings);
3521 request->proxy->proto = home->proto;
3523 request->proxy->src_ipaddr = home->src_ipaddr;
3524 request->proxy->dst_ipaddr = home->ipaddr;
3525 request->proxy->dst_port = home->port;
3526 request->home_server = home;
3527 #ifdef DEBUG_STATE_MACHINE
3528 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3529 child_state_names[request->child_state],
3530 child_state_names[REQUEST_DONE]);
3531 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3533 #ifdef HAVE_PTHREAD_H
3534 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3536 request->child_state = REQUEST_PROXIED;
3537 request->process = request_ping;
3539 rad_assert(request->proxy_listener == NULL);
3541 if (!insert_into_proxy_hash(request)) {
3542 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3545 rad_assert(!request->in_request_hash);
3546 rad_assert(!request->in_proxy_hash);
3547 rad_assert(request->ev == NULL);
3548 talloc_free(request);
3553 * Set up the timer callback.
3556 when.tv_sec += home->ping_timeout;
3558 DEBUG("PING: Waiting %u seconds for response to ping",
3559 home->ping_timeout);
3561 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3562 home->num_sent_pings++;
3564 rad_assert(request->proxy_listener != NULL);
3565 debug_packet(request, request->proxy, false);
3566 request->proxy_listener->send(request->proxy_listener,
3570 * Add +/- 2s of jitter, as suggested in RFC 3539
3571 * and in the Issues and Fixes draft.
3574 home->when.tv_sec += home->ping_interval;
3576 add_jitter(&home->when);
3578 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3579 INSERT_EVENT(ping_home_server, home);
3582 static void home_trigger(home_server_t *home, char const *trigger)
3584 REQUEST *my_request;
3585 RADIUS_PACKET *my_packet;
3587 my_request = talloc_zero(NULL, REQUEST);
3588 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3589 my_request->proxy = my_packet;
3590 my_packet->dst_ipaddr = home->ipaddr;
3591 my_packet->src_ipaddr = home->src_ipaddr;
3593 exec_trigger(my_request, home->cs, trigger, false);
3594 talloc_free(my_request);
3597 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3604 rad_assert((home->state == HOME_STATE_ALIVE) ||
3605 (home->state == HOME_STATE_UNKNOWN));
3608 if (home->proto == IPPROTO_TCP) {
3609 WARN("Not marking TCP server %s zombie", home->log_name);
3615 * We've received a real packet recently. Don't mark the
3616 * server as zombie until we've received NO packets for a
3617 * while. The "1/4" of zombie period was chosen rather
3618 * arbitrarily. It's a balance between too short, which
3619 * gives quick fail-over and fail-back, or too long,
3620 * where the proxy still sends packets to an unresponsive
3623 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3624 if (home->last_packet_recv >= start) {
3625 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3626 (int) (now->tv_sec - home->last_packet_recv));
3630 home->state = HOME_STATE_ZOMBIE;
3631 home_trigger(home, "home_server.zombie");
3634 * Set the home server to "zombie", as of the time
3637 home->zombie_period_start.tv_sec = start;
3638 home->zombie_period_start.tv_usec = USEC / 2;
3640 fr_event_delete(el, &home->ev);
3642 home->num_sent_pings = 0;
3643 home->num_received_pings = 0;
3645 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3646 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3647 buffer, sizeof(buffer)),
3648 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3650 ping_home_server(home);
3654 void revive_home_server(void *ctx)
3656 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3660 rad_assert(home->proto != IPPROTO_TCP);
3663 home->state = HOME_STATE_ALIVE;
3664 home->response_timeouts = 0;
3665 home_trigger(home, "home_server.alive");
3666 home->currently_outstanding = 0;
3667 gettimeofday(&home->revive_time, NULL);
3670 * Delete any outstanding events.
3673 if (home->ev) fr_event_delete(el, &home->ev);
3675 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3676 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3677 buffer, sizeof(buffer)),
3681 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3683 int previous_state = home->state;
3687 if (home->proto == IPPROTO_TCP) {
3688 WARN("Not marking TCP server dead");
3693 PROXY( "Marking home server %s port %d as dead.",
3694 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3695 buffer, sizeof(buffer)),
3698 home->state = HOME_STATE_IS_DEAD;
3699 home_trigger(home, "home_server.dead");
3701 if (home->ping_check != HOME_PING_CHECK_NONE) {
3703 * If the control socket marks us dead, start
3704 * pinging. Otherwise, we already started
3705 * pinging when it was marked "zombie".
3707 if (previous_state == HOME_STATE_ALIVE) {
3708 ping_home_server(home);
3710 DEBUG("PING: Already pinging home server %s", home->log_name);
3715 * Revive it after a fixed period of time. This
3716 * is very, very, bad.
3719 home->when.tv_sec += home->revive_interval;
3721 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3723 INSERT_EVENT(revive_home_server, home);
3727 /** Wait for a reply after proxying a request.
3729 * Retransmit the proxied packet, or time out and go to
3730 * proxy_no_reply. Mark the home server unresponsive, etc.
3732 * If we do receive a reply, we transition to proxy_running.
3735 * digraph proxy_wait_for_reply {
3736 * proxy_wait_for_reply;
3738 * proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3739 * proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3740 * proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3741 * proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3742 * proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3746 static void proxy_wait_for_reply(REQUEST *request, int action)
3748 struct timeval now, when;
3749 struct timeval *response_window = NULL;
3750 home_server_t *home = request->home_server;
3753 VERIFY_REQUEST(request);
3755 TRACE_STATE_MACHINE;
3758 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3759 rad_assert(request->home_server != NULL);
3761 gettimeofday(&now, NULL);
3766 * We have a reply, ignore the retransmit.
3768 if (request->proxy_reply) return;
3771 * The request was proxied to a virtual server.
3772 * Ignore the retransmit.
3774 if (request->home_server->server) return;
3777 * Use a new connection when the home server is
3778 * dead, or when there's no proxy listener, or
3779 * when the listener is failed or dead.
3781 * If the listener is known or frozen, use it for
3784 if ((home->state == HOME_STATE_IS_DEAD) ||
3785 !request->proxy_listener ||
3786 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3787 request_proxy_anew(request);
3793 * The home server is still alive, but TCP. We
3794 * rely on TCP to get the request and reply back.
3795 * So there's no need to retransmit.
3797 if (home->proto == IPPROTO_TCP) {
3798 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3799 inet_ntop(request->proxy->dst_ipaddr.af,
3800 &request->proxy->dst_ipaddr.ipaddr,
3801 buffer, sizeof(buffer)),
3802 request->proxy->dst_port,
3803 request->proxy->id);
3809 * More than one retransmit a second is stupid,
3810 * and should be suppressed by the proxy.
3812 when = request->proxy_retransmit;
3815 if (timercmp(&now, &when, <)) {
3816 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3817 inet_ntop(request->proxy->dst_ipaddr.af,
3818 &request->proxy->dst_ipaddr.ipaddr,
3819 buffer, sizeof(buffer)),
3820 request->proxy->dst_port,
3821 request->proxy->id);
3825 #ifdef WITH_ACCOUNTING
3827 * If we update the Acct-Delay-Time, we need to
3830 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3831 fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3832 request_proxy_anew(request);
3837 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3838 inet_ntop(request->proxy->dst_ipaddr.af,
3839 &request->proxy->dst_ipaddr.ipaddr,
3840 buffer, sizeof(buffer)),
3841 request->proxy->dst_port,
3842 request->proxy->id);
3843 request->num_proxied_requests++;
3845 rad_assert(request->proxy_listener != NULL);
3846 FR_STATS_TYPE_INC(home->stats.total_requests);
3847 home->last_packet_sent = now.tv_sec;
3848 request->proxy_retransmit = now;
3849 debug_packet(request, request->proxy, false);
3850 request->proxy_listener->send(request->proxy_listener, request);
3853 case FR_ACTION_TIMER:
3854 response_window = request_response_window(request);
3857 if (!request->proxy_listener ||
3858 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3859 remove_from_proxy_hash(request);
3861 when = request->packet->timestamp;
3862 when.tv_sec += request->root->max_request_time;
3864 if (timercmp(&when, &now, >)) {
3865 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3866 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3873 * Wake up "response_window" time in the future.
3874 * i.e. when MY packet hasn't received a response.
3876 * Note that we DO NOT mark the home server as
3877 * zombie if it doesn't respond to us. It may be
3878 * responding to other (better looking) packets.
3880 when = request->proxy->timestamp;
3881 timeradd(&when, response_window, &when);
3884 * Not at the response window. Set the timer for
3887 if (timercmp(&when, &now, >)) {
3888 struct timeval diff;
3889 timersub(&when, &now, &diff);
3891 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3892 (int) diff.tv_sec, (int) diff.tv_usec);
3893 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3898 RDEBUG("No proxy response, giving up on request and marking it done");
3901 * If we haven't received any packets for
3902 * "response_window", then mark the home server
3905 * If the connection is TCP, then another
3906 * "watchdog timer" function takes care of pings,
3907 * etc. So we don't need to do it here.
3909 * This check should really be part of a home
3910 * server state machine.
3912 if (((home->state == HOME_STATE_ALIVE) ||
3913 (home->state == HOME_STATE_UNKNOWN))
3915 && (home->proto != IPPROTO_TCP)
3918 home->response_timeouts++;
3919 if (home->response_timeouts >= home->max_response_timeouts)
3920 mark_home_server_zombie(home, &now, response_window);
3923 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3924 if (home->type == HOME_TYPE_AUTH) {
3925 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3926 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3929 else if (home->type == HOME_TYPE_ACCT) {
3930 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3931 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3936 * There was no response within the window. Stop
3937 * the request. If the client retransmitted, it
3938 * may have failed over to another home server.
3939 * But that one may be dead, too.
3941 * The extra verbose message if we have a username,
3942 * is extremely useful if the proxy is part of a chain
3943 * and the final home server, is not the one we're
3946 if (request->username) {
3947 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3948 "server %s port %d",
3949 request->username->vp_strvalue,
3950 inet_ntop(request->proxy->dst_ipaddr.af,
3951 &request->proxy->dst_ipaddr.ipaddr,
3952 buffer, sizeof(buffer)),
3953 request->proxy->dst_port);
3955 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3956 inet_ntop(request->proxy->dst_ipaddr.af,
3957 &request->proxy->dst_ipaddr.ipaddr,
3958 buffer, sizeof(buffer)),
3959 request->proxy->dst_port);
3962 if (setup_post_proxy_fail(request)) {
3963 request_queue_or_run(request, proxy_no_reply);
3965 gettimeofday(&request->reply->timestamp, NULL);
3966 request_cleanup_delay_init(request);
3971 * We received a new reply. Go process it.
3973 case FR_ACTION_PROXY_REPLY:
3974 request_queue_or_run(request, proxy_running);
3978 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3982 #endif /* WITH_PROXY */
3985 /***********************************************************************
3989 ***********************************************************************/
3991 static int null_handler(UNUSED REQUEST *request)
3997 * See if we need to originate a CoA request.
3999 static void request_coa_originate(REQUEST *request)
4001 int rcode, pre_proxy_type = 0;
4007 VERIFY_REQUEST(request);
4009 rad_assert(request->coa != NULL);
4010 rad_assert(request->proxy == NULL);
4011 rad_assert(!request->in_proxy_hash);
4012 rad_assert(request->proxy_reply == NULL);
4015 * Check whether we want to originate one, or cancel one.
4017 vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4019 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
4023 if (vp->vp_integer == 0) {
4025 TALLOC_FREE(request->coa);
4033 * src_ipaddr will be set up in proxy_encode.
4035 memset(&ipaddr, 0, sizeof(ipaddr));
4036 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4038 ipaddr.af = AF_INET;
4039 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4041 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4042 ipaddr.af = AF_INET6;
4043 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4044 ipaddr.prefix = 128;
4045 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4046 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4048 if (!coa->home_pool) {
4049 RWDEBUG2("No such home_server_pool %s",
4055 * Prefer the pool to one server
4057 } else if (request->client->coa_pool) {
4058 coa->home_pool = request->client->coa_pool;
4060 } else if (request->client->coa_server) {
4061 coa->home_server = request->client->coa_server;
4065 * If all else fails, send it to the client that
4066 * originated this request.
4068 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4072 * Use the pool, if it exists.
4074 if (coa->home_pool) {
4075 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4076 if (!coa->home_server) {
4077 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4080 home_server_update_request(coa->home_server, coa);
4082 } else if (!coa->home_server) {
4083 uint16_t port = PW_COA_UDP_PORT;
4085 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4086 if (vp) port = vp->vp_integer;
4088 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4089 if (!coa->home_server) {
4090 RWDEBUG2("Unknown destination %s:%d for CoA request.",
4091 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4092 buffer, sizeof(buffer)), port);
4097 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4099 switch (vp->vp_integer) {
4100 case PW_CODE_COA_REQUEST:
4101 case PW_CODE_DISCONNECT_REQUEST:
4102 coa->proxy->code = vp->vp_integer;
4106 DEBUG("Cannot set CoA Packet-Type to code %d",
4112 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4115 * The rest of the server code assumes that
4116 * request->packet && request->reply exist. Copy them
4117 * from the original request.
4119 rad_assert(coa->packet != NULL);
4120 rad_assert(coa->packet->vps == NULL);
4122 coa->packet = rad_copy_packet(coa, request->packet);
4123 coa->reply = rad_copy_packet(coa, request->reply);
4125 coa->config = fr_pair_list_copy(coa, request->config);
4126 coa->num_coa_requests = 0;
4127 coa->handle = null_handler;
4128 coa->number = request->number; /* it's associated with the same request */
4131 * Call the pre-proxy routines.
4133 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4135 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4136 /* Must be a validation issue */
4138 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4139 pre_proxy_type = vp->vp_integer;
4142 if (coa->home_pool && coa->home_pool->virtual_server) {
4143 char const *old_server = coa->server;
4145 coa->server = coa->home_pool->virtual_server;
4146 RDEBUG2("server %s {", coa->server);
4148 rcode = process_pre_proxy(pre_proxy_type, coa);
4151 coa->server = old_server;
4153 rcode = process_pre_proxy(pre_proxy_type, coa);
4160 * Only send the CoA packet if the pre-proxy code succeeded.
4162 case RLM_MODULE_NOOP:
4164 case RLM_MODULE_UPDATED:
4169 * Source IP / port is set when the proxy socket
4172 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4173 coa->proxy->dst_port = coa->home_server->port;
4175 if (!insert_into_proxy_hash(coa)) {
4176 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4181 * We CANNOT divorce the CoA request from the parent
4182 * request. This function is running in a child thread,
4183 * and we need access to the main event loop in order to
4184 * to add the timers for the CoA packet.
4186 * Instead, we wait for the timer on the parent request
4189 gettimeofday(&coa->proxy->timestamp, NULL);
4190 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4191 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4192 coa->delay = 0; /* need to calculate a new delay */
4195 * If requested, put a State attribute into the packet,
4196 * and cache the VPS.
4198 fr_state_put_vps(coa, NULL, coa->packet);
4201 * Encode the packet before we do anything else.
4203 coa->proxy_listener->encode(coa->proxy_listener, coa);
4204 debug_packet(coa, coa->proxy, false);
4206 #ifdef DEBUG_STATE_MACHINE
4207 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4208 child_state_names[request->child_state],
4209 child_state_names[REQUEST_PROXIED]);
4213 * Set the state function, then the state, no child, and
4216 coa->process = coa_wait_for_reply;
4217 coa->child_state = REQUEST_PROXIED;
4219 #ifdef HAVE_PTHREAD_H
4220 coa->child_pid = NO_SUCH_CHILD_PID;
4223 if (we_are_master()) coa_separate(request->coa);
4226 * And send the packet.
4228 coa->proxy_listener->send(coa->proxy_listener, coa);
4232 static void coa_retransmit(REQUEST *request)
4234 uint32_t delay, frac;
4235 struct timeval now, when, mrd;
4238 VERIFY_REQUEST(request);
4240 fr_event_now(el, &now);
4242 if (request->delay == 0) {
4244 * Implement re-transmit algorithm as per RFC 5080
4247 * We want IRT + RAND*IRT
4248 * or 0.9 IRT + rand(0,.2) IRT
4250 * 2^20 ~ USEC, and we want 2.
4251 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4253 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4254 request->delay = delay * request->home_server->coa_irt;
4255 delay = request->home_server->coa_irt * USEC;
4256 delay -= delay / 10;
4257 delay += request->delay;
4258 request->delay = delay;
4260 when = request->proxy->timestamp;
4261 tv_add(&when, delay);
4263 if (timercmp(&when, &now, >)) {
4264 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4270 * Retransmit CoA request.
4274 * Cap count at MRC, if it is non-zero.
4276 if (request->home_server->coa_mrc &&
4277 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4278 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4280 inet_ntop(request->proxy->dst_ipaddr.af,
4281 &request->proxy->dst_ipaddr.ipaddr,
4282 buffer, sizeof(buffer)),
4283 request->proxy->dst_port);
4285 if (setup_post_proxy_fail(request)) {
4286 request_queue_or_run(request, coa_no_reply);
4288 request_done(request, FR_ACTION_DONE);
4294 * RFC 5080 Section 2.2.1
4296 * RT = 2*RTprev + RAND*RTprev
4297 * = 1.9 * RTprev + rand(0,.2) * RTprev
4298 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4301 delay ^= (delay >> 16);
4303 frac = request->delay / 5;
4304 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4306 delay += (2 * request->delay) - (request->delay / 10);
4309 * Cap delay at MRT, if MRT is non-zero.
4311 if (request->home_server->coa_mrt &&
4312 (delay > (request->home_server->coa_mrt * USEC))) {
4313 int mrt_usec = request->home_server->coa_mrt * USEC;
4316 * delay = MRT + RAND * MRT
4317 * = 0.9 MRT + rand(0,.2) * MRT
4320 delay ^= (delay >> 15);
4322 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4323 delay += mrt_usec - (mrt_usec / 10);
4326 request->delay = delay;
4328 tv_add(&when, request->delay);
4329 mrd = request->proxy->timestamp;
4330 mrd.tv_sec += request->home_server->coa_mrd;
4333 * Cap duration at MRD.
4335 if (timercmp(&mrd, &when, <)) {
4338 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4340 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4342 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4344 RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4345 inet_ntop(request->proxy->dst_ipaddr.af,
4346 &request->proxy->dst_ipaddr.ipaddr,
4347 buffer, sizeof(buffer)),
4348 request->proxy->dst_port,
4349 request->proxy->id);
4351 request->proxy_listener->send(request->proxy_listener,
4356 /** Wait for a reply after originating a CoA a request.
4358 * Retransmit the proxied packet, or time out and go to
4359 * coa_no_reply. Mark the home server unresponsive, etc.
4361 * If we do receive a reply, we transition to coa_running.
4364 * digraph coa_wait_for_reply {
4365 * coa_wait_for_reply;
4367 * coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4368 * coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4369 * coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4370 * coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4374 static void coa_wait_for_reply(REQUEST *request, int action)
4376 VERIFY_REQUEST(request);
4378 TRACE_STATE_MACHINE;
4382 if (request->parent) coa_separate(request);
4385 case FR_ACTION_TIMER:
4386 if (request_max_time(request)) break;
4388 coa_retransmit(request);
4391 case FR_ACTION_PROXY_REPLY:
4392 request_queue_or_run(request, coa_running);
4396 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4401 static void coa_separate(REQUEST *request)
4403 VERIFY_REQUEST(request);
4404 #ifdef DEBUG_STATE_MACHINE
4405 int action = FR_ACTION_TIMER;
4408 TRACE_STATE_MACHINE;
4411 rad_assert(request->parent != NULL);
4412 rad_assert(request->parent->coa == request);
4413 rad_assert(request->ev == NULL);
4414 rad_assert(!request->in_request_hash);
4415 rad_assert(request->coa == NULL);
4417 rad_assert(request->proxy_reply || request->proxy_listener);
4419 (void) talloc_steal(NULL, request);
4420 request->parent->coa = NULL;
4421 request->parent = NULL;
4423 if (we_are_master()) {
4425 coa_retransmit(request);
4430 /** Process a request after the CoA has timed out.
4432 * Run the packet through Post-Proxy-Type Fail
4435 * digraph coa_no_reply {
4438 * coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4439 * coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4440 * coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4441 * coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4442 * coa_no_reply -> done [ label = "TIMER >= timeout" ];
4446 static void coa_no_reply(REQUEST *request, int action)
4450 VERIFY_REQUEST(request);
4452 TRACE_STATE_MACHINE;
4456 case FR_ACTION_TIMER:
4457 (void) request_max_time(request);
4460 case FR_ACTION_PROXY_REPLY: /* too late! */
4461 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4462 inet_ntop(request->proxy->src_ipaddr.af,
4463 &request->proxy->src_ipaddr.ipaddr,
4464 buffer, sizeof(buffer)),
4465 request->proxy->dst_port, request->proxy->id);
4469 if (process_proxy_reply(request, NULL)) {
4470 request->handle(request);
4472 request_done(request, FR_ACTION_DONE);
4476 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4482 /** Process the request after receiving a coa reply.
4484 * Throught the post-proxy section, and the through the handler
4488 * digraph coa_running {
4491 * coa_running -> timer [ label = "TIMER < max_request_time" ];
4492 * coa_running -> process_proxy_reply [ label = "RUN" ];
4493 * coa_running -> done [ label = "TIMER >= timeout" ];
4497 static void coa_running(REQUEST *request, int action)
4499 VERIFY_REQUEST(request);
4501 TRACE_STATE_MACHINE;
4505 case FR_ACTION_TIMER:
4506 (void) request_max_time(request);
4510 if (process_proxy_reply(request, request->proxy_reply)) {
4511 request->handle(request);
4513 request_done(request, FR_ACTION_DONE);
4517 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4521 #endif /* WITH_COA */
4523 /***********************************************************************
4525 * End of the State machine. Start of additional helper code.
4527 ***********************************************************************/
4529 /***********************************************************************
4533 ***********************************************************************/
4534 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4536 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4538 rad_assert(xel == el);
4540 if ((listener->fd < 0)
4542 #ifndef WITH_DETAIL_THREAD
4543 && (listener->type != RAD_LISTEN_DETAIL)
4549 listener->print(listener, buffer, sizeof(buffer));
4550 ERROR("FATAL: Asked to read from closed socket: %s",
4553 rad_panic("Socket was closed on us!");
4557 listener->recv(listener);
4561 #ifdef WITH_DETAIL_THREAD
4564 * This function is called periodically to see if this detail
4565 * file is available for reading.
4567 static void event_poll_detail(void *ctx)
4570 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4571 struct timeval when, now;
4572 listen_detail_t *detail = this->data;
4574 rad_assert(this->type == RAD_LISTEN_DETAIL);
4577 event_socket_handler(el, this->fd, this);
4579 fr_event_now(el, &now);
4583 * Backdoor API to get the delay until the next poll
4586 delay = this->encode(this, NULL);
4587 if (delay == 0) goto redo;
4589 tv_add(&when, delay);
4592 if (!fr_event_insert(el, event_poll_detail, this,
4593 &when, &detail->ev)) {
4594 ERROR("Failed creating handler");
4598 #endif /* WITH_DETAIL_THREAD */
4599 #endif /* WITH_DETAIL */
4601 static void event_status(struct timeval *wake)
4603 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4607 if (rad_debug_lvl == 0) {
4609 INFO("Ready to process requests");
4610 just_started = false;
4616 INFO("Ready to process requests");
4618 } else if ((wake->tv_sec != 0) ||
4619 (wake->tv_usec >= 100000)) {
4620 DEBUG("Waking up in %d.%01u seconds.",
4621 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4626 * FIXME: Put this somewhere else, where it isn't called
4627 * all of the time...
4630 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4632 * If there are no child threads, then there may
4633 * be child processes. In that case, wait for
4634 * their exit status, and throw that exit status
4635 * away. This helps get rid of zxombie children.
4637 while (waitpid(-1, &argval, WNOHANG) > 0) {
4645 static void listener_free_cb(void *ctx)
4647 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4650 if (this->count > 0) {
4651 struct timeval when;
4652 listen_socket_t *sock = this->data;
4654 fr_event_now(el, &when);
4658 if (!fr_event_insert(el, listener_free_cb, this, &when,
4660 rad_panic("Failed to insert event");
4667 * It's all free, close the socket.
4670 this->print(this, buffer, sizeof(buffer));
4671 DEBUG("... cleaning up socket %s", buffer);
4672 rad_assert(this->next == NULL);
4678 static int proxy_eol_cb(void *ctx, void *data)
4680 struct timeval when;
4681 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4683 if (request->proxy_listener != ctx) return 0;
4686 * We don't care if it's being processed in a child thread.
4689 #ifdef WITH_ACCOUNTING
4691 * Accounting packets should be deleted immediately.
4692 * They will never be retransmitted by the client.
4694 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4695 RDEBUG("Stopping request due to failed connection to home server");
4696 request->master_state = REQUEST_STOP_PROCESSING;
4701 * Reset the timer to be now, so that the request is
4702 * quickly updated. But spread the requests randomly
4703 * over the next second, so that we don't overload the
4706 fr_event_now(el, &when);
4707 tv_add(&when, fr_rand() % USEC);
4708 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4711 * Don't delete it from the list.
4717 static int event_new_fd(rad_listen_t *this)
4723 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4725 this->print(this, buffer, sizeof(buffer));
4727 if (this->status == RAD_LISTEN_STATUS_INIT) {
4728 listen_socket_t *sock = this->data;
4730 rad_assert(sock != NULL);
4732 DEBUG("Listening on %s", buffer);
4734 INFO(" ... adding new socket %s", buffer);
4738 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4739 home_server_t *home;
4742 if (!home || !home->limit.max_connections) {
4743 INFO(" ... adding new socket %s", buffer);
4745 INFO(" ... adding new socket %s (%u of %u)", buffer,
4746 home->limit.num_connections, home->limit.max_connections);
4752 switch (this->type) {
4755 * Detail files are always known, and aren't
4756 * put into the socket event loop.
4758 case RAD_LISTEN_DETAIL:
4759 this->status = RAD_LISTEN_STATUS_KNOWN;
4761 #ifndef WITH_DETAIL_THREAD
4763 * Set up the first poll interval.
4765 event_poll_detail(this);
4768 break; /* add the FD to the list */
4770 #endif /* WITH_DETAIL */
4774 * Add it to the list of sockets we can use.
4775 * Server sockets (i.e. auth/acct) are never
4776 * added to the packet list.
4778 case RAD_LISTEN_PROXY:
4780 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4783 * Add timers to outgoing child sockets, if necessary.
4785 if (sock->proto == IPPROTO_TCP && sock->opened &&
4786 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4787 struct timeval when;
4789 when.tv_sec = sock->opened + 1;
4793 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4795 rad_panic("Failed to insert event");
4800 #endif /* WITH_PROXY */
4803 * FIXME: put idle timers on command sockets.
4809 * Add timers to incoming child sockets, if necessary.
4811 if (sock->proto == IPPROTO_TCP && sock->opened &&
4812 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4813 struct timeval when;
4815 when.tv_sec = sock->opened + 1;
4819 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4821 ERROR("Failed adding timer for socket: %s", fr_strerror());
4827 } /* switch over listener types */
4830 * All sockets: add the FD to the event handler.
4832 if (!fr_event_fd_insert(el, 0, this->fd,
4833 event_socket_handler, this)) {
4834 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4838 this->status = RAD_LISTEN_STATUS_KNOWN;
4844 * The socket has reached a timeout. Try to close it.
4846 if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4848 * Requests are still using the socket. Wait for
4851 if (this->count > 0) {
4852 struct timeval when;
4853 listen_socket_t *sock = this->data;
4856 * Try again to clean up the socket in 30
4859 gettimeofday(&when, NULL);
4863 if (!fr_event_insert(el,
4864 (fr_event_callback_t) event_new_fd,
4865 this, &when, &sock->ev)) {
4866 rad_panic("Failed to insert event");
4872 fr_event_fd_delete(el, 0, this->fd);
4873 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4877 * The socket has had a catastrophic error. Close it.
4879 if (this->status == RAD_LISTEN_STATUS_EOL) {
4881 * Remove it from the list of live FD's.
4883 fr_event_fd_delete(el, 0, this->fd);
4887 * Tell all requests using this socket that the socket is dead.
4889 if (this->type == RAD_LISTEN_PROXY) {
4890 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4891 if (!fr_packet_list_socket_freeze(proxy_list,
4893 ERROR("Fatal error freezing socket: %s", fr_strerror());
4897 if (this->count > 0) {
4898 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4900 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4905 * Requests are still using the socket. Wait for
4908 if (this->count > 0) {
4909 struct timeval when;
4910 listen_socket_t *sock = this->data;
4913 * Try again to clean up the socket in 30
4916 gettimeofday(&when, NULL);
4920 if (!fr_event_insert(el,
4921 (fr_event_callback_t) event_new_fd,
4922 this, &when, &sock->ev)) {
4923 rad_panic("Failed to insert event");
4930 * No one is using the socket. We can remove it now.
4932 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4933 } /* socket is at EOL */
4939 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4942 listen_socket_t *sock = this->data;
4944 struct timeval when;
4947 * Re-open the socket, pointing it to /dev/null.
4948 * This means that all writes proceed without
4949 * blocking, and all reads return "no data".
4951 * This leaves the socket active, so any child
4952 * threads won't go insane. But it means that
4953 * they cannot send or receive any packets.
4955 * This is EXTRA work in the normal case, when
4956 * sockets are closed without error. But it lets
4957 * us have one simple processing method for all
4960 devnull = open("/dev/null", O_RDWR);
4962 ERROR("FATAL failure opening /dev/null: %s",
4963 fr_syserror(errno));
4966 if (dup2(devnull, this->fd) < 0) {
4967 ERROR("FATAL failure closing socket: %s",
4968 fr_syserror(errno));
4974 rad_assert(this->type != RAD_LISTEN_DETAIL);
4980 * The socket is dead. Force all proxied packets
4981 * to stop using it. And then remove it from the
4982 * list of outgoing sockets.
4984 if (this->type == RAD_LISTEN_PROXY) {
4985 home_server_t *home;
4988 if (!home || !home->limit.max_connections) {
4989 INFO(" ... shutting down socket %s", buffer);
4991 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4992 home->limit.num_connections, home->limit.max_connections);
4995 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4996 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4998 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4999 ERROR("Fatal error removing socket %s: %s",
5000 buffer, fr_strerror());
5003 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
5007 INFO(" ... shutting down socket %s", buffer);
5010 * EOL all requests using this socket.
5012 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
5016 * No child threads, clean it up now.
5020 if (sock->ev) fr_event_delete(el, &sock->ev);
5026 * Wait until all requests using this socket are done.
5028 gettimeofday(&when, NULL);
5032 if (!fr_event_insert(el, listener_free_cb, this, &when,
5034 rad_panic("Failed to insert event");
5037 #endif /* WITH_TCP */
5042 /***********************************************************************
5046 ***********************************************************************/
5048 static void handle_signal_self(int flag)
5052 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5053 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5054 INFO("Signalled to exit");
5055 fr_event_loop_exit(el, 1);
5057 INFO("Signalled to terminate");
5058 fr_event_loop_exit(el, 2);
5062 } /* else exit/term flags weren't set */
5065 * Tell the even loop to stop processing.
5067 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5069 static time_t last_hup = 0;
5072 if ((int) (when - last_hup) < 5) {
5073 INFO("Ignoring HUP (less than 5s since last one)");
5077 INFO("Received HUP signal");
5081 exec_trigger(NULL, NULL, "server.signal.hup", true);
5082 fr_event_loop_exit(el, 0x80);
5085 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5086 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5090 * FIXME: O(N) loops suck.
5092 for (this = main_config.listen;
5094 this = this->next) {
5095 if (this->type != RAD_LISTEN_DETAIL) continue;
5098 * This one didn't send the signal, skip
5101 if (!this->decode(this, NULL)) continue;
5104 * Go service the interrupt.
5106 event_poll_detail(this);
5111 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5113 * There are new listeners in the list. Run
5114 * event_new_fd() on them.
5116 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5117 rad_listen_t *this, *next;
5119 FD_MUTEX_LOCK(&fd_mutex);
5122 * FIXME: unlock the mutex before calling
5125 for (this = new_listeners; this != NULL; this = next) {
5132 new_listeners = NULL;
5133 FD_MUTEX_UNLOCK(&fd_mutex);
5138 #ifndef HAVE_PTHREAD_H
5139 void radius_signal_self(int flag)
5141 return handle_signal_self(flag);
5145 static int self_pipe[2] = { -1, -1 };
5148 * Inform ourselves that we received a signal.
5150 void radius_signal_self(int flag)
5156 * The read MUST be non-blocking for this to work.
5158 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5162 for (i = 0; i < rcode; i++) {
5163 buffer[0] |= buffer[i];
5171 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5175 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5176 UNUSED int fd, UNUSED void *ctx)
5181 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5182 if (rcode <= 0) return;
5185 * Merge pending signals.
5187 for (i = 0; i < rcode; i++) {
5188 buffer[0] |= buffer[i];
5191 handle_signal_self(buffer[0]);
5193 #endif /* HAVE_PTHREAD_H */
5195 /***********************************************************************
5197 * Bootstrapping code.
5199 ***********************************************************************/
5202 * Externally-visibly functions.
5204 int radius_event_init(TALLOC_CTX *ctx) {
5205 el = fr_event_list_create(ctx, event_status);
5211 static int packet_entry_cmp(void const *one, void const *two)
5213 RADIUS_PACKET const * const *a = one;
5214 RADIUS_PACKET const * const *b = two;
5216 return fr_packet_cmp(*a, *b);
5221 * They haven't defined a proxy listener. Automatically
5222 * add one for them, with the correct address family.
5224 static void create_default_proxy_listener(int af)
5228 listen_socket_t *sock;
5231 memset(&home, 0, sizeof(home));
5234 * Open a default UDP port
5236 home.proto = IPPROTO_UDP;
5240 * Set the address family.
5242 home.src_ipaddr.af = af;
5243 home.ipaddr.af = af;
5246 * Get the correct listener.
5248 this = proxy_new_listener(proxy_ctx, &home, port);
5254 if (!fr_packet_list_socket_add(proxy_list, this->fd,
5256 &sock->other_ipaddr, sock->other_port,
5258 ERROR("Failed adding proxy socket");
5263 * Insert the FD into list of FDs to listen on.
5265 radius_update_listener(this);
5269 * See if we automatically need to open a proxy socket.
5271 static void check_proxy(rad_listen_t *head)
5274 bool has_v4, has_v6;
5277 if (check_config) return;
5278 if (!main_config.proxy_requests) return;
5280 if (!home_servers_udp) return;
5283 * We passed "-i" on the command line. Use that address
5284 * family for the proxy socket.
5286 if (main_config.myip.af != AF_UNSPEC) {
5287 create_default_proxy_listener(main_config.myip.af);
5291 defined_proxy = has_v4 = has_v6 = false;
5294 * Figure out if we need to open a proxy socket, and if
5297 for (this = head; this != NULL; this = this->next) {
5298 listen_socket_t *sock;
5300 switch (this->type) {
5301 case RAD_LISTEN_PROXY:
5302 defined_proxy = true;
5305 case RAD_LISTEN_AUTH:
5307 case RAD_LISTEN_ACCT:
5310 case RAD_LISTEN_COA:
5313 if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5314 if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5323 * Assume they know what they're doing.
5325 if (defined_proxy) return;
5327 if (has_v4) create_default_proxy_listener(AF_INET);
5329 if (has_v6) create_default_proxy_listener(AF_INET6);
5333 int radius_event_start(CONF_SECTION *cs, bool have_children)
5335 rad_listen_t *head = NULL;
5337 if (fr_start_time != (time_t)-1) return 0;
5339 time(&fr_start_time);
5341 if (!check_config) {
5343 * radius_event_init() must be called first
5347 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5348 if (!pl) return 0; /* leak el */
5351 request_num_counter = 0;
5354 if (main_config.proxy_requests && !check_config) {
5356 * Create the tree for managing proxied requests and
5359 proxy_list = fr_packet_list_create(1);
5360 if (!proxy_list) return 0;
5362 #ifdef HAVE_PTHREAD_H
5363 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5364 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5365 fr_syserror(errno));
5371 * The "init_delay" is set to "response_window".
5372 * Reset it to half of "response_window" in order
5373 * to give the event loop enough time to service
5374 * the event before hitting "response_window".
5376 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5377 main_config.init_delay.tv_usec >>= 1;
5378 main_config.init_delay.tv_sec >>= 1;
5380 proxy_ctx = talloc_init("proxy");
5385 * Move all of the thread calls to this file?
5387 * It may be best for the mutexes to be in this file...
5389 spawn_flag = have_children;
5391 #ifdef HAVE_PTHREAD_H
5392 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5395 * Initialize the threads ONLY if we're spawning, AND
5396 * we're running normally.
5398 if (have_children && !check_config &&
5399 (thread_pool_init(cs, &spawn_flag) < 0)) {
5405 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5407 if (listen_init(cs, &head, spawn_flag) < 0) {
5414 #ifdef HAVE_PTHREAD_H
5416 * Child threads need a pipe to signal us, as do the
5419 if (pipe(self_pipe) < 0) {
5420 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5423 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5424 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5425 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5428 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5429 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5430 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5433 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5435 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5436 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5441 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5444 * The server temporarily switches to an unprivileged
5445 * user very early in the bootstrapping process.
5446 * However, some sockets MAY require privileged access
5447 * (bind to device, or to port < 1024, or to raw
5448 * sockets). Those sockets need to call suid up/down
5449 * themselves around the functions that need a privileged
5452 if (listen_init(cs, &head, spawn_flag) < 0) {
5456 main_config.listen = head;
5463 * At this point, no one has any business *ever* going
5466 rad_suid_down_permanent();
5473 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5475 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5477 VERIFY_REQUEST(request);
5479 request->master_state = REQUEST_STOP_PROCESSING;
5481 #ifdef HAVE_PTHREAD_H
5482 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5486 * If it's queued we can't delete it from the queue.
5488 * Otherwise, it's OK to delete it. Even RUNNING, because
5489 * that will get caught by the check above.
5491 if (request->child_state == REQUEST_QUEUED) return 0;
5493 request->in_proxy_hash = false;
5495 if (!request->in_request_hash) {
5496 request_done(request, FR_ACTION_DONE);
5500 * Delete it from the list.
5507 static int request_delete_cb(UNUSED void *ctx, void *data)
5509 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5511 VERIFY_REQUEST(request);
5513 request->master_state = REQUEST_STOP_PROCESSING;
5516 * Not done, or the child thread is still processing it.
5518 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5520 #ifdef HAVE_PTHREAD_H
5521 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5525 rad_assert(request->in_proxy_hash == false);
5528 request->in_request_hash = false;
5530 if (request->ev) fr_event_delete(el, &request->ev);
5532 if (main_config.memory_report) {
5533 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5534 request->packet->id,
5535 (unsigned int) (request->timestamp - fr_start_time));
5540 rad_assert(!request->coa->in_proxy_hash);
5544 request_free(request);
5547 * Delete it from the list, and continue;
5553 void radius_event_free(void)
5559 * There are requests in the proxy hash that aren't
5560 * referenced from anywhere else. Remove them first.
5563 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5567 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5571 * Now that all requests have been marked "please stop",
5572 * ensure that all of the threads have exited.
5574 #ifdef HAVE_PTHREAD_H
5579 * Walk the lists again, ensuring that all
5580 * requests are done.
5582 if (main_config.memory_report) {
5587 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5588 num = fr_packet_list_num_elements(proxy_list);
5590 ERROR("Proxy list has %d requests still in it.", num);
5595 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5596 num = rbtree_num_elements(pl);
5598 ERROR("Request list has %d requests still in it.", num);
5607 fr_packet_list_free(proxy_list);
5610 if (proxy_ctx) talloc_free(proxy_ctx);
5615 if (debug_condition) talloc_free(debug_condition);
5618 int radius_event_process(void)
5622 return fr_event_loop(el);