2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Defines the state machines that control how requests are processed.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
34 #include <freeradius-devel/rad_assert.h>
37 #include <freeradius-devel/detail.h>
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
47 extern pid_t radius_pid;
48 extern fr_cond_t *debug_condition;
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static rbtree_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57 /* Currently we do not run a second event loop for modules. */
61 static char const *action_codes[] = {
72 #ifdef DEBUG_STATE_MACHINE
73 # define TRACE_STATE_MACHINE \
74 if (rad_debug_lvl) do { \
75 struct timeval debug_tv; \
76 gettimeofday(&debug_tv, NULL); \
77 debug_tv.tv_sec -= fr_start_time; \
78 printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79 request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80 __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81 child_state_names[request->child_state]); \
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
102 # define TRACE_STATE_MACHINE {}
105 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
107 ERROR("%s[%u]: %s", file, line, msg);
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
113 /** Declare a state in the state machine
115 * Expands to the start of a function definition for a given state.
117 * @param _x the name of the state.
119 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
121 static void request_timer(void *ctx);
123 /** Insert #REQUEST back into the event heap, to continue executing at a future time
125 * @param file the state machine timer call occurred in.
126 * @param line the state machine timer call occurred on.
127 * @param request to set add the timer event for.
128 * @param when the event should fine.
129 * @param action to perform when we resume processing the request.
131 static inline void state_machine_timer(char const *file, int line, REQUEST *request,
132 struct timeval *when, fr_state_action_t action)
134 request->timer_action = action;
135 if (!fr_event_insert(el, request_timer, request, when, &request->ev)) {
136 _rad_panic(file, line, "Failed to insert event");
140 /** @copybrief state_machine_timer
142 * @param _x the action to perform when we resume processing the request.
144 #define STATE_MACHINE_TIMER(_x) state_machine_timer(__FILE__, __LINE__, request, &when, _x)
147 * We need a different VERIFY_REQUEST macro in process.c
148 * To avoid the race conditions with the master thread
149 * checking the REQUEST whilst it's being worked on by
152 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
153 # undef VERIFY_REQUEST
154 # define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
158 * @section request_timeline
160 * Time sequence of a request
163 * RQ-----------------P=============================Y-J-C
164 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
167 * - R: received. Duplicate detection is done, and request is
170 * - Q: Request is placed onto a queue for child threads to pick up.
171 * If there are no child threads, the request goes immediately
174 * - P: Processing the request through the modules.
176 * - Y: Reply is ready. Rejects MAY be delayed here. All other
177 * replies are sent immediately.
179 * - J: Reject is sent "response_delay" after the reply is ready.
181 * - C: For Access-Requests, After "cleanup_delay", the request is
182 * deleted. Accounting-Request packets go directly from Y to C.
184 * - M: Max request time. If the request hits this timer, it is
187 * Other considerations include duplicate and conflicting
188 * packets. When a dupicate packet is received, it is ignored
189 * until we've reached Y, as no response is ready. If the reply
190 * is a reject, duplicates are ignored until J, when we're ready
191 * to send the reply. In between the reply being sent (Y or J),
192 * and C, the server responds to duplicates by sending the cached
195 * Conflicting packets are sent in 2 situations.
197 * The first is in between R and Y. In that case, we consider
198 * it as a hint that we're taking too long, and the NAS has given
199 * up on the request. We then behave just as if the M timer was
200 * reached, and we discard the current request. This allows us
201 * to process the new one.
203 * The second case is when we're at Y, but we haven't yet
204 * finished processing the request. This is a race condition in
205 * the threading code (avoiding locks is faster). It means that
206 * a thread has actually encoded and sent the reply, and that the
207 * NAS has responded with a new packet. The server can then
208 * safely mark the current request as "OK to delete", and behaves
209 * just as if the M timer was reached. This usually happens only
210 * in high-load situations.
212 * Duplicate packets are sent when the NAS thinks we're taking
213 * too long, and wants a reply. From R-Y, duplicates are
214 * ignored. From Y-J (for Access-Rejects), duplicates are also
215 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
216 * they cause the "cleanup_delay" time to be extended. This
217 * extension means that we're more likely to send a duplicate
218 * reply (if we have one), or to suppress processing the packet
219 * twice if we didn't reply to it.
221 * All functions in this file should be thread-safe, and should
222 * assume thet the REQUEST structure is being accessed
223 * simultaneously by the main thread, and by the child worker
224 * threads. This means that timers, etc. cannot be updated in
227 * Instead, the master thread periodically calls request->process
228 * with action TIMER. It's up to the individual functions to
229 * determine how to handle that. They need to check if they're
230 * being called from a child thread or the master, and then do
231 * different things based on that.
234 static fr_packet_list_t *proxy_list = NULL;
235 static TALLOC_CTX *proxy_ctx = NULL;
238 #ifdef HAVE_PTHREAD_H
240 static pthread_mutex_t proxy_mutex;
241 static bool proxy_no_new_sockets = false;
244 # define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
245 # define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
247 static pthread_t NO_SUCH_CHILD_PID;
248 # define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
252 * This is easier than ifdef's throughout the code.
254 # define PTHREAD_MUTEX_LOCK(_x)
255 # define PTHREAD_MUTEX_UNLOCK(_x)
256 # define NO_CHILD_THREAD
259 #ifdef HAVE_PTHREAD_H
260 static bool we_are_master(void)
263 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
271 * Assertions are debug checks.
274 # define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
279 * No threads: we're always master.
281 # define we_are_master(_x) (1)
282 #endif /* HAVE_PTHREAD_H */
284 #ifndef ASSERT_MASTER
285 # define ASSERT_MASTER
288 static int event_new_fd(rad_listen_t *this);
291 * We need mutexes around the event FD list *only* in certain
294 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
295 static rad_listen_t *new_listeners = NULL;
297 static pthread_mutex_t fd_mutex;
298 # define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
299 # define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
301 void radius_update_listener(rad_listen_t *this)
304 * Just do it ourselves.
306 if (we_are_master()) {
311 FD_MUTEX_LOCK(&fd_mutex);
314 * If it's already in the list, don't add it again.
317 FD_MUTEX_UNLOCK(&fd_mutex);
322 * Otherwise, add it to the list
324 this->next = new_listeners;
325 new_listeners = this;
326 FD_MUTEX_UNLOCK(&fd_mutex);
327 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
330 void radius_update_listener(rad_listen_t *this)
333 * No threads. Just insert it.
338 * This is easier than ifdef's throughout the code.
340 # define FD_MUTEX_LOCK(_x)
341 # define FD_MUTEX_UNLOCK(_x)
344 static int request_num_counter = 1;
346 static int request_will_proxy(REQUEST *request) CC_HINT(nonnull);
347 static int request_proxy(REQUEST *request, int retransmit) CC_HINT(nonnull);
348 STATE_MACHINE_DECL(request_ping) CC_HINT(nonnull);
350 STATE_MACHINE_DECL(request_response_delay) CC_HINT(nonnull);
351 STATE_MACHINE_DECL(request_cleanup_delay) CC_HINT(nonnull);
352 STATE_MACHINE_DECL(request_running) CC_HINT(nonnull);
353 STATE_MACHINE_DECL(request_done) CC_HINT(nonnull);
355 STATE_MACHINE_DECL(proxy_no_reply) CC_HINT(nonnull);
356 STATE_MACHINE_DECL(proxy_running) CC_HINT(nonnull);
357 STATE_MACHINE_DECL(proxy_wait_for_reply) CC_HINT(nonnull);
359 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply) CC_HINT(nonnull (1));
360 static void remove_from_proxy_hash(REQUEST *request) CC_HINT(nonnull);
361 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank) CC_HINT(nonnull);
362 static int insert_into_proxy_hash(REQUEST *request) CC_HINT(nonnull);
365 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
366 RADCLIENT *client, RAD_REQUEST_FUNP fun);
367 static int request_pre_handler(REQUEST *request, UNUSED int action) CC_HINT(nonnull);
370 static void request_coa_originate(REQUEST *request) CC_HINT(nonnull);
371 STATE_MACHINE_DECL(coa_wait_for_reply) CC_HINT(nonnull);
372 STATE_MACHINE_DECL(coa_no_reply) CC_HINT(nonnull);
373 STATE_MACHINE_DECL(coa_running) CC_HINT(nonnull);
374 static void coa_separate(REQUEST *request) CC_HINT(nonnull);
375 # define COA_SEPARATE if (request->coa) coa_separate(request->coa);
377 # define COA_SEPARATE
380 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
383 #define USEC (1000000)
385 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
387 static void tv_add(struct timeval *tv, int usec_delay)
389 if (usec_delay >= USEC) {
390 tv->tv_sec += usec_delay / USEC;
393 tv->tv_usec += usec_delay;
395 if (tv->tv_usec >= USEC) {
396 tv->tv_sec += tv->tv_usec / USEC;
402 * Debug the packet if requested.
404 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
406 char src_ipaddr[128];
407 char dst_ipaddr[128];
410 if (!RDEBUG_ENABLED) return;
413 * Client-specific debugging re-prints the input
414 * packet into the client log.
416 * This really belongs in a utility library
418 if (is_radius_code(packet->code)) {
419 RDEBUG("%s %s Id %i from %s%s%s:%i to %s%s%s:%i length %zu",
420 received ? "Received" : "Sent",
421 fr_packet_codes[packet->code],
423 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
424 inet_ntop(packet->src_ipaddr.af,
425 &packet->src_ipaddr.ipaddr,
426 src_ipaddr, sizeof(src_ipaddr)),
427 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
429 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
430 inet_ntop(packet->dst_ipaddr.af,
431 &packet->dst_ipaddr.ipaddr,
432 dst_ipaddr, sizeof(dst_ipaddr)),
433 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
437 RDEBUG("%s code %u Id %i from %s%s%s:%i to %s%s%s:%i length %zu\n",
438 received ? "Received" : "Sent",
441 packet->src_ipaddr.af == AF_INET6 ? "[" : "",
442 inet_ntop(packet->src_ipaddr.af,
443 &packet->src_ipaddr.ipaddr,
444 src_ipaddr, sizeof(src_ipaddr)),
445 packet->src_ipaddr.af == AF_INET6 ? "]" : "",
447 packet->dst_ipaddr.af == AF_INET6 ? "[" : "",
448 inet_ntop(packet->dst_ipaddr.af,
449 &packet->dst_ipaddr.ipaddr,
450 dst_ipaddr, sizeof(dst_ipaddr)),
451 packet->dst_ipaddr.af == AF_INET6 ? "]" : "",
457 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
459 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
464 /***********************************************************************
466 * Start of RADIUS server state machine.
468 ***********************************************************************/
470 static struct timeval *request_response_window(REQUEST *request)
472 VERIFY_REQUEST(request);
474 if (request->client) {
476 * The client hasn't set the response window. Return
477 * either the home server one, if set, or the global one.
479 if (!timerisset(&request->client->response_window)) {
480 return &request->home_server->response_window;
483 if (timercmp(&request->client->response_window,
484 &request->home_server->response_window, <)) {
485 return &request->client->response_window;
489 rad_assert(request->home_server != NULL);
490 return &request->home_server->response_window;
494 * Determine initial request processing delay.
496 static int request_init_delay(REQUEST *request)
498 struct timeval half_response_window;
500 VERIFY_REQUEST(request);
502 /* Allow client response window to lower initial delay */
503 if (timerisset(&request->client->response_window)) {
504 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
505 half_response_window.tv_usec =
506 ((request->client->response_window.tv_sec & 1) * USEC +
507 request->client->response_window.tv_usec) >> 1;
508 if (timercmp(&half_response_window, &request->root->init_delay, <))
509 return (int)half_response_window.tv_sec * USEC +
510 (int)half_response_window.tv_usec;
513 return (int)request->root->init_delay.tv_sec * USEC +
514 (int)request->root->init_delay.tv_usec;
518 * Callback for ALL timer events related to the request.
520 static void request_timer(void *ctx)
522 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
525 action = request->timer_action;
529 request->process(request, action);
533 * Wrapper for talloc pools. If there's no parent, just free the
534 * request. If there is a parent, free the parent INSTEAD of the
537 static void request_free(REQUEST *request)
541 rad_assert(request->ev == NULL);
542 rad_assert(!request->in_request_hash);
543 rad_assert(!request->in_proxy_hash);
545 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
546 talloc_free(request);
550 ptr = talloc_parent(request);
551 rad_assert(ptr != NULL);
557 static void proxy_reply_too_late(REQUEST *request)
561 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
562 inet_ntop(request->proxy->dst_ipaddr.af,
563 &request->proxy->dst_ipaddr.ipaddr,
564 buffer, sizeof(buffer)),
565 request->proxy->dst_port, request->proxy->id);
570 /** Mark a request DONE and clean it up.
572 * When a request is DONE, it can have ties to a number of other
573 * portions of the server. The request hash, proxy hash, events,
574 * child threads, etc. This function takes care of either cleaning
575 * up the request, or managing the timers to wait for the ties to be
580 * done -> done [ label = "still running" ];
584 static void request_done(REQUEST *request, int action)
586 struct timeval now, when;
588 VERIFY_REQUEST(request);
593 * Force this no matter what.
595 request->process = request_done;
599 * Tell the detail listener that we're done.
601 if (request->listener &&
602 (request->listener->type == RAD_LISTEN_DETAIL) &&
603 (request->simul_max != 1)) {
604 request->simul_max = 1;
605 request->listener->send(request->listener,
610 #ifdef HAVE_PTHREAD_H
612 * If called from a child thread, mark ourselves as done,
613 * and wait for the master thread timer to clean us up.
615 if (!we_are_master()) {
617 request->child_state = REQUEST_DONE;
623 * Mark the request as STOP.
625 request->master_state = REQUEST_STOP_PROCESSING;
629 * Move the CoA request to its own handler.
632 coa_separate(request->coa);
633 } else if (request->parent && (request->parent->coa == request)) {
634 coa_separate(request);
639 * It doesn't hurt to send duplicate replies. All other
640 * signals are ignored, as the request will be cleaned up
646 rad_assert(request->listener != NULL);
648 if (request->reply->code != 0) {
649 request->listener->send(request->listener, request);
652 RDEBUG("No reply. Ignoring retransmit");
657 * Mark the request as done.
660 #ifdef HAVE_PTHREAD_H
662 * If the child is still running, leave it alone.
664 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
669 #ifdef DEBUG_STATE_MACHINE
670 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
671 request->number, __FUNCTION__,
672 child_state_names[request->child_state],
673 child_state_names[REQUEST_DONE]);
675 request->child_state = REQUEST_DONE;
679 * Called when the child is taking too long to
680 * finish. We've already marked it "please
681 * stop", so we don't complain any more.
683 case FR_ACTION_TIMER:
687 case FR_ACTION_PROXY_REPLY:
688 proxy_reply_too_late(request);
697 * Remove it from the request hash.
699 if (request->in_request_hash) {
700 if (!rbtree_deletebydata(pl, &request->packet)) {
703 request->in_request_hash = false;
708 * Wait for the proxy ID to expire. This allows us to
709 * avoid re-use of proxy IDs for a while.
711 if (request->in_proxy_hash) {
712 rad_assert(request->proxy != NULL);
714 fr_event_now(el, &now);
715 when = request->proxy->timestamp;
718 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
719 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
720 (request->packet->code != request->proxy->code)) {
721 when.tv_sec += request->home_server->coa_mrd;
724 timeradd(&when, request_response_window(request), &when);
727 * We haven't received all responses, AND there's still
728 * time to wait. Do so.
730 if ((request->num_proxied_requests > request->num_proxied_responses) &&
732 (request->home_server->proto != IPPROTO_TCP) &&
734 timercmp(&now, &when, <)) {
735 RDEBUG("Waiting for more responses from the home server");
742 remove_from_proxy_hash(request);
746 #ifdef HAVE_PTHREAD_H
748 * If there's no children, we can mark the request as done.
750 if (!spawn_flag) request->child_state = REQUEST_DONE;
754 * If the child is still running, wait for it to be finished.
756 if (request->child_state <= REQUEST_RUNNING) {
757 gettimeofday(&now, NULL);
762 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
763 tv_add(&when, request->delay);
764 request->delay += request->delay >> 1;
765 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
767 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
771 #ifdef HAVE_PTHREAD_H
772 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
776 * @todo: do final states for TCP sockets, too?
778 request_stats_final(request);
780 if (request->listener) {
781 request->listener->count--;
784 * If we're the last one, remove the listener now.
786 if ((request->listener->count == 0) &&
787 (request->listener->status >= RAD_LISTEN_STATUS_FROZEN)) {
788 event_new_fd(request->listener);
793 if (request->packet) {
794 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
796 (unsigned int) (request->timestamp - fr_start_time));
797 } /* else don't print anything */
800 fr_event_delete(el, &request->ev);
801 request_free(request);
805 static void request_cleanup_delay_init(REQUEST *request)
807 struct timeval now, when;
809 VERIFY_REQUEST(request);
812 * Do cleanup delay ONLY for RADIUS packets from a real
813 * client. Everything else just gets cleaned up
816 if (request->packet->dst_port == 0) goto done;
819 * Accounting packets shouldn't be retransmitted. They
820 * should always be updated with Acct-Delay-Time.
822 #ifdef WITH_ACCOUNTING
823 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
827 if (request->listener->type == RAD_LISTEN_DHCP) goto done;
831 if (request->listener->type == RAD_LISTEN_VQP) goto done;
834 if (!request->root->cleanup_delay) goto done;
836 gettimeofday(&now, NULL);
838 rad_assert(request->reply->timestamp.tv_sec != 0);
839 when = request->reply->timestamp;
841 request->delay = request->root->cleanup_delay;
842 when.tv_sec += request->delay;
845 * Set timer for when we need to clean it up.
847 if (timercmp(&when, &now, >)) {
848 #ifdef DEBUG_STATE_MACHINE
849 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
851 request->process = request_cleanup_delay;
852 request->child_state = REQUEST_CLEANUP_DELAY;
855 * Update this if we can, otherwise let the timers pick it up.
857 if (we_are_master()) {
858 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
866 * Otherwise just clean it up.
869 request_done(request, FR_ACTION_DONE);
874 * Enforce max_request_time.
876 static bool request_max_time(REQUEST *request)
878 struct timeval now, when;
879 rad_assert(request->magic == REQUEST_MAGIC);
880 #ifdef DEBUG_STATE_MACHINE
881 int action = FR_ACTION_TIMER;
884 VERIFY_REQUEST(request);
890 * The child thread has acknowledged it's done.
891 * Transition to the DONE state.
893 * If the request was marked STOP, then the "check for
894 * stop" macro already took care of it.
896 if (request->child_state == REQUEST_DONE) {
898 request_done(request, FR_ACTION_DONE);
903 * The request is still running. Enforce max_request_time.
905 fr_event_now(el, &now);
906 when = request->packet->timestamp;
907 when.tv_sec += request->root->max_request_time;
910 * Taking too long: tell it to die.
912 if (timercmp(&now, &when, >=)) {
913 #ifdef HAVE_PTHREAD_H
915 * If there's a child thread processing it,
919 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
920 ERROR("Unresponsive child for request %u, in component %s module %s",
922 request->component ? request->component : "<core>",
923 request->module ? request->module : "<core>");
924 exec_trigger(request, NULL, "server.thread.unresponsive", true);
928 * Tell the request that it's done.
934 * Sleep for some more. We HOPE that the child will
935 * become responsive at some point in the future. We do
936 * this by adding 50% to the current timer.
939 tv_add(&when, request->delay);
940 request->delay += request->delay >> 1;
941 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
945 static void request_queue_or_run(REQUEST *request,
946 fr_request_process_t process)
948 #ifdef DEBUG_STATE_MACHINE
949 int action = FR_ACTION_TIMER;
952 VERIFY_REQUEST(request);
957 * Do this here so that fewer other functions need to do
960 if (request->master_state == REQUEST_STOP_PROCESSING) {
961 #ifdef DEBUG_STATE_MACHINE
962 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
963 request->number, __FUNCTION__,
964 master_state_names[request->master_state],
965 child_state_names[request->child_state],
966 child_state_names[REQUEST_DONE]);
968 request_done(request, FR_ACTION_DONE);
972 request->process = process;
974 if (we_are_master()) {
978 * (re) set the initial delay.
980 request->delay = request_init_delay(request);
981 if (request->delay > USEC) request->delay = USEC;
982 gettimeofday(&when, NULL);
983 tv_add(&when, request->delay);
984 request->delay += request->delay >> 1;
986 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
988 #ifdef HAVE_PTHREAD_H
991 * A child thread will eventually pick it up.
993 if (request_enqueue(request)) return;
996 * Otherwise we're not going to do anything with
999 request_done(request, FR_ACTION_DONE);
1005 request->child_state = REQUEST_RUNNING;
1006 request->process(request, FR_ACTION_RUN);
1010 * Requests that care about child process exit
1011 * codes have already either called
1012 * rad_waitpid(), or they've given up.
1014 while (waitpid(-1, NULL, WNOHANG) > 0);
1019 static void request_dup(REQUEST *request)
1021 ERROR("(%u) Ignoring duplicate packet from "
1022 "client %s port %d - ID: %u due to unfinished request "
1023 "in component %s module %s",
1024 request->number, request->client->shortname,
1025 request->packet->src_port,request->packet->id,
1026 request->component, request->module);
1030 /** Sit on a request until it's time to clean it up.
1032 * A NAS may not see a response from the server. When the NAS
1033 * retransmits, we want to be able to send a cached reply back. The
1034 * alternative is to re-process the packet, which does bad things for
1035 * EAP, among others.
1037 * IF we do see a NAS retransmit, we extend the cleanup delay,
1038 * because the NAS might miss our cached reply.
1040 * Otherwise, once we reach cleanup_delay, we transition to DONE.
1043 * digraph cleanup_delay {
1045 * send_reply [ label = "send_reply\nincrease cleanup delay" ];
1047 * cleanup_delay -> send_reply [ label = "DUP" ];
1048 * send_reply -> cleanup_delay;
1049 * cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1050 * cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
1051 * cleanup_delay -> done [ label = "TIMER >= timeout" ];
1055 static void request_cleanup_delay(REQUEST *request, int action)
1057 struct timeval when, now;
1059 VERIFY_REQUEST(request);
1061 TRACE_STATE_MACHINE;
1068 if (request->reply->code != 0) {
1069 request->listener->send(request->listener, request);
1071 RDEBUG("No reply. Ignoring retransmit");
1075 * Double the cleanup_delay to catch retransmits.
1077 when = request->reply->timestamp;
1078 request->delay += request->delay;
1079 when.tv_sec += request->delay;
1081 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1085 case FR_ACTION_PROXY_REPLY:
1086 proxy_reply_too_late(request);
1090 case FR_ACTION_TIMER:
1091 fr_event_now(el, &now);
1093 rad_assert(request->root->cleanup_delay > 0);
1095 when = request->reply->timestamp;
1096 when.tv_sec += request->root->cleanup_delay;
1098 if (timercmp(&when, &now, >)) {
1099 #ifdef DEBUG_STATE_MACHINE
1100 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1102 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1104 } /* else it's time to clean up */
1106 request_done(request, REQUEST_DONE);
1110 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1116 /** Sit on a request until it's time to respond to it.
1118 * For security reasons, rejects (and maybe some other) packets are
1119 * delayed for a while before we respond. This delay means that
1120 * badly behaved NASes don't hammer the server with authentication
1123 * Otherwise, once we reach response_delay, we send the reply, and
1124 * transition to cleanup_delay.
1127 * digraph response_delay {
1128 * response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1129 * response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1130 * response_delay -> send_reply [ label = "TIMER >= timeout" ];
1131 * send_reply -> cleanup_delay;
1135 static void request_response_delay(REQUEST *request, int action)
1137 struct timeval when, now;
1139 VERIFY_REQUEST(request);
1141 TRACE_STATE_MACHINE;
1148 ERROR("(%u) Discarding duplicate request from "
1149 "client %s port %d - ID: %u due to delayed response",
1150 request->number, request->client->shortname,
1151 request->packet->src_port,request->packet->id);
1155 case FR_ACTION_PROXY_REPLY:
1156 proxy_reply_too_late(request);
1160 case FR_ACTION_TIMER:
1161 fr_event_now(el, &now);
1163 rad_assert(request->response_delay.tv_sec > 0);
1166 * See if it's time to send the reply. If not,
1167 * we wait some more.
1169 when = request->reply->timestamp;
1171 tv_add(&when, request->response_delay.tv_sec * USEC);
1172 tv_add(&when, request->response_delay.tv_usec);
1174 if (timercmp(&when, &now, >)) {
1175 #ifdef DEBUG_STATE_MACHINE
1176 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1178 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1180 } /* else it's time to send the reject */
1182 RDEBUG2("Sending delayed response");
1183 debug_packet(request, request->reply, false);
1184 request->listener->send(request->listener, request);
1187 * Clean up the request.
1189 request_cleanup_delay_init(request);
1193 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1199 static int request_pre_handler(REQUEST *request, UNUSED int action)
1203 VERIFY_REQUEST(request);
1205 TRACE_STATE_MACHINE;
1207 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1210 * Don't decode the packet if it's an internal "fake"
1211 * request. Instead, just return so that the caller can
1214 if (request->packet->dst_port == 0) {
1215 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1216 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1220 if (!request->packet->vps) { /* FIXME: check for correct state */
1221 rcode = request->listener->decode(request->listener, request);
1224 if (debug_condition) {
1226 * Ignore parse errors.
1228 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1229 request->log.lvl = L_DBG_LVL_2;
1230 request->log.func = vradlog_request;
1235 debug_packet(request, request->packet, true);
1241 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1242 request->reply->offset = -2; /* bad authenticator */
1246 if (!request->username) {
1247 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1254 /** Do the final processing of a request before we reply to the NAS.
1256 * Various cleanups, suppress responses, copy Proxy-State, and set
1257 * response_delay or cleanup_delay;
1259 static void request_finish(REQUEST *request, int action)
1263 VERIFY_REQUEST(request);
1265 TRACE_STATE_MACHINE;
1268 (void) action; /* -Wunused */
1272 * Don't do post-auth if we're a CoA request originated
1273 * from an Access-Request. See request_alloc_coa() for
1276 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1280 * Override the response code if a control:Response-Packet-Type attribute is present.
1282 vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1284 if (vp->vp_integer == 256) {
1285 RDEBUG2("Not responding to request");
1286 request->reply->code = 0;
1288 request->reply->code = vp->vp_integer;
1292 * Catch Auth-Type := Reject BEFORE proxying the packet.
1294 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1295 if (request->reply->code == 0) {
1296 vp = fr_pair_find_by_num(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1297 if (!vp || (vp->vp_integer != 5)) {
1298 RDEBUG2("There was no response configured: "
1299 "rejecting request");
1302 request->reply->code = PW_CODE_ACCESS_REJECT;
1307 * Copy Proxy-State from the request to the reply.
1309 vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps,
1310 PW_PROXY_STATE, 0, TAG_ANY);
1311 if (vp) fr_pair_add(&request->reply->vps, vp);
1314 * Call Post-Auth for Access-Request packets.
1316 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1317 rad_postauth(request);
1322 * Maybe originate a CoA request.
1324 if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1325 request_coa_originate(request);
1330 * Clean up. These are no longer needed.
1332 gettimeofday(&request->reply->timestamp, NULL);
1335 * Fake packets get marked as "done", and have the
1336 * proxy-reply section deal with the reply attributes.
1337 * We therefore don't free the reply attributes.
1339 if (request->packet->dst_port == 0) {
1340 RDEBUG("Finished internally proxied request.");
1342 request->child_state = REQUEST_DONE;
1348 * Always send the reply to the detail listener.
1350 if (request->listener->type == RAD_LISTEN_DETAIL) {
1351 request->simul_max = 1;
1354 * But only print the reply if there is one.
1356 if (request->reply->code != 0) {
1357 debug_packet(request, request->reply, false);
1360 request->listener->send(request->listener, request);
1366 * Ignore all "do not respond" packets.
1367 * Except for the detail ones, which need to ping
1368 * the detail file reader so that it will retransmit.
1370 if (!request->reply->code) {
1371 RDEBUG("Not sending reply to client.");
1376 * If it's not in the request hash, we MIGHT not want to
1379 * If duplicate packets are allowed, then then only
1380 * reason to NOT be in the request hash is because we
1381 * don't want to send a reply.
1383 * FIXME: this is crap. The rest of the state handling
1384 * should use a different field so that we don't have two
1387 * Otherwise duplicates are forbidden, and the request is
1388 * SUPPOSED to avoid the request hash.
1390 * In that case, we need to send a reply.
1392 if (!request->in_request_hash &&
1393 !request->listener->nodup) {
1394 RDEBUG("Suppressing reply to client.");
1399 * See if we need to delay an Access-Reject packet.
1401 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1402 (request->root->reject_delay.tv_sec > 0)) {
1403 request->response_delay = request->root->reject_delay;
1407 * If we timed out a proxy packet, don't delay
1408 * the reject any more.
1410 if (request->proxy && !request->proxy_reply) {
1411 request->response_delay.tv_sec = 0;
1412 request->response_delay.tv_usec = 0;
1420 if ((request->response_delay.tv_sec == 0) &&
1421 (request->response_delay.tv_usec == 0)) {
1424 * Don't print a reply if there's none to send.
1426 if (request->reply->code != 0) {
1427 debug_packet(request, request->reply, false);
1428 request->listener->send(request->listener, request);
1432 RDEBUG2("Finished request");
1433 request->component = "<core>";
1434 request->module = "<done>";
1436 request_cleanup_delay_init(request);
1440 * Encode and sign it here, so that the master
1441 * thread can just send the encoded data, which
1442 * means it does less work.
1444 RDEBUG2("Delaying response for %d.%06d seconds",
1445 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1446 request->listener->encode(request->listener, request);
1447 request->component = "<core>";
1448 request->module = "<delay>";
1449 request->process = request_response_delay;
1451 request->child_state = REQUEST_RESPONSE_DELAY;
1455 /** Process a request from a client.
1457 * The outcome might be that the request is proxied.
1461 * running -> running [ label = "TIMER < max_request_time" ];
1462 * running -> done [ label = "TIMER >= max_request_time" ];
1463 * running -> proxy [ label = "proxied" ];
1464 * running -> dup [ label = "DUP", arrowhead = "none" ];
1468 static void request_running(REQUEST *request, int action)
1470 VERIFY_REQUEST(request);
1472 TRACE_STATE_MACHINE;
1476 case FR_ACTION_TIMER:
1478 (void) request_max_time(request);
1482 request_dup(request);
1486 if (!request_pre_handler(request, action)) {
1487 #ifdef DEBUG_STATE_MACHINE
1488 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1489 request->number, __FUNCTION__,
1490 child_state_names[request->child_state],
1491 child_state_names[REQUEST_DONE]);
1495 request->child_state = REQUEST_DONE;
1499 rad_assert(request->handle != NULL);
1500 request->handle(request);
1504 * We may need to send a proxied request.
1506 if ((action == FR_ACTION_RUN) &&
1507 request_will_proxy(request)) {
1508 #ifdef DEBUG_STATE_MACHINE
1509 if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1513 * takes care of setting
1514 * up the post proxy fail
1517 if (request_proxy(request, 0) < 0) goto req_finished;
1521 #ifdef DEBUG_STATE_MACHINE
1522 if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1528 request_finish(request, action);
1533 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1538 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1539 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1542 RADIUS_PACKET **packet_p;
1543 REQUEST *request = NULL;
1545 listen_socket_t *sock = NULL;
1547 VERIFY_PACKET(packet);
1550 * Set the last packet received.
1552 gettimeofday(&now, NULL);
1554 packet->timestamp = now;
1556 #ifdef WITH_ACCOUNTING
1557 if (listener->type != RAD_LISTEN_DETAIL)
1560 sock = listener->data;
1561 sock->last_packet = now.tv_sec;
1564 packet->proto = sock->proto;
1569 * Skip everything if required.
1571 if (listener->nodup) goto skip_dup;
1573 packet_p = rbtree_finddata(pl, &packet);
1575 rad_child_state_t child_state;
1577 request = fr_packet2myptr(REQUEST, packet, packet_p);
1578 rad_assert(request->in_request_hash);
1579 child_state = request->child_state;
1582 * Same src/dst ip/port, length, and
1583 * authentication vector: must be a duplicate.
1585 if ((request->packet->data_len == packet->data_len) &&
1586 (memcmp(request->packet->vector, packet->vector,
1587 sizeof(packet->vector)) == 0)) {
1590 switch (packet->code) {
1591 case PW_CODE_ACCESS_REQUEST:
1592 FR_STATS_INC(auth, total_dup_requests);
1595 #ifdef WITH_ACCOUNTING
1596 case PW_CODE_ACCOUNTING_REQUEST:
1597 FR_STATS_INC(acct, total_dup_requests);
1601 case PW_CODE_COA_REQUEST:
1602 FR_STATS_INC(coa, total_dup_requests);
1605 case PW_CODE_DISCONNECT_REQUEST:
1606 FR_STATS_INC(dsc, total_dup_requests);
1613 #endif /* WITH_STATS */
1616 * Tell the state machine that there's a
1617 * duplicate request.
1619 request->process(request, FR_ACTION_DUP);
1620 return 0; /* duplicate of live request */
1624 * Mark the request as done ASAP, and before we
1625 * log anything. The child may stop processing
1626 * the request just as we're logging the
1629 request_done(request, FR_ACTION_DONE);
1633 * It's a new request, not a duplicate. If the
1634 * old one is done, then we can clean it up.
1636 if (child_state <= REQUEST_RUNNING) {
1638 * The request is still QUEUED or RUNNING. That's a problem.
1640 ERROR("Received conflicting packet from "
1641 "client %s port %d - ID: %u due to "
1642 "unfinished request. Giving up on old request.",
1644 packet->src_port, packet->id);
1648 * Mark the old request as done. If there's no
1649 * child, the request will be cleaned up
1650 * immediately. If there is a child, we'll set a
1651 * timer to go clean up the request.
1653 } /* else the new packet is unique */
1656 * Quench maximum number of outstanding requests.
1658 if (main_config.max_requests &&
1659 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1660 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1662 packet->src_port, packet->id);
1663 WARN("Please check the configuration file.\n"
1664 "\tThe value for 'max_requests' is probably set too low.\n"));
1666 exec_trigger(NULL, NULL, "server.max_requests", true);
1672 * Rate-limit the incoming packets
1674 if (sock && sock->max_rate) {
1677 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1678 if (pps > sock->max_rate) {
1679 DEBUG("Dropping request due to rate limiting");
1682 sock->rate_pps_now++;
1686 * Allocate a pool for the request.
1689 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1691 talloc_set_name_const(ctx, "request_receive_pool");
1694 * The packet is still allocated from a different
1695 * context, but oh well.
1697 (void) talloc_steal(ctx, packet);
1700 request = request_setup(ctx, listener, packet, client, fun);
1707 * Mark it as a "real" request with a context.
1709 request->options |= RAD_REQUEST_OPTION_CTX;
1712 * Remember the request in the list.
1714 if (!listener->nodup) {
1715 if (!rbtree_insert(pl, &request->packet)) {
1716 RERROR("Failed to insert request in the list of live requests: discarding it");
1717 request_done(request, FR_ACTION_DONE);
1721 request->in_request_hash = true;
1725 * Process it. Send a response, and free it.
1727 if (listener->synchronous) {
1729 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1732 request->listener->decode(request->listener, request);
1733 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1734 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1738 if (request->reply->code != 0) {
1739 request->listener->send(request->listener, request);
1741 RDEBUG("Not sending reply");
1745 * Don't do delayed reject. Oh well.
1747 request_free(request);
1752 * Otherwise, insert it into the state machine.
1753 * The child threads will take care of processing it.
1755 request_queue_or_run(request, request_running);
1761 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1762 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1767 * Create and initialize the new request.
1769 request = request_alloc(ctx);
1774 request->reply = rad_alloc(request, false);
1775 if (!request->reply) {
1777 talloc_free(request);
1781 request->listener = listener;
1782 request->client = client;
1783 request->packet = talloc_steal(request, packet);
1784 request->number = request_num_counter++;
1785 request->priority = listener->type;
1786 request->master_state = REQUEST_ACTIVE;
1787 request->child_state = REQUEST_RUNNING;
1788 #ifdef DEBUG_STATE_MACHINE
1789 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1790 request->number, __FUNCTION__,
1791 child_state_names[request->child_state],
1792 child_state_names[REQUEST_RUNNING]);
1794 #ifdef HAVE_PTHREAD_H
1795 request->child_pid = NO_SUCH_CHILD_PID;
1797 request->handle = fun;
1801 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1802 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1803 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1804 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1805 #ifdef WITH_ACCOUNTING
1806 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1807 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1808 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1811 #endif /* WITH_STATS */
1814 * Status-Server packets go to the head of the queue.
1816 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1819 * Set virtual server identity
1821 if (client->server) {
1822 request->server = client->server;
1823 } else if (listener->server) {
1824 request->server = listener->server;
1826 request->server = NULL;
1829 request->root = &main_config;
1831 request->listener->count++;
1835 * The request passes many of our sanity checks.
1836 * From here on in, if anything goes wrong, we
1837 * send a reject message, instead of dropping the
1842 * Build the reply template from the request.
1845 request->reply->sockfd = request->packet->sockfd;
1846 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1847 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1848 request->reply->dst_port = request->packet->src_port;
1849 request->reply->src_port = request->packet->dst_port;
1850 request->reply->id = request->packet->id;
1851 request->reply->code = 0; /* UNKNOWN code */
1852 memcpy(request->reply->vector, request->packet->vector,
1853 sizeof(request->reply->vector));
1854 request->reply->vps = NULL;
1855 request->reply->data = NULL;
1856 request->reply->data_len = 0;
1862 /***********************************************************************
1866 ***********************************************************************/
1869 * Timer function for all TCP sockets.
1871 static void tcp_socket_timer(void *ctx)
1873 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1874 listen_socket_t *sock = listener->data;
1875 struct timeval end, now;
1877 fr_socket_limit_t *limit;
1881 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1883 fr_event_now(el, &now);
1885 switch (listener->type) {
1887 case RAD_LISTEN_PROXY:
1888 limit = &sock->home->limit;
1892 case RAD_LISTEN_AUTH:
1893 #ifdef WITH_ACCOUNTING
1894 case RAD_LISTEN_ACCT:
1896 limit = &sock->limit;
1904 * If we enforce a lifetime, do it now.
1906 if (limit->lifetime > 0) {
1907 end.tv_sec = sock->opened + limit->lifetime;
1910 if (timercmp(&end, &now, <=)) {
1911 listener->print(listener, buffer, sizeof(buffer));
1912 DEBUG("Reached maximum lifetime on socket %s", buffer);
1918 * Proxy sockets get frozen, so that we don't use
1919 * them for new requests. But we do keep them
1920 * open to listen for replies to requests we had
1923 if (listener->type == RAD_LISTEN_PROXY) {
1924 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1925 if (!fr_packet_list_socket_freeze(proxy_list,
1927 ERROR("Fatal error freezing socket: %s", fr_strerror());
1930 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1935 * Mark the socket as "don't use if at all possible".
1937 listener->status = RAD_LISTEN_STATUS_FROZEN;
1938 event_new_fd(listener);
1947 * Enforce an idle timeout.
1949 if (limit->idle_timeout > 0) {
1950 struct timeval idle;
1952 rad_assert(sock->last_packet != 0);
1953 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1956 if (timercmp(&idle, &now, <=)) {
1957 listener->print(listener, buffer, sizeof(buffer));
1958 DEBUG("Reached idle timeout on socket %s", buffer);
1963 * Enforce the minimum of idle timeout or lifetime.
1965 if (timercmp(&idle, &end, <)) {
1971 * Wake up at t + 0.5s. The code above checks if the timers
1972 * are <= t. This addition gives us a bit of leeway.
1974 end.tv_usec = USEC / 2;
1977 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1978 rad_panic("Failed to insert event");
1985 * Add +/- 2s of jitter, as suggested in RFC 3539
1988 static void add_jitter(struct timeval *when)
1995 jitter ^= (jitter >> 10);
1996 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1999 * Add in ~ (4 * USEC) of jitter.
2001 tv_add(when, jitter);
2005 * Called by socket_del to remove requests with this socket
2007 static int eol_proxy_listener(void *ctx, void *data)
2009 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2010 RADIUS_PACKET **proxy_p = data;
2013 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2014 if (request->proxy_listener != this) return 0;
2017 * The normal "remove_from_proxy_hash" tries to grab the
2018 * proxy mutex. We already have it held, so grabbing it
2019 * again will cause a deadlock. Instead, call the "no
2020 * lock" version of the function.
2022 rad_assert(request->in_proxy_hash == true);
2023 remove_from_proxy_hash_nl(request, false);
2026 * Don't mark it as DONE. The client can retransmit, and
2027 * the packet SHOULD be re-proxied somewhere else.
2029 * Return "2" means that the rbtree code will remove it
2030 * from the tree, and we don't need to do it ourselves.
2034 #endif /* WITH_PROXY */
2036 static int eol_listener(void *ctx, void *data)
2038 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2039 RADIUS_PACKET **packet_p = data;
2042 request = fr_packet2myptr(REQUEST, packet, packet_p);
2043 if (request->listener != this) return 0;
2045 request->master_state = REQUEST_STOP_PROCESSING;
2046 request->process = request_done;
2050 #endif /* WITH_TCP */
2053 /***********************************************************************
2055 * Proxy handlers for the state machine.
2057 ***********************************************************************/
2060 * Called with the proxy mutex held
2062 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2064 VERIFY_REQUEST(request);
2066 if (!request->in_proxy_hash) return;
2068 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2069 request->in_proxy_hash = false;
2072 * On the FIRST reply, decrement the count of outstanding
2073 * requests. Note that this is NOT the count of sent
2074 * packets, but whether or not the home server has
2077 if (request->home_server &&
2078 request->home_server->currently_outstanding) {
2079 request->home_server->currently_outstanding--;
2082 * If we're NOT sending it packets, AND it's been
2083 * a while since we got a response, then we don't
2084 * know if it's alive or dead.
2086 if ((request->home_server->currently_outstanding == 0) &&
2087 (request->home_server->state == HOME_STATE_ALIVE)) {
2088 struct timeval when, now;
2090 when.tv_sec = request->home_server->last_packet_recv ;
2093 timeradd(&when, request_response_window(request), &when);
2094 gettimeofday(&now, NULL);
2097 * last_packet + response_window
2099 * We *administratively* mark the home
2100 * server as "unknown" state, because we
2101 * haven't seen a packet for a while.
2103 if (timercmp(&now, &when, >)) {
2104 request->home_server->state = HOME_STATE_UNKNOWN;
2105 request->home_server->last_packet_sent = 0;
2106 request->home_server->last_packet_recv = 0;
2112 rad_assert(request->proxy_listener != NULL);
2113 request->proxy_listener->count--;
2115 request->proxy_listener = NULL;
2118 * Got from YES in hash, to NO, not in hash while we hold
2119 * the mutex. This guarantees that when another thread
2120 * grabs the mutex, the "not in hash" flag is correct.
2124 static void remove_from_proxy_hash(REQUEST *request)
2126 VERIFY_REQUEST(request);
2129 * Check this without grabbing the mutex because it's a
2130 * lot faster that way.
2132 if (!request->in_proxy_hash) return;
2135 * The "not in hash" flag is definitive. However, if the
2136 * flag says that it IS in the hash, there might still be
2137 * a race condition where it isn't.
2139 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2141 if (!request->in_proxy_hash) {
2142 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2146 remove_from_proxy_hash_nl(request, true);
2148 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2151 static int insert_into_proxy_hash(REQUEST *request)
2155 bool success = false;
2156 void *proxy_listener;
2158 VERIFY_REQUEST(request);
2160 rad_assert(request->proxy != NULL);
2161 rad_assert(request->home_server != NULL);
2162 rad_assert(proxy_list != NULL);
2165 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2166 proxy_listener = NULL;
2167 request->num_proxied_requests = 1;
2168 request->num_proxied_responses = 0;
2170 for (tries = 0; tries < 2; tries++) {
2172 listen_socket_t *sock;
2174 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2175 success = fr_packet_list_id_alloc(proxy_list,
2176 request->home_server->proto,
2177 &request->proxy, &proxy_listener);
2180 if (tries > 0) continue; /* try opening new socket only once */
2182 #ifdef HAVE_PTHREAD_H
2183 if (proxy_no_new_sockets) break;
2186 RDEBUG3("proxy: Trying to open a new listener to the home server");
2187 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2189 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2193 request->proxy->src_port = 0; /* Use any new socket */
2194 proxy_listener = this;
2197 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2199 &sock->other_ipaddr, sock->other_port,
2202 #ifdef HAVE_PTHREAD_H
2203 proxy_no_new_sockets = true;
2205 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2208 * This is bad. However, the
2209 * packet list now supports 256
2210 * open sockets, which should
2211 * minimize this problem.
2213 ERROR("Failed adding proxy socket: %s",
2219 * Add it to the event loop. Ensure that we have
2220 * only one mutex locked at a time.
2222 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2223 radius_update_listener(this);
2224 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2227 if (!proxy_listener || !success) {
2228 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2229 REDEBUG2("proxy: Failed allocating Id for proxied request");
2231 request->proxy_listener = NULL;
2232 request->in_proxy_hash = false;
2236 rad_assert(request->proxy->id >= 0);
2238 request->proxy_listener = proxy_listener;
2239 request->in_proxy_hash = true;
2240 RDEBUG3("proxy: request is now in proxy hash");
2243 * Keep track of maximum outstanding requests to a
2244 * particular home server. 'max_outstanding' is
2245 * enforced in home_server_ldb(), in realms.c.
2247 request->home_server->currently_outstanding++;
2250 request->proxy_listener->count++;
2253 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2255 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2256 inet_ntop(request->proxy->dst_ipaddr.af,
2257 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2258 request->proxy->dst_port,
2259 request->proxy->id);
2264 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2267 int post_proxy_type = 0;
2270 VERIFY_REQUEST(request);
2273 * There may be a proxy reply, but it may be too late.
2275 if (!request->home_server->server && !request->proxy_listener) return 0;
2278 * Delete any reply we had accumulated until now.
2280 RDEBUG2("Clearing existing &reply: attributes");
2281 fr_pair_list_free(&request->reply->vps);
2284 * Run the packet through the post-proxy stage,
2285 * BEFORE playing games with the attributes.
2287 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2289 post_proxy_type = vp->vp_integer;
2291 * If we have a proxy_reply, and it was a reject, or a NAK
2292 * setup Post-Proxy <type>.
2294 * If the <type> doesn't have a section, then the Post-Proxy
2295 * section is ignored.
2298 DICT_VALUE *dval = NULL;
2300 switch (reply->code) {
2301 case PW_CODE_ACCESS_REJECT:
2302 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2303 if (dval) post_proxy_type = dval->value;
2306 case PW_CODE_DISCONNECT_NAK:
2307 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2308 if (dval) post_proxy_type = dval->value;
2311 case PW_CODE_COA_NAK:
2312 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2313 if (dval) post_proxy_type = dval->value;
2321 * Create config:Post-Proxy-Type
2324 vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2325 vp->vp_integer = dval->value;
2329 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2330 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2333 VERIFY_PACKET(reply);
2336 * Decode the packet if required.
2338 if (request->proxy_listener) {
2339 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2340 debug_packet(request, reply, true);
2343 * Pro-actively remove it from the proxy hash.
2344 * This is later than in 2.1.x, but it means that
2345 * the replies are authenticated before being
2346 * removed from the hash.
2349 (request->num_proxied_requests <= request->num_proxied_responses)) {
2350 remove_from_proxy_hash(request);
2353 rad_assert(!request->in_proxy_hash);
2355 } else if (request->in_proxy_hash) {
2356 remove_from_proxy_hash(request);
2359 if (request->home_pool && request->home_pool->virtual_server) {
2360 char const *old_server = request->server;
2362 request->server = request->home_pool->virtual_server;
2363 RDEBUG2("server %s {", request->server);
2365 rcode = process_post_proxy(post_proxy_type, request);
2368 request->server = old_server;
2370 rcode = process_post_proxy(post_proxy_type, request);
2374 if (request->packet->code == request->proxy->code)
2376 * Don't run the next bit if we originated a CoA
2377 * packet, after receiving an Access-Request or
2378 * Accounting-Request.
2383 * There may NOT be a proxy reply, as we may be
2384 * running Post-Proxy-Type = Fail.
2387 fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2390 * Delete the Proxy-State Attributes from
2391 * the reply. These include Proxy-State
2392 * attributes from us and remote server.
2394 fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2398 default: /* Don't do anything */
2400 case RLM_MODULE_FAIL:
2403 case RLM_MODULE_HANDLED:
2410 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2414 home->state = HOME_STATE_ALIVE;
2415 home->response_timeouts = 0;
2416 exec_trigger(request, home->cs, "home_server.alive", false);
2417 home->currently_outstanding = 0;
2418 home->num_sent_pings = 0;
2419 home->num_received_pings = 0;
2420 gettimeofday(&home->revive_time, NULL);
2422 fr_event_delete(el, &home->ev);
2424 RPROXY("Marking home server %s port %d alive",
2425 inet_ntop(request->proxy->dst_ipaddr.af,
2426 &request->proxy->dst_ipaddr.ipaddr,
2427 buffer, sizeof(buffer)),
2428 request->proxy->dst_port);
2432 int request_proxy_reply(RADIUS_PACKET *packet)
2434 RADIUS_PACKET **proxy_p;
2439 VERIFY_PACKET(packet);
2441 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2442 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2445 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2446 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2447 fr_packet_codes[packet->code],
2448 inet_ntop(packet->src_ipaddr.af,
2449 &packet->src_ipaddr.ipaddr,
2450 buffer, sizeof(buffer)),
2451 packet->src_port, packet->id);
2455 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2456 request->num_proxied_responses++; /* needs to be protected by lock */
2458 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2461 * No reply, BUT the current packet fails verification:
2462 * ignore it. This does the MD5 calculations in the
2463 * server core, but I guess we can fix that later.
2465 if (!request->proxy_reply &&
2466 (rad_verify(packet, request->proxy,
2467 request->home_server->secret) != 0)) {
2468 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2473 * The home server sent us a packet which doesn't match
2474 * something we have: ignore it. This is done only to
2475 * catch the case of broken systems.
2477 if (request->proxy_reply &&
2478 (memcmp(request->proxy_reply->vector,
2480 sizeof(request->proxy_reply->vector)) != 0)) {
2481 RDEBUG2("Ignoring conflicting proxy reply");
2485 gettimeofday(&now, NULL);
2488 * Status-Server packets don't count as real packets.
2490 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2491 listen_socket_t *sock = request->proxy_listener->data;
2493 request->home_server->last_packet_recv = now.tv_sec;
2494 sock->last_packet = now.tv_sec;
2498 * If we have previously seen a reply, ignore the
2501 if (request->proxy_reply) {
2502 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2503 inet_ntop(packet->src_ipaddr.af,
2504 &packet->src_ipaddr.ipaddr,
2505 buffer, sizeof(buffer)),
2506 packet->src_port, packet->id);
2511 * Call the state machine to do something useful with the
2514 request->proxy_reply = talloc_steal(request, packet);
2515 packet->timestamp = now;
2516 request->priority = RAD_LISTEN_PROXY;
2520 * Update the proxy listener stats here, because only one
2521 * thread accesses that at a time. The home_server and
2522 * main proxy_*_stats structures are updated once the
2523 * request is cleaned up.
2525 request->proxy_listener->stats.total_responses++;
2527 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2528 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2530 switch (request->proxy->code) {
2531 case PW_CODE_ACCESS_REQUEST:
2532 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2534 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2535 request->proxy_listener->stats.total_access_accepts++;
2537 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2538 request->proxy_listener->stats.total_access_rejects++;
2540 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2541 request->proxy_listener->stats.total_access_challenges++;
2545 #ifdef WITH_ACCOUNTING
2546 case PW_CODE_ACCOUNTING_REQUEST:
2547 request->proxy_listener->stats.total_responses++;
2548 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2554 case PW_CODE_COA_REQUEST:
2555 request->proxy_listener->stats.total_responses++;
2556 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2559 case PW_CODE_DISCONNECT_REQUEST:
2560 request->proxy_listener->stats.total_responses++;
2561 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2571 * If we hadn't been sending the home server packets for
2572 * a while, just mark it alive. Or, if it was zombie,
2573 * it's now responded, and is therefore alive.
2575 if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2576 (request->home_server->state == HOME_STATE_ZOMBIE)) {
2577 mark_home_server_alive(request, request->home_server);
2581 * Tell the request state machine that we have a proxy
2582 * reply. Depending on the function, this should either
2583 * ignore it, or process it.
2585 request->process(request, FR_ACTION_PROXY_REPLY);
2591 static int setup_post_proxy_fail(REQUEST *request)
2593 DICT_VALUE const *dval = NULL;
2596 VERIFY_REQUEST(request);
2598 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2599 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2600 "Fail-Authentication");
2601 #ifdef WITH_ACCOUNTING
2602 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2603 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2608 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2609 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2611 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2612 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2615 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2619 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2622 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2626 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2627 if (!vp) vp = radius_pair_create(request, &request->config,
2628 PW_POST_PROXY_TYPE, 0);
2629 vp->vp_integer = dval->value;
2635 /** Process a request after the proxy has timed out.
2637 * Run the packet through Post-Proxy-Type Fail
2640 * digraph proxy_no_reply {
2643 * proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2644 * proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2645 * proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2646 * proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2647 * proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2651 static void proxy_no_reply(REQUEST *request, int action)
2653 VERIFY_REQUEST(request);
2655 TRACE_STATE_MACHINE;
2660 request_dup(request);
2663 case FR_ACTION_TIMER:
2664 (void) request_max_time(request);
2667 case FR_ACTION_PROXY_REPLY:
2668 proxy_reply_too_late(request);
2672 if (process_proxy_reply(request, NULL)) {
2673 request->handle(request);
2675 request_finish(request, action);
2679 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2684 /** Process the request after receiving a proxy reply.
2686 * Throught the post-proxy section, and the through the handler
2690 * digraph proxy_running {
2693 * proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2694 * proxy_running -> timer [ label = "TIMER < max_request_time" ];
2695 * proxy_running -> process_proxy_reply [ label = "RUN" ];
2696 * proxy_running -> done [ label = "TIMER >= timeout" ];
2700 static void proxy_running(REQUEST *request, int action)
2702 VERIFY_REQUEST(request);
2704 TRACE_STATE_MACHINE;
2709 request_dup(request);
2712 case FR_ACTION_TIMER:
2713 (void) request_max_time(request);
2717 if (process_proxy_reply(request, request->proxy_reply)) {
2718 request->handle(request);
2720 request_finish(request, action);
2723 default: /* duplicate proxy replies are suppressed */
2724 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2729 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2731 * Whether a request will be proxied is determined by the attributes present
2732 * in request->config. If any of the following attributes are found, the
2733 * request may be proxied.
2735 * The key attributes are:
2736 * - PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2737 * - PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2738 * - PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2739 * - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2741 * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2743 * If request should be proxied, will:
2744 * - Add request:Proxy-State
2745 * - Strip the current username value of its realm (depending on config)
2746 * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2748 * - Call the pre-process section in the current server, or in the virtual server
2749 * associated with the home server pool we're proxying to.
2751 * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2752 * specific function.
2754 * @param request The #REQUEST to evaluate for proxying.
2755 * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2757 static int request_will_proxy(REQUEST *request)
2759 int rcode, pre_proxy_type = 0;
2760 char const *realmname = NULL;
2761 VALUE_PAIR *vp, *strippedname;
2762 home_server_t *home;
2763 REALM *realm = NULL;
2764 home_pool_t *pool = NULL;
2766 VERIFY_REQUEST(request);
2768 if (!request->root->proxy_requests) return 0;
2769 if (request->packet->dst_port == 0) return 0;
2770 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2771 if (request->in_proxy_hash) return 0;
2774 * FIXME: for 3.0, allow this only for rejects?
2776 if (request->reply->code != 0) return 0;
2778 vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2780 realm = realm_find2(vp->vp_strvalue);
2782 REDEBUG2("Cannot proxy to unknown realm %s",
2787 realmname = vp->vp_strvalue;
2790 * Figure out which pool to use.
2792 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2793 pool = realm->auth_pool;
2795 #ifdef WITH_ACCOUNTING
2796 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2797 pool = realm->acct_pool;
2801 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2802 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2803 pool = realm->coa_pool;
2810 } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2813 switch (request->packet->code) {
2814 case PW_CODE_ACCESS_REQUEST:
2815 pool_type = HOME_TYPE_AUTH;
2818 #ifdef WITH_ACCOUNTING
2819 case PW_CODE_ACCOUNTING_REQUEST:
2820 pool_type = HOME_TYPE_ACCT;
2825 case PW_CODE_COA_REQUEST:
2826 case PW_CODE_DISCONNECT_REQUEST:
2827 pool_type = HOME_TYPE_COA;
2835 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2838 * Send it directly to a home server (i.e. NAS)
2840 } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2841 ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2843 fr_ipaddr_t dst_ipaddr;
2845 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2847 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2848 dst_ipaddr.af = AF_INET;
2849 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2850 dst_ipaddr.prefix = 32;
2852 dst_ipaddr.af = AF_INET6;
2853 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2854 dst_ipaddr.prefix = 128;
2857 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2859 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2860 dst_port = PW_AUTH_UDP_PORT;
2862 #ifdef WITH_ACCOUNTING
2863 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2864 dst_port = PW_ACCT_UDP_PORT;
2868 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2869 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2870 dst_port = PW_COA_UDP_PORT;
2872 } else { /* shouldn't happen for RADIUS... */
2877 dst_port = vp->vp_integer;
2881 * Nothing does CoA over TCP.
2883 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2887 WARN("No such home server %s port %u",
2888 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2889 (unsigned int) dst_port);
2894 * The home server is alive (or may be alive).
2895 * Send the packet to the IP.
2897 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2900 * The home server is dead. If you wanted
2901 * fail-over, you should have proxied to a pool.
2912 RWDEBUG2("Cancelling proxy as no home pool exists");
2916 if (request->listener->synchronous) {
2917 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2921 request->home_pool = pool;
2923 home = home_server_ldb(realmname, pool, request);
2926 REDEBUG2("Failed to find live home server: Cancelling proxy");
2931 home_server_update_request(home, request);
2935 * Once we've decided to proxy a request, we cannot send
2936 * a CoA packet. So we free up any CoA packet here.
2938 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2942 * Remember that we sent the request to a Realm.
2944 if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2947 * Strip the name, if told to.
2949 * Doing it here catches the case of proxied tunneled
2952 if (realm && (realm->strip_realm == true) &&
2953 (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2955 * If there's a Stripped-User-Name attribute in
2956 * the request, then use THAT as the User-Name
2957 * for the proxied request, instead of the
2960 * This is done by making a copy of the
2961 * Stripped-User-Name attribute, turning it into
2962 * a User-Name attribute, deleting the
2963 * Stripped-User-Name and User-Name attributes
2964 * from the vps list, and making the new
2965 * User-Name the head of the vps list.
2967 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2970 vp = radius_pair_create(NULL, NULL,
2972 rad_assert(vp != NULL); /* handled by above function */
2973 /* Insert at the START of the list */
2974 /* FIXME: Can't make assumptions about ordering */
2975 fr_cursor_init(&cursor, &vp);
2976 fr_cursor_merge(&cursor, request->proxy->vps);
2977 request->proxy->vps = vp;
2979 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
2982 * Do NOT delete Stripped-User-Name.
2987 * If there is no PW_CHAP_CHALLENGE attribute but
2988 * there is a PW_CHAP_PASSWORD we need to add it
2989 * since we can't use the request authenticator
2990 * anymore - we changed it.
2992 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2993 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2994 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2995 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2996 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
3000 * The RFC's say we have to do this, but FreeRADIUS
3003 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3004 fr_pair_value_sprintf(vp, "%u", request->packet->id);
3007 * Should be done BEFORE inserting into proxy hash, as
3008 * pre-proxy may use this information, or change it.
3010 request->proxy->code = request->packet->code;
3013 * Call the pre-proxy routines.
3015 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3017 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3018 /* Must be a validation issue */
3020 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3021 pre_proxy_type = vp->vp_integer;
3025 * home_pool may be NULL when originating CoA packets,
3026 * because they go directly to an IP address.
3028 if (request->home_pool && request->home_pool->virtual_server) {
3029 char const *old_server = request->server;
3031 request->server = request->home_pool->virtual_server;
3033 RDEBUG2("server %s {", request->server);
3035 rcode = process_pre_proxy(pre_proxy_type, request);
3039 request->server = old_server;
3041 rcode = process_pre_proxy(pre_proxy_type, request);
3045 case RLM_MODULE_FAIL:
3046 case RLM_MODULE_INVALID:
3047 case RLM_MODULE_NOTFOUND:
3048 case RLM_MODULE_USERLOCK:
3050 /* FIXME: debug print failed stuff */
3053 case RLM_MODULE_REJECT:
3054 case RLM_MODULE_HANDLED:
3058 * Only proxy the packet if the pre-proxy code succeeded.
3060 case RLM_MODULE_NOOP:
3062 case RLM_MODULE_UPDATED:
3067 static int proxy_to_virtual_server(REQUEST *request)
3071 if (request->packet->dst_port == 0) {
3072 WARN("Cannot proxy an internal request");
3076 DEBUG("Proxying to virtual server %s",
3077 request->home_server->server);
3080 * Packets to virtual servers don't get
3081 * retransmissions sent to them. And the virtual
3082 * server is run ONLY if we have no child
3083 * threads, or we're running in a child thread.
3085 rad_assert(!spawn_flag || !we_are_master());
3087 fake = request_alloc_fake(request);
3089 fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3090 talloc_free(request->proxy);
3092 fake->server = request->home_server->server;
3093 fake->handle = request->handle;
3094 fake->process = NULL; /* should never be run for anything */
3097 * Run the virtual server.
3099 request_running(fake, FR_ACTION_RUN);
3101 request->proxy = talloc_steal(request, fake->packet);
3102 fake->packet = NULL;
3103 request->proxy_reply = talloc_steal(request, fake->reply);
3109 * No reply code, toss the reply we have,
3110 * and do post-proxy-type Fail.
3112 if (!request->proxy_reply->code) {
3113 TALLOC_FREE(request->proxy_reply);
3114 setup_post_proxy_fail(request);
3118 * Do the proxy reply (if any)
3120 if (process_proxy_reply(request, request->proxy_reply)) {
3121 request->handle(request);
3124 return -1; /* so we call request_finish */
3128 static int request_proxy(REQUEST *request, int retransmit)
3132 VERIFY_REQUEST(request);
3134 rad_assert(request->parent == NULL);
3135 rad_assert(request->home_server != NULL);
3137 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3141 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
3142 request_done(request->coa, FR_ACTION_DONE);
3147 * The request may need sending to a virtual server.
3148 * This code is more than a little screwed up. The rest
3149 * of the state machine doesn't handle parent / child
3150 * relationships well. i.e. if the child request takes
3151 * too long, the core will mark the *parent* as "stop
3152 * processing". And the child will continue without
3153 * knowing anything...
3155 * So, we have some horrible hacks to get around that.
3157 if (request->home_server->server) return proxy_to_virtual_server(request);
3160 * We're actually sending a proxied packet. Do that now.
3162 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3163 RPROXY("Failed to insert request into the proxy list");
3167 rad_assert(request->proxy->id >= 0);
3169 if (rad_debug_lvl) {
3170 struct timeval *response_window;
3172 response_window = request_response_window(request);
3175 if (request->home_server->tls) {
3176 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3177 inet_ntop(request->proxy->dst_ipaddr.af,
3178 &request->proxy->dst_ipaddr.ipaddr,
3179 buffer, sizeof(buffer)),
3180 request->proxy->dst_port,
3181 (int) response_window->tv_sec, (int) response_window->tv_usec);
3184 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3185 inet_ntop(request->proxy->dst_ipaddr.af,
3186 &request->proxy->dst_ipaddr.ipaddr,
3187 buffer, sizeof(buffer)),
3188 request->proxy->dst_port,
3189 (int) response_window->tv_sec, (int) response_window->tv_usec);
3194 gettimeofday(&request->proxy_retransmit, NULL);
3196 request->proxy->timestamp = request->proxy_retransmit;
3198 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3201 * Encode the packet before we do anything else.
3203 request->proxy_listener->encode(request->proxy_listener, request);
3204 debug_packet(request, request->proxy, false);
3207 * Set the state function, then the state, no child, and
3210 request->process = proxy_wait_for_reply;
3211 request->child_state = REQUEST_PROXIED;
3215 * And send the packet.
3217 request->proxy_listener->send(request->proxy_listener, request);
3222 * Proxy the packet as if it was new.
3224 static int request_proxy_anew(REQUEST *request)
3226 home_server_t *home;
3228 VERIFY_REQUEST(request);
3231 * Delete the request from the proxy list.
3233 * The packet list code takes care of ensuring that IDs
3234 * aren't reused until all 256 IDs have been used. So
3235 * there's a 1/256 chance of re-using the same ID when
3236 * we're sending to the same home server. Which is
3239 remove_from_proxy_hash(request);
3242 * Find a live home server for the request.
3244 home = home_server_ldb(NULL, request->home_pool, request);
3246 REDEBUG2("Failed to find live home server for request");
3248 if (setup_post_proxy_fail(request)) {
3249 request_queue_or_run(request, proxy_running);
3251 gettimeofday(&request->reply->timestamp, NULL);
3252 request_cleanup_delay_init(request);
3257 #ifdef WITH_ACCOUNTING
3259 * Update the Acct-Delay-Time attribute.
3261 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3264 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3265 if (!vp) vp = radius_pair_create(request->proxy,
3266 &request->proxy->vps,
3267 PW_ACCT_DELAY_TIME, 0);
3271 gettimeofday(&now, NULL);
3272 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3278 * May have failed over to a "fallback" virtual server.
3279 * If so, run that instead of doing proxying to a real
3283 request->home_server = home;
3284 TALLOC_FREE(request->proxy);
3286 (void) proxy_to_virtual_server(request);
3290 home_server_update_request(home, request);
3292 if (!insert_into_proxy_hash(request)) {
3293 RPROXY("Failed to insert retransmission into the proxy list");
3294 goto post_proxy_fail;
3298 * Free the old packet, to force re-encoding
3300 talloc_free(request->proxy->data);
3301 request->proxy->data = NULL;
3302 request->proxy->data_len = 0;
3304 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3310 /** Ping a home server.
3313 static void request_ping(REQUEST *request, int action)
3315 home_server_t *home = request->home_server;
3318 VERIFY_REQUEST(request);
3320 TRACE_STATE_MACHINE;
3324 case FR_ACTION_TIMER:
3325 ERROR("No response to status check %d ID %u for home server %s port %d",
3328 inet_ntop(request->proxy->dst_ipaddr.af,
3329 &request->proxy->dst_ipaddr.ipaddr,
3330 buffer, sizeof(buffer)),
3331 request->proxy->dst_port);
3334 case FR_ACTION_PROXY_REPLY:
3335 rad_assert(request->in_proxy_hash);
3337 request->home_server->num_received_pings++;
3338 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3339 request->number, request->proxy->id, home->num_received_pings);
3342 * Remove the request from any hashes
3344 fr_event_delete(el, &request->ev);
3345 remove_from_proxy_hash(request);
3348 * The control socket may have marked the home server as
3349 * alive. OR, it may have suddenly started responding to
3350 * requests again. If so, don't re-do the "make alive"
3353 if (home->state == HOME_STATE_ALIVE) break;
3356 * It's dead, and we haven't received enough ping
3357 * responses to mark it "alive". Wait a bit.
3359 * If it's zombie, we mark it alive immediately.
3361 if ((home->state == HOME_STATE_IS_DEAD) &&
3362 (home->num_received_pings < home->num_pings_to_alive)) {
3367 * Mark it alive and delete any outstanding
3370 mark_home_server_alive(request, home);
3374 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3378 rad_assert(!request->in_request_hash);
3379 rad_assert(request->ev == NULL);
3381 request_done(request, FR_ACTION_DONE);
3385 * Called from start of zombie period, OR after control socket
3386 * marks the home server dead.
3388 static void ping_home_server(void *ctx)
3390 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3393 struct timeval when, now;
3395 if ((home->state == HOME_STATE_ALIVE) ||
3397 (home->proto == IPPROTO_TCP) ||
3399 (home->ev != NULL)) {
3403 gettimeofday(&now, NULL);
3407 * We've run out of zombie time. Mark it dead.
3409 if (home->state == HOME_STATE_ZOMBIE) {
3410 when = home->zombie_period_start;
3411 when.tv_sec += home->zombie_period;
3413 if (timercmp(&when, &now, <)) {
3414 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3415 mark_home_server_dead(home, &now);
3420 * We're not supposed to be pinging it. Just wake up
3421 * when we're supposed to mark it dead.
3423 if (home->ping_check == HOME_PING_CHECK_NONE) {
3424 if (home->state == HOME_STATE_ZOMBIE) {
3425 home->when = home->zombie_period_start;
3426 home->when.tv_sec += home->zombie_period;
3427 INSERT_EVENT(ping_home_server, home);
3431 * Else mark_home_server_dead will set a timer
3432 * for revive_interval.
3438 request = request_alloc(NULL);
3439 if (!request) return;
3440 request->number = request_num_counter++;
3443 request->proxy = rad_alloc(request, true);
3444 rad_assert(request->proxy != NULL);
3446 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3447 request->proxy->code = PW_CODE_STATUS_SERVER;
3449 fr_pair_make(request->proxy, &request->proxy->vps,
3450 "Message-Authenticator", "0x00", T_OP_SET);
3452 } else if (home->type == HOME_TYPE_AUTH) {
3453 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3455 fr_pair_make(request->proxy, &request->proxy->vps,
3456 "User-Name", home->ping_user_name, T_OP_SET);
3457 fr_pair_make(request->proxy, &request->proxy->vps,
3458 "User-Password", home->ping_user_password, T_OP_SET);
3459 fr_pair_make(request->proxy, &request->proxy->vps,
3460 "Service-Type", "Authenticate-Only", T_OP_SET);
3461 fr_pair_make(request->proxy, &request->proxy->vps,
3462 "Message-Authenticator", "0x00", T_OP_SET);
3465 #ifdef WITH_ACCOUNTING
3466 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3468 fr_pair_make(request->proxy, &request->proxy->vps,
3469 "User-Name", home->ping_user_name, T_OP_SET);
3470 fr_pair_make(request->proxy, &request->proxy->vps,
3471 "Acct-Status-Type", "Stop", T_OP_SET);
3472 fr_pair_make(request->proxy, &request->proxy->vps,
3473 "Acct-Session-Id", "00000000", T_OP_SET);
3474 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3475 "Event-Timestamp", "0", T_OP_SET);
3476 vp->vp_date = now.tv_sec;
3478 rad_assert("Internal sanity check failed");
3482 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3483 "NAS-Identifier", "", T_OP_SET);
3485 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3486 home->num_sent_pings);
3490 request->proxy->proto = home->proto;
3492 request->proxy->src_ipaddr = home->src_ipaddr;
3493 request->proxy->dst_ipaddr = home->ipaddr;
3494 request->proxy->dst_port = home->port;
3495 request->home_server = home;
3496 #ifdef DEBUG_STATE_MACHINE
3497 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3498 child_state_names[request->child_state],
3499 child_state_names[REQUEST_DONE]);
3500 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3502 #ifdef HAVE_PTHREAD_H
3503 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3505 request->child_state = REQUEST_PROXIED;
3506 request->process = request_ping;
3508 rad_assert(request->proxy_listener == NULL);
3510 if (!insert_into_proxy_hash(request)) {
3511 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3514 rad_assert(!request->in_request_hash);
3515 rad_assert(!request->in_proxy_hash);
3516 rad_assert(request->ev == NULL);
3517 talloc_free(request);
3522 * Set up the timer callback.
3525 when.tv_sec += home->ping_timeout;
3527 DEBUG("PING: Waiting %u seconds for response to ping",
3528 home->ping_timeout);
3530 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3531 home->num_sent_pings++;
3533 rad_assert(request->proxy_listener != NULL);
3534 debug_packet(request, request->proxy, false);
3535 request->proxy_listener->send(request->proxy_listener,
3539 * Add +/- 2s of jitter, as suggested in RFC 3539
3540 * and in the Issues and Fixes draft.
3543 home->when.tv_sec += home->ping_interval;
3545 add_jitter(&home->when);
3547 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3548 INSERT_EVENT(ping_home_server, home);
3551 static void home_trigger(home_server_t *home, char const *trigger)
3553 REQUEST *my_request;
3554 RADIUS_PACKET *my_packet;
3556 my_request = talloc_zero(NULL, REQUEST);
3557 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3558 my_request->proxy = my_packet;
3559 my_packet->dst_ipaddr = home->ipaddr;
3560 my_packet->src_ipaddr = home->src_ipaddr;
3562 exec_trigger(my_request, home->cs, trigger, false);
3563 talloc_free(my_request);
3566 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3573 rad_assert((home->state == HOME_STATE_ALIVE) ||
3574 (home->state == HOME_STATE_UNKNOWN));
3577 if (home->proto == IPPROTO_TCP) {
3578 WARN("Not marking TCP server %s zombie", home->log_name);
3584 * We've received a real packet recently. Don't mark the
3585 * server as zombie until we've received NO packets for a
3586 * while. The "1/4" of zombie period was chosen rather
3587 * arbitrarily. It's a balance between too short, which
3588 * gives quick fail-over and fail-back, or too long,
3589 * where the proxy still sends packets to an unresponsive
3592 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3593 if (home->last_packet_recv >= start) {
3594 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3595 (int) (now->tv_sec - home->last_packet_recv));
3599 home->state = HOME_STATE_ZOMBIE;
3600 home_trigger(home, "home_server.zombie");
3603 * Set the home server to "zombie", as of the time
3606 home->zombie_period_start.tv_sec = start;
3607 home->zombie_period_start.tv_usec = USEC / 2;
3609 fr_event_delete(el, &home->ev);
3611 home->num_sent_pings = 0;
3612 home->num_received_pings = 0;
3614 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3615 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3616 buffer, sizeof(buffer)),
3617 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3619 ping_home_server(home);
3623 void revive_home_server(void *ctx)
3625 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3629 rad_assert(home->proto != IPPROTO_TCP);
3632 home->state = HOME_STATE_ALIVE;
3633 home->response_timeouts = 0;
3634 home_trigger(home, "home_server.alive");
3635 home->currently_outstanding = 0;
3636 gettimeofday(&home->revive_time, NULL);
3639 * Delete any outstanding events.
3642 if (home->ev) fr_event_delete(el, &home->ev);
3644 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3645 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3646 buffer, sizeof(buffer)),
3650 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3652 int previous_state = home->state;
3656 if (home->proto == IPPROTO_TCP) {
3657 WARN("Not marking TCP server dead");
3662 PROXY( "Marking home server %s port %d as dead.",
3663 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3664 buffer, sizeof(buffer)),
3667 home->state = HOME_STATE_IS_DEAD;
3668 home_trigger(home, "home_server.dead");
3670 if (home->ping_check != HOME_PING_CHECK_NONE) {
3672 * If the control socket marks us dead, start
3673 * pinging. Otherwise, we already started
3674 * pinging when it was marked "zombie".
3676 if (previous_state == HOME_STATE_ALIVE) {
3677 ping_home_server(home);
3679 DEBUG("PING: Already pinging home server %s", home->log_name);
3684 * Revive it after a fixed period of time. This
3685 * is very, very, bad.
3688 home->when.tv_sec += home->revive_interval;
3690 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3692 INSERT_EVENT(revive_home_server, home);
3696 /** Wait for a reply after proxying a request.
3698 * Retransmit the proxied packet, or time out and go to
3699 * proxy_no_reply. Mark the home server unresponsive, etc.
3701 * If we do receive a reply, we transition to proxy_running.
3704 * digraph proxy_wait_for_reply {
3705 * proxy_wait_for_reply;
3707 * proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3708 * proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3709 * proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3710 * proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3711 * proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3715 static void proxy_wait_for_reply(REQUEST *request, int action)
3717 struct timeval now, when;
3718 struct timeval *response_window = NULL;
3719 home_server_t *home = request->home_server;
3722 VERIFY_REQUEST(request);
3724 TRACE_STATE_MACHINE;
3727 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3728 rad_assert(request->home_server != NULL);
3730 gettimeofday(&now, NULL);
3735 * We have a reply, ignore the retransmit.
3737 if (request->proxy_reply) return;
3740 * The request was proxied to a virtual server.
3741 * Ignore the retransmit.
3743 if (request->home_server->server) return;
3746 * Use a new connection when the home server is
3747 * dead, or when there's no proxy listener, or
3748 * when the listener is failed or dead.
3750 * If the listener is known or frozen, use it for
3753 if ((home->state == HOME_STATE_IS_DEAD) ||
3754 !request->proxy_listener ||
3755 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3756 request_proxy_anew(request);
3762 * The home server is still alive, but TCP. We
3763 * rely on TCP to get the request and reply back.
3764 * So there's no need to retransmit.
3766 if (home->proto == IPPROTO_TCP) {
3767 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3768 inet_ntop(request->proxy->dst_ipaddr.af,
3769 &request->proxy->dst_ipaddr.ipaddr,
3770 buffer, sizeof(buffer)),
3771 request->proxy->dst_port,
3772 request->proxy->id);
3778 * More than one retransmit a second is stupid,
3779 * and should be suppressed by the proxy.
3781 when = request->proxy_retransmit;
3784 if (timercmp(&now, &when, <)) {
3785 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3786 inet_ntop(request->proxy->dst_ipaddr.af,
3787 &request->proxy->dst_ipaddr.ipaddr,
3788 buffer, sizeof(buffer)),
3789 request->proxy->dst_port,
3790 request->proxy->id);
3794 #ifdef WITH_ACCOUNTING
3796 * If we update the Acct-Delay-Time, we need to
3799 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3800 fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3801 request_proxy_anew(request);
3806 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3807 inet_ntop(request->proxy->dst_ipaddr.af,
3808 &request->proxy->dst_ipaddr.ipaddr,
3809 buffer, sizeof(buffer)),
3810 request->proxy->dst_port,
3811 request->proxy->id);
3812 request->num_proxied_requests++;
3814 rad_assert(request->proxy_listener != NULL);
3815 FR_STATS_TYPE_INC(home->stats.total_requests);
3816 home->last_packet_sent = now.tv_sec;
3817 request->proxy_retransmit = now;
3818 debug_packet(request, request->proxy, false);
3819 request->proxy_listener->send(request->proxy_listener, request);
3822 case FR_ACTION_TIMER:
3823 response_window = request_response_window(request);
3826 if (!request->proxy_listener ||
3827 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3828 remove_from_proxy_hash(request);
3830 when = request->packet->timestamp;
3831 when.tv_sec += request->root->max_request_time;
3833 if (timercmp(&when, &now, >)) {
3834 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3835 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3842 * Wake up "response_window" time in the future.
3843 * i.e. when MY packet hasn't received a response.
3845 * Note that we DO NOT mark the home server as
3846 * zombie if it doesn't respond to us. It may be
3847 * responding to other (better looking) packets.
3849 when = request->proxy->timestamp;
3850 timeradd(&when, response_window, &when);
3853 * Not at the response window. Set the timer for
3856 if (timercmp(&when, &now, >)) {
3857 struct timeval diff;
3858 timersub(&when, &now, &diff);
3860 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3861 (int) diff.tv_sec, (int) diff.tv_usec);
3862 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3867 RDEBUG("No proxy response, giving up on request and marking it done");
3870 * If we haven't received any packets for
3871 * "response_window", then mark the home server
3874 * If the connection is TCP, then another
3875 * "watchdog timer" function takes care of pings,
3876 * etc. So we don't need to do it here.
3878 * This check should really be part of a home
3879 * server state machine.
3881 if (((home->state == HOME_STATE_ALIVE) ||
3882 (home->state == HOME_STATE_UNKNOWN))
3884 && (home->proto != IPPROTO_TCP)
3887 home->response_timeouts++;
3888 if (home->response_timeouts >= home->max_response_timeouts)
3889 mark_home_server_zombie(home, &now, response_window);
3892 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3893 if (home->type == HOME_TYPE_AUTH) {
3894 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3895 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3898 else if (home->type == HOME_TYPE_ACCT) {
3899 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3900 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3905 * There was no response within the window. Stop
3906 * the request. If the client retransmitted, it
3907 * may have failed over to another home server.
3908 * But that one may be dead, too.
3910 * The extra verbose message if we have a username,
3911 * is extremely useful if the proxy is part of a chain
3912 * and the final home server, is not the one we're
3915 if (request->username) {
3916 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3917 "server %s port %d",
3918 request->username->vp_strvalue,
3919 inet_ntop(request->proxy->dst_ipaddr.af,
3920 &request->proxy->dst_ipaddr.ipaddr,
3921 buffer, sizeof(buffer)),
3922 request->proxy->dst_port);
3924 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3925 inet_ntop(request->proxy->dst_ipaddr.af,
3926 &request->proxy->dst_ipaddr.ipaddr,
3927 buffer, sizeof(buffer)),
3928 request->proxy->dst_port);
3931 if (setup_post_proxy_fail(request)) {
3932 request_queue_or_run(request, proxy_no_reply);
3934 gettimeofday(&request->reply->timestamp, NULL);
3935 request_cleanup_delay_init(request);
3940 * We received a new reply. Go process it.
3942 case FR_ACTION_PROXY_REPLY:
3943 request_queue_or_run(request, proxy_running);
3947 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3951 #endif /* WITH_PROXY */
3954 /***********************************************************************
3958 ***********************************************************************/
3960 static int null_handler(UNUSED REQUEST *request)
3966 * See if we need to originate a CoA request.
3968 static void request_coa_originate(REQUEST *request)
3970 int rcode, pre_proxy_type = 0;
3976 VERIFY_REQUEST(request);
3978 rad_assert(request->coa != NULL);
3979 rad_assert(request->proxy == NULL);
3980 rad_assert(!request->in_proxy_hash);
3981 rad_assert(request->proxy_reply == NULL);
3984 * Check whether we want to originate one, or cancel one.
3986 vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3988 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3992 if (vp->vp_integer == 0) {
3994 TALLOC_FREE(request->coa);
4002 * src_ipaddr will be set up in proxy_encode.
4004 memset(&ipaddr, 0, sizeof(ipaddr));
4005 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4007 ipaddr.af = AF_INET;
4008 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4010 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4011 ipaddr.af = AF_INET6;
4012 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4013 ipaddr.prefix = 128;
4014 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4015 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4017 if (!coa->home_pool) {
4018 RWDEBUG2("No such home_server_pool %s",
4024 * Prefer the pool to one server
4026 } else if (request->client->coa_pool) {
4027 coa->home_pool = request->client->coa_pool;
4029 } else if (request->client->coa_server) {
4030 coa->home_server = request->client->coa_server;
4034 * If all else fails, send it to the client that
4035 * originated this request.
4037 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4041 * Use the pool, if it exists.
4043 if (coa->home_pool) {
4044 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4045 if (!coa->home_server) {
4046 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4049 home_server_update_request(coa->home_server, coa);
4051 } else if (!coa->home_server) {
4052 uint16_t port = PW_COA_UDP_PORT;
4054 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4055 if (vp) port = vp->vp_integer;
4057 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4058 if (!coa->home_server) {
4059 RWDEBUG2("Unknown destination %s:%d for CoA request.",
4060 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4061 buffer, sizeof(buffer)), port);
4066 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4068 switch (vp->vp_integer) {
4069 case PW_CODE_COA_REQUEST:
4070 case PW_CODE_DISCONNECT_REQUEST:
4071 coa->proxy->code = vp->vp_integer;
4075 DEBUG("Cannot set CoA Packet-Type to code %d",
4081 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4084 * The rest of the server code assumes that
4085 * request->packet && request->reply exist. Copy them
4086 * from the original request.
4088 rad_assert(coa->packet != NULL);
4089 rad_assert(coa->packet->vps == NULL);
4091 coa->packet = rad_copy_packet(coa, request->packet);
4092 coa->reply = rad_copy_packet(coa, request->reply);
4094 coa->config = fr_pair_list_copy(coa, request->config);
4095 coa->num_coa_requests = 0;
4096 coa->handle = null_handler;
4097 coa->number = request->number; /* it's associated with the same request */
4100 * Call the pre-proxy routines.
4102 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4104 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4105 /* Must be a validation issue */
4107 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4108 pre_proxy_type = vp->vp_integer;
4111 if (coa->home_pool && coa->home_pool->virtual_server) {
4112 char const *old_server = coa->server;
4114 coa->server = coa->home_pool->virtual_server;
4115 RDEBUG2("server %s {", coa->server);
4117 rcode = process_pre_proxy(pre_proxy_type, coa);
4120 coa->server = old_server;
4122 rcode = process_pre_proxy(pre_proxy_type, coa);
4129 * Only send the CoA packet if the pre-proxy code succeeded.
4131 case RLM_MODULE_NOOP:
4133 case RLM_MODULE_UPDATED:
4138 * Source IP / port is set when the proxy socket
4141 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4142 coa->proxy->dst_port = coa->home_server->port;
4144 if (!insert_into_proxy_hash(coa)) {
4145 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4150 * We CANNOT divorce the CoA request from the parent
4151 * request. This function is running in a child thread,
4152 * and we need access to the main event loop in order to
4153 * to add the timers for the CoA packet.
4155 * Instead, we wait for the timer on the parent request
4158 gettimeofday(&coa->proxy->timestamp, NULL);
4159 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4160 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4161 coa->delay = 0; /* need to calculate a new delay */
4164 * If requested, put a State attribute into the packet,
4165 * and cache the VPS.
4167 fr_state_put_vps(coa, NULL, coa->packet);
4170 * Encode the packet before we do anything else.
4172 coa->proxy_listener->encode(coa->proxy_listener, coa);
4173 debug_packet(coa, coa->proxy, false);
4175 #ifdef DEBUG_STATE_MACHINE
4176 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4177 child_state_names[request->child_state],
4178 child_state_names[REQUEST_PROXIED]);
4182 * Set the state function, then the state, no child, and
4185 coa->process = coa_wait_for_reply;
4186 coa->child_state = REQUEST_PROXIED;
4188 #ifdef HAVE_PTHREAD_H
4189 coa->child_pid = NO_SUCH_CHILD_PID;
4192 if (we_are_master()) coa_separate(request->coa);
4195 * And send the packet.
4197 coa->proxy_listener->send(coa->proxy_listener, coa);
4201 static void coa_retransmit(REQUEST *request)
4203 uint32_t delay, frac;
4204 struct timeval now, when, mrd;
4207 VERIFY_REQUEST(request);
4209 fr_event_now(el, &now);
4211 if (request->delay == 0) {
4213 * Implement re-transmit algorithm as per RFC 5080
4216 * We want IRT + RAND*IRT
4217 * or 0.9 IRT + rand(0,.2) IRT
4219 * 2^20 ~ USEC, and we want 2.
4220 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4222 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4223 request->delay = delay * request->home_server->coa_irt;
4224 delay = request->home_server->coa_irt * USEC;
4225 delay -= delay / 10;
4226 delay += request->delay;
4227 request->delay = delay;
4229 when = request->proxy->timestamp;
4230 tv_add(&when, delay);
4232 if (timercmp(&when, &now, >)) {
4233 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4239 * Retransmit CoA request.
4243 * Cap count at MRC, if it is non-zero.
4245 if (request->home_server->coa_mrc &&
4246 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4247 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4249 inet_ntop(request->proxy->dst_ipaddr.af,
4250 &request->proxy->dst_ipaddr.ipaddr,
4251 buffer, sizeof(buffer)),
4252 request->proxy->dst_port);
4254 if (setup_post_proxy_fail(request)) {
4255 request_queue_or_run(request, coa_no_reply);
4257 request_done(request, FR_ACTION_DONE);
4263 * RFC 5080 Section 2.2.1
4265 * RT = 2*RTprev + RAND*RTprev
4266 * = 1.9 * RTprev + rand(0,.2) * RTprev
4267 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4270 delay ^= (delay >> 16);
4272 frac = request->delay / 5;
4273 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4275 delay += (2 * request->delay) - (request->delay / 10);
4278 * Cap delay at MRT, if MRT is non-zero.
4280 if (request->home_server->coa_mrt &&
4281 (delay > (request->home_server->coa_mrt * USEC))) {
4282 int mrt_usec = request->home_server->coa_mrt * USEC;
4285 * delay = MRT + RAND * MRT
4286 * = 0.9 MRT + rand(0,.2) * MRT
4289 delay ^= (delay >> 15);
4291 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4292 delay += mrt_usec - (mrt_usec / 10);
4295 request->delay = delay;
4297 tv_add(&when, request->delay);
4298 mrd = request->proxy->timestamp;
4299 mrd.tv_sec += request->home_server->coa_mrd;
4302 * Cap duration at MRD.
4304 if (timercmp(&mrd, &when, <)) {
4307 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4309 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4311 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4313 RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4314 inet_ntop(request->proxy->dst_ipaddr.af,
4315 &request->proxy->dst_ipaddr.ipaddr,
4316 buffer, sizeof(buffer)),
4317 request->proxy->dst_port,
4318 request->proxy->id);
4320 request->proxy_listener->send(request->proxy_listener,
4325 /** Wait for a reply after originating a CoA a request.
4327 * Retransmit the proxied packet, or time out and go to
4328 * coa_no_reply. Mark the home server unresponsive, etc.
4330 * If we do receive a reply, we transition to coa_running.
4333 * digraph coa_wait_for_reply {
4334 * coa_wait_for_reply;
4336 * coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4337 * coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4338 * coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4339 * coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4343 static void coa_wait_for_reply(REQUEST *request, int action)
4345 VERIFY_REQUEST(request);
4347 TRACE_STATE_MACHINE;
4351 if (request->parent) coa_separate(request);
4354 case FR_ACTION_TIMER:
4355 if (request_max_time(request)) break;
4357 coa_retransmit(request);
4360 case FR_ACTION_PROXY_REPLY:
4361 request_queue_or_run(request, coa_running);
4365 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4370 static void coa_separate(REQUEST *request)
4372 VERIFY_REQUEST(request);
4373 #ifdef DEBUG_STATE_MACHINE
4374 int action = FR_ACTION_TIMER;
4377 TRACE_STATE_MACHINE;
4380 rad_assert(request->parent != NULL);
4381 rad_assert(request->parent->coa == request);
4382 rad_assert(request->ev == NULL);
4383 rad_assert(!request->in_request_hash);
4384 rad_assert(request->coa == NULL);
4386 rad_assert(request->proxy_reply || request->proxy_listener);
4388 (void) talloc_steal(NULL, request);
4389 request->parent->coa = NULL;
4390 request->parent = NULL;
4392 if (we_are_master()) {
4394 coa_retransmit(request);
4399 /** Process a request after the CoA has timed out.
4401 * Run the packet through Post-Proxy-Type Fail
4404 * digraph coa_no_reply {
4407 * coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4408 * coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4409 * coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4410 * coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4411 * coa_no_reply -> done [ label = "TIMER >= timeout" ];
4415 static void coa_no_reply(REQUEST *request, int action)
4419 VERIFY_REQUEST(request);
4421 TRACE_STATE_MACHINE;
4425 case FR_ACTION_TIMER:
4426 (void) request_max_time(request);
4429 case FR_ACTION_PROXY_REPLY: /* too late! */
4430 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4431 inet_ntop(request->proxy->src_ipaddr.af,
4432 &request->proxy->src_ipaddr.ipaddr,
4433 buffer, sizeof(buffer)),
4434 request->proxy->dst_port, request->proxy->id);
4438 if (process_proxy_reply(request, NULL)) {
4439 request->handle(request);
4441 request_done(request, FR_ACTION_DONE);
4445 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4451 /** Process the request after receiving a coa reply.
4453 * Throught the post-proxy section, and the through the handler
4457 * digraph coa_running {
4460 * coa_running -> timer [ label = "TIMER < max_request_time" ];
4461 * coa_running -> process_proxy_reply [ label = "RUN" ];
4462 * coa_running -> done [ label = "TIMER >= timeout" ];
4466 static void coa_running(REQUEST *request, int action)
4468 VERIFY_REQUEST(request);
4470 TRACE_STATE_MACHINE;
4474 case FR_ACTION_TIMER:
4475 (void) request_max_time(request);
4479 if (process_proxy_reply(request, request->proxy_reply)) {
4480 request->handle(request);
4482 request_done(request, FR_ACTION_DONE);
4486 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4490 #endif /* WITH_COA */
4492 /***********************************************************************
4494 * End of the State machine. Start of additional helper code.
4496 ***********************************************************************/
4498 /***********************************************************************
4502 ***********************************************************************/
4503 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4505 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4507 rad_assert(xel == el);
4509 if ((listener->fd < 0)
4511 #ifndef WITH_DETAIL_THREAD
4512 && (listener->type != RAD_LISTEN_DETAIL)
4518 listener->print(listener, buffer, sizeof(buffer));
4519 ERROR("FATAL: Asked to read from closed socket: %s",
4522 rad_panic("Socket was closed on us!");
4526 listener->recv(listener);
4530 #ifdef WITH_DETAIL_THREAD
4533 * This function is called periodically to see if this detail
4534 * file is available for reading.
4536 static void event_poll_detail(void *ctx)
4539 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4540 struct timeval when, now;
4541 listen_detail_t *detail = this->data;
4543 rad_assert(this->type == RAD_LISTEN_DETAIL);
4546 event_socket_handler(el, this->fd, this);
4548 fr_event_now(el, &now);
4552 * Backdoor API to get the delay until the next poll
4555 delay = this->encode(this, NULL);
4556 if (delay == 0) goto redo;
4558 tv_add(&when, delay);
4561 if (!fr_event_insert(el, event_poll_detail, this,
4562 &when, &detail->ev)) {
4563 ERROR("Failed creating handler");
4567 #endif /* WITH_DETAIL_THREAD */
4568 #endif /* WITH_DETAIL */
4570 static void event_status(struct timeval *wake)
4572 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4576 if (rad_debug_lvl == 0) {
4578 INFO("Ready to process requests");
4579 just_started = false;
4585 INFO("Ready to process requests");
4587 } else if ((wake->tv_sec != 0) ||
4588 (wake->tv_usec >= 100000)) {
4589 DEBUG("Waking up in %d.%01u seconds.",
4590 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4595 * FIXME: Put this somewhere else, where it isn't called
4596 * all of the time...
4599 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4601 * If there are no child threads, then there may
4602 * be child processes. In that case, wait for
4603 * their exit status, and throw that exit status
4604 * away. This helps get rid of zxombie children.
4606 while (waitpid(-1, &argval, WNOHANG) > 0) {
4614 static void listener_free_cb(void *ctx)
4616 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4619 if (this->count > 0) {
4620 struct timeval when;
4621 listen_socket_t *sock = this->data;
4623 fr_event_now(el, &when);
4627 if (!fr_event_insert(el, listener_free_cb, this, &when,
4629 rad_panic("Failed to insert event");
4636 * It's all free, close the socket.
4639 this->print(this, buffer, sizeof(buffer));
4640 DEBUG("... cleaning up socket %s", buffer);
4641 rad_assert(this->next == NULL);
4647 static int proxy_eol_cb(void *ctx, void *data)
4649 struct timeval when;
4650 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4652 if (request->proxy_listener != ctx) return 0;
4655 * We don't care if it's being processed in a child thread.
4658 #ifdef WITH_ACCOUNTING
4660 * Accounting packets should be deleted immediately.
4661 * They will never be retransmitted by the client.
4663 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4664 RDEBUG("Stopping request due to failed connection to home server");
4665 request->master_state = REQUEST_STOP_PROCESSING;
4670 * Reset the timer to be now, so that the request is
4671 * quickly updated. But spread the requests randomly
4672 * over the next second, so that we don't overload the
4675 fr_event_now(el, &when);
4676 tv_add(&when, fr_rand() % USEC);
4677 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4680 * Don't delete it from the list.
4686 static int event_new_fd(rad_listen_t *this)
4692 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4694 this->print(this, buffer, sizeof(buffer));
4696 if (this->status == RAD_LISTEN_STATUS_INIT) {
4697 listen_socket_t *sock = this->data;
4699 rad_assert(sock != NULL);
4701 DEBUG("Listening on %s", buffer);
4703 INFO(" ... adding new socket %s", buffer);
4707 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4708 home_server_t *home;
4711 if (!home || !home->limit.max_connections) {
4712 INFO(" ... adding new socket %s", buffer);
4714 INFO(" ... adding new socket %s (%u of %u)", buffer,
4715 home->limit.num_connections, home->limit.max_connections);
4721 switch (this->type) {
4724 * Detail files are always known, and aren't
4725 * put into the socket event loop.
4727 case RAD_LISTEN_DETAIL:
4728 this->status = RAD_LISTEN_STATUS_KNOWN;
4730 #ifndef WITH_DETAIL_THREAD
4732 * Set up the first poll interval.
4734 event_poll_detail(this);
4737 break; /* add the FD to the list */
4739 #endif /* WITH_DETAIL */
4743 * Add it to the list of sockets we can use.
4744 * Server sockets (i.e. auth/acct) are never
4745 * added to the packet list.
4747 case RAD_LISTEN_PROXY:
4749 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4752 * Add timers to outgoing child sockets, if necessary.
4754 if (sock->proto == IPPROTO_TCP && sock->opened &&
4755 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4756 struct timeval when;
4758 when.tv_sec = sock->opened + 1;
4762 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4764 rad_panic("Failed to insert event");
4769 #endif /* WITH_PROXY */
4772 * FIXME: put idle timers on command sockets.
4778 * Add timers to incoming child sockets, if necessary.
4780 if (sock->proto == IPPROTO_TCP && sock->opened &&
4781 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4782 struct timeval when;
4784 when.tv_sec = sock->opened + 1;
4788 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4790 ERROR("Failed adding timer for socket: %s", fr_strerror());
4796 } /* switch over listener types */
4799 * All sockets: add the FD to the event handler.
4801 if (!fr_event_fd_insert(el, 0, this->fd,
4802 event_socket_handler, this)) {
4803 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4807 this->status = RAD_LISTEN_STATUS_KNOWN;
4813 * The socket has reached a timeout. Try to close it.
4815 if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4817 * Requests are still using the socket. Wait for
4820 if (this->count > 0) {
4821 struct timeval when;
4822 listen_socket_t *sock = this->data;
4825 * Try again to clean up the socket in 30
4828 gettimeofday(&when, NULL);
4832 if (!fr_event_insert(el,
4833 (fr_event_callback_t) event_new_fd,
4834 this, &when, &sock->ev)) {
4835 rad_panic("Failed to insert event");
4841 fr_event_fd_delete(el, 0, this->fd);
4842 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4846 * The socket has had a catastrophic error. Close it.
4848 if (this->status == RAD_LISTEN_STATUS_EOL) {
4850 * Remove it from the list of live FD's.
4852 fr_event_fd_delete(el, 0, this->fd);
4856 * Tell all requests using this socket that the socket is dead.
4858 if (this->type == RAD_LISTEN_PROXY) {
4859 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4860 if (!fr_packet_list_socket_freeze(proxy_list,
4862 ERROR("Fatal error freezing socket: %s", fr_strerror());
4866 if (this->count > 0) {
4867 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4869 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4874 * Requests are still using the socket. Wait for
4877 if (this->count > 0) {
4878 struct timeval when;
4879 listen_socket_t *sock = this->data;
4882 * Try again to clean up the socket in 30
4885 gettimeofday(&when, NULL);
4889 if (!fr_event_insert(el,
4890 (fr_event_callback_t) event_new_fd,
4891 this, &when, &sock->ev)) {
4892 rad_panic("Failed to insert event");
4899 * No one is using the socket. We can remove it now.
4901 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4902 } /* socket is at EOL */
4908 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4911 listen_socket_t *sock = this->data;
4913 struct timeval when;
4916 * Re-open the socket, pointing it to /dev/null.
4917 * This means that all writes proceed without
4918 * blocking, and all reads return "no data".
4920 * This leaves the socket active, so any child
4921 * threads won't go insane. But it means that
4922 * they cannot send or receive any packets.
4924 * This is EXTRA work in the normal case, when
4925 * sockets are closed without error. But it lets
4926 * us have one simple processing method for all
4929 devnull = open("/dev/null", O_RDWR);
4931 ERROR("FATAL failure opening /dev/null: %s",
4932 fr_syserror(errno));
4935 if (dup2(devnull, this->fd) < 0) {
4936 ERROR("FATAL failure closing socket: %s",
4937 fr_syserror(errno));
4943 rad_assert(this->type != RAD_LISTEN_DETAIL);
4949 * The socket is dead. Force all proxied packets
4950 * to stop using it. And then remove it from the
4951 * list of outgoing sockets.
4953 if (this->type == RAD_LISTEN_PROXY) {
4954 home_server_t *home;
4957 if (!home || !home->limit.max_connections) {
4958 INFO(" ... shutting down socket %s", buffer);
4960 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4961 home->limit.num_connections, home->limit.max_connections);
4964 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4965 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4967 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4968 ERROR("Fatal error removing socket %s: %s",
4969 buffer, fr_strerror());
4972 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4976 INFO(" ... shutting down socket %s", buffer);
4979 * EOL all requests using this socket.
4981 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4985 * No child threads, clean it up now.
4989 if (sock->ev) fr_event_delete(el, &sock->ev);
4995 * Wait until all requests using this socket are done.
4997 gettimeofday(&when, NULL);
5001 if (!fr_event_insert(el, listener_free_cb, this, &when,
5003 rad_panic("Failed to insert event");
5006 #endif /* WITH_TCP */
5011 /***********************************************************************
5015 ***********************************************************************/
5017 static void handle_signal_self(int flag)
5021 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5022 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5023 INFO("Signalled to exit");
5024 fr_event_loop_exit(el, 1);
5026 INFO("Signalled to terminate");
5027 fr_event_loop_exit(el, 2);
5031 } /* else exit/term flags weren't set */
5034 * Tell the even loop to stop processing.
5036 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5038 static time_t last_hup = 0;
5041 if ((int) (when - last_hup) < 5) {
5042 INFO("Ignoring HUP (less than 5s since last one)");
5046 INFO("Received HUP signal");
5050 exec_trigger(NULL, NULL, "server.signal.hup", true);
5051 fr_event_loop_exit(el, 0x80);
5054 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5055 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5059 * FIXME: O(N) loops suck.
5061 for (this = main_config.listen;
5063 this = this->next) {
5064 if (this->type != RAD_LISTEN_DETAIL) continue;
5067 * This one didn't send the signal, skip
5070 if (!this->decode(this, NULL)) continue;
5073 * Go service the interrupt.
5075 event_poll_detail(this);
5080 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5082 * There are new listeners in the list. Run
5083 * event_new_fd() on them.
5085 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5086 rad_listen_t *this, *next;
5088 FD_MUTEX_LOCK(&fd_mutex);
5091 * FIXME: unlock the mutex before calling
5094 for (this = new_listeners; this != NULL; this = next) {
5101 new_listeners = NULL;
5102 FD_MUTEX_UNLOCK(&fd_mutex);
5107 #ifndef HAVE_PTHREAD_H
5108 void radius_signal_self(int flag)
5110 return handle_signal_self(flag);
5114 static int self_pipe[2] = { -1, -1 };
5117 * Inform ourselves that we received a signal.
5119 void radius_signal_self(int flag)
5125 * The read MUST be non-blocking for this to work.
5127 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5131 for (i = 0; i < rcode; i++) {
5132 buffer[0] |= buffer[i];
5140 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5144 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5145 UNUSED int fd, UNUSED void *ctx)
5150 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5151 if (rcode <= 0) return;
5154 * Merge pending signals.
5156 for (i = 0; i < rcode; i++) {
5157 buffer[0] |= buffer[i];
5160 handle_signal_self(buffer[0]);
5162 #endif /* HAVE_PTHREAD_H */
5164 /***********************************************************************
5166 * Bootstrapping code.
5168 ***********************************************************************/
5171 * Externally-visibly functions.
5173 int radius_event_init(TALLOC_CTX *ctx) {
5174 el = fr_event_list_create(ctx, event_status);
5180 static int packet_entry_cmp(void const *one, void const *two)
5182 RADIUS_PACKET const * const *a = one;
5183 RADIUS_PACKET const * const *b = two;
5185 return fr_packet_cmp(*a, *b);
5190 * They haven't defined a proxy listener. Automatically
5191 * add one for them, with the correct address family.
5193 static void create_default_proxy_listener(int af)
5197 listen_socket_t *sock;
5200 memset(&home, 0, sizeof(home));
5203 * Open a default UDP port
5205 home.proto = IPPROTO_UDP;
5209 * Set the address family.
5211 home.src_ipaddr.af = af;
5212 home.ipaddr.af = af;
5215 * Get the correct listener.
5217 this = proxy_new_listener(proxy_ctx, &home, port);
5223 if (!fr_packet_list_socket_add(proxy_list, this->fd,
5225 &sock->other_ipaddr, sock->other_port,
5227 ERROR("Failed adding proxy socket");
5232 * Insert the FD into list of FDs to listen on.
5234 radius_update_listener(this);
5238 * See if we automatically need to open a proxy socket.
5240 static void check_proxy(rad_listen_t *head)
5243 bool has_v4, has_v6;
5246 if (check_config) return;
5247 if (!main_config.proxy_requests) return;
5249 if (!home_servers_udp) return;
5252 * We passed "-i" on the command line. Use that address
5253 * family for the proxy socket.
5255 if (main_config.myip.af != AF_UNSPEC) {
5256 create_default_proxy_listener(main_config.myip.af);
5260 defined_proxy = has_v4 = has_v6 = false;
5263 * Figure out if we need to open a proxy socket, and if
5266 for (this = head; this != NULL; this = this->next) {
5267 listen_socket_t *sock;
5269 switch (this->type) {
5270 case RAD_LISTEN_PROXY:
5271 defined_proxy = true;
5274 case RAD_LISTEN_AUTH:
5276 case RAD_LISTEN_ACCT:
5279 case RAD_LISTEN_COA:
5282 if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5283 if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5292 * Assume they know what they're doing.
5294 if (defined_proxy) return;
5296 if (has_v4) create_default_proxy_listener(AF_INET);
5298 if (has_v6) create_default_proxy_listener(AF_INET6);
5302 int radius_event_start(CONF_SECTION *cs, bool have_children)
5304 rad_listen_t *head = NULL;
5306 if (fr_start_time != (time_t)-1) return 0;
5308 time(&fr_start_time);
5310 if (!check_config) {
5312 * radius_event_init() must be called first
5316 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5317 if (!pl) return 0; /* leak el */
5320 request_num_counter = 0;
5323 if (main_config.proxy_requests && !check_config) {
5325 * Create the tree for managing proxied requests and
5328 proxy_list = fr_packet_list_create(1);
5329 if (!proxy_list) return 0;
5331 #ifdef HAVE_PTHREAD_H
5332 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5333 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5334 fr_syserror(errno));
5340 * The "init_delay" is set to "response_window".
5341 * Reset it to half of "response_window" in order
5342 * to give the event loop enough time to service
5343 * the event before hitting "response_window".
5345 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5346 main_config.init_delay.tv_usec >>= 1;
5347 main_config.init_delay.tv_sec >>= 1;
5349 proxy_ctx = talloc_init("proxy");
5354 * Move all of the thread calls to this file?
5356 * It may be best for the mutexes to be in this file...
5358 spawn_flag = have_children;
5360 #ifdef HAVE_PTHREAD_H
5361 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5364 * Initialize the threads ONLY if we're spawning, AND
5365 * we're running normally.
5367 if (have_children && !check_config &&
5368 (thread_pool_init(cs, &spawn_flag) < 0)) {
5374 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5376 if (listen_init(cs, &head, spawn_flag) < 0) {
5383 #ifdef HAVE_PTHREAD_H
5385 * Child threads need a pipe to signal us, as do the
5388 if (pipe(self_pipe) < 0) {
5389 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5392 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5393 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5394 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5397 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5398 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5399 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5402 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5404 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5405 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5410 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5413 * The server temporarily switches to an unprivileged
5414 * user very early in the bootstrapping process.
5415 * However, some sockets MAY require privileged access
5416 * (bind to device, or to port < 1024, or to raw
5417 * sockets). Those sockets need to call suid up/down
5418 * themselves around the functions that need a privileged
5421 if (listen_init(cs, &head, spawn_flag) < 0) {
5425 main_config.listen = head;
5432 * At this point, no one has any business *ever* going
5435 rad_suid_down_permanent();
5442 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5444 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5446 VERIFY_REQUEST(request);
5448 request->master_state = REQUEST_STOP_PROCESSING;
5450 #ifdef HAVE_PTHREAD_H
5451 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5455 * If it's queued we can't delete it from the queue.
5457 * Otherwise, it's OK to delete it. Even RUNNING, because
5458 * that will get caught by the check above.
5460 if (request->child_state == REQUEST_QUEUED) return 0;
5462 request->in_proxy_hash = false;
5464 if (!request->in_request_hash) {
5465 request_done(request, FR_ACTION_DONE);
5469 * Delete it from the list.
5476 static int request_delete_cb(UNUSED void *ctx, void *data)
5478 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5480 VERIFY_REQUEST(request);
5482 request->master_state = REQUEST_STOP_PROCESSING;
5485 * Not done, or the child thread is still processing it.
5487 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5489 #ifdef HAVE_PTHREAD_H
5490 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5494 rad_assert(request->in_proxy_hash == false);
5497 request->in_request_hash = false;
5499 if (request->ev) fr_event_delete(el, &request->ev);
5501 if (main_config.memory_report) {
5502 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5503 request->packet->id,
5504 (unsigned int) (request->timestamp - fr_start_time));
5509 rad_assert(!request->coa->in_proxy_hash);
5513 request_free(request);
5516 * Delete it from the list, and continue;
5522 void radius_event_free(void)
5528 * There are requests in the proxy hash that aren't
5529 * referenced from anywhere else. Remove them first.
5532 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5536 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5540 * Now that all requests have been marked "please stop",
5541 * ensure that all of the threads have exited.
5543 #ifdef HAVE_PTHREAD_H
5548 * Walk the lists again, ensuring that all
5549 * requests are done.
5551 if (main_config.memory_report) {
5556 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5557 num = fr_packet_list_num_elements(proxy_list);
5559 ERROR("Proxy list has %d requests still in it.", num);
5564 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5565 num = rbtree_num_elements(pl);
5567 ERROR("Request list has %d requests still in it.", num);
5576 fr_packet_list_free(proxy_list);
5579 if (proxy_ctx) talloc_free(proxy_ctx);
5584 if (debug_condition) talloc_free(debug_condition);
5587 int radius_event_process(void)
5591 return fr_event_loop(el);