2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Defines the state machines that control how requests are processed.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
34 #include <freeradius-devel/rad_assert.h>
37 #include <freeradius-devel/detail.h>
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
47 extern pid_t radius_pid;
48 extern fr_cond_t *debug_condition;
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static rbtree_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57 /* Currently we do not run a second event loop for modules. */
61 static char const *action_codes[] = {
72 #ifdef DEBUG_STATE_MACHINE
73 # define TRACE_STATE_MACHINE \
74 if (debug_flag) do { \
75 struct timeval debug_tv; \
76 gettimeofday(&debug_tv, NULL); \
77 debug_tv.tv_sec -= fr_start_time; \
78 printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79 request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80 __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81 child_state_names[request->child_state]); \
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
102 # define TRACE_STATE_MACHINE {}
105 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:%i to %s:%i length %zu",
420 received ? "Received" : "Sent",
421 fr_packet_codes[packet->code],
423 inet_ntop(packet->src_ipaddr.af,
424 &packet->src_ipaddr.ipaddr,
425 src_ipaddr, sizeof(src_ipaddr)),
427 inet_ntop(packet->dst_ipaddr.af,
428 &packet->dst_ipaddr.ipaddr,
429 dst_ipaddr, sizeof(dst_ipaddr)),
433 RDEBUG("%s code %i Id %i from %s:%i to %s:%i length %zu",
434 received ? "Received" : "Sent",
437 inet_ntop(packet->src_ipaddr.af,
438 &packet->src_ipaddr.ipaddr,
439 src_ipaddr, sizeof(src_ipaddr)),
441 inet_ntop(packet->dst_ipaddr.af,
442 &packet->dst_ipaddr.ipaddr,
443 dst_ipaddr, sizeof(dst_ipaddr)),
449 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
451 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
456 /***********************************************************************
458 * Start of RADIUS server state machine.
460 ***********************************************************************/
462 static struct timeval *request_response_window(REQUEST *request)
464 VERIFY_REQUEST(request);
466 if (request->client) {
468 * The client hasn't set the response window. Return
469 * either the home server one, if set, or the global one.
471 if (!timerisset(&request->client->response_window)) {
472 return &request->home_server->response_window;
475 if (timercmp(&request->client->response_window,
476 &request->home_server->response_window, <)) {
477 return &request->client->response_window;
481 rad_assert(request->home_server != NULL);
482 return &request->home_server->response_window;
486 * Determine initial request processing delay.
488 static int request_init_delay(REQUEST *request)
490 struct timeval half_response_window;
492 VERIFY_REQUEST(request);
494 /* Allow client response window to lower initial delay */
495 if (timerisset(&request->client->response_window)) {
496 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
497 half_response_window.tv_usec =
498 ((request->client->response_window.tv_sec & 1) * USEC +
499 request->client->response_window.tv_usec) >> 1;
500 if (timercmp(&half_response_window, &request->root->init_delay, <))
501 return (int)half_response_window.tv_sec * USEC +
502 (int)half_response_window.tv_usec;
505 return (int)request->root->init_delay.tv_sec * USEC +
506 (int)request->root->init_delay.tv_usec;
510 * Callback for ALL timer events related to the request.
512 static void request_timer(void *ctx)
514 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
517 action = request->timer_action;
521 request->process(request, action);
525 * Wrapper for talloc pools. If there's no parent, just free the
526 * request. If there is a parent, free the parent INSTEAD of the
529 static void request_free(REQUEST *request)
533 rad_assert(request->ev == NULL);
534 rad_assert(!request->in_request_hash);
535 rad_assert(!request->in_proxy_hash);
537 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
538 talloc_free(request);
542 ptr = talloc_parent(request);
543 rad_assert(ptr != NULL);
549 static void proxy_reply_too_late(REQUEST *request)
553 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
554 inet_ntop(request->proxy->dst_ipaddr.af,
555 &request->proxy->dst_ipaddr.ipaddr,
556 buffer, sizeof(buffer)),
557 request->proxy->dst_port, request->proxy->id);
562 /** Mark a request DONE and clean it up.
564 * When a request is DONE, it can have ties to a number of other
565 * portions of the server. The request hash, proxy hash, events,
566 * child threads, etc. This function takes care of either cleaning
567 * up the request, or managing the timers to wait for the ties to be
572 * done -> done [ label = "still running" ];
576 static void request_done(REQUEST *request, int action)
578 struct timeval now, when;
580 VERIFY_REQUEST(request);
585 * Force this no matter what.
587 request->process = request_done;
591 * Tell the detail listener that we're done.
593 if (request->listener &&
594 (request->listener->type == RAD_LISTEN_DETAIL) &&
595 (request->simul_max != 1)) {
596 request->simul_max = 1;
597 request->listener->send(request->listener,
602 #ifdef HAVE_PTHREAD_H
604 * If called from a child thread, mark ourselves as done,
605 * and wait for the master thread timer to clean us up.
607 if (!we_are_master()) {
609 request->child_state = REQUEST_DONE;
615 * Mark the request as STOP.
617 request->master_state = REQUEST_STOP_PROCESSING;
621 * Move the CoA request to its own handler.
624 coa_separate(request->coa);
625 } else if (request->parent && (request->parent->coa == request)) {
626 coa_separate(request);
631 * It doesn't hurt to send duplicate replies. All other
632 * signals are ignored, as the request will be cleaned up
638 rad_assert(request->listener != NULL);
640 if (request->reply->code != 0) {
641 request->listener->send(request->listener, request);
644 RDEBUG("No reply. Ignoring retransmit");
649 * Mark the request as done.
652 #ifdef HAVE_PTHREAD_H
654 * If the child is still running, leave it alone.
656 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
661 #ifdef DEBUG_STATE_MACHINE
662 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
663 request->number, __FUNCTION__,
664 child_state_names[request->child_state],
665 child_state_names[REQUEST_DONE]);
667 request->child_state = REQUEST_DONE;
671 * Called when the child is taking too long to
672 * finish. We've already marked it "please
673 * stop", so we don't complain any more.
675 case FR_ACTION_TIMER:
679 case FR_ACTION_PROXY_REPLY:
680 proxy_reply_too_late(request);
689 * Remove it from the request hash.
691 if (request->in_request_hash) {
692 if (!rbtree_deletebydata(pl, &request->packet)) {
695 request->in_request_hash = false;
700 * Wait for the proxy ID to expire. This allows us to
701 * avoid re-use of proxy IDs for a while.
703 if (request->in_proxy_hash) {
704 rad_assert(request->proxy != NULL);
706 fr_event_now(el, &now);
707 when = request->proxy->timestamp;
710 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
711 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
712 (request->packet->code != request->proxy->code)) {
713 when.tv_sec += request->home_server->coa_mrd;
716 timeradd(&when, request_response_window(request), &when);
719 * We haven't received all responses, AND there's still
720 * time to wait. Do so.
722 if ((request->num_proxied_requests > request->num_proxied_responses) &&
724 (request->home_server->proto != IPPROTO_TCP) &&
726 timercmp(&now, &when, <)) {
727 RDEBUG("Waiting for more responses from the home server");
734 remove_from_proxy_hash(request);
738 #ifdef HAVE_PTHREAD_H
740 * If there's no children, we can mark the request as done.
742 if (!spawn_flag) request->child_state = REQUEST_DONE;
746 * If the child is still running, wait for it to be finished.
748 if (request->child_state <= REQUEST_RUNNING) {
749 gettimeofday(&now, NULL);
754 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
755 tv_add(&when, request->delay);
756 request->delay += request->delay >> 1;
757 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
759 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
763 #ifdef HAVE_PTHREAD_H
764 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
768 * @todo: do final states for TCP sockets, too?
770 request_stats_final(request);
772 if (request->listener) {
773 request->listener->count--;
776 * If we're the last one, remove the listener now.
778 if ((request->listener->count == 0) &&
779 (request->listener->status == RAD_LISTEN_STATUS_EOL)) {
780 request->listener->status = RAD_LISTEN_STATUS_REMOVE_NOW;
781 event_new_fd(request->listener);
786 if (request->packet) {
787 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
789 (unsigned int) (request->timestamp - fr_start_time));
790 } /* else don't print anything */
793 fr_event_delete(el, &request->ev);
794 request_free(request);
798 static void request_cleanup_delay_init(REQUEST *request)
800 struct timeval now, when;
802 VERIFY_REQUEST(request);
804 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
808 * If the packets are from the detail file, we can clean them up now.
810 if (request->listener->type == RAD_LISTEN_DETAIL) goto done;
813 if (!request->root->cleanup_delay) goto done;
815 gettimeofday(&now, NULL);
817 rad_assert(request->reply->timestamp.tv_sec != 0);
818 when = request->reply->timestamp;
820 request->delay = request->root->cleanup_delay;
821 when.tv_sec += request->delay;
824 * Set timer for when we need to clean it up.
826 if (timercmp(&when, &now, >)) {
827 #ifdef DEBUG_STATE_MACHINE
828 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
830 request->process = request_cleanup_delay;
831 request->child_state = REQUEST_CLEANUP_DELAY;
834 * Update this if we can, otherwise let the timers pick it up.
836 if (we_are_master()) {
837 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
845 * Otherwise just clean it up.
848 request_done(request, FR_ACTION_DONE);
853 * Enforce max_request_time.
855 static void request_max_time(REQUEST *request)
857 struct timeval now, when;
858 rad_assert(request->magic == REQUEST_MAGIC);
859 #ifdef DEBUG_STATE_MACHINE
860 int action = FR_ACTION_TIMER;
863 VERIFY_REQUEST(request);
869 * The child thread has acknowledged it's done.
870 * Transition to the DONE state.
872 * If the request was marked STOP, then the "check for
873 * stop" macro already took care of it.
875 if (request->child_state == REQUEST_DONE) {
877 request_done(request, FR_ACTION_DONE);
882 * The request is still running. Enforce max_request_time.
884 fr_event_now(el, &now);
885 when = request->packet->timestamp;
886 when.tv_sec += request->root->max_request_time;
889 * Taking too long: tell it to die.
891 if (timercmp(&now, &when, >=)) {
892 #ifdef HAVE_PTHREAD_H
894 * If there's a child thread processing it,
898 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
899 ERROR("Unresponsive child for request %u, in component %s module %s",
901 request->component ? request->component : "<core>",
902 request->module ? request->module : "<core>");
903 exec_trigger(request, NULL, "server.thread.unresponsive", true);
907 * Tell the request that it's done.
913 * Sleep for some more. We HOPE that the child will
914 * become responsive at some point in the future. We do
915 * this by adding 50% to the current timer.
918 tv_add(&when, request->delay);
919 request->delay += request->delay >> 1;
920 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
923 static void request_queue_or_run(REQUEST *request,
924 fr_request_process_t process)
926 #ifdef DEBUG_STATE_MACHINE
927 int action = FR_ACTION_TIMER;
930 VERIFY_REQUEST(request);
935 * Do this here so that fewer other functions need to do
938 if (request->master_state == REQUEST_STOP_PROCESSING) {
939 #ifdef DEBUG_STATE_MACHINE
940 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
941 request->number, __FUNCTION__,
942 master_state_names[request->master_state],
943 child_state_names[request->child_state],
944 child_state_names[REQUEST_DONE]);
946 request_done(request, FR_ACTION_DONE);
950 request->process = process;
952 if (we_are_master()) {
956 * (re) set the initial delay.
958 request->delay = request_init_delay(request);
959 if (request->delay > USEC) request->delay = USEC;
960 gettimeofday(&when, NULL);
961 tv_add(&when, request->delay);
962 request->delay += request->delay >> 1;
964 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
966 #ifdef HAVE_PTHREAD_H
969 * A child thread will eventually pick it up.
971 if (request_enqueue(request)) return;
974 * Otherwise we're not going to do anything with
977 request_done(request, FR_ACTION_DONE);
983 request->child_state = REQUEST_RUNNING;
984 request->process(request, FR_ACTION_RUN);
988 * Requests that care about child process exit
989 * codes have already either called
990 * rad_waitpid(), or they've given up.
992 while (waitpid(-1, NULL, WNOHANG) > 0);
997 static void request_dup(REQUEST *request)
999 ERROR("(%u) Ignoring duplicate packet from "
1000 "client %s port %d - ID: %u due to unfinished request "
1001 "in component %s module %s",
1002 request->number, request->client->shortname,
1003 request->packet->src_port,request->packet->id,
1004 request->component, request->module);
1008 /** Sit on a request until it's time to clean it up.
1010 * A NAS may not see a response from the server. When the NAS
1011 * retransmits, we want to be able to send a cached reply back. The
1012 * alternative is to re-process the packet, which does bad things for
1013 * EAP, among others.
1015 * IF we do see a NAS retransmit, we extend the cleanup delay,
1016 * because the NAS might miss our cached reply.
1018 * Otherwise, once we reach cleanup_delay, we transition to DONE.
1021 * digraph cleanup_delay {
1023 * send_reply [ label = "send_reply\nincrease cleanup delay" ];
1025 * cleanup_delay -> send_reply [ label = "DUP" ];
1026 * send_reply -> cleanup_delay;
1027 * cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY" ];
1028 * proxy_reply_too_late -> cleanup_delay;
1029 * cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
1030 * cleanup_delay -> done [ label = "TIMER >= timeout" ];
1034 static void request_cleanup_delay(REQUEST *request, int action)
1036 struct timeval when, now;
1038 VERIFY_REQUEST(request);
1040 TRACE_STATE_MACHINE;
1047 if (request->reply->code != 0) {
1048 request->listener->send(request->listener, request);
1050 RDEBUG("No reply. Ignoring retransmit");
1054 * Double the cleanup_delay to catch retransmits.
1056 when = request->reply->timestamp;
1057 request->delay += request->delay;
1058 when.tv_sec += request->delay;
1060 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1064 case FR_ACTION_PROXY_REPLY:
1065 proxy_reply_too_late(request);
1069 case FR_ACTION_TIMER:
1070 fr_event_now(el, &now);
1072 rad_assert(request->root->cleanup_delay > 0);
1074 when = request->reply->timestamp;
1075 when.tv_sec += request->root->cleanup_delay;
1077 if (timercmp(&when, &now, >)) {
1078 #ifdef DEBUG_STATE_MACHINE
1079 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1081 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1083 } /* else it's time to clean up */
1085 request_done(request, REQUEST_DONE);
1089 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1095 /** Sit on a request until it's time to respond to it.
1097 * For security reasons, rejects (and maybe some other) packets are
1098 * delayed for a while before we respond. This delay means that
1099 * badly behaved NASes don't hammer the server with authentication
1102 * Otherwise, once we reach response_delay, we send the reply, and
1103 * transition to cleanup_delay.
1106 * digraph response_delay {
1107 * response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY" ];
1108 * proxy_reply_too_late -> response_delay;
1109 * response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1110 * response_delay -> send_reply [ label = "TIMER >= timeout" ];
1111 * send_reply -> cleanup_delay;
1115 static void request_response_delay(REQUEST *request, int action)
1117 struct timeval when, now;
1119 VERIFY_REQUEST(request);
1121 TRACE_STATE_MACHINE;
1128 ERROR("(%u) Discarding duplicate request from "
1129 "client %s port %d - ID: %u due to delayed response",
1130 request->number, request->client->shortname,
1131 request->packet->src_port,request->packet->id);
1135 case FR_ACTION_PROXY_REPLY:
1136 proxy_reply_too_late(request);
1140 case FR_ACTION_TIMER:
1141 fr_event_now(el, &now);
1143 rad_assert(request->response_delay.tv_sec > 0);
1146 * See if it's time to send the reply. If not,
1147 * we wait some more.
1149 when = request->reply->timestamp;
1151 tv_add(&when, request->response_delay.tv_sec * USEC);
1152 tv_add(&when, request->response_delay.tv_usec);
1154 if (timercmp(&when, &now, >)) {
1155 #ifdef DEBUG_STATE_MACHINE
1156 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1158 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1160 } /* else it's time to send the reject */
1162 RDEBUG2("Sending delayed response");
1163 debug_packet(request, request->reply, false);
1164 request->listener->send(request->listener, request);
1167 * Clean up the request.
1169 request_cleanup_delay_init(request);
1173 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1179 static int request_pre_handler(REQUEST *request, UNUSED int action)
1183 VERIFY_REQUEST(request);
1185 TRACE_STATE_MACHINE;
1187 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1190 * Don't decode the packet if it's an internal "fake"
1191 * request. Instead, just return so that the caller can
1194 if (request->packet->dst_port == 0) {
1195 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1196 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1200 if (!request->packet->vps) { /* FIXME: check for correct state */
1201 rcode = request->listener->decode(request->listener, request);
1204 if (debug_condition) {
1206 * Ignore parse errors.
1208 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1209 request->log.lvl = L_DBG_LVL_2;
1210 request->log.func = vradlog_request;
1215 debug_packet(request, request->packet, true);
1221 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1222 request->reply->offset = -2; /* bad authenticator */
1226 if (!request->username) {
1227 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1234 /** Do the final processing of a request before we reply to the NAS.
1236 * Various cleanups, suppress responses, copy Proxy-State, and set
1237 * response_delay or cleanup_delay;
1239 static void request_finish(REQUEST *request, int action)
1243 VERIFY_REQUEST(request);
1245 TRACE_STATE_MACHINE;
1248 (void) action; /* -Wunused */
1252 * Don't do post-auth if we're a CoA request originated
1253 * from an Access-Request. See request_alloc_coa() for
1256 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1260 * Override the response code if a control:Response-Packet-Type attribute is present.
1262 vp = pairfind(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1264 if (vp->vp_integer == 256) {
1265 RDEBUG2("Not responding to request");
1266 request->reply->code = 0;
1268 request->reply->code = vp->vp_integer;
1272 * Catch Auth-Type := Reject BEFORE proxying the packet.
1274 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1275 if (request->reply->code == 0) {
1276 vp = pairfind(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1277 if (!vp || (vp->vp_integer != 5)) {
1278 RDEBUG2("There was no response configured: "
1279 "rejecting request");
1282 request->reply->code = PW_CODE_ACCESS_REJECT;
1287 * Copy Proxy-State from the request to the reply.
1289 vp = paircopy_by_num(request->reply, request->packet->vps,
1290 PW_PROXY_STATE, 0, TAG_ANY);
1291 if (vp) pairadd(&request->reply->vps, vp);
1294 * Call Post-Auth for Access-Request packets.
1296 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1297 rad_postauth(request);
1302 * Clean up. These are no longer needed.
1304 gettimeofday(&request->reply->timestamp, NULL);
1307 * Fake packets get marked as "done", and have the
1308 * proxy-reply section deal with the reply attributes.
1309 * We therefore don't free the reply attributes.
1311 if (request->packet->dst_port == 0) {
1312 RDEBUG("Finished internally proxied request.");
1314 request->child_state = REQUEST_DONE;
1320 * Always send the reply to the detail listener.
1322 if (request->listener->type == RAD_LISTEN_DETAIL) {
1323 request->simul_max = 1;
1324 request->listener->send(request->listener, request);
1326 * But only print the reply if there is one.
1328 if (request->reply->code != 0) {
1329 debug_packet(request, request->reply, false);
1336 * Ignore all "do not respond" packets.
1337 * Except for the detail ones, which need to ping
1338 * the detail file reader so that it will retransmit.
1340 if (!request->reply->code) {
1341 RDEBUG("Not sending reply to client.");
1346 * If it's not in the request hash, we MIGHT not want to
1349 * If duplicate packets are allowed, then then only
1350 * reason to NOT be in the request hash is because we
1351 * don't want to send a reply.
1353 * FIXME: this is crap. The rest of the state handling
1354 * should use a different field so that we don't have two
1357 * Otherwise duplicates are forbidden, and the request is
1358 * SUPPOSED to avoid the request hash.
1360 * In that case, we need to send a reply.
1362 if (!request->in_request_hash &&
1363 !request->listener->nodup) {
1364 RDEBUG("Suppressing reply to client.");
1369 * See if we need to delay an Access-Reject packet.
1371 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1372 (request->root->reject_delay.tv_sec > 0)) {
1373 request->response_delay = request->root->reject_delay;
1377 * If we timed out a proxy packet, don't delay
1378 * the reject any more.
1380 if (request->proxy && !request->proxy_reply) {
1381 request->response_delay.tv_sec = 0;
1382 request->response_delay.tv_usec = 0;
1390 if (request->response_delay.tv_sec == 0) {
1391 rad_assert(request->response_delay.tv_usec == 0);
1394 * Don't print a reply if there's none to send.
1396 if (request->reply->code != 0) {
1397 request->listener->send(request->listener, request);
1398 debug_packet(request, request->reply, false);
1402 RDEBUG2("Finished request");
1403 request->component = "<core>";
1404 request->module = "<done>";
1406 #ifdef WITH_ACCOUNTING
1408 * Accounting packets can be cleaned up now.
1410 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1412 request->child_state = REQUEST_DONE;
1419 * If the packets are from the detail file, we can clean them up now.
1421 if (request->listener->type == RAD_LISTEN_DETAIL) {
1423 request->child_state = REQUEST_DONE;
1430 * If we've originated this CoA request, it gets
1433 if (request->proxy &&
1434 ((request->proxy->code == PW_CODE_COA_REQUEST) ||
1435 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
1436 (request->packet->code != request->proxy->code)) {
1438 request->child_state = REQUEST_DONE;
1444 * Clean up the request.
1446 request_cleanup_delay_init(request);
1450 * Encode and sign it here, so that the master
1451 * thread can just send the encoded data, which
1452 * means it does less work.
1454 RDEBUG2("Delaying response for %d.%06d seconds",
1455 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1456 request->listener->encode(request->listener, request);
1457 request->component = "<core>";
1458 request->module = "<delay>";
1459 request->process = request_response_delay;
1461 request->child_state = REQUEST_RESPONSE_DELAY;
1465 /** Process a request from a client.
1467 * The outcome might be that the request is proxied.
1471 * running -> running [ label = "TIMER < max_request_time" ];
1472 * running -> done [ label = "TIMER >= max_request_time" ];
1473 * running -> proxy [ label = "proxied" ];
1474 * running -> dup [ label = "DUP", arrowhead = "none" ];
1478 static void request_running(REQUEST *request, int action)
1480 VERIFY_REQUEST(request);
1482 TRACE_STATE_MACHINE;
1486 case FR_ACTION_TIMER:
1488 request_max_time(request);
1492 request_dup(request);
1496 if (!request_pre_handler(request, action)) {
1497 #ifdef DEBUG_STATE_MACHINE
1498 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1499 request->number, __FUNCTION__,
1500 child_state_names[request->child_state],
1501 child_state_names[REQUEST_DONE]);
1505 request->child_state = REQUEST_DONE;
1509 rad_assert(request->handle != NULL);
1510 request->handle(request);
1514 * We may need to send a proxied request.
1516 if ((action == FR_ACTION_RUN) &&
1517 request_will_proxy(request)) {
1518 #ifdef DEBUG_STATE_MACHINE
1519 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1523 * takes care of setting
1524 * up the post proxy fail
1527 if (request_proxy(request, 0) < 0) goto req_finished;
1531 #ifdef DEBUG_STATE_MACHINE
1532 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1537 * Maybe originate a CoA request.
1539 if ((action == FR_ACTION_RUN) && request->coa) {
1540 request_coa_originate(request);
1547 request_finish(request, action);
1552 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1557 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1558 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1561 RADIUS_PACKET **packet_p;
1562 REQUEST *request = NULL;
1564 listen_socket_t *sock = NULL;
1566 VERIFY_PACKET(packet);
1569 * Set the last packet received.
1571 gettimeofday(&now, NULL);
1573 packet->timestamp = now;
1575 #ifdef WITH_ACCOUNTING
1576 if (listener->type != RAD_LISTEN_DETAIL)
1579 sock = listener->data;
1580 sock->last_packet = now.tv_sec;
1584 * Skip everything if required.
1586 if (listener->nodup) goto skip_dup;
1588 packet_p = rbtree_finddata(pl, &packet);
1590 rad_child_state_t child_state;
1592 request = fr_packet2myptr(REQUEST, packet, packet_p);
1593 rad_assert(request->in_request_hash);
1594 child_state = request->child_state;
1597 * Same src/dst ip/port, length, and
1598 * authentication vector: must be a duplicate.
1600 if ((request->packet->data_len == packet->data_len) &&
1601 (memcmp(request->packet->vector, packet->vector,
1602 sizeof(packet->vector)) == 0)) {
1605 switch (packet->code) {
1606 case PW_CODE_ACCESS_REQUEST:
1607 FR_STATS_INC(auth, total_dup_requests);
1610 #ifdef WITH_ACCOUNTING
1611 case PW_CODE_ACCOUNTING_REQUEST:
1612 FR_STATS_INC(acct, total_dup_requests);
1616 case PW_CODE_COA_REQUEST:
1617 FR_STATS_INC(coa, total_dup_requests);
1620 case PW_CODE_DISCONNECT_REQUEST:
1621 FR_STATS_INC(dsc, total_dup_requests);
1628 #endif /* WITH_STATS */
1631 * Tell the state machine that there's a
1632 * duplicate request.
1634 request->process(request, FR_ACTION_DUP);
1635 return 0; /* duplicate of live request */
1639 * Mark the request as done ASAP, and before we
1640 * log anything. The child may stop processing
1641 * the request just as we're logging the
1644 request_done(request, FR_ACTION_DONE);
1648 * It's a new request, not a duplicate. If the
1649 * old one is done, then we can clean it up.
1651 if (child_state <= REQUEST_RUNNING) {
1653 * The request is still QUEUED or RUNNING. That's a problem.
1655 ERROR("Received conflicting packet from "
1656 "client %s port %d - ID: %u due to "
1657 "unfinished request. Giving up on old request.",
1659 packet->src_port, packet->id);
1663 * Mark the old request as done. If there's no
1664 * child, the request will be cleaned up
1665 * immediately. If there is a child, we'll set a
1666 * timer to go clean up the request.
1668 } /* else the new packet is unique */
1671 * Quench maximum number of outstanding requests.
1673 if (main_config.max_requests &&
1674 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1675 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1677 packet->src_port, packet->id);
1678 WARN("Please check the configuration file.\n"
1679 "\tThe value for 'max_requests' is probably set too low.\n"));
1681 exec_trigger(NULL, NULL, "server.max_requests", true);
1687 * Rate-limit the incoming packets
1689 if (sock && sock->max_rate) {
1692 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1693 if (pps > sock->max_rate) {
1694 DEBUG("Dropping request due to rate limiting");
1697 sock->rate_pps_now++;
1701 * Allocate a pool for the request.
1704 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1708 * The packet is still allocated from a different
1709 * context, but oh well.
1711 (void) talloc_steal(ctx, packet);
1714 request = request_setup(ctx, listener, packet, client, fun);
1721 * Mark it as a "real" request with a context.
1723 request->options |= RAD_REQUEST_OPTION_CTX;
1726 * Remember the request in the list.
1728 if (!listener->nodup) {
1729 if (!rbtree_insert(pl, &request->packet)) {
1730 RERROR("Failed to insert request in the list of live requests: discarding it");
1731 request_done(request, FR_ACTION_DONE);
1735 request->in_request_hash = true;
1739 * Process it. Send a response, and free it.
1741 if (listener->synchronous) {
1743 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1746 request->listener->decode(request->listener, request);
1747 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1748 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1752 if (request->reply->code != 0) {
1753 request->listener->send(request->listener, request);
1755 RDEBUG("Not sending reply");
1759 * Don't do delayed reject. Oh well.
1761 request_free(request);
1766 * Otherwise, insert it into the state machine.
1767 * The child threads will take care of processing it.
1769 request_queue_or_run(request, request_running);
1775 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1776 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1781 * Create and initialize the new request.
1783 request = request_alloc(ctx);
1788 request->reply = rad_alloc(request, false);
1789 if (!request->reply) {
1791 talloc_free(request);
1795 request->listener = listener;
1796 request->client = client;
1797 request->packet = talloc_steal(request, packet);
1798 request->number = request_num_counter++;
1799 request->priority = listener->type;
1800 request->master_state = REQUEST_ACTIVE;
1801 request->child_state = REQUEST_RUNNING;
1802 #ifdef DEBUG_STATE_MACHINE
1803 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1804 request->number, __FUNCTION__,
1805 child_state_names[request->child_state],
1806 child_state_names[REQUEST_RUNNING]);
1808 #ifdef HAVE_PTHREAD_H
1809 request->child_pid = NO_SUCH_CHILD_PID;
1811 request->handle = fun;
1815 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1816 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1817 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1818 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1819 #ifdef WITH_ACCOUNTING
1820 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1821 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1822 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1825 #endif /* WITH_STATS */
1828 * Status-Server packets go to the head of the queue.
1830 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1833 * Set virtual server identity
1835 if (client->server) {
1836 request->server = client->server;
1837 } else if (listener->server) {
1838 request->server = listener->server;
1840 request->server = NULL;
1843 request->root = &main_config;
1845 request->listener->count++;
1849 * The request passes many of our sanity checks.
1850 * From here on in, if anything goes wrong, we
1851 * send a reject message, instead of dropping the
1856 * Build the reply template from the request.
1859 request->reply->sockfd = request->packet->sockfd;
1860 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1861 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1862 request->reply->dst_port = request->packet->src_port;
1863 request->reply->src_port = request->packet->dst_port;
1864 request->reply->id = request->packet->id;
1865 request->reply->code = 0; /* UNKNOWN code */
1866 memcpy(request->reply->vector, request->packet->vector,
1867 sizeof(request->reply->vector));
1868 request->reply->vps = NULL;
1869 request->reply->data = NULL;
1870 request->reply->data_len = 0;
1876 /***********************************************************************
1880 ***********************************************************************/
1883 * Timer function for all TCP sockets.
1885 static void tcp_socket_timer(void *ctx)
1887 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1888 listen_socket_t *sock = listener->data;
1889 struct timeval end, now;
1891 fr_socket_limit_t *limit;
1895 fr_event_now(el, &now);
1897 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1899 switch (listener->type) {
1901 case RAD_LISTEN_PROXY:
1902 limit = &sock->home->limit;
1906 case RAD_LISTEN_AUTH:
1907 #ifdef WITH_ACCOUNTING
1908 case RAD_LISTEN_ACCT:
1910 limit = &sock->limit;
1918 * If we enforce a lifetime, do it now.
1920 if (limit->lifetime > 0) {
1921 end.tv_sec = sock->opened + limit->lifetime;
1924 if (timercmp(&end, &now, <=)) {
1925 listener->print(listener, buffer, sizeof(buffer));
1926 DEBUG("Reached maximum lifetime on socket %s", buffer);
1930 listener->status = RAD_LISTEN_STATUS_EOL;
1931 event_new_fd(listener);
1940 * Enforce an idle timeout.
1942 if (limit->idle_timeout > 0) {
1943 struct timeval idle;
1945 rad_assert(sock->last_packet != 0);
1946 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1949 if (timercmp(&idle, &now, <=)) {
1950 listener->print(listener, buffer, sizeof(buffer));
1951 DEBUG("Reached idle timeout on socket %s", buffer);
1956 * Enforce the minimum of idle timeout or lifetime.
1958 if (timercmp(&idle, &end, <)) {
1964 * Wake up at t + 0.5s. The code above checks if the timers
1965 * are <= t. This addition gives us a bit of leeway.
1967 end.tv_usec = USEC / 2;
1970 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1971 rad_panic("Failed to insert event");
1978 * Add +/- 2s of jitter, as suggested in RFC 3539
1981 static void add_jitter(struct timeval *when)
1988 jitter ^= (jitter >> 10);
1989 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1992 * Add in ~ (4 * USEC) of jitter.
1994 tv_add(when, jitter);
1998 * Called by socket_del to remove requests with this socket
2000 static int eol_proxy_listener(void *ctx, void *data)
2002 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2003 RADIUS_PACKET **proxy_p = data;
2006 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2007 if (request->proxy_listener != this) return 0;
2010 * The normal "remove_from_proxy_hash" tries to grab the
2011 * proxy mutex. We already have it held, so grabbing it
2012 * again will cause a deadlock. Instead, call the "no
2013 * lock" version of the function.
2015 rad_assert(request->in_proxy_hash == true);
2016 remove_from_proxy_hash_nl(request, false);
2019 * Don't mark it as DONE. The client can retransmit, and
2020 * the packet SHOULD be re-proxied somewhere else.
2022 * Return "2" means that the rbtree code will remove it
2023 * from the tree, and we don't need to do it ourselves.
2027 #endif /* WITH_PROXY */
2029 static int eol_listener(void *ctx, void *data)
2031 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2032 RADIUS_PACKET **packet_p = data;
2035 request = fr_packet2myptr(REQUEST, packet, packet_p);
2036 if (request->listener != this) return 0;
2038 request->master_state = REQUEST_STOP_PROCESSING;
2039 request->process = request_done;
2043 #endif /* WITH_TCP */
2046 /***********************************************************************
2048 * Proxy handlers for the state machine.
2050 ***********************************************************************/
2053 * Called with the proxy mutex held
2055 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2057 VERIFY_REQUEST(request);
2059 if (!request->in_proxy_hash) return;
2061 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2062 request->in_proxy_hash = false;
2065 * On the FIRST reply, decrement the count of outstanding
2066 * requests. Note that this is NOT the count of sent
2067 * packets, but whether or not the home server has
2070 if (request->home_server &&
2071 request->home_server->currently_outstanding) {
2072 request->home_server->currently_outstanding--;
2075 * If we're NOT sending it packets, AND it's been
2076 * a while since we got a response, then we don't
2077 * know if it's alive or dead.
2079 if ((request->home_server->currently_outstanding == 0) &&
2080 (request->home_server->state == HOME_STATE_ALIVE)) {
2081 struct timeval when, now;
2083 when.tv_sec = request->home_server->last_packet_recv ;
2086 timeradd(&when, request_response_window(request), &when);
2087 gettimeofday(&now, NULL);
2090 * last_packet + response_window
2092 * We *administratively* mark the home
2093 * server as "unknown" state, because we
2094 * haven't seen a packet for a while.
2096 if (timercmp(&now, &when, >)) {
2097 request->home_server->state = HOME_STATE_UNKNOWN;
2098 request->home_server->last_packet_sent = 0;
2099 request->home_server->last_packet_recv = 0;
2105 rad_assert(request->proxy_listener != NULL);
2106 request->proxy_listener->count--;
2108 request->proxy_listener = NULL;
2111 * Got from YES in hash, to NO, not in hash while we hold
2112 * the mutex. This guarantees that when another thread
2113 * grabs the mutex, the "not in hash" flag is correct.
2115 RDEBUG3("proxy: request is no longer in proxy hash");
2118 static void remove_from_proxy_hash(REQUEST *request)
2120 VERIFY_REQUEST(request);
2123 * Check this without grabbing the mutex because it's a
2124 * lot faster that way.
2126 if (!request->in_proxy_hash) return;
2129 * The "not in hash" flag is definitive. However, if the
2130 * flag says that it IS in the hash, there might still be
2131 * a race condition where it isn't.
2133 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2135 if (!request->in_proxy_hash) {
2136 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2140 remove_from_proxy_hash_nl(request, true);
2142 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2145 static int insert_into_proxy_hash(REQUEST *request)
2149 bool success = false;
2150 void *proxy_listener;
2152 VERIFY_REQUEST(request);
2154 rad_assert(request->proxy != NULL);
2155 rad_assert(request->home_server != NULL);
2156 rad_assert(proxy_list != NULL);
2159 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2160 proxy_listener = NULL;
2161 request->num_proxied_requests = 1;
2162 request->num_proxied_responses = 0;
2164 for (tries = 0; tries < 2; tries++) {
2166 listen_socket_t *sock;
2168 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2169 success = fr_packet_list_id_alloc(proxy_list,
2170 request->home_server->proto,
2171 &request->proxy, &proxy_listener);
2174 if (tries > 0) continue; /* try opening new socket only once */
2176 #ifdef HAVE_PTHREAD_H
2177 if (proxy_no_new_sockets) break;
2180 RDEBUG3("proxy: Trying to open a new listener to the home server");
2181 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2183 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2187 request->proxy->src_port = 0; /* Use any new socket */
2188 proxy_listener = this;
2191 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2193 &sock->other_ipaddr, sock->other_port,
2196 #ifdef HAVE_PTHREAD_H
2197 proxy_no_new_sockets = true;
2199 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2202 * This is bad. However, the
2203 * packet list now supports 256
2204 * open sockets, which should
2205 * minimize this problem.
2207 ERROR("Failed adding proxy socket: %s",
2213 * Add it to the event loop. Ensure that we have
2214 * only one mutex locked at a time.
2216 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2217 radius_update_listener(this);
2218 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2221 if (!proxy_listener || !success) {
2222 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2223 REDEBUG2("proxy: Failed allocating Id for proxied request");
2225 request->proxy_listener = NULL;
2226 request->in_proxy_hash = false;
2230 rad_assert(request->proxy->id >= 0);
2232 request->proxy_listener = proxy_listener;
2233 request->in_proxy_hash = true;
2234 RDEBUG3("proxy: request is now in proxy hash");
2237 * Keep track of maximum outstanding requests to a
2238 * particular home server. 'max_outstanding' is
2239 * enforced in home_server_ldb(), in realms.c.
2241 request->home_server->currently_outstanding++;
2244 request->proxy_listener->count++;
2247 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2249 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2250 inet_ntop(request->proxy->dst_ipaddr.af,
2251 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2252 request->proxy->dst_port,
2253 request->proxy->id);
2258 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2261 int post_proxy_type = 0;
2264 VERIFY_REQUEST(request);
2267 * There may be a proxy reply, but it may be too late.
2269 if (!request->home_server->server && !request->proxy_listener) return 0;
2272 * Delete any reply we had accumulated until now.
2274 RDEBUG2("Clearing existing &reply: attributes");
2275 pairfree(&request->reply->vps);
2278 * Run the packet through the post-proxy stage,
2279 * BEFORE playing games with the attributes.
2281 vp = pairfind(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2283 post_proxy_type = vp->vp_integer;
2285 * If we have a proxy_reply, and it was a reject, or a NAK
2286 * setup Post-Proxy <type>.
2288 * If the <type> doesn't have a section, then the Post-Proxy
2289 * section is ignored.
2292 DICT_VALUE *dval = NULL;
2294 switch (reply->code) {
2295 case PW_CODE_ACCESS_REJECT:
2296 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2297 if (dval) post_proxy_type = dval->value;
2300 case PW_CODE_DISCONNECT_NAK:
2301 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2302 if (dval) post_proxy_type = dval->value;
2305 case PW_CODE_COA_NAK:
2306 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2307 if (dval) post_proxy_type = dval->value;
2315 * Create config:Post-Proxy-Type
2318 vp = radius_paircreate(request, &request->config, PW_POST_PROXY_TYPE, 0);
2319 vp->vp_integer = dval->value;
2323 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2324 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2327 VERIFY_PACKET(reply);
2330 * Decode the packet if required.
2332 if (request->proxy_listener) {
2333 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2334 debug_packet(request, reply, true);
2337 * Pro-actively remove it from the proxy hash.
2338 * This is later than in 2.1.x, but it means that
2339 * the replies are authenticated before being
2340 * removed from the hash.
2343 (request->num_proxied_requests <= request->num_proxied_responses)) {
2344 remove_from_proxy_hash(request);
2347 rad_assert(!request->in_proxy_hash);
2349 } else if (request->in_proxy_hash) {
2350 remove_from_proxy_hash(request);
2353 if (request->home_pool && request->home_pool->virtual_server) {
2354 char const *old_server = request->server;
2356 request->server = request->home_pool->virtual_server;
2357 RDEBUG2("server %s {", request->server);
2359 rcode = process_post_proxy(post_proxy_type, request);
2362 request->server = old_server;
2364 rcode = process_post_proxy(post_proxy_type, request);
2368 if (request->packet->code == request->proxy->code)
2370 * Don't run the next bit if we originated a CoA
2371 * packet, after receiving an Access-Request or
2372 * Accounting-Request.
2377 * There may NOT be a proxy reply, as we may be
2378 * running Post-Proxy-Type = Fail.
2381 pairadd(&request->reply->vps, paircopy(request->reply, reply->vps));
2384 * Delete the Proxy-State Attributes from
2385 * the reply. These include Proxy-State
2386 * attributes from us and remote server.
2388 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2392 default: /* Don't do anything */
2394 case RLM_MODULE_FAIL:
2397 case RLM_MODULE_HANDLED:
2404 int request_proxy_reply(RADIUS_PACKET *packet)
2406 RADIUS_PACKET **proxy_p;
2411 VERIFY_PACKET(packet);
2413 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2414 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2417 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2418 PROXY("No outstanding request was found for reply from host %s port %d - ID %u",
2419 inet_ntop(packet->src_ipaddr.af,
2420 &packet->src_ipaddr.ipaddr,
2421 buffer, sizeof(buffer)),
2422 packet->src_port, packet->id);
2426 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2427 request->num_proxied_responses++; /* needs to be protected by lock */
2429 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2432 * No reply, BUT the current packet fails verification:
2433 * ignore it. This does the MD5 calculations in the
2434 * server core, but I guess we can fix that later.
2436 if (!request->proxy_reply &&
2437 (rad_verify(packet, request->proxy,
2438 request->home_server->secret) != 0)) {
2439 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2444 * The home server sent us a packet which doesn't match
2445 * something we have: ignore it. This is done only to
2446 * catch the case of broken systems.
2448 if (request->proxy_reply &&
2449 (memcmp(request->proxy_reply->vector,
2451 sizeof(request->proxy_reply->vector)) != 0)) {
2452 RDEBUG2("Ignoring conflicting proxy reply");
2456 gettimeofday(&now, NULL);
2459 * Status-Server packets don't count as real packets.
2461 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2462 listen_socket_t *sock = request->proxy_listener->data;
2464 request->home_server->last_packet_recv = now.tv_sec;
2465 sock->last_packet = now.tv_sec;
2469 * If we have previously seen a reply, ignore the
2472 if (request->proxy_reply) {
2473 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2474 inet_ntop(packet->src_ipaddr.af,
2475 &packet->src_ipaddr.ipaddr,
2476 buffer, sizeof(buffer)),
2477 packet->src_port, packet->id);
2482 * Call the state machine to do something useful with the
2485 request->proxy_reply = talloc_steal(request, packet);
2486 packet->timestamp = now;
2487 request->priority = RAD_LISTEN_PROXY;
2491 * Update the proxy listener stats here, because only one
2492 * thread accesses that at a time. The home_server and
2493 * main proxy_*_stats structures are updated once the
2494 * request is cleaned up.
2496 request->proxy_listener->stats.total_responses++;
2498 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2499 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2501 switch (request->proxy->code) {
2502 case PW_CODE_ACCESS_REQUEST:
2503 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2505 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2506 request->proxy_listener->stats.total_access_accepts++;
2508 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2509 request->proxy_listener->stats.total_access_rejects++;
2511 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2512 request->proxy_listener->stats.total_access_challenges++;
2516 #ifdef WITH_ACCOUNTING
2517 case PW_CODE_ACCOUNTING_REQUEST:
2518 request->proxy_listener->stats.total_responses++;
2519 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2525 case PW_CODE_COA_REQUEST:
2526 request->proxy_listener->stats.total_responses++;
2527 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2530 case PW_CODE_DISCONNECT_REQUEST:
2531 request->proxy_listener->stats.total_responses++;
2532 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2542 * We've received a reply. If we hadn't been sending it
2543 * packets for a while, just mark it alive.
2545 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2546 request->home_server->state = HOME_STATE_ALIVE;
2547 request->home_server->response_timeouts = 0;
2551 * Tell the request state machine that we have a proxy
2552 * reply. Depending on the function, this should either
2553 * ignore it, or process it.
2555 request->process(request, FR_ACTION_PROXY_REPLY);
2561 static int setup_post_proxy_fail(REQUEST *request)
2563 DICT_VALUE const *dval = NULL;
2566 VERIFY_REQUEST(request);
2568 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2569 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2570 "Fail-Authentication");
2571 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2572 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2575 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2576 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2578 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2579 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2582 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2586 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2589 pairdelete(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2593 vp = pairfind(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2594 if (!vp) vp = radius_paircreate(request, &request->config,
2595 PW_POST_PROXY_TYPE, 0);
2596 vp->vp_integer = dval->value;
2602 /** Process a request after the proxy has timed out.
2604 * Run the packet through Post-Proxy-Type Fail
2606 static void proxy_no_reply(REQUEST *request, int action)
2608 VERIFY_REQUEST(request);
2610 TRACE_STATE_MACHINE;
2615 request_dup(request);
2618 case FR_ACTION_TIMER:
2619 request_max_time(request);
2622 case FR_ACTION_PROXY_REPLY:
2623 proxy_reply_too_late(request);
2627 if (process_proxy_reply(request, NULL)) {
2628 request->handle(request);
2630 request_finish(request, action);
2634 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2639 /** Process the request after receiving a proxy reply.
2641 * Throught the post-proxy section, and the through the handler
2644 static void proxy_running(REQUEST *request, int action)
2646 VERIFY_REQUEST(request);
2648 TRACE_STATE_MACHINE;
2653 request_dup(request);
2656 case FR_ACTION_TIMER:
2657 request_max_time(request);
2661 if (process_proxy_reply(request, request->proxy_reply)) {
2662 request->handle(request);
2664 request_finish(request, action);
2667 default: /* duplicate proxy replies are suppressed */
2668 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2673 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2675 * Whether a request will be proxied is determined by the attributes present
2676 * in request->config. If any of the following attributes are found, the
2677 * request may be proxied.
2679 * The key attributes are:
2680 * - #PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2681 * - #PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2682 * - #PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2683 * - #PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2685 * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2687 * If request should be proxied, will:
2688 * - Add request:Proxy-State
2689 * - Strip the current username value of its realm (depending on config)
2690 * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2692 * - Call the pre-process section in the current server, or in the virtual server
2693 * associated with the home server pool we're proxying to.
2695 * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2696 * specific function.
2698 * @param request The #REQUEST to evaluate for proxying.
2699 * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2701 static int request_will_proxy(REQUEST *request)
2703 int rcode, pre_proxy_type = 0;
2704 char const *realmname = NULL;
2705 VALUE_PAIR *vp, *strippedname;
2706 home_server_t *home;
2707 REALM *realm = NULL;
2708 home_pool_t *pool = NULL;
2710 VERIFY_REQUEST(request);
2712 if (!request->root->proxy_requests) return 0;
2713 if (request->packet->dst_port == 0) return 0;
2714 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2715 if (request->in_proxy_hash) return 0;
2718 * FIXME: for 3.0, allow this only for rejects?
2720 if (request->reply->code != 0) return 0;
2722 vp = pairfind(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2724 realm = realm_find2(vp->vp_strvalue);
2726 REDEBUG2("Cannot proxy to unknown realm %s",
2731 realmname = vp->vp_strvalue;
2734 * Figure out which pool to use.
2736 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2737 pool = realm->auth_pool;
2739 #ifdef WITH_ACCOUNTING
2740 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2741 pool = realm->acct_pool;
2745 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2746 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2747 pool = realm->coa_pool;
2754 } else if ((vp = pairfind(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2757 switch (request->packet->code) {
2758 case PW_CODE_ACCESS_REQUEST:
2759 pool_type = HOME_TYPE_AUTH;
2762 #ifdef WITH_ACCOUNTING
2763 case PW_CODE_ACCOUNTING_REQUEST:
2764 pool_type = HOME_TYPE_ACCT;
2769 case PW_CODE_COA_REQUEST:
2770 case PW_CODE_DISCONNECT_REQUEST:
2771 pool_type = HOME_TYPE_COA;
2779 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2782 * Send it directly to a home server (i.e. NAS)
2784 } else if (((vp = pairfind(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2785 ((vp = pairfind(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2788 fr_ipaddr_t dst_ipaddr;
2790 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2792 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2793 dst_ipaddr.af = AF_INET;
2794 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2795 dst_ipaddr.prefix = 32;
2797 dst_ipaddr.af = AF_INET6;
2798 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2799 dst_ipaddr.prefix = 128;
2802 port = pairfind(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2804 dst_port = PW_COA_UDP_PORT;
2806 dst_port = vp->vp_integer;
2810 * Nothing does CoA over TCP.
2812 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2816 WARN("No such CoA home server %s port %u",
2817 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2818 (unsigned int) dst_port);
2829 RWDEBUG2("Cancelling proxy as no home pool exists");
2833 if (request->listener->synchronous) {
2834 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2838 request->home_pool = pool;
2840 home = home_server_ldb(realmname, pool, request);
2843 REDEBUG2("Failed to find live home server: Cancelling proxy");
2848 home_server_update_request(home, request);
2852 * Once we've decided to proxy a request, we cannot send
2853 * a CoA packet. So we free up any CoA packet here.
2855 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2859 * Remember that we sent the request to a Realm.
2861 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2864 * Strip the name, if told to.
2866 * Doing it here catches the case of proxied tunneled
2869 if (realm && (realm->strip_realm == true) &&
2870 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2872 * If there's a Stripped-User-Name attribute in
2873 * the request, then use THAT as the User-Name
2874 * for the proxied request, instead of the
2877 * This is done by making a copy of the
2878 * Stripped-User-Name attribute, turning it into
2879 * a User-Name attribute, deleting the
2880 * Stripped-User-Name and User-Name attributes
2881 * from the vps list, and making the new
2882 * User-Name the head of the vps list.
2884 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2887 vp = radius_paircreate(NULL, NULL,
2889 rad_assert(vp != NULL); /* handled by above function */
2890 /* Insert at the START of the list */
2891 /* FIXME: Can't make assumptions about ordering */
2892 fr_cursor_init(&cursor, &vp);
2893 fr_cursor_merge(&cursor, request->proxy->vps);
2894 request->proxy->vps = vp;
2896 pairstrcpy(vp, strippedname->vp_strvalue);
2899 * Do NOT delete Stripped-User-Name.
2904 * If there is no PW_CHAP_CHALLENGE attribute but
2905 * there is a PW_CHAP_PASSWORD we need to add it
2906 * since we can't use the request authenticator
2907 * anymore - we changed it.
2909 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2910 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2911 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2912 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2913 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2917 * The RFC's say we have to do this, but FreeRADIUS
2920 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2921 pairsprintf(vp, "%u", request->packet->id);
2924 * Should be done BEFORE inserting into proxy hash, as
2925 * pre-proxy may use this information, or change it.
2927 request->proxy->code = request->packet->code;
2930 * Call the pre-proxy routines.
2932 vp = pairfind(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2934 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2935 /* Must be a validation issue */
2937 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2938 pre_proxy_type = vp->vp_integer;
2942 * home_pool may be NULL when originating CoA packets,
2943 * because they go directly to an IP address.
2945 if (request->home_pool && request->home_pool->virtual_server) {
2946 char const *old_server = request->server;
2948 request->server = request->home_pool->virtual_server;
2950 RDEBUG2("server %s {", request->server);
2952 rcode = process_pre_proxy(pre_proxy_type, request);
2956 request->server = old_server;
2958 rcode = process_pre_proxy(pre_proxy_type, request);
2962 case RLM_MODULE_FAIL:
2963 case RLM_MODULE_INVALID:
2964 case RLM_MODULE_NOTFOUND:
2965 case RLM_MODULE_USERLOCK:
2967 /* FIXME: debug print failed stuff */
2970 case RLM_MODULE_REJECT:
2971 case RLM_MODULE_HANDLED:
2975 * Only proxy the packet if the pre-proxy code succeeded.
2977 case RLM_MODULE_NOOP:
2979 case RLM_MODULE_UPDATED:
2984 static int request_proxy(REQUEST *request, int retransmit)
2988 VERIFY_REQUEST(request);
2990 rad_assert(request->parent == NULL);
2991 rad_assert(request->home_server != NULL);
2993 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2997 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2998 request_done(request->coa, FR_ACTION_DONE);
3003 * The request may need sending to a virtual server.
3004 * This code is more than a little screwed up. The rest
3005 * of the state machine doesn't handle parent / child
3006 * relationships well. i.e. if the child request takes
3007 * too long, the core will mark the *parent* as "stop
3008 * processing". And the child will continue without
3009 * knowing anything...
3011 * So, we have some horrible hacks to get around that.
3013 if (request->home_server->server) {
3016 if (request->packet->dst_port == 0) {
3017 WARN("Cannot proxy an internal request");
3021 DEBUG("Proxying to virtual server %s",
3022 request->home_server->server);
3025 * Packets to virtual serrers don't get
3026 * retransmissions sent to them. And the virtual
3027 * server is run ONLY if we have no child
3028 * threads, or we're running in a child thread.
3030 rad_assert(retransmit == 0);
3031 rad_assert(!spawn_flag || !we_are_master());
3033 fake = request_alloc_fake(request);
3035 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
3036 talloc_free(request->proxy);
3038 fake->server = request->home_server->server;
3039 fake->handle = request->handle;
3040 fake->process = NULL; /* should never be run for anything */
3043 * Run the virtual server.
3045 request_running(fake, FR_ACTION_RUN);
3047 request->proxy = talloc_steal(request, fake->packet);
3048 fake->packet = NULL;
3049 request->proxy_reply = talloc_steal(request, fake->reply);
3055 * No reply code, toss the reply we have,
3056 * and do post-proxy-type Fail.
3058 if (!request->proxy_reply->code) {
3059 TALLOC_FREE(request->proxy_reply);
3060 setup_post_proxy_fail(request);
3064 * Do the proxy reply (if any)
3066 if (process_proxy_reply(request, request->proxy_reply)) {
3067 request->handle(request);
3070 return -1; /* so we call request_finish */
3074 * We're actually sending a proxied packet. Do that now.
3076 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3077 RPROXY("Failed to insert request into the proxy list");
3081 rad_assert(request->proxy->id >= 0);
3084 struct timeval *response_window;
3086 response_window = request_response_window(request);
3089 if (request->home_server->tls) {
3090 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3091 inet_ntop(request->proxy->dst_ipaddr.af,
3092 &request->proxy->dst_ipaddr.ipaddr,
3093 buffer, sizeof(buffer)),
3094 request->proxy->dst_port,
3095 (int) response_window->tv_sec, (int) response_window->tv_usec);
3098 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3099 inet_ntop(request->proxy->dst_ipaddr.af,
3100 &request->proxy->dst_ipaddr.ipaddr,
3101 buffer, sizeof(buffer)),
3102 request->proxy->dst_port,
3103 (int) response_window->tv_sec, (int) response_window->tv_usec);
3108 gettimeofday(&request->proxy_retransmit, NULL);
3110 request->proxy->timestamp = request->proxy_retransmit;
3112 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3115 * Encode the packet before we do anything else.
3117 request->proxy_listener->encode(request->proxy_listener, request);
3118 debug_packet(request, request->proxy, false);
3121 * Set the state function, then the state, no child, and
3124 request->process = proxy_wait_for_reply;
3125 request->child_state = REQUEST_PROXIED;
3129 * And send the packet.
3131 request->proxy_listener->send(request->proxy_listener, request);
3136 * Proxy the packet as if it was new.
3138 static int request_proxy_anew(REQUEST *request)
3140 home_server_t *home;
3142 VERIFY_REQUEST(request);
3145 * Delete the request from the proxy list.
3147 * The packet list code takes care of ensuring that IDs
3148 * aren't reused until all 256 IDs have been used. So
3149 * there's a 1/256 chance of re-using the same ID when
3150 * we're sending to the same home server. Which is
3153 remove_from_proxy_hash(request);
3156 * Find a live home server for the request.
3158 home = home_server_ldb(NULL, request->home_pool, request);
3160 REDEBUG2("Failed to find live home server for request");
3162 if (setup_post_proxy_fail(request)) {
3163 request_queue_or_run(request, proxy_running);
3165 gettimeofday(&request->reply->timestamp, NULL);
3166 request_cleanup_delay_init(request);
3170 home_server_update_request(home, request);
3172 if (!insert_into_proxy_hash(request)) {
3173 RPROXY("Failed to insert retransmission into the proxy list");
3174 goto post_proxy_fail;
3178 * Free the old packet, to force re-encoding
3180 talloc_free(request->proxy->data);
3181 request->proxy->data = NULL;
3182 request->proxy->data_len = 0;
3184 #ifdef WITH_ACCOUNTING
3186 * Update the Acct-Delay-Time attribute.
3188 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3191 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3192 if (!vp) vp = radius_paircreate(request->proxy,
3193 &request->proxy->vps,
3194 PW_ACCT_DELAY_TIME, 0);
3198 gettimeofday(&now, NULL);
3199 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3204 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3210 /** Ping a home server.
3213 static void request_ping(REQUEST *request, int action)
3215 home_server_t *home = request->home_server;
3218 VERIFY_REQUEST(request);
3220 TRACE_STATE_MACHINE;
3224 case FR_ACTION_TIMER:
3225 ERROR("No response to status check %d for home server %s port %d",
3227 inet_ntop(request->proxy->dst_ipaddr.af,
3228 &request->proxy->dst_ipaddr.ipaddr,
3229 buffer, sizeof(buffer)),
3230 request->proxy->dst_port);
3233 case FR_ACTION_PROXY_REPLY:
3234 rad_assert(request->in_proxy_hash);
3236 request->home_server->num_received_pings++;
3237 RPROXY("Received response to status check %d (%d in current sequence)",
3238 request->number, home->num_received_pings);
3241 * Remove the request from any hashes
3243 fr_event_delete(el, &request->ev);
3244 remove_from_proxy_hash(request);
3247 * The control socket may have marked the home server as
3248 * alive. OR, it may have suddenly started responding to
3249 * requests again. If so, don't re-do the "make alive"
3252 if (home->state == HOME_STATE_ALIVE) break;
3255 * It's dead, and we haven't received enough ping
3256 * responses to mark it "alive". Wait a bit.
3258 * If it's zombie, we mark it alive immediately.
3260 if ((home->state == HOME_STATE_IS_DEAD) &&
3261 (home->num_received_pings < home->num_pings_to_alive)) {
3266 * Mark it alive and delete any outstanding
3269 home->state = HOME_STATE_ALIVE;
3270 home->response_timeouts = 0;
3271 exec_trigger(request, home->cs, "home_server.alive", false);
3272 home->currently_outstanding = 0;
3273 home->num_sent_pings = 0;
3274 home->num_received_pings = 0;
3275 gettimeofday(&home->revive_time, NULL);
3277 fr_event_delete(el, &home->ev);
3279 RPROXY("Marking home server %s port %d alive",
3280 inet_ntop(request->proxy->dst_ipaddr.af,
3281 &request->proxy->dst_ipaddr.ipaddr,
3282 buffer, sizeof(buffer)),
3283 request->proxy->dst_port);
3287 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3291 rad_assert(!request->in_request_hash);
3292 rad_assert(request->ev == NULL);
3294 request_done(request, FR_ACTION_DONE);
3298 * Called from start of zombie period, OR after control socket
3299 * marks the home server dead.
3301 static void ping_home_server(void *ctx)
3303 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3306 struct timeval when, now;
3308 if ((home->state == HOME_STATE_ALIVE) ||
3310 (home->proto == IPPROTO_TCP) ||
3312 (home->ev != NULL)) {
3316 gettimeofday(&now, NULL);
3320 * We've run out of zombie time. Mark it dead.
3322 if (home->state == HOME_STATE_ZOMBIE) {
3323 when = home->zombie_period_start;
3324 when.tv_sec += home->zombie_period;
3326 if (timercmp(&when, &now, <)) {
3327 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3328 mark_home_server_dead(home, &now);
3333 * We're not supposed to be pinging it. Just wake up
3334 * when we're supposed to mark it dead.
3336 if (home->ping_check == HOME_PING_CHECK_NONE) {
3337 if (home->state == HOME_STATE_ZOMBIE) {
3338 when = home->zombie_period_start;
3339 when.tv_sec += home->zombie_period;
3340 INSERT_EVENT(ping_home_server, home);
3344 * Else mark_home_server_dead will set a timer
3345 * for revive_interval.
3351 request = request_alloc(NULL);
3352 if (!request) return;
3353 request->number = request_num_counter++;
3356 request->proxy = rad_alloc(request, true);
3357 rad_assert(request->proxy != NULL);
3359 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3360 request->proxy->code = PW_CODE_STATUS_SERVER;
3362 pairmake(request->proxy, &request->proxy->vps,
3363 "Message-Authenticator", "0x00", T_OP_SET);
3365 } else if (home->type == HOME_TYPE_AUTH) {
3366 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3368 pairmake(request->proxy, &request->proxy->vps,
3369 "User-Name", home->ping_user_name, T_OP_SET);
3370 pairmake(request->proxy, &request->proxy->vps,
3371 "User-Password", home->ping_user_password, T_OP_SET);
3372 pairmake(request->proxy, &request->proxy->vps,
3373 "Service-Type", "Authenticate-Only", T_OP_SET);
3374 pairmake(request->proxy, &request->proxy->vps,
3375 "Message-Authenticator", "0x00", T_OP_SET);
3378 #ifdef WITH_ACCOUNTING
3379 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3381 pairmake(request->proxy, &request->proxy->vps,
3382 "User-Name", home->ping_user_name, T_OP_SET);
3383 pairmake(request->proxy, &request->proxy->vps,
3384 "Acct-Status-Type", "Stop", T_OP_SET);
3385 pairmake(request->proxy, &request->proxy->vps,
3386 "Acct-Session-Id", "00000000", T_OP_SET);
3387 vp = pairmake(request->proxy, &request->proxy->vps,
3388 "Event-Timestamp", "0", T_OP_SET);
3389 vp->vp_date = now.tv_sec;
3391 rad_assert("Internal sanity check failed");
3395 vp = pairmake(request->proxy, &request->proxy->vps,
3396 "NAS-Identifier", "", T_OP_SET);
3398 pairsprintf(vp, "Status Check %u. Are you alive?",
3399 home->num_sent_pings);
3402 request->proxy->src_ipaddr = home->src_ipaddr;
3403 request->proxy->dst_ipaddr = home->ipaddr;
3404 request->proxy->dst_port = home->port;
3405 request->home_server = home;
3406 #ifdef DEBUG_STATE_MACHINE
3407 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3408 child_state_names[request->child_state],
3409 child_state_names[REQUEST_DONE]);
3410 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3412 #ifdef HAVE_PTHREAD_H
3413 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3415 request->child_state = REQUEST_PROXIED;
3416 request->process = request_ping;
3418 rad_assert(request->proxy_listener == NULL);
3420 if (!insert_into_proxy_hash(request)) {
3421 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3424 rad_assert(!request->in_request_hash);
3425 rad_assert(!request->in_proxy_hash);
3426 rad_assert(request->ev == NULL);
3427 talloc_free(request);
3432 * Set up the timer callback.
3435 when.tv_sec += home->ping_timeout;
3437 DEBUG("PING: Waiting %u seconds for response to ping",
3438 home->ping_timeout);
3440 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3441 home->num_sent_pings++;
3443 rad_assert(request->proxy_listener != NULL);
3444 request->proxy_listener->send(request->proxy_listener,
3448 * Add +/- 2s of jitter, as suggested in RFC 3539
3449 * and in the Issues and Fixes draft.
3452 home->when.tv_sec += home->ping_interval;
3454 add_jitter(&home->when);
3456 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3457 INSERT_EVENT(ping_home_server, home);
3460 static void home_trigger(home_server_t *home, char const *trigger)
3462 REQUEST *my_request;
3463 RADIUS_PACKET *my_packet;
3465 my_request = talloc_zero(NULL, REQUEST);
3466 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3467 my_request->proxy = my_packet;
3468 my_packet->dst_ipaddr = home->ipaddr;
3469 my_packet->src_ipaddr = home->src_ipaddr;
3471 exec_trigger(my_request, home->cs, trigger, false);
3472 talloc_free(my_request);
3475 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3482 rad_assert((home->state == HOME_STATE_ALIVE) ||
3483 (home->state == HOME_STATE_UNKNOWN));
3486 if (home->proto == IPPROTO_TCP) {
3487 WARN("Not marking TCP server %s zombie", home->log_name);
3493 * We've received a real packet recently. Don't mark the
3494 * server as zombie until we've received NO packets for a
3495 * while. The "1/4" of zombie period was chosen rather
3496 * arbitrarily. It's a balance between too short, which
3497 * gives quick fail-over and fail-back, or too long,
3498 * where the proxy still sends packets to an unresponsive
3501 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3502 if (home->last_packet_recv >= start) {
3503 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3504 (int) (now->tv_sec - home->last_packet_recv));
3508 home->state = HOME_STATE_ZOMBIE;
3509 home_trigger(home, "home_server.zombie");
3512 * Set the home server to "zombie", as of the time
3515 home->zombie_period_start.tv_sec = start;
3516 home->zombie_period_start.tv_usec = USEC / 2;
3518 fr_event_delete(el, &home->ev);
3520 home->num_sent_pings = 0;
3521 home->num_received_pings = 0;
3523 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3524 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3525 buffer, sizeof(buffer)),
3526 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3528 ping_home_server(home);
3532 void revive_home_server(void *ctx)
3534 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3538 rad_assert(home->proto != IPPROTO_TCP);
3541 home->state = HOME_STATE_ALIVE;
3542 home->response_timeouts = 0;
3543 home_trigger(home, "home_server.alive");
3544 home->currently_outstanding = 0;
3545 gettimeofday(&home->revive_time, NULL);
3548 * Delete any outstanding events.
3551 if (home->ev) fr_event_delete(el, &home->ev);
3553 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3554 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3555 buffer, sizeof(buffer)),
3559 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3561 int previous_state = home->state;
3565 if (home->proto == IPPROTO_TCP) {
3566 WARN("Not marking TCP server dead");
3571 PROXY( "Marking home server %s port %d as dead.",
3572 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3573 buffer, sizeof(buffer)),
3576 home->state = HOME_STATE_IS_DEAD;
3577 home_trigger(home, "home_server.dead");
3579 if (home->ping_check != HOME_PING_CHECK_NONE) {
3581 * If the control socket marks us dead, start
3582 * pinging. Otherwise, we already started
3583 * pinging when it was marked "zombie".
3585 if (previous_state == HOME_STATE_ALIVE) {
3586 ping_home_server(home);
3588 DEBUG("PING: Already pinging home server %s", home->log_name);
3593 * Revive it after a fixed period of time. This
3594 * is very, very, bad.
3597 home->when.tv_sec += home->revive_interval;
3599 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3601 INSERT_EVENT(revive_home_server, home);
3605 /** Wait for a reply after proxying a request.
3607 * Retransmit the proxied packet, or time out and go to
3608 * proxy_no_reply. Mark the home server unresponsive, etc.
3610 * If we do receive a reply, we transition to proxy_running.
3612 static void proxy_wait_for_reply(REQUEST *request, int action)
3614 struct timeval now, when;
3615 struct timeval *response_window = NULL;
3616 home_server_t *home = request->home_server;
3619 VERIFY_REQUEST(request);
3621 TRACE_STATE_MACHINE;
3624 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3625 rad_assert(request->home_server != NULL);
3627 gettimeofday(&now, NULL);
3632 * We have a reply, ignore the retransmit.
3634 if (request->proxy_reply) return;
3637 * The request was proxied to a virtual server.
3638 * Ignore the retransmit.
3640 if (request->home_server->server) return;
3642 if ((home->state == HOME_STATE_IS_DEAD) ||
3643 !request->proxy_listener ||
3644 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3645 request_proxy_anew(request);
3650 if (home->proto == IPPROTO_TCP) {
3651 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3652 inet_ntop(request->proxy->dst_ipaddr.af,
3653 &request->proxy->dst_ipaddr.ipaddr,
3654 buffer, sizeof(buffer)),
3655 request->proxy->dst_port,
3656 request->proxy->id);
3662 * More than one retransmit a second is stupid,
3663 * and should be suppressed by the proxy.
3665 when = request->proxy_retransmit;
3668 if (timercmp(&now, &when, <)) {
3669 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3670 inet_ntop(request->proxy->dst_ipaddr.af,
3671 &request->proxy->dst_ipaddr.ipaddr,
3672 buffer, sizeof(buffer)),
3673 request->proxy->dst_port,
3674 request->proxy->id);
3678 #ifdef WITH_ACCOUNTING
3680 * If we update the Acct-Delay-Time, we need to
3683 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3684 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3685 request_proxy_anew(request);
3690 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3691 inet_ntop(request->proxy->dst_ipaddr.af,
3692 &request->proxy->dst_ipaddr.ipaddr,
3693 buffer, sizeof(buffer)),
3694 request->proxy->dst_port,
3695 request->proxy->id);
3696 request->num_proxied_requests++;
3698 rad_assert(request->proxy_listener != NULL);
3699 FR_STATS_TYPE_INC(home->stats.total_requests);
3700 home->last_packet_sent = now.tv_sec;
3701 request->proxy_retransmit = now;
3702 request->proxy_listener->send(request->proxy_listener, request);
3703 debug_packet(request, request->proxy, false);
3706 case FR_ACTION_TIMER:
3707 response_window = request_response_window(request);
3710 if (!request->proxy_listener ||
3711 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3712 remove_from_proxy_hash(request);
3714 when = request->packet->timestamp;
3715 when.tv_sec += request->root->max_request_time;
3717 if (timercmp(&when, &now, >)) {
3718 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3719 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3726 * Wake up "response_window" time in the future.
3727 * i.e. when MY packet hasn't received a response.
3729 * Note that we DO NOT mark the home server as
3730 * zombie if it doesn't respond to us. It may be
3731 * responding to other (better looking) packets.
3733 when = request->proxy->timestamp;
3734 timeradd(&when, response_window, &when);
3737 * Not at the response window. Set the timer for
3740 if (timercmp(&when, &now, >)) {
3741 struct timeval diff;
3742 timersub(&when, &now, &diff);
3744 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3745 (int) diff.tv_sec, (int) diff.tv_usec);
3746 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3751 RDEBUG("No proxy response, giving up on request and marking it done");
3754 * If we haven't received any packets for
3755 * "response_window", then mark the home server
3758 * If the connection is TCP, then another
3759 * "watchdog timer" function takes care of pings,
3760 * etc. So we don't need to do it here.
3762 * This check should really be part of a home
3763 * server state machine.
3765 if (((home->state == HOME_STATE_ALIVE) ||
3766 (home->state == HOME_STATE_UNKNOWN))
3768 && (home->proto != IPPROTO_TCP)
3771 home->response_timeouts++;
3772 if (home->response_timeouts >= home->max_response_timeouts)
3773 mark_home_server_zombie(home, &now, response_window);
3776 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3777 if (home->type == HOME_TYPE_AUTH) {
3778 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3779 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3782 else if (home->type == HOME_TYPE_ACCT) {
3783 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3784 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3789 * There was no response within the window. Stop
3790 * the request. If the client retransmitted, it
3791 * may have failed over to another home server.
3792 * But that one may be dead, too.
3794 * The extra verbose message if we have a username,
3795 * is extremely useful if the proxy is part of a chain
3796 * and the final home server, is not the one we're
3799 if (request->username) {
3800 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3801 "server %s port %d",
3802 request->username->vp_strvalue,
3803 inet_ntop(request->proxy->dst_ipaddr.af,
3804 &request->proxy->dst_ipaddr.ipaddr,
3805 buffer, sizeof(buffer)),
3806 request->proxy->dst_port);
3808 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3809 inet_ntop(request->proxy->dst_ipaddr.af,
3810 &request->proxy->dst_ipaddr.ipaddr,
3811 buffer, sizeof(buffer)),
3812 request->proxy->dst_port);
3815 if (setup_post_proxy_fail(request)) {
3816 request_queue_or_run(request, proxy_no_reply);
3818 gettimeofday(&request->reply->timestamp, NULL);
3819 request_cleanup_delay_init(request);
3824 * We received a new reply. Go process it.
3826 case FR_ACTION_PROXY_REPLY:
3827 request_queue_or_run(request, proxy_running);
3831 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3835 #endif /* WITH_PROXY */
3838 /***********************************************************************
3842 ***********************************************************************/
3844 static int null_handler(UNUSED REQUEST *request)
3850 * See if we need to originate a CoA request.
3852 static void request_coa_originate(REQUEST *request)
3854 int rcode, pre_proxy_type = 0;
3860 VERIFY_REQUEST(request);
3862 rad_assert(request->coa != NULL);
3863 rad_assert(request->proxy == NULL);
3864 rad_assert(!request->in_proxy_hash);
3865 rad_assert(request->proxy_reply == NULL);
3868 * Check whether we want to originate one, or cancel one.
3870 vp = pairfind(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3872 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3876 if (vp->vp_integer == 0) {
3878 TALLOC_FREE(request->coa);
3886 * src_ipaddr will be set up in proxy_encode.
3888 memset(&ipaddr, 0, sizeof(ipaddr));
3889 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3891 ipaddr.af = AF_INET;
3892 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3894 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3895 ipaddr.af = AF_INET6;
3896 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3897 ipaddr.prefix = 128;
3898 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3899 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3901 if (!coa->home_pool) {
3902 RWDEBUG2("No such home_server_pool %s",
3908 * Prefer the pool to one server
3910 } else if (request->client->coa_pool) {
3911 coa->home_pool = request->client->coa_pool;
3913 } else if (request->client->coa_server) {
3914 coa->home_server = request->client->coa_server;
3918 * If all else fails, send it to the client that
3919 * originated this request.
3921 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3925 * Use the pool, if it exists.
3927 if (coa->home_pool) {
3928 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3929 if (!coa->home_server) {
3930 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3933 home_server_update_request(coa->home_server, coa);
3935 } else if (!coa->home_server) {
3936 uint16_t port = PW_COA_UDP_PORT;
3938 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3939 if (vp) port = vp->vp_integer;
3941 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3942 if (!coa->home_server) {
3943 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3944 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3945 buffer, sizeof(buffer)), port);
3950 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3952 switch (vp->vp_integer) {
3953 case PW_CODE_COA_REQUEST:
3954 case PW_CODE_DISCONNECT_REQUEST:
3955 coa->proxy->code = vp->vp_integer;
3959 DEBUG("Cannot set CoA Packet-Type to code %d",
3965 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3968 * The rest of the server code assumes that
3969 * request->packet && request->reply exist. Copy them
3970 * from the original request.
3972 rad_assert(coa->packet != NULL);
3973 rad_assert(coa->packet->vps == NULL);
3975 coa->packet = rad_copy_packet(coa, request->packet);
3976 coa->reply = rad_copy_packet(coa, request->reply);
3978 coa->config = paircopy(coa, request->config);
3979 coa->num_coa_requests = 0;
3980 coa->handle = null_handler;
3981 coa->number = request->number; /* it's associated with the same request */
3984 * Call the pre-proxy routines.
3986 vp = pairfind(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3988 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3989 /* Must be a validation issue */
3991 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3992 pre_proxy_type = vp->vp_integer;
3995 if (coa->home_pool && coa->home_pool->virtual_server) {
3996 char const *old_server = coa->server;
3998 coa->server = coa->home_pool->virtual_server;
3999 RDEBUG2("server %s {", coa->server);
4001 rcode = process_pre_proxy(pre_proxy_type, coa);
4004 coa->server = old_server;
4006 rcode = process_pre_proxy(pre_proxy_type, coa);
4013 * Only send the CoA packet if the pre-proxy code succeeded.
4015 case RLM_MODULE_NOOP:
4017 case RLM_MODULE_UPDATED:
4022 * Source IP / port is set when the proxy socket
4025 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4026 coa->proxy->dst_port = coa->home_server->port;
4028 if (!insert_into_proxy_hash(coa)) {
4029 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4034 * We CANNOT divorce the CoA request from the parent
4035 * request. This function is running in a child thread,
4036 * and we need access to the main event loop in order to
4037 * to add the timers for the CoA packet.
4039 * Instead, we wait for the timer on the parent request
4042 gettimeofday(&coa->proxy->timestamp, NULL);
4043 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4044 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4045 coa->delay = 0; /* need to calculate a new delay */
4048 * If requested, put a State attribute into the packet,
4049 * and cache the VPS.
4051 fr_state_put_vps(coa, NULL, coa->packet);
4054 * Encode the packet before we do anything else.
4056 coa->proxy_listener->encode(coa->proxy_listener, coa);
4057 debug_packet(coa, coa->proxy, false);
4059 #ifdef DEBUG_STATE_MACHINE
4060 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4061 child_state_names[request->child_state],
4062 child_state_names[REQUEST_PROXIED]);
4066 * Set the state function, then the state, no child, and
4069 coa->process = coa_wait_for_reply;
4070 coa->child_state = REQUEST_PROXIED;
4072 #ifdef HAVE_PTHREAD_H
4073 coa->child_pid = NO_SUCH_CHILD_PID;
4077 * And send the packet.
4079 coa->proxy_listener->send(coa->proxy_listener, coa);
4083 static void coa_retransmit(REQUEST *request)
4085 uint32_t delay, frac;
4086 struct timeval now, when, mrd;
4088 VERIFY_REQUEST(request);
4090 fr_event_now(el, &now);
4093 * FIXME: Enforce max_request_time
4096 if (request->delay == 0) {
4098 * Implement re-transmit algorithm as per RFC 5080
4101 * We want IRT + RAND*IRT
4102 * or 0.9 IRT + rand(0,.2) IRT
4104 * 2^20 ~ USEC, and we want 2.
4105 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4107 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4108 request->delay = delay * request->home_server->coa_irt;
4109 delay = request->home_server->coa_irt * USEC;
4110 delay -= delay / 10;
4111 delay += request->delay;
4112 request->delay = delay;
4114 when = request->proxy->timestamp;
4115 tv_add(&when, delay);
4117 if (timercmp(&when, &now, >)) {
4118 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4124 * Retransmit CoA request.
4128 * Cap count at MRC, if it is non-zero.
4130 if (request->home_server->coa_mrc &&
4131 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4134 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4136 inet_ntop(request->proxy->dst_ipaddr.af,
4137 &request->proxy->dst_ipaddr.ipaddr,
4138 buffer, sizeof(buffer)),
4139 request->proxy->dst_port);
4141 if (setup_post_proxy_fail(request)) {
4142 request_queue_or_run(request, coa_no_reply);
4144 request_done(request, FR_ACTION_DONE);
4150 * RFC 5080 Section 2.2.1
4152 * RT = 2*RTprev + RAND*RTprev
4153 * = 1.9 * RTprev + rand(0,.2) * RTprev
4154 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4157 delay ^= (delay >> 16);
4159 frac = request->delay / 5;
4160 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4162 delay += (2 * request->delay) - (request->delay / 10);
4165 * Cap delay at MRT, if MRT is non-zero.
4167 if (request->home_server->coa_mrt &&
4168 (delay > (request->home_server->coa_mrt * USEC))) {
4169 int mrt_usec = request->home_server->coa_mrt * USEC;
4172 * delay = MRT + RAND * MRT
4173 * = 0.9 MRT + rand(0,.2) * MRT
4176 delay ^= (delay >> 15);
4178 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4179 delay += mrt_usec - (mrt_usec / 10);
4182 request->delay = delay;
4184 tv_add(&when, request->delay);
4185 mrd = request->proxy->timestamp;
4186 mrd.tv_sec += request->home_server->coa_mrd;
4189 * Cap duration at MRD.
4191 if (timercmp(&mrd, &when, <)) {
4194 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4196 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4198 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4200 request->proxy_listener->send(request->proxy_listener,
4205 /** Wait for a reply after originating a CoA a request.
4207 * Retransmit the proxied packet, or time out and go to
4208 * coa_no_reply. Mark the home server unresponsive, etc.
4210 * If we do receive a reply, we transition to coa_running.
4212 static void coa_wait_for_reply(REQUEST *request, int action)
4214 VERIFY_REQUEST(request);
4216 TRACE_STATE_MACHINE;
4221 case FR_ACTION_TIMER:
4222 if (request->parent) coa_separate(request);
4224 coa_retransmit(request);
4227 case FR_ACTION_PROXY_REPLY:
4228 if (request->parent) coa_separate(request);
4230 request_queue_or_run(request, coa_running);
4234 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4239 static void coa_separate(REQUEST *request)
4241 VERIFY_REQUEST(request);
4242 #ifdef DEBUG_STATE_MACHINE
4243 int action = FR_ACTION_TIMER;
4246 TRACE_STATE_MACHINE;
4249 rad_assert(request->parent != NULL);
4250 rad_assert(request->parent->coa == request);
4251 rad_assert(request->ev == NULL);
4252 rad_assert(!request->in_request_hash);
4253 rad_assert(request->coa == NULL);
4255 rad_assert(request->proxy_reply || request->proxy_listener);
4257 (void) talloc_steal(NULL, request);
4258 request->parent->coa = NULL;
4259 request->parent = NULL;
4263 /** Process a request after the CoA has timed out.
4265 * Run the packet through Post-Proxy-Type Fail
4267 static void coa_no_reply(REQUEST *request, int action)
4271 VERIFY_REQUEST(request);
4273 TRACE_STATE_MACHINE;
4277 case FR_ACTION_TIMER:
4278 request_max_time(request);
4281 case FR_ACTION_PROXY_REPLY: /* too late! */
4282 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4283 inet_ntop(request->proxy->src_ipaddr.af,
4284 &request->proxy->src_ipaddr.ipaddr,
4285 buffer, sizeof(buffer)),
4286 request->proxy->dst_port, request->proxy->id);
4290 if (process_proxy_reply(request, NULL)) {
4291 request->handle(request);
4293 request_done(request, FR_ACTION_DONE);
4297 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4303 /** Process the request after receiving a coa reply.
4305 * Throught the post-proxy section, and the through the handler
4308 static void coa_running(REQUEST *request, int action)
4310 VERIFY_REQUEST(request);
4312 TRACE_STATE_MACHINE;
4316 case FR_ACTION_TIMER:
4317 request_max_time(request);
4321 if (process_proxy_reply(request, request->proxy_reply)) {
4322 request->handle(request);
4324 request_done(request, FR_ACTION_DONE);
4328 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4332 #endif /* WITH_COA */
4334 /***********************************************************************
4336 * End of the State machine. Start of additional helper code.
4338 ***********************************************************************/
4340 /***********************************************************************
4344 ***********************************************************************/
4345 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4347 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4349 rad_assert(xel == el);
4351 if ((listener->fd < 0)
4353 #ifndef WITH_DETAIL_THREAD
4354 && (listener->type != RAD_LISTEN_DETAIL)
4360 listener->print(listener, buffer, sizeof(buffer));
4361 ERROR("FATAL: Asked to read from closed socket: %s",
4364 rad_panic("Socket was closed on us!");
4368 listener->recv(listener);
4372 #ifdef WITH_DETAIL_THREAD
4375 * This function is called periodically to see if this detail
4376 * file is available for reading.
4378 static void event_poll_detail(void *ctx)
4381 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4382 struct timeval when, now;
4383 listen_detail_t *detail = this->data;
4385 rad_assert(this->type == RAD_LISTEN_DETAIL);
4388 event_socket_handler(el, this->fd, this);
4390 fr_event_now(el, &now);
4394 * Backdoor API to get the delay until the next poll
4397 delay = this->encode(this, NULL);
4398 if (delay == 0) goto redo;
4400 tv_add(&when, delay);
4403 if (!fr_event_insert(el, event_poll_detail, this,
4404 &when, &detail->ev)) {
4405 ERROR("Failed creating handler");
4409 #endif /* WITH_DETAIL_THREAD */
4410 #endif /* WITH_DETAIL */
4412 static void event_status(struct timeval *wake)
4414 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4418 if (debug_flag == 0) {
4420 INFO("Ready to process requests");
4421 just_started = false;
4427 INFO("Ready to process requests");
4429 } else if ((wake->tv_sec != 0) ||
4430 (wake->tv_usec >= 100000)) {
4431 DEBUG("Waking up in %d.%01u seconds.",
4432 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4437 * FIXME: Put this somewhere else, where it isn't called
4438 * all of the time...
4441 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4443 * If there are no child threads, then there may
4444 * be child processes. In that case, wait for
4445 * their exit status, and throw that exit status
4446 * away. This helps get rid of zxombie children.
4448 while (waitpid(-1, &argval, WNOHANG) > 0) {
4456 static void listener_free_cb(void *ctx)
4458 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4461 if (this->count > 0) {
4462 struct timeval when;
4463 listen_socket_t *sock = this->data;
4465 fr_event_now(el, &when);
4469 if (!fr_event_insert(el, listener_free_cb, this, &when,
4471 rad_panic("Failed to insert event");
4478 * It's all free, close the socket.
4481 this->print(this, buffer, sizeof(buffer));
4482 DEBUG("... cleaning up socket %s", buffer);
4483 rad_assert(this->next == NULL);
4489 static int proxy_eol_cb(void *ctx, void *data)
4491 struct timeval when;
4492 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4494 if (request->proxy_listener != ctx) return 0;
4497 * We don't care if it's being processed in a child thread.
4500 #ifdef WITH_ACCOUNTING
4502 * Accounting packets should be deleted immediately.
4503 * They will never be retransmitted by the client.
4505 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4506 RDEBUG("Stopping request due to failed connection to home server");
4507 request->master_state = REQUEST_STOP_PROCESSING;
4512 * Reset the timer to be now, so that the request is
4513 * quickly updated. But spread the requests randomly
4514 * over the next second, so that we don't overload the
4517 fr_event_now(el, &when);
4518 tv_add(&when, fr_rand() % USEC);
4519 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4522 * Don't delete it from the list.
4528 static int event_new_fd(rad_listen_t *this)
4534 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4536 this->print(this, buffer, sizeof(buffer));
4538 if (this->status == RAD_LISTEN_STATUS_INIT) {
4539 listen_socket_t *sock = this->data;
4541 rad_assert(sock != NULL);
4543 DEBUG("Listening on %s", buffer);
4546 } else if (this->type == RAD_LISTEN_PROXY) {
4547 home_server_t *home;
4550 if (!home || !home->limit.max_connections) {
4551 INFO(" ... adding new socket %s", buffer);
4553 INFO(" ... adding new socket %s (%u of %u)", buffer,
4554 home->limit.num_connections, home->limit.max_connections);
4559 INFO(" ... adding new socket %s", buffer);
4562 switch (this->type) {
4565 * Detail files are always known, and aren't
4566 * put into the socket event loop.
4568 case RAD_LISTEN_DETAIL:
4569 this->status = RAD_LISTEN_STATUS_KNOWN;
4571 #ifndef WITH_DETAIL_THREAD
4573 * Set up the first poll interval.
4575 event_poll_detail(this);
4578 break; /* add the FD to the list */
4580 #endif /* WITH_DETAIL */
4584 * Add it to the list of sockets we can use.
4585 * Server sockets (i.e. auth/acct) are never
4586 * added to the packet list.
4588 case RAD_LISTEN_PROXY:
4590 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4593 * Add timers to outgoing child sockets, if necessary.
4595 if (sock->proto == IPPROTO_TCP && sock->opened &&
4596 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4597 struct timeval when;
4599 when.tv_sec = sock->opened + 1;
4603 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4605 rad_panic("Failed to insert event");
4610 #endif /* WITH_PROXY */
4613 * FIXME: put idle timers on command sockets.
4619 * Add timers to incoming child sockets, if necessary.
4621 if (sock->proto == IPPROTO_TCP && sock->opened &&
4622 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4623 struct timeval when;
4625 when.tv_sec = sock->opened + 1;
4629 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4631 ERROR("Failed adding timer for socket: %s", fr_strerror());
4637 } /* switch over listener types */
4640 * All sockets: add the FD to the event handler.
4642 if (!fr_event_fd_insert(el, 0, this->fd,
4643 event_socket_handler, this)) {
4644 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4648 this->status = RAD_LISTEN_STATUS_KNOWN;
4654 * Stop using this socket, if at all possible.
4656 if (this->status == RAD_LISTEN_STATUS_EOL) {
4658 * Remove it from the list of live FD's.
4660 fr_event_fd_delete(el, 0, this->fd);
4664 * Proxy sockets get frozen, so that we don't use
4665 * them for new requests. But we do keep them
4666 * open to listen for replies to requests we had
4669 if (this->type == RAD_LISTEN_PROXY) {
4670 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4671 if (!fr_packet_list_socket_freeze(proxy_list,
4673 ERROR("Fatal error freezing socket: %s", fr_strerror());
4677 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4678 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4683 * Requests are still using the socket. Wait for
4686 if (this->count > 0) {
4687 struct timeval when;
4688 listen_socket_t *sock = this->data;
4691 * Try again to clean up the socket in 30
4694 gettimeofday(&when, NULL);
4698 if (!fr_event_insert(el,
4699 (fr_event_callback_t) event_new_fd,
4700 this, &when, &sock->ev)) {
4701 rad_panic("Failed to insert event");
4708 * No one is using the socket. We can remove it now.
4710 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4711 } /* socket is at EOL */
4717 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4720 listen_socket_t *sock = this->data;
4722 struct timeval when;
4725 * Re-open the socket, pointing it to /dev/null.
4726 * This means that all writes proceed without
4727 * blocking, and all reads return "no data".
4729 * This leaves the socket active, so any child
4730 * threads won't go insane. But it means that
4731 * they cannot send or receive any packets.
4733 * This is EXTRA work in the normal case, when
4734 * sockets are closed without error. But it lets
4735 * us have one simple processing method for all
4738 devnull = open("/dev/null", O_RDWR);
4740 ERROR("FATAL failure opening /dev/null: %s",
4741 fr_syserror(errno));
4744 if (dup2(devnull, this->fd) < 0) {
4745 ERROR("FATAL failure closing socket: %s",
4746 fr_syserror(errno));
4752 rad_assert(this->type != RAD_LISTEN_DETAIL);
4758 * The socket is dead. Force all proxied packets
4759 * to stop using it. And then remove it from the
4760 * list of outgoing sockets.
4762 if (this->type == RAD_LISTEN_PROXY) {
4763 home_server_t *home;
4766 if (!home || !home->limit.max_connections) {
4767 INFO(" ... shutting down socket %s", buffer);
4769 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4770 home->limit.num_connections, home->limit.max_connections);
4773 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4774 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4776 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4777 ERROR("Fatal error removing socket %s: %s",
4778 buffer, fr_strerror());
4781 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4785 INFO(" ... shutting down socket %s", buffer);
4788 * EOL all requests using this socket.
4790 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4794 * No child threads, clean it up now.
4798 if (sock->ev) fr_event_delete(el, &sock->ev);
4804 * Wait until all requests using this socket are done.
4806 gettimeofday(&when, NULL);
4810 if (!fr_event_insert(el, listener_free_cb, this, &when,
4812 rad_panic("Failed to insert event");
4815 #endif /* WITH_TCP */
4820 /***********************************************************************
4824 ***********************************************************************/
4826 static void handle_signal_self(int flag)
4830 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4831 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4832 INFO("Signalled to exit");
4833 fr_event_loop_exit(el, 1);
4835 INFO("Signalled to terminate");
4836 fr_event_loop_exit(el, 2);
4840 } /* else exit/term flags weren't set */
4843 * Tell the even loop to stop processing.
4845 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4847 static time_t last_hup = 0;
4850 if ((int) (when - last_hup) < 5) {
4851 INFO("Ignoring HUP (less than 5s since last one)");
4855 INFO("Received HUP signal");
4859 exec_trigger(NULL, NULL, "server.signal.hup", true);
4860 fr_event_loop_exit(el, 0x80);
4863 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
4864 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4868 * FIXME: O(N) loops suck.
4870 for (this = main_config.listen;
4872 this = this->next) {
4873 if (this->type != RAD_LISTEN_DETAIL) continue;
4876 * This one didn't send the signal, skip
4879 if (!this->decode(this, NULL)) continue;
4882 * Go service the interrupt.
4884 event_poll_detail(this);
4889 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
4891 * There are new listeners in the list. Run
4892 * event_new_fd() on them.
4894 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4895 rad_listen_t *this, *next;
4897 FD_MUTEX_LOCK(&fd_mutex);
4900 * FIXME: unlock the mutex before calling
4903 for (this = new_listeners; this != NULL; this = next) {
4910 new_listeners = NULL;
4911 FD_MUTEX_UNLOCK(&fd_mutex);
4916 #ifndef HAVE_PTHREAD_H
4917 void radius_signal_self(int flag)
4919 return handle_signal_self(flag);
4923 static int self_pipe[2] = { -1, -1 };
4926 * Inform ourselves that we received a signal.
4928 void radius_signal_self(int flag)
4934 * The read MUST be non-blocking for this to work.
4936 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4940 for (i = 0; i < rcode; i++) {
4941 buffer[0] |= buffer[i];
4949 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4953 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4954 UNUSED int fd, UNUSED void *ctx)
4959 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4960 if (rcode <= 0) return;
4963 * Merge pending signals.
4965 for (i = 0; i < rcode; i++) {
4966 buffer[0] |= buffer[i];
4969 handle_signal_self(buffer[0]);
4971 #endif /* HAVE_PTHREAD_H */
4973 /***********************************************************************
4975 * Bootstrapping code.
4977 ***********************************************************************/
4980 * Externally-visibly functions.
4982 int radius_event_init(TALLOC_CTX *ctx) {
4983 el = fr_event_list_create(ctx, event_status);
4989 static int packet_entry_cmp(void const *one, void const *two)
4991 RADIUS_PACKET const * const *a = one;
4992 RADIUS_PACKET const * const *b = two;
4994 return fr_packet_cmp(*a, *b);
4998 int radius_event_start(CONF_SECTION *cs, bool have_children)
5000 rad_listen_t *head = NULL;
5002 if (fr_start_time != (time_t)-1) return 0;
5004 time(&fr_start_time);
5006 if (!check_config) {
5008 * radius_event_init() must be called first
5012 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5013 if (!pl) return 0; /* leak el */
5016 request_num_counter = 0;
5019 if (main_config.proxy_requests && !check_config) {
5021 * Create the tree for managing proxied requests and
5024 proxy_list = fr_packet_list_create(1);
5025 if (!proxy_list) return 0;
5027 #ifdef HAVE_PTHREAD_H
5028 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5029 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5030 fr_syserror(errno));
5036 * The "init_delay" is set to "response_window".
5037 * Reset it to half of "response_window" in order
5038 * to give the event loop enough time to service
5039 * the event before hitting "response_window".
5041 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5042 main_config.init_delay.tv_usec >>= 1;
5043 main_config.init_delay.tv_sec >>= 1;
5045 proxy_ctx = talloc_init("proxy");
5050 * Move all of the thread calls to this file?
5052 * It may be best for the mutexes to be in this file...
5054 spawn_flag = have_children;
5056 #ifdef HAVE_PTHREAD_H
5057 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5060 * Initialize the threads ONLY if we're spawning, AND
5061 * we're running normally.
5063 if (have_children && !check_config &&
5064 (thread_pool_init(cs, &spawn_flag) < 0)) {
5070 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5072 if (listen_init(cs, &head, spawn_flag) < 0) {
5079 #ifdef HAVE_PTHREAD_H
5081 * Child threads need a pipe to signal us, as do the
5084 if (pipe(self_pipe) < 0) {
5085 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5088 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5089 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5090 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5093 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5094 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5095 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5098 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5100 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5101 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5106 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5109 * The server temporarily switches to an unprivileged
5110 * user very early in the bootstrapping process.
5111 * However, some sockets MAY require privileged access
5112 * (bind to device, or to port < 1024, or to raw
5113 * sockets). Those sockets need to call suid up/down
5114 * themselves around the functions that need a privileged
5117 if (listen_init(cs, &head, spawn_flag) < 0) {
5121 main_config.listen = head;
5124 * At this point, no one has any business *ever* going
5127 rad_suid_down_permanent();
5134 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5136 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5138 VERIFY_REQUEST(request);
5140 request->master_state = REQUEST_STOP_PROCESSING;
5142 #ifdef HAVE_PTHREAD_H
5143 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5147 * If it's queued we can't delete it from the queue.
5149 * Otherwise, it's OK to delete it. Even RUNNING, because
5150 * that will get caught by the check above.
5152 if (request->child_state == REQUEST_QUEUED) return 0;
5154 request->in_proxy_hash = false;
5156 if (!request->in_request_hash) {
5157 request_done(request, FR_ACTION_DONE);
5161 * Delete it from the list.
5168 static int request_delete_cb(UNUSED void *ctx, void *data)
5170 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5172 VERIFY_REQUEST(request);
5174 request->master_state = REQUEST_STOP_PROCESSING;
5177 * Not done, or the child thread is still processing it.
5179 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5181 #ifdef HAVE_PTHREAD_H
5182 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5186 rad_assert(request->in_proxy_hash == false);
5189 request->in_request_hash = false;
5191 if (request->ev) fr_event_delete(el, &request->ev);
5193 if (main_config.memory_report) {
5194 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5195 request->packet->id,
5196 (unsigned int) (request->timestamp - fr_start_time));
5201 rad_assert(!request->coa->in_proxy_hash);
5205 request_free(request);
5208 * Delete it from the list, and continue;
5214 void radius_event_free(void)
5220 * There are requests in the proxy hash that aren't
5221 * referenced from anywhere else. Remove them first.
5224 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5228 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5232 * Now that all requests have been marked "please stop",
5233 * ensure that all of the threads have exited.
5235 #ifdef HAVE_PTHREAD_H
5240 * Walk the lists again, ensuring that all
5241 * requests are done.
5243 if (main_config.memory_report) {
5248 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5249 num = fr_packet_list_num_elements(proxy_list);
5251 ERROR("Proxy list has %d requests still in it.", num);
5256 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5257 num = rbtree_num_elements(pl);
5259 ERROR("Request list has %d requests still in it.", num);
5268 fr_packet_list_free(proxy_list);
5271 if (proxy_ctx) talloc_free(proxy_ctx);
5276 if (debug_condition) talloc_free(debug_condition);
5279 int radius_event_process(void)
5283 return fr_event_loop(el);