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);
1164 * See if it's time to send the reply. If not,
1165 * we wait some more.
1167 when = request->reply->timestamp;
1169 tv_add(&when, request->response_delay.tv_sec * USEC);
1170 tv_add(&when, request->response_delay.tv_usec);
1172 if (timercmp(&when, &now, >)) {
1173 #ifdef DEBUG_STATE_MACHINE
1174 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1176 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1178 } /* else it's time to send the reject */
1180 RDEBUG2("Sending delayed response");
1181 debug_packet(request, request->reply, false);
1182 request->listener->send(request->listener, request);
1185 * Clean up the request.
1187 request_cleanup_delay_init(request);
1191 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1197 static int request_pre_handler(REQUEST *request, UNUSED int action)
1201 VERIFY_REQUEST(request);
1203 TRACE_STATE_MACHINE;
1205 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1208 * Don't decode the packet if it's an internal "fake"
1209 * request. Instead, just return so that the caller can
1212 if (request->packet->dst_port == 0) {
1213 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1214 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1218 if (!request->packet->vps) { /* FIXME: check for correct state */
1219 rcode = request->listener->decode(request->listener, request);
1222 if (debug_condition) {
1224 * Ignore parse errors.
1226 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1227 request->log.lvl = L_DBG_LVL_2;
1228 request->log.func = vradlog_request;
1233 debug_packet(request, request->packet, true);
1239 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1240 request->reply->offset = -2; /* bad authenticator */
1244 if (!request->username) {
1245 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1252 /** Do the final processing of a request before we reply to the NAS.
1254 * Various cleanups, suppress responses, copy Proxy-State, and set
1255 * response_delay or cleanup_delay;
1257 static void request_finish(REQUEST *request, int action)
1261 VERIFY_REQUEST(request);
1263 TRACE_STATE_MACHINE;
1266 (void) action; /* -Wunused */
1270 * Don't do post-auth if we're a CoA request originated
1271 * from an Access-Request. See request_alloc_coa() for
1274 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1278 * Override the response code if a control:Response-Packet-Type attribute is present.
1280 vp = fr_pair_find_by_num(request->config, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1282 if (vp->vp_integer == 256) {
1283 RDEBUG2("Not responding to request");
1284 request->reply->code = 0;
1286 request->reply->code = vp->vp_integer;
1290 * Catch Auth-Type := Reject BEFORE proxying the packet.
1292 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1293 if (request->reply->code == 0) {
1294 vp = fr_pair_find_by_num(request->config, PW_AUTH_TYPE, 0, TAG_ANY);
1295 if (!vp || (vp->vp_integer != 5)) {
1296 RDEBUG2("There was no response configured: "
1297 "rejecting request");
1300 request->reply->code = PW_CODE_ACCESS_REJECT;
1305 * Copy Proxy-State from the request to the reply.
1307 vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps,
1308 PW_PROXY_STATE, 0, TAG_ANY);
1309 if (vp) fr_pair_add(&request->reply->vps, vp);
1312 * Call Post-Auth for Access-Request packets.
1314 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1315 rad_postauth(request);
1320 * Maybe originate a CoA request.
1322 if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1323 request_coa_originate(request);
1328 * Clean up. These are no longer needed.
1330 gettimeofday(&request->reply->timestamp, NULL);
1333 * Fake packets get marked as "done", and have the
1334 * proxy-reply section deal with the reply attributes.
1335 * We therefore don't free the reply attributes.
1337 if (request->packet->dst_port == 0) {
1338 RDEBUG("Finished internally proxied request.");
1340 request->child_state = REQUEST_DONE;
1346 * Always send the reply to the detail listener.
1348 if (request->listener->type == RAD_LISTEN_DETAIL) {
1349 request->simul_max = 1;
1352 * But only print the reply if there is one.
1354 if (request->reply->code != 0) {
1355 debug_packet(request, request->reply, false);
1358 request->listener->send(request->listener, request);
1364 * Ignore all "do not respond" packets.
1365 * Except for the detail ones, which need to ping
1366 * the detail file reader so that it will retransmit.
1368 if (!request->reply->code) {
1369 RDEBUG("Not sending reply to client.");
1374 * If it's not in the request hash, we MIGHT not want to
1377 * If duplicate packets are allowed, then then only
1378 * reason to NOT be in the request hash is because we
1379 * don't want to send a reply.
1381 * FIXME: this is crap. The rest of the state handling
1382 * should use a different field so that we don't have two
1385 * Otherwise duplicates are forbidden, and the request is
1386 * SUPPOSED to avoid the request hash.
1388 * In that case, we need to send a reply.
1390 if (!request->in_request_hash &&
1391 !request->listener->nodup) {
1392 RDEBUG("Suppressing reply to client.");
1397 * See if we need to delay an Access-Reject packet.
1399 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1400 (request->root->reject_delay.tv_sec > 0)) {
1401 request->response_delay = request->root->reject_delay;
1405 * If we timed out a proxy packet, don't delay
1406 * the reject any more.
1408 if (request->proxy && !request->proxy_reply) {
1409 request->response_delay.tv_sec = 0;
1410 request->response_delay.tv_usec = 0;
1418 if ((request->response_delay.tv_sec == 0) &&
1419 (request->response_delay.tv_usec == 0)) {
1422 * Don't print a reply if there's none to send.
1424 if (request->reply->code != 0) {
1425 debug_packet(request, request->reply, false);
1426 request->listener->send(request->listener, request);
1430 RDEBUG2("Finished request");
1431 request->component = "<core>";
1432 request->module = "<done>";
1434 request_cleanup_delay_init(request);
1438 * Encode and sign it here, so that the master
1439 * thread can just send the encoded data, which
1440 * means it does less work.
1442 RDEBUG2("Delaying response for %d.%06d seconds",
1443 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1444 request->listener->encode(request->listener, request);
1445 request->component = "<core>";
1446 request->module = "<delay>";
1447 request->process = request_response_delay;
1449 request->child_state = REQUEST_RESPONSE_DELAY;
1453 /** Process a request from a client.
1455 * The outcome might be that the request is proxied.
1459 * running -> running [ label = "TIMER < max_request_time" ];
1460 * running -> done [ label = "TIMER >= max_request_time" ];
1461 * running -> proxy [ label = "proxied" ];
1462 * running -> dup [ label = "DUP", arrowhead = "none" ];
1466 static void request_running(REQUEST *request, int action)
1468 VERIFY_REQUEST(request);
1470 TRACE_STATE_MACHINE;
1474 case FR_ACTION_TIMER:
1476 (void) request_max_time(request);
1480 request_dup(request);
1484 if (!request_pre_handler(request, action)) {
1485 #ifdef DEBUG_STATE_MACHINE
1486 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1487 request->number, __FUNCTION__,
1488 child_state_names[request->child_state],
1489 child_state_names[REQUEST_DONE]);
1493 request->child_state = REQUEST_DONE;
1497 rad_assert(request->handle != NULL);
1498 request->handle(request);
1502 * We may need to send a proxied request.
1504 if ((action == FR_ACTION_RUN) &&
1505 request_will_proxy(request)) {
1506 #ifdef DEBUG_STATE_MACHINE
1507 if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1511 * takes care of setting
1512 * up the post proxy fail
1515 if (request_proxy(request, 0) < 0) goto req_finished;
1519 #ifdef DEBUG_STATE_MACHINE
1520 if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1526 request_finish(request, action);
1531 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1536 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1537 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1540 RADIUS_PACKET **packet_p;
1541 REQUEST *request = NULL;
1543 listen_socket_t *sock = NULL;
1545 VERIFY_PACKET(packet);
1548 * Set the last packet received.
1550 gettimeofday(&now, NULL);
1552 packet->timestamp = now;
1554 #ifdef WITH_ACCOUNTING
1555 if (listener->type != RAD_LISTEN_DETAIL)
1558 sock = listener->data;
1559 sock->last_packet = now.tv_sec;
1562 packet->proto = sock->proto;
1567 * Skip everything if required.
1569 if (listener->nodup) goto skip_dup;
1571 packet_p = rbtree_finddata(pl, &packet);
1573 rad_child_state_t child_state;
1575 request = fr_packet2myptr(REQUEST, packet, packet_p);
1576 rad_assert(request->in_request_hash);
1577 child_state = request->child_state;
1580 * Same src/dst ip/port, length, and
1581 * authentication vector: must be a duplicate.
1583 if ((request->packet->data_len == packet->data_len) &&
1584 (memcmp(request->packet->vector, packet->vector,
1585 sizeof(packet->vector)) == 0)) {
1588 switch (packet->code) {
1589 case PW_CODE_ACCESS_REQUEST:
1590 FR_STATS_INC(auth, total_dup_requests);
1593 #ifdef WITH_ACCOUNTING
1594 case PW_CODE_ACCOUNTING_REQUEST:
1595 FR_STATS_INC(acct, total_dup_requests);
1599 case PW_CODE_COA_REQUEST:
1600 FR_STATS_INC(coa, total_dup_requests);
1603 case PW_CODE_DISCONNECT_REQUEST:
1604 FR_STATS_INC(dsc, total_dup_requests);
1611 #endif /* WITH_STATS */
1614 * Tell the state machine that there's a
1615 * duplicate request.
1617 request->process(request, FR_ACTION_DUP);
1618 return 0; /* duplicate of live request */
1622 * Mark the request as done ASAP, and before we
1623 * log anything. The child may stop processing
1624 * the request just as we're logging the
1627 request_done(request, FR_ACTION_DONE);
1631 * It's a new request, not a duplicate. If the
1632 * old one is done, then we can clean it up.
1634 if (child_state <= REQUEST_RUNNING) {
1636 * The request is still QUEUED or RUNNING. That's a problem.
1638 ERROR("Received conflicting packet from "
1639 "client %s port %d - ID: %u due to "
1640 "unfinished request. Giving up on old request.",
1642 packet->src_port, packet->id);
1646 * Mark the old request as done. If there's no
1647 * child, the request will be cleaned up
1648 * immediately. If there is a child, we'll set a
1649 * timer to go clean up the request.
1651 } /* else the new packet is unique */
1654 * Quench maximum number of outstanding requests.
1656 if (main_config.max_requests &&
1657 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1658 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1660 packet->src_port, packet->id);
1661 WARN("Please check the configuration file.\n"
1662 "\tThe value for 'max_requests' is probably set too low.\n"));
1664 exec_trigger(NULL, NULL, "server.max_requests", true);
1670 * Rate-limit the incoming packets
1672 if (sock && sock->max_rate) {
1675 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1676 if (pps > sock->max_rate) {
1677 DEBUG("Dropping request due to rate limiting");
1680 sock->rate_pps_now++;
1684 * Allocate a pool for the request.
1687 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1689 talloc_set_name_const(ctx, "request_receive_pool");
1692 * The packet is still allocated from a different
1693 * context, but oh well.
1695 (void) talloc_steal(ctx, packet);
1698 request = request_setup(ctx, listener, packet, client, fun);
1705 * Mark it as a "real" request with a context.
1707 request->options |= RAD_REQUEST_OPTION_CTX;
1710 * Remember the request in the list.
1712 if (!listener->nodup) {
1713 if (!rbtree_insert(pl, &request->packet)) {
1714 RERROR("Failed to insert request in the list of live requests: discarding it");
1715 request_done(request, FR_ACTION_DONE);
1719 request->in_request_hash = true;
1723 * Process it. Send a response, and free it.
1725 if (listener->synchronous) {
1727 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1730 request->listener->decode(request->listener, request);
1731 request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1732 request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1736 if (request->reply->code != 0) {
1737 request->listener->send(request->listener, request);
1739 RDEBUG("Not sending reply");
1743 * Don't do delayed reject. Oh well.
1745 request_free(request);
1750 * Otherwise, insert it into the state machine.
1751 * The child threads will take care of processing it.
1753 request_queue_or_run(request, request_running);
1759 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1760 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1765 * Create and initialize the new request.
1767 request = request_alloc(ctx);
1772 request->reply = rad_alloc(request, false);
1773 if (!request->reply) {
1775 talloc_free(request);
1779 request->listener = listener;
1780 request->client = client;
1781 request->packet = talloc_steal(request, packet);
1782 request->number = request_num_counter++;
1783 request->priority = listener->type;
1784 request->master_state = REQUEST_ACTIVE;
1785 request->child_state = REQUEST_RUNNING;
1786 #ifdef DEBUG_STATE_MACHINE
1787 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1788 request->number, __FUNCTION__,
1789 child_state_names[request->child_state],
1790 child_state_names[REQUEST_RUNNING]);
1792 #ifdef HAVE_PTHREAD_H
1793 request->child_pid = NO_SUCH_CHILD_PID;
1795 request->handle = fun;
1799 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1800 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1801 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1802 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1803 #ifdef WITH_ACCOUNTING
1804 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1805 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1806 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1809 #endif /* WITH_STATS */
1812 * Status-Server packets go to the head of the queue.
1814 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1817 * Set virtual server identity
1819 if (client->server) {
1820 request->server = client->server;
1821 } else if (listener->server) {
1822 request->server = listener->server;
1824 request->server = NULL;
1827 request->root = &main_config;
1829 request->listener->count++;
1833 * The request passes many of our sanity checks.
1834 * From here on in, if anything goes wrong, we
1835 * send a reject message, instead of dropping the
1840 * Build the reply template from the request.
1843 request->reply->sockfd = request->packet->sockfd;
1844 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1845 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1846 request->reply->dst_port = request->packet->src_port;
1847 request->reply->src_port = request->packet->dst_port;
1848 request->reply->id = request->packet->id;
1849 request->reply->code = 0; /* UNKNOWN code */
1850 memcpy(request->reply->vector, request->packet->vector,
1851 sizeof(request->reply->vector));
1852 request->reply->vps = NULL;
1853 request->reply->data = NULL;
1854 request->reply->data_len = 0;
1860 /***********************************************************************
1864 ***********************************************************************/
1867 * Timer function for all TCP sockets.
1869 static void tcp_socket_timer(void *ctx)
1871 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1872 listen_socket_t *sock = listener->data;
1873 struct timeval end, now;
1875 fr_socket_limit_t *limit;
1879 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1881 fr_event_now(el, &now);
1883 switch (listener->type) {
1885 case RAD_LISTEN_PROXY:
1886 limit = &sock->home->limit;
1890 case RAD_LISTEN_AUTH:
1891 #ifdef WITH_ACCOUNTING
1892 case RAD_LISTEN_ACCT:
1894 limit = &sock->limit;
1902 * If we enforce a lifetime, do it now.
1904 if (limit->lifetime > 0) {
1905 end.tv_sec = sock->opened + limit->lifetime;
1908 if (timercmp(&end, &now, <=)) {
1909 listener->print(listener, buffer, sizeof(buffer));
1910 DEBUG("Reached maximum lifetime on socket %s", buffer);
1916 * Proxy sockets get frozen, so that we don't use
1917 * them for new requests. But we do keep them
1918 * open to listen for replies to requests we had
1921 if (listener->type == RAD_LISTEN_PROXY) {
1922 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1923 if (!fr_packet_list_socket_freeze(proxy_list,
1925 ERROR("Fatal error freezing socket: %s", fr_strerror());
1928 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1933 * Mark the socket as "don't use if at all possible".
1935 listener->status = RAD_LISTEN_STATUS_FROZEN;
1936 event_new_fd(listener);
1945 * Enforce an idle timeout.
1947 if (limit->idle_timeout > 0) {
1948 struct timeval idle;
1950 rad_assert(sock->last_packet != 0);
1951 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1954 if (timercmp(&idle, &now, <=)) {
1955 listener->print(listener, buffer, sizeof(buffer));
1956 DEBUG("Reached idle timeout on socket %s", buffer);
1961 * Enforce the minimum of idle timeout or lifetime.
1963 if (timercmp(&idle, &end, <)) {
1969 * Wake up at t + 0.5s. The code above checks if the timers
1970 * are <= t. This addition gives us a bit of leeway.
1972 end.tv_usec = USEC / 2;
1975 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1976 rad_panic("Failed to insert event");
1983 * Add +/- 2s of jitter, as suggested in RFC 3539
1986 static void add_jitter(struct timeval *when)
1993 jitter ^= (jitter >> 10);
1994 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1997 * Add in ~ (4 * USEC) of jitter.
1999 tv_add(when, jitter);
2003 * Called by socket_del to remove requests with this socket
2005 static int eol_proxy_listener(void *ctx, void *data)
2007 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2008 RADIUS_PACKET **proxy_p = data;
2011 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2012 if (request->proxy_listener != this) return 0;
2015 * The normal "remove_from_proxy_hash" tries to grab the
2016 * proxy mutex. We already have it held, so grabbing it
2017 * again will cause a deadlock. Instead, call the "no
2018 * lock" version of the function.
2020 rad_assert(request->in_proxy_hash == true);
2021 remove_from_proxy_hash_nl(request, false);
2024 * Don't mark it as DONE. The client can retransmit, and
2025 * the packet SHOULD be re-proxied somewhere else.
2027 * Return "2" means that the rbtree code will remove it
2028 * from the tree, and we don't need to do it ourselves.
2032 #endif /* WITH_PROXY */
2034 static int eol_listener(void *ctx, void *data)
2036 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2037 RADIUS_PACKET **packet_p = data;
2040 request = fr_packet2myptr(REQUEST, packet, packet_p);
2041 if (request->listener != this) return 0;
2043 request->master_state = REQUEST_STOP_PROCESSING;
2044 request->process = request_done;
2048 #endif /* WITH_TCP */
2051 /***********************************************************************
2053 * Proxy handlers for the state machine.
2055 ***********************************************************************/
2058 * Called with the proxy mutex held
2060 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2062 VERIFY_REQUEST(request);
2064 if (!request->in_proxy_hash) return;
2066 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2067 request->in_proxy_hash = false;
2070 * On the FIRST reply, decrement the count of outstanding
2071 * requests. Note that this is NOT the count of sent
2072 * packets, but whether or not the home server has
2075 if (request->home_server &&
2076 request->home_server->currently_outstanding) {
2077 request->home_server->currently_outstanding--;
2080 * If we're NOT sending it packets, AND it's been
2081 * a while since we got a response, then we don't
2082 * know if it's alive or dead.
2084 if ((request->home_server->currently_outstanding == 0) &&
2085 (request->home_server->state == HOME_STATE_ALIVE)) {
2086 struct timeval when, now;
2088 when.tv_sec = request->home_server->last_packet_recv ;
2091 timeradd(&when, request_response_window(request), &when);
2092 gettimeofday(&now, NULL);
2095 * last_packet + response_window
2097 * We *administratively* mark the home
2098 * server as "unknown" state, because we
2099 * haven't seen a packet for a while.
2101 if (timercmp(&now, &when, >)) {
2102 request->home_server->state = HOME_STATE_UNKNOWN;
2103 request->home_server->last_packet_sent = 0;
2104 request->home_server->last_packet_recv = 0;
2110 rad_assert(request->proxy_listener != NULL);
2111 request->proxy_listener->count--;
2113 request->proxy_listener = NULL;
2116 * Got from YES in hash, to NO, not in hash while we hold
2117 * the mutex. This guarantees that when another thread
2118 * grabs the mutex, the "not in hash" flag is correct.
2122 static void remove_from_proxy_hash(REQUEST *request)
2124 VERIFY_REQUEST(request);
2127 * Check this without grabbing the mutex because it's a
2128 * lot faster that way.
2130 if (!request->in_proxy_hash) return;
2133 * The "not in hash" flag is definitive. However, if the
2134 * flag says that it IS in the hash, there might still be
2135 * a race condition where it isn't.
2137 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2139 if (!request->in_proxy_hash) {
2140 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2144 remove_from_proxy_hash_nl(request, true);
2146 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2149 static int insert_into_proxy_hash(REQUEST *request)
2153 bool success = false;
2154 void *proxy_listener;
2156 VERIFY_REQUEST(request);
2158 rad_assert(request->proxy != NULL);
2159 rad_assert(request->home_server != NULL);
2160 rad_assert(proxy_list != NULL);
2163 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2164 proxy_listener = NULL;
2165 request->num_proxied_requests = 1;
2166 request->num_proxied_responses = 0;
2168 for (tries = 0; tries < 2; tries++) {
2170 listen_socket_t *sock;
2172 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2173 success = fr_packet_list_id_alloc(proxy_list,
2174 request->home_server->proto,
2175 &request->proxy, &proxy_listener);
2178 if (tries > 0) continue; /* try opening new socket only once */
2180 #ifdef HAVE_PTHREAD_H
2181 if (proxy_no_new_sockets) break;
2184 RDEBUG3("proxy: Trying to open a new listener to the home server");
2185 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2187 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2191 request->proxy->src_port = 0; /* Use any new socket */
2192 proxy_listener = this;
2195 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2197 &sock->other_ipaddr, sock->other_port,
2200 #ifdef HAVE_PTHREAD_H
2201 proxy_no_new_sockets = true;
2203 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2206 * This is bad. However, the
2207 * packet list now supports 256
2208 * open sockets, which should
2209 * minimize this problem.
2211 ERROR("Failed adding proxy socket: %s",
2217 * Add it to the event loop. Ensure that we have
2218 * only one mutex locked at a time.
2220 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2221 radius_update_listener(this);
2222 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2225 if (!proxy_listener || !success) {
2226 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2227 REDEBUG2("proxy: Failed allocating Id for proxied request");
2229 request->proxy_listener = NULL;
2230 request->in_proxy_hash = false;
2234 rad_assert(request->proxy->id >= 0);
2236 request->proxy_listener = proxy_listener;
2237 request->in_proxy_hash = true;
2238 RDEBUG3("proxy: request is now in proxy hash");
2241 * Keep track of maximum outstanding requests to a
2242 * particular home server. 'max_outstanding' is
2243 * enforced in home_server_ldb(), in realms.c.
2245 request->home_server->currently_outstanding++;
2248 request->proxy_listener->count++;
2251 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2253 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2254 inet_ntop(request->proxy->dst_ipaddr.af,
2255 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2256 request->proxy->dst_port,
2257 request->proxy->id);
2262 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2265 int post_proxy_type = 0;
2268 VERIFY_REQUEST(request);
2271 * There may be a proxy reply, but it may be too late.
2273 if (!request->home_server->server && !request->proxy_listener) return 0;
2276 * Delete any reply we had accumulated until now.
2278 RDEBUG2("Clearing existing &reply: attributes");
2279 fr_pair_list_free(&request->reply->vps);
2282 * Run the packet through the post-proxy stage,
2283 * BEFORE playing games with the attributes.
2285 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2287 post_proxy_type = vp->vp_integer;
2289 * If we have a proxy_reply, and it was a reject, or a NAK
2290 * setup Post-Proxy <type>.
2292 * If the <type> doesn't have a section, then the Post-Proxy
2293 * section is ignored.
2296 DICT_VALUE *dval = NULL;
2298 switch (reply->code) {
2299 case PW_CODE_ACCESS_REJECT:
2300 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2301 if (dval) post_proxy_type = dval->value;
2304 case PW_CODE_DISCONNECT_NAK:
2305 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2306 if (dval) post_proxy_type = dval->value;
2309 case PW_CODE_COA_NAK:
2310 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2311 if (dval) post_proxy_type = dval->value;
2319 * Create config:Post-Proxy-Type
2322 vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2323 vp->vp_integer = dval->value;
2327 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2328 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2331 VERIFY_PACKET(reply);
2334 * Decode the packet if required.
2336 if (request->proxy_listener) {
2337 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2338 debug_packet(request, reply, true);
2341 * Pro-actively remove it from the proxy hash.
2342 * This is later than in 2.1.x, but it means that
2343 * the replies are authenticated before being
2344 * removed from the hash.
2347 (request->num_proxied_requests <= request->num_proxied_responses)) {
2348 remove_from_proxy_hash(request);
2351 rad_assert(!request->in_proxy_hash);
2353 } else if (request->in_proxy_hash) {
2354 remove_from_proxy_hash(request);
2357 if (request->home_pool && request->home_pool->virtual_server) {
2358 char const *old_server = request->server;
2360 request->server = request->home_pool->virtual_server;
2361 RDEBUG2("server %s {", request->server);
2363 rcode = process_post_proxy(post_proxy_type, request);
2366 request->server = old_server;
2368 rcode = process_post_proxy(post_proxy_type, request);
2372 if (request->packet->code == request->proxy->code)
2374 * Don't run the next bit if we originated a CoA
2375 * packet, after receiving an Access-Request or
2376 * Accounting-Request.
2381 * There may NOT be a proxy reply, as we may be
2382 * running Post-Proxy-Type = Fail.
2385 fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2388 * Delete the Proxy-State Attributes from
2389 * the reply. These include Proxy-State
2390 * attributes from us and remote server.
2392 fr_pair_delete_by_num(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2396 default: /* Don't do anything */
2398 case RLM_MODULE_FAIL:
2401 case RLM_MODULE_HANDLED:
2408 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2412 home->state = HOME_STATE_ALIVE;
2413 home->response_timeouts = 0;
2414 exec_trigger(request, home->cs, "home_server.alive", false);
2415 home->currently_outstanding = 0;
2416 home->num_sent_pings = 0;
2417 home->num_received_pings = 0;
2418 gettimeofday(&home->revive_time, NULL);
2420 fr_event_delete(el, &home->ev);
2422 RPROXY("Marking home server %s port %d alive",
2423 inet_ntop(request->proxy->dst_ipaddr.af,
2424 &request->proxy->dst_ipaddr.ipaddr,
2425 buffer, sizeof(buffer)),
2426 request->proxy->dst_port);
2430 int request_proxy_reply(RADIUS_PACKET *packet)
2432 RADIUS_PACKET **proxy_p;
2437 VERIFY_PACKET(packet);
2439 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2440 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2443 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2444 PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2445 fr_packet_codes[packet->code],
2446 inet_ntop(packet->src_ipaddr.af,
2447 &packet->src_ipaddr.ipaddr,
2448 buffer, sizeof(buffer)),
2449 packet->src_port, packet->id);
2453 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2454 request->num_proxied_responses++; /* needs to be protected by lock */
2456 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2459 * No reply, BUT the current packet fails verification:
2460 * ignore it. This does the MD5 calculations in the
2461 * server core, but I guess we can fix that later.
2463 if (!request->proxy_reply &&
2464 (rad_verify(packet, request->proxy,
2465 request->home_server->secret) != 0)) {
2466 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2471 * The home server sent us a packet which doesn't match
2472 * something we have: ignore it. This is done only to
2473 * catch the case of broken systems.
2475 if (request->proxy_reply &&
2476 (memcmp(request->proxy_reply->vector,
2478 sizeof(request->proxy_reply->vector)) != 0)) {
2479 RDEBUG2("Ignoring conflicting proxy reply");
2483 gettimeofday(&now, NULL);
2486 * Status-Server packets don't count as real packets.
2488 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2489 listen_socket_t *sock = request->proxy_listener->data;
2491 request->home_server->last_packet_recv = now.tv_sec;
2492 sock->last_packet = now.tv_sec;
2496 * If we have previously seen a reply, ignore the
2499 if (request->proxy_reply) {
2500 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2501 inet_ntop(packet->src_ipaddr.af,
2502 &packet->src_ipaddr.ipaddr,
2503 buffer, sizeof(buffer)),
2504 packet->src_port, packet->id);
2509 * Call the state machine to do something useful with the
2512 request->proxy_reply = talloc_steal(request, packet);
2513 packet->timestamp = now;
2514 request->priority = RAD_LISTEN_PROXY;
2518 * Update the proxy listener stats here, because only one
2519 * thread accesses that at a time. The home_server and
2520 * main proxy_*_stats structures are updated once the
2521 * request is cleaned up.
2523 request->proxy_listener->stats.total_responses++;
2525 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2526 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2528 switch (request->proxy->code) {
2529 case PW_CODE_ACCESS_REQUEST:
2530 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2532 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2533 request->proxy_listener->stats.total_access_accepts++;
2535 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2536 request->proxy_listener->stats.total_access_rejects++;
2538 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2539 request->proxy_listener->stats.total_access_challenges++;
2543 #ifdef WITH_ACCOUNTING
2544 case PW_CODE_ACCOUNTING_REQUEST:
2545 request->proxy_listener->stats.total_responses++;
2546 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2552 case PW_CODE_COA_REQUEST:
2553 request->proxy_listener->stats.total_responses++;
2554 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2557 case PW_CODE_DISCONNECT_REQUEST:
2558 request->proxy_listener->stats.total_responses++;
2559 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2569 * If we hadn't been sending the home server packets for
2570 * a while, just mark it alive. Or, if it was zombie,
2571 * it's now responded, and is therefore alive.
2573 if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2574 (request->home_server->state == HOME_STATE_ZOMBIE)) {
2575 mark_home_server_alive(request, request->home_server);
2579 * Tell the request state machine that we have a proxy
2580 * reply. Depending on the function, this should either
2581 * ignore it, or process it.
2583 request->process(request, FR_ACTION_PROXY_REPLY);
2589 static int setup_post_proxy_fail(REQUEST *request)
2591 DICT_VALUE const *dval = NULL;
2594 VERIFY_REQUEST(request);
2596 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2597 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2598 "Fail-Authentication");
2599 #ifdef WITH_ACCOUNTING
2600 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2601 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2606 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2607 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2609 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2610 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2613 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2617 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2620 fr_pair_delete_by_num(&request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2624 vp = fr_pair_find_by_num(request->config, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2625 if (!vp) vp = radius_pair_create(request, &request->config,
2626 PW_POST_PROXY_TYPE, 0);
2627 vp->vp_integer = dval->value;
2633 /** Process a request after the proxy has timed out.
2635 * Run the packet through Post-Proxy-Type Fail
2638 * digraph proxy_no_reply {
2641 * proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2642 * proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2643 * proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2644 * proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2645 * proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2649 static void proxy_no_reply(REQUEST *request, int action)
2651 VERIFY_REQUEST(request);
2653 TRACE_STATE_MACHINE;
2658 request_dup(request);
2661 case FR_ACTION_TIMER:
2662 (void) request_max_time(request);
2665 case FR_ACTION_PROXY_REPLY:
2666 proxy_reply_too_late(request);
2670 if (process_proxy_reply(request, NULL)) {
2671 request->handle(request);
2673 request_finish(request, action);
2677 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2682 /** Process the request after receiving a proxy reply.
2684 * Throught the post-proxy section, and the through the handler
2688 * digraph proxy_running {
2691 * proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2692 * proxy_running -> timer [ label = "TIMER < max_request_time" ];
2693 * proxy_running -> process_proxy_reply [ label = "RUN" ];
2694 * proxy_running -> done [ label = "TIMER >= timeout" ];
2698 static void proxy_running(REQUEST *request, int action)
2700 VERIFY_REQUEST(request);
2702 TRACE_STATE_MACHINE;
2707 request_dup(request);
2710 case FR_ACTION_TIMER:
2711 (void) request_max_time(request);
2715 if (process_proxy_reply(request, request->proxy_reply)) {
2716 request->handle(request);
2718 request_finish(request, action);
2721 default: /* duplicate proxy replies are suppressed */
2722 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2727 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2729 * Whether a request will be proxied is determined by the attributes present
2730 * in request->config. If any of the following attributes are found, the
2731 * request may be proxied.
2733 * The key attributes are:
2734 * - PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2735 * - PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2736 * - PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2737 * - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2739 * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2741 * If request should be proxied, will:
2742 * - Add request:Proxy-State
2743 * - Strip the current username value of its realm (depending on config)
2744 * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2746 * - Call the pre-process section in the current server, or in the virtual server
2747 * associated with the home server pool we're proxying to.
2749 * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2750 * specific function.
2752 * @param request The #REQUEST to evaluate for proxying.
2753 * @return 0 if not proxying, 1 if request should be proxied, -1 on error.
2755 static int request_will_proxy(REQUEST *request)
2757 int rcode, pre_proxy_type = 0;
2758 char const *realmname = NULL;
2759 VALUE_PAIR *vp, *strippedname;
2760 home_server_t *home;
2761 REALM *realm = NULL;
2762 home_pool_t *pool = NULL;
2764 VERIFY_REQUEST(request);
2766 if (!request->root->proxy_requests) return 0;
2767 if (request->packet->dst_port == 0) return 0;
2768 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2769 if (request->in_proxy_hash) return 0;
2772 * FIXME: for 3.0, allow this only for rejects?
2774 if (request->reply->code != 0) return 0;
2776 vp = fr_pair_find_by_num(request->config, PW_PROXY_TO_REALM, 0, TAG_ANY);
2778 realm = realm_find2(vp->vp_strvalue);
2780 REDEBUG2("Cannot proxy to unknown realm %s",
2785 realmname = vp->vp_strvalue;
2788 * Figure out which pool to use.
2790 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2791 pool = realm->auth_pool;
2793 #ifdef WITH_ACCOUNTING
2794 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2795 pool = realm->acct_pool;
2799 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2800 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2801 pool = realm->coa_pool;
2808 } else if ((vp = fr_pair_find_by_num(request->config, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2811 switch (request->packet->code) {
2812 case PW_CODE_ACCESS_REQUEST:
2813 pool_type = HOME_TYPE_AUTH;
2816 #ifdef WITH_ACCOUNTING
2817 case PW_CODE_ACCOUNTING_REQUEST:
2818 pool_type = HOME_TYPE_ACCT;
2823 case PW_CODE_COA_REQUEST:
2824 case PW_CODE_DISCONNECT_REQUEST:
2825 pool_type = HOME_TYPE_COA;
2833 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2836 * Send it directly to a home server (i.e. NAS)
2838 } else if (((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2839 ((vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2841 fr_ipaddr_t dst_ipaddr;
2843 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2845 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2846 dst_ipaddr.af = AF_INET;
2847 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2848 dst_ipaddr.prefix = 32;
2850 dst_ipaddr.af = AF_INET6;
2851 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2852 dst_ipaddr.prefix = 128;
2855 vp = fr_pair_find_by_num(request->config, PW_PACKET_DST_PORT, 0, TAG_ANY);
2857 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2858 dst_port = PW_AUTH_UDP_PORT;
2860 #ifdef WITH_ACCOUNTING
2861 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2862 dst_port = PW_ACCT_UDP_PORT;
2866 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2867 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2868 dst_port = PW_COA_UDP_PORT;
2870 } else { /* shouldn't happen for RADIUS... */
2875 dst_port = vp->vp_integer;
2879 * Nothing does CoA over TCP.
2881 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2885 WARN("No such home server %s port %u",
2886 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2887 (unsigned int) dst_port);
2892 * The home server is alive (or may be alive).
2893 * Send the packet to the IP.
2895 if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2898 * The home server is dead. If you wanted
2899 * fail-over, you should have proxied to a pool.
2910 RWDEBUG2("Cancelling proxy as no home pool exists");
2914 if (request->listener->synchronous) {
2915 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2919 request->home_pool = pool;
2921 home = home_server_ldb(realmname, pool, request);
2924 REDEBUG2("Failed to find live home server: Cancelling proxy");
2929 home_server_update_request(home, request);
2933 * Once we've decided to proxy a request, we cannot send
2934 * a CoA packet. So we free up any CoA packet here.
2936 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2940 * Remember that we sent the request to a Realm.
2942 if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2945 * Strip the name, if told to.
2947 * Doing it here catches the case of proxied tunneled
2950 if (realm && (realm->strip_realm == true) &&
2951 (strippedname = fr_pair_find_by_num(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2953 * If there's a Stripped-User-Name attribute in
2954 * the request, then use THAT as the User-Name
2955 * for the proxied request, instead of the
2958 * This is done by making a copy of the
2959 * Stripped-User-Name attribute, turning it into
2960 * a User-Name attribute, deleting the
2961 * Stripped-User-Name and User-Name attributes
2962 * from the vps list, and making the new
2963 * User-Name the head of the vps list.
2965 vp = fr_pair_find_by_num(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2968 vp = radius_pair_create(NULL, NULL,
2970 rad_assert(vp != NULL); /* handled by above function */
2971 /* Insert at the START of the list */
2972 /* FIXME: Can't make assumptions about ordering */
2973 fr_cursor_init(&cursor, &vp);
2974 fr_cursor_merge(&cursor, request->proxy->vps);
2975 request->proxy->vps = vp;
2977 fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
2980 * Do NOT delete Stripped-User-Name.
2985 * If there is no PW_CHAP_CHALLENGE attribute but
2986 * there is a PW_CHAP_PASSWORD we need to add it
2987 * since we can't use the request authenticator
2988 * anymore - we changed it.
2990 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2991 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2992 fr_pair_find_by_num(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2993 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2994 fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2998 * The RFC's say we have to do this, but FreeRADIUS
3001 vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
3002 fr_pair_value_sprintf(vp, "%u", request->packet->id);
3005 * Should be done BEFORE inserting into proxy hash, as
3006 * pre-proxy may use this information, or change it.
3008 request->proxy->code = request->packet->code;
3011 * Call the pre-proxy routines.
3013 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3015 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3016 /* Must be a validation issue */
3018 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3019 pre_proxy_type = vp->vp_integer;
3023 * home_pool may be NULL when originating CoA packets,
3024 * because they go directly to an IP address.
3026 if (request->home_pool && request->home_pool->virtual_server) {
3027 char const *old_server = request->server;
3029 request->server = request->home_pool->virtual_server;
3031 RDEBUG2("server %s {", request->server);
3033 rcode = process_pre_proxy(pre_proxy_type, request);
3037 request->server = old_server;
3039 rcode = process_pre_proxy(pre_proxy_type, request);
3043 case RLM_MODULE_FAIL:
3044 case RLM_MODULE_INVALID:
3045 case RLM_MODULE_NOTFOUND:
3046 case RLM_MODULE_USERLOCK:
3048 /* FIXME: debug print failed stuff */
3051 case RLM_MODULE_REJECT:
3052 case RLM_MODULE_HANDLED:
3056 * Only proxy the packet if the pre-proxy code succeeded.
3058 case RLM_MODULE_NOOP:
3060 case RLM_MODULE_UPDATED:
3065 static int proxy_to_virtual_server(REQUEST *request)
3069 if (request->packet->dst_port == 0) {
3070 WARN("Cannot proxy an internal request");
3074 DEBUG("Proxying to virtual server %s",
3075 request->home_server->server);
3078 * Packets to virtual servers don't get
3079 * retransmissions sent to them. And the virtual
3080 * server is run ONLY if we have no child
3081 * threads, or we're running in a child thread.
3083 rad_assert(!spawn_flag || !we_are_master());
3085 fake = request_alloc_fake(request);
3087 fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3088 talloc_free(request->proxy);
3090 fake->server = request->home_server->server;
3091 fake->handle = request->handle;
3092 fake->process = NULL; /* should never be run for anything */
3095 * Run the virtual server.
3097 request_running(fake, FR_ACTION_RUN);
3099 request->proxy = talloc_steal(request, fake->packet);
3100 fake->packet = NULL;
3101 request->proxy_reply = talloc_steal(request, fake->reply);
3107 * No reply code, toss the reply we have,
3108 * and do post-proxy-type Fail.
3110 if (!request->proxy_reply->code) {
3111 TALLOC_FREE(request->proxy_reply);
3112 setup_post_proxy_fail(request);
3116 * Do the proxy reply (if any)
3118 if (process_proxy_reply(request, request->proxy_reply)) {
3119 request->handle(request);
3122 return -1; /* so we call request_finish */
3126 static int request_proxy(REQUEST *request, int retransmit)
3130 VERIFY_REQUEST(request);
3132 rad_assert(request->parent == NULL);
3133 rad_assert(request->home_server != NULL);
3135 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3139 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
3140 request_done(request->coa, FR_ACTION_DONE);
3145 * The request may need sending to a virtual server.
3146 * This code is more than a little screwed up. The rest
3147 * of the state machine doesn't handle parent / child
3148 * relationships well. i.e. if the child request takes
3149 * too long, the core will mark the *parent* as "stop
3150 * processing". And the child will continue without
3151 * knowing anything...
3153 * So, we have some horrible hacks to get around that.
3155 if (request->home_server->server) return proxy_to_virtual_server(request);
3158 * We're actually sending a proxied packet. Do that now.
3160 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3161 RPROXY("Failed to insert request into the proxy list");
3165 rad_assert(request->proxy->id >= 0);
3167 if (rad_debug_lvl) {
3168 struct timeval *response_window;
3170 response_window = request_response_window(request);
3173 if (request->home_server->tls) {
3174 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3175 inet_ntop(request->proxy->dst_ipaddr.af,
3176 &request->proxy->dst_ipaddr.ipaddr,
3177 buffer, sizeof(buffer)),
3178 request->proxy->dst_port,
3179 (int) response_window->tv_sec, (int) response_window->tv_usec);
3182 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3183 inet_ntop(request->proxy->dst_ipaddr.af,
3184 &request->proxy->dst_ipaddr.ipaddr,
3185 buffer, sizeof(buffer)),
3186 request->proxy->dst_port,
3187 (int) response_window->tv_sec, (int) response_window->tv_usec);
3192 gettimeofday(&request->proxy_retransmit, NULL);
3194 request->proxy->timestamp = request->proxy_retransmit;
3196 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3199 * Encode the packet before we do anything else.
3201 request->proxy_listener->encode(request->proxy_listener, request);
3202 debug_packet(request, request->proxy, false);
3205 * Set the state function, then the state, no child, and
3208 request->process = proxy_wait_for_reply;
3209 request->child_state = REQUEST_PROXIED;
3213 * And send the packet.
3215 request->proxy_listener->send(request->proxy_listener, request);
3220 * Proxy the packet as if it was new.
3222 static int request_proxy_anew(REQUEST *request)
3224 home_server_t *home;
3226 VERIFY_REQUEST(request);
3229 * Delete the request from the proxy list.
3231 * The packet list code takes care of ensuring that IDs
3232 * aren't reused until all 256 IDs have been used. So
3233 * there's a 1/256 chance of re-using the same ID when
3234 * we're sending to the same home server. Which is
3237 remove_from_proxy_hash(request);
3240 * Find a live home server for the request.
3242 home = home_server_ldb(NULL, request->home_pool, request);
3244 REDEBUG2("Failed to find live home server for request");
3246 if (setup_post_proxy_fail(request)) {
3247 request_queue_or_run(request, proxy_running);
3249 gettimeofday(&request->reply->timestamp, NULL);
3250 request_cleanup_delay_init(request);
3255 #ifdef WITH_ACCOUNTING
3257 * Update the Acct-Delay-Time attribute.
3259 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3262 vp = fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3263 if (!vp) vp = radius_pair_create(request->proxy,
3264 &request->proxy->vps,
3265 PW_ACCT_DELAY_TIME, 0);
3269 gettimeofday(&now, NULL);
3270 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3276 * May have failed over to a "fallback" virtual server.
3277 * If so, run that instead of doing proxying to a real
3281 request->home_server = home;
3282 TALLOC_FREE(request->proxy);
3284 (void) proxy_to_virtual_server(request);
3288 home_server_update_request(home, request);
3290 if (!insert_into_proxy_hash(request)) {
3291 RPROXY("Failed to insert retransmission into the proxy list");
3292 goto post_proxy_fail;
3296 * Free the old packet, to force re-encoding
3298 talloc_free(request->proxy->data);
3299 request->proxy->data = NULL;
3300 request->proxy->data_len = 0;
3302 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3308 /** Ping a home server.
3311 static void request_ping(REQUEST *request, int action)
3313 home_server_t *home = request->home_server;
3316 VERIFY_REQUEST(request);
3318 TRACE_STATE_MACHINE;
3322 case FR_ACTION_TIMER:
3323 ERROR("No response to status check %d ID %u for home server %s port %d",
3326 inet_ntop(request->proxy->dst_ipaddr.af,
3327 &request->proxy->dst_ipaddr.ipaddr,
3328 buffer, sizeof(buffer)),
3329 request->proxy->dst_port);
3332 case FR_ACTION_PROXY_REPLY:
3333 rad_assert(request->in_proxy_hash);
3335 request->home_server->num_received_pings++;
3336 RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3337 request->number, request->proxy->id, home->num_received_pings);
3340 * Remove the request from any hashes
3342 fr_event_delete(el, &request->ev);
3343 remove_from_proxy_hash(request);
3346 * The control socket may have marked the home server as
3347 * alive. OR, it may have suddenly started responding to
3348 * requests again. If so, don't re-do the "make alive"
3351 if (home->state == HOME_STATE_ALIVE) break;
3354 * It's dead, and we haven't received enough ping
3355 * responses to mark it "alive". Wait a bit.
3357 * If it's zombie, we mark it alive immediately.
3359 if ((home->state == HOME_STATE_IS_DEAD) &&
3360 (home->num_received_pings < home->num_pings_to_alive)) {
3365 * Mark it alive and delete any outstanding
3368 mark_home_server_alive(request, home);
3372 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3376 rad_assert(!request->in_request_hash);
3377 rad_assert(request->ev == NULL);
3379 request_done(request, FR_ACTION_DONE);
3383 * Called from start of zombie period, OR after control socket
3384 * marks the home server dead.
3386 static void ping_home_server(void *ctx)
3388 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3391 struct timeval when, now;
3393 if ((home->state == HOME_STATE_ALIVE) ||
3395 (home->proto == IPPROTO_TCP) ||
3397 (home->ev != NULL)) {
3401 gettimeofday(&now, NULL);
3405 * We've run out of zombie time. Mark it dead.
3407 if (home->state == HOME_STATE_ZOMBIE) {
3408 when = home->zombie_period_start;
3409 when.tv_sec += home->zombie_period;
3411 if (timercmp(&when, &now, <)) {
3412 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3413 mark_home_server_dead(home, &now);
3418 * We're not supposed to be pinging it. Just wake up
3419 * when we're supposed to mark it dead.
3421 if (home->ping_check == HOME_PING_CHECK_NONE) {
3422 if (home->state == HOME_STATE_ZOMBIE) {
3423 home->when = home->zombie_period_start;
3424 home->when.tv_sec += home->zombie_period;
3425 INSERT_EVENT(ping_home_server, home);
3429 * Else mark_home_server_dead will set a timer
3430 * for revive_interval.
3436 request = request_alloc(NULL);
3437 if (!request) return;
3438 request->number = request_num_counter++;
3441 request->proxy = rad_alloc(request, true);
3442 rad_assert(request->proxy != NULL);
3444 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3445 request->proxy->code = PW_CODE_STATUS_SERVER;
3447 fr_pair_make(request->proxy, &request->proxy->vps,
3448 "Message-Authenticator", "0x00", T_OP_SET);
3450 } else if (home->type == HOME_TYPE_AUTH) {
3451 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3453 fr_pair_make(request->proxy, &request->proxy->vps,
3454 "User-Name", home->ping_user_name, T_OP_SET);
3455 fr_pair_make(request->proxy, &request->proxy->vps,
3456 "User-Password", home->ping_user_password, T_OP_SET);
3457 fr_pair_make(request->proxy, &request->proxy->vps,
3458 "Service-Type", "Authenticate-Only", T_OP_SET);
3459 fr_pair_make(request->proxy, &request->proxy->vps,
3460 "Message-Authenticator", "0x00", T_OP_SET);
3463 #ifdef WITH_ACCOUNTING
3464 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3466 fr_pair_make(request->proxy, &request->proxy->vps,
3467 "User-Name", home->ping_user_name, T_OP_SET);
3468 fr_pair_make(request->proxy, &request->proxy->vps,
3469 "Acct-Status-Type", "Stop", T_OP_SET);
3470 fr_pair_make(request->proxy, &request->proxy->vps,
3471 "Acct-Session-Id", "00000000", T_OP_SET);
3472 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3473 "Event-Timestamp", "0", T_OP_SET);
3474 vp->vp_date = now.tv_sec;
3476 rad_assert("Internal sanity check failed");
3480 vp = fr_pair_make(request->proxy, &request->proxy->vps,
3481 "NAS-Identifier", "", T_OP_SET);
3483 fr_pair_value_sprintf(vp, "Status Check %u. Are you alive?",
3484 home->num_sent_pings);
3488 request->proxy->proto = home->proto;
3490 request->proxy->src_ipaddr = home->src_ipaddr;
3491 request->proxy->dst_ipaddr = home->ipaddr;
3492 request->proxy->dst_port = home->port;
3493 request->home_server = home;
3494 #ifdef DEBUG_STATE_MACHINE
3495 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3496 child_state_names[request->child_state],
3497 child_state_names[REQUEST_DONE]);
3498 if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3500 #ifdef HAVE_PTHREAD_H
3501 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3503 request->child_state = REQUEST_PROXIED;
3504 request->process = request_ping;
3506 rad_assert(request->proxy_listener == NULL);
3508 if (!insert_into_proxy_hash(request)) {
3509 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3512 rad_assert(!request->in_request_hash);
3513 rad_assert(!request->in_proxy_hash);
3514 rad_assert(request->ev == NULL);
3515 talloc_free(request);
3520 * Set up the timer callback.
3523 when.tv_sec += home->ping_timeout;
3525 DEBUG("PING: Waiting %u seconds for response to ping",
3526 home->ping_timeout);
3528 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3529 home->num_sent_pings++;
3531 rad_assert(request->proxy_listener != NULL);
3532 debug_packet(request, request->proxy, false);
3533 request->proxy_listener->send(request->proxy_listener,
3537 * Add +/- 2s of jitter, as suggested in RFC 3539
3538 * and in the Issues and Fixes draft.
3541 home->when.tv_sec += home->ping_interval;
3543 add_jitter(&home->when);
3545 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3546 INSERT_EVENT(ping_home_server, home);
3549 static void home_trigger(home_server_t *home, char const *trigger)
3551 REQUEST *my_request;
3552 RADIUS_PACKET *my_packet;
3554 my_request = talloc_zero(NULL, REQUEST);
3555 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3556 my_request->proxy = my_packet;
3557 my_packet->dst_ipaddr = home->ipaddr;
3558 my_packet->src_ipaddr = home->src_ipaddr;
3560 exec_trigger(my_request, home->cs, trigger, false);
3561 talloc_free(my_request);
3564 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3571 rad_assert((home->state == HOME_STATE_ALIVE) ||
3572 (home->state == HOME_STATE_UNKNOWN));
3575 if (home->proto == IPPROTO_TCP) {
3576 WARN("Not marking TCP server %s zombie", home->log_name);
3582 * We've received a real packet recently. Don't mark the
3583 * server as zombie until we've received NO packets for a
3584 * while. The "1/4" of zombie period was chosen rather
3585 * arbitrarily. It's a balance between too short, which
3586 * gives quick fail-over and fail-back, or too long,
3587 * where the proxy still sends packets to an unresponsive
3590 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3591 if (home->last_packet_recv >= start) {
3592 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3593 (int) (now->tv_sec - home->last_packet_recv));
3597 home->state = HOME_STATE_ZOMBIE;
3598 home_trigger(home, "home_server.zombie");
3601 * Set the home server to "zombie", as of the time
3604 home->zombie_period_start.tv_sec = start;
3605 home->zombie_period_start.tv_usec = USEC / 2;
3607 fr_event_delete(el, &home->ev);
3609 home->num_sent_pings = 0;
3610 home->num_received_pings = 0;
3612 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3613 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3614 buffer, sizeof(buffer)),
3615 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3617 ping_home_server(home);
3621 void revive_home_server(void *ctx)
3623 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3627 rad_assert(home->proto != IPPROTO_TCP);
3630 home->state = HOME_STATE_ALIVE;
3631 home->response_timeouts = 0;
3632 home_trigger(home, "home_server.alive");
3633 home->currently_outstanding = 0;
3634 gettimeofday(&home->revive_time, NULL);
3637 * Delete any outstanding events.
3640 if (home->ev) fr_event_delete(el, &home->ev);
3642 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3643 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3644 buffer, sizeof(buffer)),
3648 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3650 int previous_state = home->state;
3654 if (home->proto == IPPROTO_TCP) {
3655 WARN("Not marking TCP server dead");
3660 PROXY( "Marking home server %s port %d as dead.",
3661 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3662 buffer, sizeof(buffer)),
3665 home->state = HOME_STATE_IS_DEAD;
3666 home_trigger(home, "home_server.dead");
3668 if (home->ping_check != HOME_PING_CHECK_NONE) {
3670 * If the control socket marks us dead, start
3671 * pinging. Otherwise, we already started
3672 * pinging when it was marked "zombie".
3674 if (previous_state == HOME_STATE_ALIVE) {
3675 ping_home_server(home);
3677 DEBUG("PING: Already pinging home server %s", home->log_name);
3682 * Revive it after a fixed period of time. This
3683 * is very, very, bad.
3686 home->when.tv_sec += home->revive_interval;
3688 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3690 INSERT_EVENT(revive_home_server, home);
3694 /** Wait for a reply after proxying a request.
3696 * Retransmit the proxied packet, or time out and go to
3697 * proxy_no_reply. Mark the home server unresponsive, etc.
3699 * If we do receive a reply, we transition to proxy_running.
3702 * digraph proxy_wait_for_reply {
3703 * proxy_wait_for_reply;
3705 * proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3706 * proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3707 * proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3708 * proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3709 * proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3713 static void proxy_wait_for_reply(REQUEST *request, int action)
3715 struct timeval now, when;
3716 struct timeval *response_window = NULL;
3717 home_server_t *home = request->home_server;
3720 VERIFY_REQUEST(request);
3722 TRACE_STATE_MACHINE;
3725 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3726 rad_assert(request->home_server != NULL);
3728 gettimeofday(&now, NULL);
3733 * We have a reply, ignore the retransmit.
3735 if (request->proxy_reply) return;
3738 * The request was proxied to a virtual server.
3739 * Ignore the retransmit.
3741 if (request->home_server->server) return;
3744 * Use a new connection when the home server is
3745 * dead, or when there's no proxy listener, or
3746 * when the listener is failed or dead.
3748 * If the listener is known or frozen, use it for
3751 if ((home->state == HOME_STATE_IS_DEAD) ||
3752 !request->proxy_listener ||
3753 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3754 request_proxy_anew(request);
3760 * The home server is still alive, but TCP. We
3761 * rely on TCP to get the request and reply back.
3762 * So there's no need to retransmit.
3764 if (home->proto == IPPROTO_TCP) {
3765 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3766 inet_ntop(request->proxy->dst_ipaddr.af,
3767 &request->proxy->dst_ipaddr.ipaddr,
3768 buffer, sizeof(buffer)),
3769 request->proxy->dst_port,
3770 request->proxy->id);
3776 * More than one retransmit a second is stupid,
3777 * and should be suppressed by the proxy.
3779 when = request->proxy_retransmit;
3782 if (timercmp(&now, &when, <)) {
3783 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3784 inet_ntop(request->proxy->dst_ipaddr.af,
3785 &request->proxy->dst_ipaddr.ipaddr,
3786 buffer, sizeof(buffer)),
3787 request->proxy->dst_port,
3788 request->proxy->id);
3792 #ifdef WITH_ACCOUNTING
3794 * If we update the Acct-Delay-Time, we need to
3797 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3798 fr_pair_find_by_num(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3799 request_proxy_anew(request);
3804 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3805 inet_ntop(request->proxy->dst_ipaddr.af,
3806 &request->proxy->dst_ipaddr.ipaddr,
3807 buffer, sizeof(buffer)),
3808 request->proxy->dst_port,
3809 request->proxy->id);
3810 request->num_proxied_requests++;
3812 rad_assert(request->proxy_listener != NULL);
3813 FR_STATS_TYPE_INC(home->stats.total_requests);
3814 home->last_packet_sent = now.tv_sec;
3815 request->proxy_retransmit = now;
3816 debug_packet(request, request->proxy, false);
3817 request->proxy_listener->send(request->proxy_listener, request);
3820 case FR_ACTION_TIMER:
3821 response_window = request_response_window(request);
3824 if (!request->proxy_listener ||
3825 (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3826 remove_from_proxy_hash(request);
3828 when = request->packet->timestamp;
3829 when.tv_sec += request->root->max_request_time;
3831 if (timercmp(&when, &now, >)) {
3832 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3833 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3840 * Wake up "response_window" time in the future.
3841 * i.e. when MY packet hasn't received a response.
3843 * Note that we DO NOT mark the home server as
3844 * zombie if it doesn't respond to us. It may be
3845 * responding to other (better looking) packets.
3847 when = request->proxy->timestamp;
3848 timeradd(&when, response_window, &when);
3851 * Not at the response window. Set the timer for
3854 if (timercmp(&when, &now, >)) {
3855 struct timeval diff;
3856 timersub(&when, &now, &diff);
3858 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3859 (int) diff.tv_sec, (int) diff.tv_usec);
3860 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3865 RDEBUG("No proxy response, giving up on request and marking it done");
3868 * If we haven't received any packets for
3869 * "response_window", then mark the home server
3872 * If the connection is TCP, then another
3873 * "watchdog timer" function takes care of pings,
3874 * etc. So we don't need to do it here.
3876 * This check should really be part of a home
3877 * server state machine.
3879 if (((home->state == HOME_STATE_ALIVE) ||
3880 (home->state == HOME_STATE_UNKNOWN))
3882 && (home->proto != IPPROTO_TCP)
3885 home->response_timeouts++;
3886 if (home->response_timeouts >= home->max_response_timeouts)
3887 mark_home_server_zombie(home, &now, response_window);
3890 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3891 if (home->type == HOME_TYPE_AUTH) {
3892 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3893 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3896 else if (home->type == HOME_TYPE_ACCT) {
3897 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3898 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3903 * There was no response within the window. Stop
3904 * the request. If the client retransmitted, it
3905 * may have failed over to another home server.
3906 * But that one may be dead, too.
3908 * The extra verbose message if we have a username,
3909 * is extremely useful if the proxy is part of a chain
3910 * and the final home server, is not the one we're
3913 if (request->username) {
3914 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3915 "server %s port %d",
3916 request->username->vp_strvalue,
3917 inet_ntop(request->proxy->dst_ipaddr.af,
3918 &request->proxy->dst_ipaddr.ipaddr,
3919 buffer, sizeof(buffer)),
3920 request->proxy->dst_port);
3922 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3923 inet_ntop(request->proxy->dst_ipaddr.af,
3924 &request->proxy->dst_ipaddr.ipaddr,
3925 buffer, sizeof(buffer)),
3926 request->proxy->dst_port);
3929 if (setup_post_proxy_fail(request)) {
3930 request_queue_or_run(request, proxy_no_reply);
3932 gettimeofday(&request->reply->timestamp, NULL);
3933 request_cleanup_delay_init(request);
3938 * We received a new reply. Go process it.
3940 case FR_ACTION_PROXY_REPLY:
3941 request_queue_or_run(request, proxy_running);
3945 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3949 #endif /* WITH_PROXY */
3952 /***********************************************************************
3956 ***********************************************************************/
3958 static int null_handler(UNUSED REQUEST *request)
3964 * See if we need to originate a CoA request.
3966 static void request_coa_originate(REQUEST *request)
3968 int rcode, pre_proxy_type = 0;
3974 VERIFY_REQUEST(request);
3976 rad_assert(request->coa != NULL);
3977 rad_assert(request->proxy == NULL);
3978 rad_assert(!request->in_proxy_hash);
3979 rad_assert(request->proxy_reply == NULL);
3982 * Check whether we want to originate one, or cancel one.
3984 vp = fr_pair_find_by_num(request->config, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3986 vp = fr_pair_find_by_num(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3990 if (vp->vp_integer == 0) {
3992 TALLOC_FREE(request->coa);
4000 * src_ipaddr will be set up in proxy_encode.
4002 memset(&ipaddr, 0, sizeof(ipaddr));
4003 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
4005 ipaddr.af = AF_INET;
4006 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4008 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
4009 ipaddr.af = AF_INET6;
4010 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4011 ipaddr.prefix = 128;
4012 } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
4013 coa->home_pool = home_pool_byname(vp->vp_strvalue,
4015 if (!coa->home_pool) {
4016 RWDEBUG2("No such home_server_pool %s",
4022 * Prefer the pool to one server
4024 } else if (request->client->coa_pool) {
4025 coa->home_pool = request->client->coa_pool;
4027 } else if (request->client->coa_server) {
4028 coa->home_server = request->client->coa_server;
4032 * If all else fails, send it to the client that
4033 * originated this request.
4035 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4039 * Use the pool, if it exists.
4041 if (coa->home_pool) {
4042 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4043 if (!coa->home_server) {
4044 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4047 home_server_update_request(coa->home_server, coa);
4049 } else if (!coa->home_server) {
4050 uint16_t port = PW_COA_UDP_PORT;
4052 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
4053 if (vp) port = vp->vp_integer;
4055 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4056 if (!coa->home_server) {
4057 RWDEBUG2("Unknown destination %s:%d for CoA request.",
4058 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4059 buffer, sizeof(buffer)), port);
4064 vp = fr_pair_find_by_num(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
4066 switch (vp->vp_integer) {
4067 case PW_CODE_COA_REQUEST:
4068 case PW_CODE_DISCONNECT_REQUEST:
4069 coa->proxy->code = vp->vp_integer;
4073 DEBUG("Cannot set CoA Packet-Type to code %d",
4079 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4082 * The rest of the server code assumes that
4083 * request->packet && request->reply exist. Copy them
4084 * from the original request.
4086 rad_assert(coa->packet != NULL);
4087 rad_assert(coa->packet->vps == NULL);
4089 coa->packet = rad_copy_packet(coa, request->packet);
4090 coa->reply = rad_copy_packet(coa, request->reply);
4092 coa->config = fr_pair_list_copy(coa, request->config);
4093 coa->num_coa_requests = 0;
4094 coa->handle = null_handler;
4095 coa->number = request->number; /* it's associated with the same request */
4098 * Call the pre-proxy routines.
4100 vp = fr_pair_find_by_num(request->config, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
4102 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
4103 /* Must be a validation issue */
4105 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4106 pre_proxy_type = vp->vp_integer;
4109 if (coa->home_pool && coa->home_pool->virtual_server) {
4110 char const *old_server = coa->server;
4112 coa->server = coa->home_pool->virtual_server;
4113 RDEBUG2("server %s {", coa->server);
4115 rcode = process_pre_proxy(pre_proxy_type, coa);
4118 coa->server = old_server;
4120 rcode = process_pre_proxy(pre_proxy_type, coa);
4127 * Only send the CoA packet if the pre-proxy code succeeded.
4129 case RLM_MODULE_NOOP:
4131 case RLM_MODULE_UPDATED:
4136 * Source IP / port is set when the proxy socket
4139 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4140 coa->proxy->dst_port = coa->home_server->port;
4142 if (!insert_into_proxy_hash(coa)) {
4143 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4148 * We CANNOT divorce the CoA request from the parent
4149 * request. This function is running in a child thread,
4150 * and we need access to the main event loop in order to
4151 * to add the timers for the CoA packet.
4153 * Instead, we wait for the timer on the parent request
4156 gettimeofday(&coa->proxy->timestamp, NULL);
4157 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4158 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4159 coa->delay = 0; /* need to calculate a new delay */
4162 * If requested, put a State attribute into the packet,
4163 * and cache the VPS.
4165 fr_state_put_vps(coa, NULL, coa->packet);
4168 * Encode the packet before we do anything else.
4170 coa->proxy_listener->encode(coa->proxy_listener, coa);
4171 debug_packet(coa, coa->proxy, false);
4173 #ifdef DEBUG_STATE_MACHINE
4174 if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4175 child_state_names[request->child_state],
4176 child_state_names[REQUEST_PROXIED]);
4180 * Set the state function, then the state, no child, and
4183 coa->process = coa_wait_for_reply;
4184 coa->child_state = REQUEST_PROXIED;
4186 #ifdef HAVE_PTHREAD_H
4187 coa->child_pid = NO_SUCH_CHILD_PID;
4190 if (we_are_master()) coa_separate(request->coa);
4193 * And send the packet.
4195 coa->proxy_listener->send(coa->proxy_listener, coa);
4199 static void coa_retransmit(REQUEST *request)
4201 uint32_t delay, frac;
4202 struct timeval now, when, mrd;
4205 VERIFY_REQUEST(request);
4207 fr_event_now(el, &now);
4209 if (request->delay == 0) {
4211 * Implement re-transmit algorithm as per RFC 5080
4214 * We want IRT + RAND*IRT
4215 * or 0.9 IRT + rand(0,.2) IRT
4217 * 2^20 ~ USEC, and we want 2.
4218 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4220 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4221 request->delay = delay * request->home_server->coa_irt;
4222 delay = request->home_server->coa_irt * USEC;
4223 delay -= delay / 10;
4224 delay += request->delay;
4225 request->delay = delay;
4227 when = request->proxy->timestamp;
4228 tv_add(&when, delay);
4230 if (timercmp(&when, &now, >)) {
4231 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4237 * Retransmit CoA request.
4241 * Cap count at MRC, if it is non-zero.
4243 if (request->home_server->coa_mrc &&
4244 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4245 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4247 inet_ntop(request->proxy->dst_ipaddr.af,
4248 &request->proxy->dst_ipaddr.ipaddr,
4249 buffer, sizeof(buffer)),
4250 request->proxy->dst_port);
4252 if (setup_post_proxy_fail(request)) {
4253 request_queue_or_run(request, coa_no_reply);
4255 request_done(request, FR_ACTION_DONE);
4261 * RFC 5080 Section 2.2.1
4263 * RT = 2*RTprev + RAND*RTprev
4264 * = 1.9 * RTprev + rand(0,.2) * RTprev
4265 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4268 delay ^= (delay >> 16);
4270 frac = request->delay / 5;
4271 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4273 delay += (2 * request->delay) - (request->delay / 10);
4276 * Cap delay at MRT, if MRT is non-zero.
4278 if (request->home_server->coa_mrt &&
4279 (delay > (request->home_server->coa_mrt * USEC))) {
4280 int mrt_usec = request->home_server->coa_mrt * USEC;
4283 * delay = MRT + RAND * MRT
4284 * = 0.9 MRT + rand(0,.2) * MRT
4287 delay ^= (delay >> 15);
4289 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4290 delay += mrt_usec - (mrt_usec / 10);
4293 request->delay = delay;
4295 tv_add(&when, request->delay);
4296 mrd = request->proxy->timestamp;
4297 mrd.tv_sec += request->home_server->coa_mrd;
4300 * Cap duration at MRD.
4302 if (timercmp(&mrd, &when, <)) {
4305 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4307 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4309 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4311 RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4312 inet_ntop(request->proxy->dst_ipaddr.af,
4313 &request->proxy->dst_ipaddr.ipaddr,
4314 buffer, sizeof(buffer)),
4315 request->proxy->dst_port,
4316 request->proxy->id);
4318 request->proxy_listener->send(request->proxy_listener,
4323 /** Wait for a reply after originating a CoA a request.
4325 * Retransmit the proxied packet, or time out and go to
4326 * coa_no_reply. Mark the home server unresponsive, etc.
4328 * If we do receive a reply, we transition to coa_running.
4331 * digraph coa_wait_for_reply {
4332 * coa_wait_for_reply;
4334 * coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4335 * coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4336 * coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4337 * coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4341 static void coa_wait_for_reply(REQUEST *request, int action)
4343 VERIFY_REQUEST(request);
4345 TRACE_STATE_MACHINE;
4349 if (request->parent) coa_separate(request);
4352 case FR_ACTION_TIMER:
4353 if (request_max_time(request)) break;
4355 coa_retransmit(request);
4358 case FR_ACTION_PROXY_REPLY:
4359 request_queue_or_run(request, coa_running);
4363 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4368 static void coa_separate(REQUEST *request)
4370 VERIFY_REQUEST(request);
4371 #ifdef DEBUG_STATE_MACHINE
4372 int action = FR_ACTION_TIMER;
4375 TRACE_STATE_MACHINE;
4378 rad_assert(request->parent != NULL);
4379 rad_assert(request->parent->coa == request);
4380 rad_assert(request->ev == NULL);
4381 rad_assert(!request->in_request_hash);
4382 rad_assert(request->coa == NULL);
4384 rad_assert(request->proxy_reply || request->proxy_listener);
4386 (void) talloc_steal(NULL, request);
4387 request->parent->coa = NULL;
4388 request->parent = NULL;
4390 if (we_are_master()) {
4392 coa_retransmit(request);
4397 /** Process a request after the CoA has timed out.
4399 * Run the packet through Post-Proxy-Type Fail
4402 * digraph coa_no_reply {
4405 * coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4406 * coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4407 * coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4408 * coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4409 * coa_no_reply -> done [ label = "TIMER >= timeout" ];
4413 static void coa_no_reply(REQUEST *request, int action)
4417 VERIFY_REQUEST(request);
4419 TRACE_STATE_MACHINE;
4423 case FR_ACTION_TIMER:
4424 (void) request_max_time(request);
4427 case FR_ACTION_PROXY_REPLY: /* too late! */
4428 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4429 inet_ntop(request->proxy->src_ipaddr.af,
4430 &request->proxy->src_ipaddr.ipaddr,
4431 buffer, sizeof(buffer)),
4432 request->proxy->dst_port, request->proxy->id);
4436 if (process_proxy_reply(request, NULL)) {
4437 request->handle(request);
4439 request_done(request, FR_ACTION_DONE);
4443 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4449 /** Process the request after receiving a coa reply.
4451 * Throught the post-proxy section, and the through the handler
4455 * digraph coa_running {
4458 * coa_running -> timer [ label = "TIMER < max_request_time" ];
4459 * coa_running -> process_proxy_reply [ label = "RUN" ];
4460 * coa_running -> done [ label = "TIMER >= timeout" ];
4464 static void coa_running(REQUEST *request, int action)
4466 VERIFY_REQUEST(request);
4468 TRACE_STATE_MACHINE;
4472 case FR_ACTION_TIMER:
4473 (void) request_max_time(request);
4477 if (process_proxy_reply(request, request->proxy_reply)) {
4478 request->handle(request);
4480 request_done(request, FR_ACTION_DONE);
4484 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4488 #endif /* WITH_COA */
4490 /***********************************************************************
4492 * End of the State machine. Start of additional helper code.
4494 ***********************************************************************/
4496 /***********************************************************************
4500 ***********************************************************************/
4501 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4503 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4505 rad_assert(xel == el);
4507 if ((listener->fd < 0)
4509 #ifndef WITH_DETAIL_THREAD
4510 && (listener->type != RAD_LISTEN_DETAIL)
4516 listener->print(listener, buffer, sizeof(buffer));
4517 ERROR("FATAL: Asked to read from closed socket: %s",
4520 rad_panic("Socket was closed on us!");
4524 listener->recv(listener);
4528 #ifdef WITH_DETAIL_THREAD
4531 * This function is called periodically to see if this detail
4532 * file is available for reading.
4534 static void event_poll_detail(void *ctx)
4537 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4538 struct timeval when, now;
4539 listen_detail_t *detail = this->data;
4541 rad_assert(this->type == RAD_LISTEN_DETAIL);
4544 event_socket_handler(el, this->fd, this);
4546 fr_event_now(el, &now);
4550 * Backdoor API to get the delay until the next poll
4553 delay = this->encode(this, NULL);
4554 if (delay == 0) goto redo;
4556 tv_add(&when, delay);
4559 if (!fr_event_insert(el, event_poll_detail, this,
4560 &when, &detail->ev)) {
4561 ERROR("Failed creating handler");
4565 #endif /* WITH_DETAIL_THREAD */
4566 #endif /* WITH_DETAIL */
4568 static void event_status(struct timeval *wake)
4570 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4574 if (rad_debug_lvl == 0) {
4576 INFO("Ready to process requests");
4577 just_started = false;
4583 INFO("Ready to process requests");
4585 } else if ((wake->tv_sec != 0) ||
4586 (wake->tv_usec >= 100000)) {
4587 DEBUG("Waking up in %d.%01u seconds.",
4588 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4593 * FIXME: Put this somewhere else, where it isn't called
4594 * all of the time...
4597 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4599 * If there are no child threads, then there may
4600 * be child processes. In that case, wait for
4601 * their exit status, and throw that exit status
4602 * away. This helps get rid of zxombie children.
4604 while (waitpid(-1, &argval, WNOHANG) > 0) {
4612 static void listener_free_cb(void *ctx)
4614 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4617 if (this->count > 0) {
4618 struct timeval when;
4619 listen_socket_t *sock = this->data;
4621 fr_event_now(el, &when);
4625 if (!fr_event_insert(el, listener_free_cb, this, &when,
4627 rad_panic("Failed to insert event");
4634 * It's all free, close the socket.
4637 this->print(this, buffer, sizeof(buffer));
4638 DEBUG("... cleaning up socket %s", buffer);
4639 rad_assert(this->next == NULL);
4645 static int proxy_eol_cb(void *ctx, void *data)
4647 struct timeval when;
4648 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4650 if (request->proxy_listener != ctx) return 0;
4653 * We don't care if it's being processed in a child thread.
4656 #ifdef WITH_ACCOUNTING
4658 * Accounting packets should be deleted immediately.
4659 * They will never be retransmitted by the client.
4661 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4662 RDEBUG("Stopping request due to failed connection to home server");
4663 request->master_state = REQUEST_STOP_PROCESSING;
4668 * Reset the timer to be now, so that the request is
4669 * quickly updated. But spread the requests randomly
4670 * over the next second, so that we don't overload the
4673 fr_event_now(el, &when);
4674 tv_add(&when, fr_rand() % USEC);
4675 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4678 * Don't delete it from the list.
4684 static int event_new_fd(rad_listen_t *this)
4690 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4692 this->print(this, buffer, sizeof(buffer));
4694 if (this->status == RAD_LISTEN_STATUS_INIT) {
4695 listen_socket_t *sock = this->data;
4697 rad_assert(sock != NULL);
4699 DEBUG("Listening on %s", buffer);
4701 INFO(" ... adding new socket %s", buffer);
4705 if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4706 home_server_t *home;
4709 if (!home || !home->limit.max_connections) {
4710 INFO(" ... adding new socket %s", buffer);
4712 INFO(" ... adding new socket %s (%u of %u)", buffer,
4713 home->limit.num_connections, home->limit.max_connections);
4719 switch (this->type) {
4722 * Detail files are always known, and aren't
4723 * put into the socket event loop.
4725 case RAD_LISTEN_DETAIL:
4726 this->status = RAD_LISTEN_STATUS_KNOWN;
4728 #ifndef WITH_DETAIL_THREAD
4730 * Set up the first poll interval.
4732 event_poll_detail(this);
4735 break; /* add the FD to the list */
4737 #endif /* WITH_DETAIL */
4741 * Add it to the list of sockets we can use.
4742 * Server sockets (i.e. auth/acct) are never
4743 * added to the packet list.
4745 case RAD_LISTEN_PROXY:
4747 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4750 * Add timers to outgoing child sockets, if necessary.
4752 if (sock->proto == IPPROTO_TCP && sock->opened &&
4753 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4754 struct timeval when;
4756 when.tv_sec = sock->opened + 1;
4760 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4762 rad_panic("Failed to insert event");
4767 #endif /* WITH_PROXY */
4770 * FIXME: put idle timers on command sockets.
4776 * Add timers to incoming child sockets, if necessary.
4778 if (sock->proto == IPPROTO_TCP && sock->opened &&
4779 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4780 struct timeval when;
4782 when.tv_sec = sock->opened + 1;
4786 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4788 ERROR("Failed adding timer for socket: %s", fr_strerror());
4794 } /* switch over listener types */
4797 * All sockets: add the FD to the event handler.
4799 if (!fr_event_fd_insert(el, 0, this->fd,
4800 event_socket_handler, this)) {
4801 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4805 this->status = RAD_LISTEN_STATUS_KNOWN;
4811 * The socket has reached a timeout. Try to close it.
4813 if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4815 * Requests are still using the socket. Wait for
4818 if (this->count > 0) {
4819 struct timeval when;
4820 listen_socket_t *sock = this->data;
4823 * Try again to clean up the socket in 30
4826 gettimeofday(&when, NULL);
4830 if (!fr_event_insert(el,
4831 (fr_event_callback_t) event_new_fd,
4832 this, &when, &sock->ev)) {
4833 rad_panic("Failed to insert event");
4839 fr_event_fd_delete(el, 0, this->fd);
4840 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4844 * The socket has had a catastrophic error. Close it.
4846 if (this->status == RAD_LISTEN_STATUS_EOL) {
4848 * Remove it from the list of live FD's.
4850 fr_event_fd_delete(el, 0, this->fd);
4854 * Tell all requests using this socket that the socket is dead.
4856 if (this->type == RAD_LISTEN_PROXY) {
4857 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4858 if (!fr_packet_list_socket_freeze(proxy_list,
4860 ERROR("Fatal error freezing socket: %s", fr_strerror());
4864 if (this->count > 0) {
4865 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4867 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4872 * Requests are still using the socket. Wait for
4875 if (this->count > 0) {
4876 struct timeval when;
4877 listen_socket_t *sock = this->data;
4880 * Try again to clean up the socket in 30
4883 gettimeofday(&when, NULL);
4887 if (!fr_event_insert(el,
4888 (fr_event_callback_t) event_new_fd,
4889 this, &when, &sock->ev)) {
4890 rad_panic("Failed to insert event");
4897 * No one is using the socket. We can remove it now.
4899 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4900 } /* socket is at EOL */
4906 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4909 listen_socket_t *sock = this->data;
4911 struct timeval when;
4914 * Re-open the socket, pointing it to /dev/null.
4915 * This means that all writes proceed without
4916 * blocking, and all reads return "no data".
4918 * This leaves the socket active, so any child
4919 * threads won't go insane. But it means that
4920 * they cannot send or receive any packets.
4922 * This is EXTRA work in the normal case, when
4923 * sockets are closed without error. But it lets
4924 * us have one simple processing method for all
4927 devnull = open("/dev/null", O_RDWR);
4929 ERROR("FATAL failure opening /dev/null: %s",
4930 fr_syserror(errno));
4933 if (dup2(devnull, this->fd) < 0) {
4934 ERROR("FATAL failure closing socket: %s",
4935 fr_syserror(errno));
4941 rad_assert(this->type != RAD_LISTEN_DETAIL);
4947 * The socket is dead. Force all proxied packets
4948 * to stop using it. And then remove it from the
4949 * list of outgoing sockets.
4951 if (this->type == RAD_LISTEN_PROXY) {
4952 home_server_t *home;
4955 if (!home || !home->limit.max_connections) {
4956 INFO(" ... shutting down socket %s", buffer);
4958 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4959 home->limit.num_connections, home->limit.max_connections);
4962 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4963 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4965 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4966 ERROR("Fatal error removing socket %s: %s",
4967 buffer, fr_strerror());
4970 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4974 INFO(" ... shutting down socket %s", buffer);
4977 * EOL all requests using this socket.
4979 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4983 * No child threads, clean it up now.
4987 if (sock->ev) fr_event_delete(el, &sock->ev);
4993 * Wait until all requests using this socket are done.
4995 gettimeofday(&when, NULL);
4999 if (!fr_event_insert(el, listener_free_cb, this, &when,
5001 rad_panic("Failed to insert event");
5004 #endif /* WITH_TCP */
5009 /***********************************************************************
5013 ***********************************************************************/
5015 static void handle_signal_self(int flag)
5019 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5020 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5021 INFO("Signalled to exit");
5022 fr_event_loop_exit(el, 1);
5024 INFO("Signalled to terminate");
5025 fr_event_loop_exit(el, 2);
5029 } /* else exit/term flags weren't set */
5032 * Tell the even loop to stop processing.
5034 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5036 static time_t last_hup = 0;
5039 if ((int) (when - last_hup) < 5) {
5040 INFO("Ignoring HUP (less than 5s since last one)");
5044 INFO("Received HUP signal");
5048 exec_trigger(NULL, NULL, "server.signal.hup", true);
5049 fr_event_loop_exit(el, 0x80);
5052 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5053 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5057 * FIXME: O(N) loops suck.
5059 for (this = main_config.listen;
5061 this = this->next) {
5062 if (this->type != RAD_LISTEN_DETAIL) continue;
5065 * This one didn't send the signal, skip
5068 if (!this->decode(this, NULL)) continue;
5071 * Go service the interrupt.
5073 event_poll_detail(this);
5078 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5080 * There are new listeners in the list. Run
5081 * event_new_fd() on them.
5083 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5084 rad_listen_t *this, *next;
5086 FD_MUTEX_LOCK(&fd_mutex);
5089 * FIXME: unlock the mutex before calling
5092 for (this = new_listeners; this != NULL; this = next) {
5099 new_listeners = NULL;
5100 FD_MUTEX_UNLOCK(&fd_mutex);
5105 #ifndef HAVE_PTHREAD_H
5106 void radius_signal_self(int flag)
5108 return handle_signal_self(flag);
5112 static int self_pipe[2] = { -1, -1 };
5115 * Inform ourselves that we received a signal.
5117 void radius_signal_self(int flag)
5123 * The read MUST be non-blocking for this to work.
5125 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5129 for (i = 0; i < rcode; i++) {
5130 buffer[0] |= buffer[i];
5138 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5142 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5143 UNUSED int fd, UNUSED void *ctx)
5148 rcode = read(self_pipe[0], buffer, sizeof(buffer));
5149 if (rcode <= 0) return;
5152 * Merge pending signals.
5154 for (i = 0; i < rcode; i++) {
5155 buffer[0] |= buffer[i];
5158 handle_signal_self(buffer[0]);
5160 #endif /* HAVE_PTHREAD_H */
5162 /***********************************************************************
5164 * Bootstrapping code.
5166 ***********************************************************************/
5169 * Externally-visibly functions.
5171 int radius_event_init(TALLOC_CTX *ctx) {
5172 el = fr_event_list_create(ctx, event_status);
5178 static int packet_entry_cmp(void const *one, void const *two)
5180 RADIUS_PACKET const * const *a = one;
5181 RADIUS_PACKET const * const *b = two;
5183 return fr_packet_cmp(*a, *b);
5188 * They haven't defined a proxy listener. Automatically
5189 * add one for them, with the correct address family.
5191 static void create_default_proxy_listener(int af)
5195 listen_socket_t *sock;
5198 memset(&home, 0, sizeof(home));
5201 * Open a default UDP port
5203 home.proto = IPPROTO_UDP;
5207 * Set the address family.
5209 home.src_ipaddr.af = af;
5210 home.ipaddr.af = af;
5213 * Get the correct listener.
5215 this = proxy_new_listener(proxy_ctx, &home, port);
5221 if (!fr_packet_list_socket_add(proxy_list, this->fd,
5223 &sock->other_ipaddr, sock->other_port,
5225 ERROR("Failed adding proxy socket");
5230 * Insert the FD into list of FDs to listen on.
5232 radius_update_listener(this);
5236 * See if we automatically need to open a proxy socket.
5238 static void check_proxy(rad_listen_t *head)
5241 bool has_v4, has_v6;
5244 if (check_config) return;
5245 if (!main_config.proxy_requests) return;
5247 if (!home_servers_udp) return;
5250 * We passed "-i" on the command line. Use that address
5251 * family for the proxy socket.
5253 if (main_config.myip.af != AF_UNSPEC) {
5254 create_default_proxy_listener(main_config.myip.af);
5258 defined_proxy = has_v4 = has_v6 = false;
5261 * Figure out if we need to open a proxy socket, and if
5264 for (this = head; this != NULL; this = this->next) {
5265 listen_socket_t *sock;
5267 switch (this->type) {
5268 case RAD_LISTEN_PROXY:
5269 defined_proxy = true;
5272 case RAD_LISTEN_AUTH:
5274 case RAD_LISTEN_ACCT:
5277 case RAD_LISTEN_COA:
5280 if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5281 if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5290 * Assume they know what they're doing.
5292 if (defined_proxy) return;
5294 if (has_v4) create_default_proxy_listener(AF_INET);
5296 if (has_v6) create_default_proxy_listener(AF_INET6);
5300 int radius_event_start(CONF_SECTION *cs, bool have_children)
5302 rad_listen_t *head = NULL;
5304 if (fr_start_time != (time_t)-1) return 0;
5306 time(&fr_start_time);
5308 if (!check_config) {
5310 * radius_event_init() must be called first
5314 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5315 if (!pl) return 0; /* leak el */
5318 request_num_counter = 0;
5321 if (main_config.proxy_requests && !check_config) {
5323 * Create the tree for managing proxied requests and
5326 proxy_list = fr_packet_list_create(1);
5327 if (!proxy_list) return 0;
5329 #ifdef HAVE_PTHREAD_H
5330 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5331 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5332 fr_syserror(errno));
5338 * The "init_delay" is set to "response_window".
5339 * Reset it to half of "response_window" in order
5340 * to give the event loop enough time to service
5341 * the event before hitting "response_window".
5343 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5344 main_config.init_delay.tv_usec >>= 1;
5345 main_config.init_delay.tv_sec >>= 1;
5347 proxy_ctx = talloc_init("proxy");
5352 * Move all of the thread calls to this file?
5354 * It may be best for the mutexes to be in this file...
5356 spawn_flag = have_children;
5358 #ifdef HAVE_PTHREAD_H
5359 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5362 * Initialize the threads ONLY if we're spawning, AND
5363 * we're running normally.
5365 if (have_children && !check_config &&
5366 (thread_pool_init(cs, &spawn_flag) < 0)) {
5372 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5374 if (listen_init(cs, &head, spawn_flag) < 0) {
5381 #ifdef HAVE_PTHREAD_H
5383 * Child threads need a pipe to signal us, as do the
5386 if (pipe(self_pipe) < 0) {
5387 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5390 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5391 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5392 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5395 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5396 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5397 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5400 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5402 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5403 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5408 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5411 * The server temporarily switches to an unprivileged
5412 * user very early in the bootstrapping process.
5413 * However, some sockets MAY require privileged access
5414 * (bind to device, or to port < 1024, or to raw
5415 * sockets). Those sockets need to call suid up/down
5416 * themselves around the functions that need a privileged
5419 if (listen_init(cs, &head, spawn_flag) < 0) {
5423 main_config.listen = head;
5430 * At this point, no one has any business *ever* going
5433 rad_suid_down_permanent();
5440 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5442 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5444 VERIFY_REQUEST(request);
5446 request->master_state = REQUEST_STOP_PROCESSING;
5448 #ifdef HAVE_PTHREAD_H
5449 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5453 * If it's queued we can't delete it from the queue.
5455 * Otherwise, it's OK to delete it. Even RUNNING, because
5456 * that will get caught by the check above.
5458 if (request->child_state == REQUEST_QUEUED) return 0;
5460 request->in_proxy_hash = false;
5462 if (!request->in_request_hash) {
5463 request_done(request, FR_ACTION_DONE);
5467 * Delete it from the list.
5474 static int request_delete_cb(UNUSED void *ctx, void *data)
5476 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5478 VERIFY_REQUEST(request);
5480 request->master_state = REQUEST_STOP_PROCESSING;
5483 * Not done, or the child thread is still processing it.
5485 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5487 #ifdef HAVE_PTHREAD_H
5488 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5492 rad_assert(request->in_proxy_hash == false);
5495 request->in_request_hash = false;
5497 if (request->ev) fr_event_delete(el, &request->ev);
5499 if (main_config.memory_report) {
5500 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5501 request->packet->id,
5502 (unsigned int) (request->timestamp - fr_start_time));
5507 rad_assert(!request->coa->in_proxy_hash);
5511 request_free(request);
5514 * Delete it from the list, and continue;
5520 void radius_event_free(void)
5526 * There are requests in the proxy hash that aren't
5527 * referenced from anywhere else. Remove them first.
5530 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5534 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5538 * Now that all requests have been marked "please stop",
5539 * ensure that all of the threads have exited.
5541 #ifdef HAVE_PTHREAD_H
5546 * Walk the lists again, ensuring that all
5547 * requests are done.
5549 if (main_config.memory_report) {
5554 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5555 num = fr_packet_list_num_elements(proxy_list);
5557 ERROR("Proxy list has %d requests still in it.", num);
5562 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5563 num = rbtree_num_elements(pl);
5565 ERROR("Request list has %d requests still in it.", num);
5574 fr_packet_list_free(proxy_list);
5577 if (proxy_ctx) talloc_free(proxy_ctx);
5582 if (debug_condition) talloc_free(debug_condition);
5585 int radius_event_process(void)
5589 return fr_event_loop(el);