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 if (debug_flag) do { struct timeval debug_tv; \
74 gettimeofday(&debug_tv, NULL);\
75 debug_tv.tv_sec -= fr_start_time;\
76 printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
77 request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, __FUNCTION__, action_codes[action], master_state_names[request->master_state], child_state_names[request->child_state]); } while (0)
79 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
86 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
97 #define TRACE_STATE_MACHINE {}
101 * Declare a state in the state machine.
104 #define STATE_MACHINE_DECL(_x) static void CC_HINT(nonnull) _x(REQUEST *request, int action)
106 #define STATE_MACHINE_TIMER(_x) request->timer_action = _x; \
107 fr_event_insert(el, request_timer, request, \
108 &when, &request->ev);
111 * We need a different VERIFY_REQUEST macro in process.c
112 * To avoid the race conditions with the master thread
113 * checking the REQUEST whilst it's being worked on by
116 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
117 # undef VERIFY_REQUEST
118 # define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
122 * @section request_timeline
124 * Time sequence of a request
127 * RQ-----------------P=============================Y-J-C
128 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
131 * - R: received. Duplicate detection is done, and request is
134 * - Q: Request is placed onto a queue for child threads to pick up.
135 * If there are no child threads, the request goes immediately
138 * - P: Processing the request through the modules.
140 * - Y: Reply is ready. Rejects MAY be delayed here. All other
141 * replies are sent immediately.
143 * - J: Reject is sent "response_delay" after the reply is ready.
145 * - C: For Access-Requests, After "cleanup_delay", the request is
146 * deleted. Accounting-Request packets go directly from Y to C.
148 * - M: Max request time. If the request hits this timer, it is
151 * Other considerations include duplicate and conflicting
152 * packets. When a dupicate packet is received, it is ignored
153 * until we've reached Y, as no response is ready. If the reply
154 * is a reject, duplicates are ignored until J, when we're ready
155 * to send the reply. In between the reply being sent (Y or J),
156 * and C, the server responds to duplicates by sending the cached
159 * Conflicting packets are sent in 2 situations.
161 * The first is in between R and Y. In that case, we consider
162 * it as a hint that we're taking too long, and the NAS has given
163 * up on the request. We then behave just as if the M timer was
164 * reached, and we discard the current request. This allows us
165 * to process the new one.
167 * The second case is when we're at Y, but we haven't yet
168 * finished processing the request. This is a race condition in
169 * the threading code (avoiding locks is faster). It means that
170 * a thread has actually encoded and sent the reply, and that the
171 * NAS has responded with a new packet. The server can then
172 * safely mark the current request as "OK to delete", and behaves
173 * just as if the M timer was reached. This usually happens only
174 * in high-load situations.
176 * Duplicate packets are sent when the NAS thinks we're taking
177 * too long, and wants a reply. From R-Y, duplicates are
178 * ignored. From Y-J (for Access-Rejects), duplicates are also
179 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
180 * they cause the "cleanup_delay" time to be extended. This
181 * extension means that we're more likely to send a duplicate
182 * reply (if we have one), or to suppress processing the packet
183 * twice if we didn't reply to it.
185 * All functions in this file should be thread-safe, and should
186 * assume thet the REQUEST structure is being accessed
187 * simultaneously by the main thread, and by the child worker
188 * threads. This means that timers, etc. cannot be updated in
191 * Instead, the master thread periodically calls request->process
192 * with action TIMER. It's up to the individual functions to
193 * determine how to handle that. They need to check if they're
194 * being called from a child thread or the master, and then do
195 * different things based on that.
200 static fr_packet_list_t *proxy_list = NULL;
201 static TALLOC_CTX *proxy_ctx = NULL;
204 #ifdef HAVE_PTHREAD_H
206 static pthread_mutex_t proxy_mutex;
207 static bool proxy_no_new_sockets = false;
210 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
211 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
213 static pthread_t NO_SUCH_CHILD_PID;
214 #define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
218 * This is easier than ifdef's throughout the code.
220 #define PTHREAD_MUTEX_LOCK(_x)
221 #define PTHREAD_MUTEX_UNLOCK(_x)
222 #define NO_CHILD_THREAD
225 #if defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
226 static bool we_are_master(void)
229 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
235 #define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
238 #define we_are_master(_x) (1)
239 #define ASSERT_MASTER
242 static int event_new_fd(rad_listen_t *this);
245 * We need mutexes around the event FD list *only* in certain
248 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
249 static rad_listen_t *new_listeners = NULL;
251 static pthread_mutex_t fd_mutex;
252 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
253 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
255 void radius_update_listener(rad_listen_t *this)
258 * Just do it ourselves.
260 if (we_are_master()) {
265 FD_MUTEX_LOCK(&fd_mutex);
268 * If it's already in the list, don't add it again.
271 FD_MUTEX_UNLOCK(&fd_mutex);
276 * Otherwise, add it to the list
278 this->next = new_listeners;
279 new_listeners = this;
280 FD_MUTEX_UNLOCK(&fd_mutex);
281 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
284 void radius_update_listener(rad_listen_t *this)
287 * No threads. Just insert it.
292 * This is easier than ifdef's throughout the code.
294 #define FD_MUTEX_LOCK(_x)
295 #define FD_MUTEX_UNLOCK(_x)
298 static int request_num_counter = 1;
300 static int request_will_proxy(REQUEST *request);
301 static int request_proxy(REQUEST *request, int retransmit);
302 STATE_MACHINE_DECL(proxy_wait_for_reply);
303 STATE_MACHINE_DECL(proxy_no_reply);
304 STATE_MACHINE_DECL(proxy_running);
305 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply);
306 static void remove_from_proxy_hash(REQUEST *request);
307 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank);
308 static int insert_into_proxy_hash(REQUEST *request);
311 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
312 RADCLIENT *client, RAD_REQUEST_FUNP fun);
314 STATE_MACHINE_DECL(request_common);
315 STATE_MACHINE_DECL(request_response_delay);
316 STATE_MACHINE_DECL(request_cleanup_delay);
317 STATE_MACHINE_DECL(request_running);
319 static void request_coa_originate(REQUEST *request);
320 STATE_MACHINE_DECL(coa_running);
321 STATE_MACHINE_DECL(coa_wait_for_reply);
322 STATE_MACHINE_DECL(coa_no_reply);
323 STATE_MACHINE_DECL(coa_separate);
327 #define USEC (1000000)
329 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
331 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
333 ERROR("[%s:%d] %s", file, line, msg);
340 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
342 static void tv_add(struct timeval *tv, int usec_delay)
344 if (usec_delay >= USEC) {
345 tv->tv_sec += usec_delay / USEC;
348 tv->tv_usec += usec_delay;
350 if (tv->tv_usec >= USEC) {
351 tv->tv_sec += tv->tv_usec / USEC;
357 * Debug the packet if requested.
359 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, bool received)
361 char src_ipaddr[128];
362 char dst_ipaddr[128];
365 if (!RDEBUG_ENABLED) return;
368 * Client-specific debugging re-prints the input
369 * packet into the client log.
371 * This really belongs in a utility library
373 if (is_radius_code(packet->code)) {
374 RDEBUG("%s %s Id %i from %s:%i to %s:%i length %zu",
375 received ? "Received" : "Sent",
376 fr_packet_codes[packet->code],
378 inet_ntop(packet->src_ipaddr.af,
379 &packet->src_ipaddr.ipaddr,
380 src_ipaddr, sizeof(src_ipaddr)),
382 inet_ntop(packet->dst_ipaddr.af,
383 &packet->dst_ipaddr.ipaddr,
384 dst_ipaddr, sizeof(dst_ipaddr)),
388 RDEBUG("%s code %i Id %i from %s:%i to %s:%i length %zu",
389 received ? "Received" : "Sent",
392 inet_ntop(packet->src_ipaddr.af,
393 &packet->src_ipaddr.ipaddr,
394 src_ipaddr, sizeof(src_ipaddr)),
396 inet_ntop(packet->dst_ipaddr.af,
397 &packet->dst_ipaddr.ipaddr,
398 dst_ipaddr, sizeof(dst_ipaddr)),
404 rdebug_pair_list(L_DBG_LVL_1, request, packet->vps, NULL);
406 rdebug_proto_pair_list(L_DBG_LVL_1, request, packet->vps);
411 /***********************************************************************
413 * Start of RADIUS server state machine.
415 ***********************************************************************/
417 static struct timeval *request_response_window(REQUEST *request)
419 VERIFY_REQUEST(request);
421 if (request->client) {
423 * The client hasn't set the response window. Return
424 * either the home server one, if set, or the global one.
426 if (!timerisset(&request->client->response_window)) {
427 return &request->home_server->response_window;
430 if (timercmp(&request->client->response_window,
431 &request->home_server->response_window, <)) {
432 return &request->client->response_window;
436 rad_assert(request->home_server != NULL);
437 return &request->home_server->response_window;
441 * Determine initial request processing delay.
443 static int request_init_delay(REQUEST *request)
445 struct timeval half_response_window;
447 VERIFY_REQUEST(request);
449 /* Allow client response window to lower initial delay */
450 if (timerisset(&request->client->response_window)) {
451 half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
452 half_response_window.tv_usec =
453 ((request->client->response_window.tv_sec & 1) * USEC +
454 request->client->response_window.tv_usec) >> 1;
455 if (timercmp(&half_response_window, &request->root->init_delay, <))
456 return (int)half_response_window.tv_sec * USEC +
457 (int)half_response_window.tv_usec;
460 return (int)request->root->init_delay.tv_sec * USEC +
461 (int)request->root->init_delay.tv_usec;
465 * Callback for ALL timer events related to the request.
467 static void request_timer(void *ctx)
469 REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
472 action = request->timer_action;
476 request->process(request, action);
480 * Wrapper for talloc pools. If there's no parent, just free the
481 * request. If there is a parent, free the parent INSTEAD of the
484 static void request_free(REQUEST *request)
488 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
489 talloc_free(request);
493 ptr = talloc_parent(request);
494 rad_assert(ptr != NULL);
500 * Only ever called from the master thread.
502 STATE_MACHINE_DECL(request_done)
504 struct timeval now, when;
509 VERIFY_REQUEST(request);
514 * Force this no matter what.
516 request->process = request_done;
520 * Tell the detail listener that we're done.
522 if (request->listener &&
523 (request->listener->type == RAD_LISTEN_DETAIL) &&
524 (request->simul_max != 1)) {
525 request->simul_max = 1;
526 request->listener->send(request->listener,
531 #ifdef HAVE_PTHREAD_H
533 * If called from a child thread, mark ourselves as done,
534 * and wait for the master thread timer to clean us up.
536 if (!we_are_master()) {
538 request->child_state = REQUEST_DONE;
544 * Mark the request as STOP.
546 request->master_state = REQUEST_STOP_PROCESSING;
550 * Move the CoA request to its own handler.
553 coa_separate(request->coa, FR_ACTION_TIMER);
554 } else if (request->parent && (request->parent->coa == request)) {
555 coa_separate(request, FR_ACTION_TIMER);
560 * It doesn't hurt to send duplicate replies. All other
561 * signals are ignored, as the request will be cleaned up
567 rad_assert(request->listener != NULL);
569 if (request->reply->code != 0) {
570 request->listener->send(request->listener, request);
573 RDEBUG("No reply. Ignoring retransmit");
578 * Mark the request as done.
581 #ifdef HAVE_PTHREAD_H
583 * If the child is still running, leave it alone.
585 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
590 #ifdef DEBUG_STATE_MACHINE
591 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
592 request->number, __FUNCTION__,
593 child_state_names[request->child_state],
594 child_state_names[REQUEST_DONE]);
596 request->child_state = REQUEST_DONE;
600 * Called when the child is taking too long to
601 * finish. We've already marked it "please
602 * stop", so we don't complain any more.
604 case FR_ACTION_TIMER:
609 * Child is still alive, and we're receiving more
610 * packets from the home server.
612 case FR_ACTION_PROXY_REPLY:
613 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
614 inet_ntop(request->proxy->src_ipaddr.af,
615 &request->proxy->src_ipaddr.ipaddr,
616 buffer, sizeof(buffer)),
617 request->proxy->dst_port, request->proxy->id);
626 * Remove it from the request hash.
628 if (request->in_request_hash) {
629 if (!rbtree_deletebydata(pl, &request->packet)) {
632 request->in_request_hash = false;
637 * Wait for the proxy ID to expire. This allows us to
638 * avoid re-use of proxy IDs for a while.
640 if (request->in_proxy_hash) {
641 rad_assert(request->proxy != NULL);
643 fr_event_now(el, &now);
644 when = request->proxy->timestamp;
647 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
648 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
649 (request->packet->code != request->proxy->code)) {
650 when.tv_sec += request->home_server->coa_mrd;
653 timeradd(&when, request_response_window(request), &when);
656 * We haven't received all responses, AND there's still
657 * time to wait. Do so.
659 if ((request->num_proxied_requests > request->num_proxied_responses) &&
661 (request->home_server->proto != IPPROTO_TCP) &&
663 timercmp(&now, &when, <)) {
664 RDEBUG("Waiting for more responses from the home server");
671 remove_from_proxy_hash(request);
675 #ifdef HAVE_PTHREAD_H
677 * If there's no children, we can mark the request as done.
679 if (!spawn_flag) request->child_state = REQUEST_DONE;
683 * If the child is still running, wait for it to be finished.
685 if (request->child_state <= REQUEST_RUNNING) {
686 gettimeofday(&now, NULL);
691 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
692 tv_add(&when, request->delay);
693 request->delay += request->delay >> 1;
694 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
696 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
700 #ifdef HAVE_PTHREAD_H
701 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
705 * @todo: do final states for TCP sockets, too?
707 request_stats_final(request);
709 if (request->listener) {
710 request->listener->count--;
713 * If we're the last one, remove the listener now.
715 if ((request->listener->count == 0) &&
716 (request->listener->status == RAD_LISTEN_STATUS_EOL)) {
717 request->listener->status = RAD_LISTEN_STATUS_REMOVE_NOW;
718 event_new_fd(request->listener);
723 if (request->packet) {
724 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
726 (unsigned int) (request->timestamp - fr_start_time));
727 } /* else don't print anything */
730 fr_event_delete(el, &request->ev);
731 request_free(request);
735 static void request_cleanup_delay_init(REQUEST *request, struct timeval const *pnow)
737 struct timeval now, when;
739 VERIFY_REQUEST(request);
741 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
745 * If the packets are from the detail file, we can clean them up now.
747 if (request->listener->type == RAD_LISTEN_DETAIL) goto done;
750 if (!request->root->cleanup_delay) goto done;
755 gettimeofday(&now, NULL);
758 rad_assert(request->reply->timestamp.tv_sec != 0);
759 when = request->reply->timestamp;
761 request->delay = request->root->cleanup_delay;
762 when.tv_sec += request->delay;
765 * Set timer for when we need to clean it up.
767 if (timercmp(&when, &now, >)) {
768 #ifdef DEBUG_STATE_MACHINE
769 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
771 request->process = request_cleanup_delay;
772 request->child_state = REQUEST_DONE;
773 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
778 * Otherwise just clean it up.
781 request_done(request, FR_ACTION_DONE);
786 * Function to do all time-related events.
788 static void request_process_timer(REQUEST *request)
790 struct timeval now, when;
791 rad_assert(request->magic == REQUEST_MAGIC);
792 #ifdef DEBUG_STATE_MACHINE
793 int action = FR_ACTION_TIMER;
796 VERIFY_REQUEST(request);
803 * If we originated a CoA request, divorce it from the
804 * parent. Then, set up the timers so that we can clean
805 * it up as appropriate.
807 if (request->coa) coa_separate(request->coa, FR_ACTION_TIMER);
810 * If we're the request, OR it isn't originating a CoA
811 * request, check more things.
813 if (!request->proxy || (request->packet->code == request->proxy->code))
816 rad_assert(request->listener != NULL);
819 * The socket was closed. Tell the request that
820 * there is no point in continuing.
822 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
823 if ((request->master_state == REQUEST_ACTIVE) &&
824 (request->child_state < REQUEST_RESPONSE_DELAY)) {
825 WARN("Socket was closed while processing request %u: Stopping it.", request->number);
826 request->master_state = REQUEST_STOP_PROCESSING;
831 gettimeofday(&now, NULL);
834 * The request was forcibly stopped.
836 if (request->master_state == REQUEST_STOP_PROCESSING) {
837 switch (request->child_state) {
839 case REQUEST_RUNNING:
840 #ifdef HAVE_PTHREAD_H
841 rad_assert(spawn_flag == true);
846 * Sleep for some more. We HOPE that the
847 * child will become responsive at some
848 * point in the future.
851 tv_add(&when, request->delay);
852 request->delay += request->delay >> 1;
853 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
857 * These should all be managed by the master thread
860 case REQUEST_PROXIED:
862 case REQUEST_RESPONSE_DELAY:
863 case REQUEST_CLEANUP_DELAY:
866 request_done(request, FR_ACTION_DONE);
871 rad_assert(request->master_state == REQUEST_ACTIVE);
874 * It's still supposed to be running.
876 switch (request->child_state) {
878 case REQUEST_RUNNING:
879 when = request->packet->timestamp;
880 when.tv_sec += request->root->max_request_time;
883 * Taking too long: tell it to die.
885 if (timercmp(&now, &when, >=)) {
886 #ifdef HAVE_PTHREAD_H
888 * If there's a child thread processing it,
892 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
893 ERROR("Unresponsive child for request %u, in component %s module %s",
895 request->component ? request->component : "<core>",
896 request->module ? request->module : "<core>");
897 exec_trigger(request, NULL, "server.thread.unresponsive", true);
900 request->master_state = REQUEST_STOP_PROCESSING;
902 goto delay; /* sleep some more */
905 case REQUEST_PROXIED:
906 when = request->packet->timestamp;
907 when.tv_sec += request->root->max_request_time;
909 if (timercmp(&now, &when, >=)) {
910 RWDEBUG("No response to proxied request in 'max_request_time'. Stopping it.");
911 request->master_state = REQUEST_STOP_PROCESSING;
912 request_done(request, FR_ACTION_DONE);
916 rad_assert(request->proxy != NULL);
919 * Delay some more, hoping that we get a response.
921 when = request->proxy->timestamp;
922 tv_add(&when, request->delay);
924 if (timercmp(&now, &when, >=)) {
925 request->process(request, FR_ACTION_TIMER);
930 * Otherwise set the timer for the future.
932 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
934 #endif /* WITH_PROXY */
936 case REQUEST_RESPONSE_DELAY:
937 rad_assert(request->response_delay.tv_sec > 0);
939 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
942 request->process = request_response_delay;
944 when = request->reply->timestamp;
946 tv_add(&when, request->response_delay.tv_sec * USEC);
947 tv_add(&when, request->response_delay.tv_usec);
949 if (timercmp(&when, &now, >)) {
950 #ifdef DEBUG_STATE_MACHINE
951 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
953 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
955 } /* else it's time to send the reject */
957 RDEBUG2("Sending delayed response");
958 request->listener->send(request->listener, request);
959 debug_packet(request, request->reply, false);
960 request->child_state = REQUEST_CLEANUP_DELAY;
963 case REQUEST_CLEANUP_DELAY:
964 rad_assert(request->root->cleanup_delay > 0);
967 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
970 request->process = request_cleanup_delay;
972 when = request->reply->timestamp;
973 when.tv_sec += request->root->cleanup_delay;
975 if (timercmp(&when, &now, >)) {
976 #ifdef DEBUG_STATE_MACHINE
977 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
979 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
981 } /* else it's time to clean up */
990 static void request_queue_or_run(REQUEST *request,
991 fr_request_process_t process)
993 #ifdef DEBUG_STATE_MACHINE
994 int action = FR_ACTION_TIMER;
997 VERIFY_REQUEST(request);
1002 * Do this here so that fewer other functions need to do
1005 if (request->master_state == REQUEST_STOP_PROCESSING) {
1006 #ifdef DEBUG_STATE_MACHINE
1007 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
1008 request->number, __FUNCTION__,
1009 master_state_names[request->master_state],
1010 child_state_names[request->child_state],
1011 child_state_names[REQUEST_DONE]);
1013 request_done(request, FR_ACTION_DONE);
1017 request->process = process;
1019 if (we_are_master()) {
1020 struct timeval when;
1023 * (re) set the initial delay.
1025 request->delay = request_init_delay(request);
1026 if (request->delay > USEC) request->delay = USEC;
1027 gettimeofday(&when, NULL);
1028 tv_add(&when, request->delay);
1029 request->delay += request->delay >> 1;
1031 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1033 #ifdef HAVE_PTHREAD_H
1036 * A child thread will eventually pick it up.
1038 if (request_enqueue(request)) return;
1041 * Otherwise we're not going to do anything with
1044 request_done(request, FR_ACTION_DONE);
1050 request->child_state = REQUEST_RUNNING;
1051 request->process(request, FR_ACTION_RUN);
1055 * Requests that care about child process exit
1056 * codes have already either called
1057 * rad_waitpid(), or they've given up.
1059 while (waitpid(-1, NULL, WNOHANG) > 0);
1063 STATE_MACHINE_DECL(request_common)
1069 VERIFY_REQUEST(request);
1071 TRACE_STATE_MACHINE;
1075 * Bail out as early as possible.
1077 if (request->master_state == REQUEST_STOP_PROCESSING) {
1078 request_done(request, FR_ACTION_DONE);
1084 ERROR("(%u) Ignoring duplicate packet from "
1085 "client %s port %d - ID: %u due to unfinished request "
1086 "in component %s module %s",
1087 request->number, request->client->shortname,
1088 request->packet->src_port,request->packet->id,
1089 request->component, request->module);
1092 case FR_ACTION_TIMER:
1093 request_process_timer(request);
1097 case FR_ACTION_PROXY_REPLY:
1098 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
1099 inet_ntop(request->proxy->dst_ipaddr.af,
1100 &request->proxy->dst_ipaddr.ipaddr,
1101 buffer, sizeof(buffer)),
1102 request->proxy->dst_port, request->proxy->id);
1107 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1112 STATE_MACHINE_DECL(request_cleanup_delay)
1114 struct timeval when;
1116 VERIFY_REQUEST(request);
1118 TRACE_STATE_MACHINE;
1123 if (request->reply->code != 0) {
1124 request->listener->send(request->listener, request);
1126 RDEBUG("No reply. Ignoring retransmit");
1130 * Double the cleanup_delay to catch retransmits.
1132 when = request->reply->timestamp;
1133 request->delay += request->delay ;
1134 when.tv_sec += request->delay;
1136 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1140 case FR_ACTION_PROXY_REPLY:
1142 case FR_ACTION_TIMER:
1143 request_common(request, action);
1147 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1152 STATE_MACHINE_DECL(request_response_delay)
1154 VERIFY_REQUEST(request);
1156 TRACE_STATE_MACHINE;
1161 ERROR("(%u) Discarding duplicate request from "
1162 "client %s port %d - ID: %u due to delayed response",
1163 request->number, request->client->shortname,
1164 request->packet->src_port,request->packet->id);
1168 case FR_ACTION_PROXY_REPLY:
1170 case FR_ACTION_TIMER:
1171 request_common(request, action);
1175 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1181 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1185 VERIFY_REQUEST(request);
1187 TRACE_STATE_MACHINE;
1189 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1192 * Don't decode the packet if it's an internal "fake"
1193 * request. Instead, just return so that the caller can
1196 if (request->packet->dst_port == 0) {
1197 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1198 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1202 if (!request->packet->vps) { /* FIXME: check for correct state */
1203 rcode = request->listener->decode(request->listener, request);
1206 if (debug_condition) {
1208 * Ignore parse errors.
1210 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1211 request->log.lvl = L_DBG_LVL_2;
1212 request->log.func = vradlog_request;
1217 debug_packet(request, request->packet, true);
1223 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1224 request->reply->offset = -2; /* bad authenticator */
1228 if (!request->username) {
1229 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1235 STATE_MACHINE_DECL(request_finish)
1239 VERIFY_REQUEST(request);
1241 TRACE_STATE_MACHINE;
1243 (void) action; /* -Wunused */
1245 if (request->master_state == REQUEST_STOP_PROCESSING) {
1248 * Always send a reply to the detail listener.
1250 if (request->listener->type == RAD_LISTEN_DETAIL) {
1255 request->child_state = REQUEST_DONE;
1261 * Don't do post-auth if we're a CoA request originated
1262 * from an Access-Request. See request_alloc_coa() for
1265 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1269 * Override the response code if a control:Response-Packet-Type attribute is present.
1271 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1273 if (vp->vp_integer == 256) {
1274 RDEBUG2("Not responding to request");
1275 request->reply->code = 0;
1277 request->reply->code = vp->vp_integer;
1281 * Catch Auth-Type := Reject BEFORE proxying the packet.
1283 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1284 if (request->reply->code == 0) {
1285 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1287 if (!vp || (vp->vp_integer != PW_CODE_ACCESS_REJECT)) {
1288 RDEBUG2("There was no response configured: "
1289 "rejecting request");
1292 request->reply->code = PW_CODE_ACCESS_REJECT;
1297 * Copy Proxy-State from the request to the reply.
1299 vp = paircopy_by_num(request->reply, request->packet->vps,
1300 PW_PROXY_STATE, 0, TAG_ANY);
1301 if (vp) pairadd(&request->reply->vps, vp);
1304 * Call Post-Auth for Access-Request packets.
1306 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1307 rad_postauth(request);
1312 * Clean up. These are no longer needed.
1314 gettimeofday(&request->reply->timestamp, NULL);
1317 * Fake packets get marked as "done", and have the
1318 * proxy-reply section deal with the reply attributes.
1319 * We therefore don't free the reply attributes.
1321 if (request->packet->dst_port == 0) {
1322 RDEBUG("Finished internally proxied request.");
1324 request->child_state = REQUEST_DONE;
1330 * Always send the reply to the detail listener.
1332 if (request->listener->type == RAD_LISTEN_DETAIL) {
1334 request->simul_max = 1;
1335 request->listener->send(request->listener, request);
1337 * But only print the reply if there is one.
1339 if (request->reply->code != 0) {
1340 debug_packet(request, request->reply, false);
1347 * Ignore all "do not respond" packets.
1348 * Except for the detail ones, which need to ping
1349 * the detail file reader so that it will retransmit.
1351 if (!request->reply->code) {
1352 RDEBUG("Not sending reply to client.");
1357 * If it's not in the request hash, we MIGHT not want to
1360 * If duplicate packets are allowed, then then only
1361 * reason to NOT be in the request hash is because we
1362 * don't want to send a reply.
1364 * FIXME: this is crap. The rest of the state handling
1365 * should use a different field so that we don't have two
1368 * Otherwise duplicates are forbidden, and the request is
1369 * SUPPOSED to avoid the request hash.
1371 * In that case, we need to send a reply.
1373 if (!request->in_request_hash &&
1374 !request->listener->nodup) {
1375 RDEBUG("Suppressing reply to client.");
1380 * See if we need to delay an Access-Reject packet.
1382 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1383 (request->root->reject_delay.tv_sec > 0)) {
1384 request->response_delay = request->root->reject_delay;
1388 * If we timed out a proxy packet, don't delay
1389 * the reject any more.
1391 if (request->proxy && !request->proxy_reply) {
1392 request->response_delay.tv_sec = 0;
1393 request->response_delay.tv_usec = 0;
1401 if (request->response_delay.tv_sec == 0) {
1402 rad_assert(request->response_delay.tv_usec == 0);
1405 * Don't print a reply if there's none to send.
1407 if (request->reply->code != 0) {
1408 request->listener->send(request->listener, request);
1409 debug_packet(request, request->reply, false);
1413 RDEBUG2("Finished request");
1414 request->component = "<core>";
1415 request->module = "<done>";
1417 #ifdef WITH_ACCOUNTING
1419 * Accounting packets can be cleaned up now.
1421 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1423 request->child_state = REQUEST_DONE;
1430 * If the packets are from the detail file, we can clean them up now.
1432 if (request->listener->type == RAD_LISTEN_DETAIL) {
1434 request->child_state = REQUEST_DONE;
1441 * If we've originated this CoA request, it gets
1444 if (request->proxy &&
1445 ((request->proxy->code == PW_CODE_COA_REQUEST) ||
1446 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
1447 (request->packet->code != request->proxy->code)) {
1449 request->child_state = REQUEST_DONE;
1455 * No cleanup, mark the request as done.
1457 * Otherwise, mark it as "please do cleanup delay".
1459 if (request->root->cleanup_delay == 0) {
1461 request->child_state = REQUEST_DONE;
1464 request->child_state = REQUEST_CLEANUP_DELAY;
1468 * Encode and sign it here, so that the master
1469 * thread can just send the encoded data, which
1470 * means it does less work.
1472 RDEBUG2("Delaying response for %d.%06d seconds",
1473 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1474 request->listener->encode(request->listener, request);
1475 request->component = "<core>";
1476 request->module = "<delay>";
1478 request->child_state = REQUEST_RESPONSE_DELAY;
1482 STATE_MACHINE_DECL(request_running)
1484 VERIFY_REQUEST(request);
1486 TRACE_STATE_MACHINE;
1489 case FR_ACTION_TIMER:
1490 request_process_timer(request);
1494 request_common(request, action);
1498 if (!request_pre_handler(request, action)) {
1499 #ifdef DEBUG_STATE_MACHINE
1500 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1501 request->number, __FUNCTION__,
1502 child_state_names[request->child_state],
1503 child_state_names[REQUEST_DONE]);
1507 request->child_state = REQUEST_DONE;
1511 rad_assert(request->handle != NULL);
1512 request->handle(request);
1516 * We may need to send a proxied request.
1518 if ((action == FR_ACTION_RUN) &&
1519 request_will_proxy(request)) {
1520 #ifdef DEBUG_STATE_MACHINE
1521 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1525 * takes care of setting
1526 * up the post proxy fail
1529 if (request_proxy(request, 0) < 0) goto req_finished;
1533 #ifdef DEBUG_STATE_MACHINE
1534 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1539 * Maybe originate a CoA request.
1541 if ((action == FR_ACTION_RUN) && request->coa) {
1542 request_coa_originate(request);
1549 request_finish(request, action);
1554 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1559 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1560 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1563 RADIUS_PACKET **packet_p;
1564 REQUEST *request = NULL;
1566 listen_socket_t *sock = NULL;
1568 VERIFY_PACKET(packet);
1571 * Set the last packet received.
1573 gettimeofday(&now, NULL);
1575 packet->timestamp = now;
1577 #ifdef WITH_ACCOUNTING
1578 if (listener->type != RAD_LISTEN_DETAIL)
1581 sock = listener->data;
1582 sock->last_packet = now.tv_sec;
1586 * Skip everything if required.
1588 if (listener->nodup) goto skip_dup;
1590 packet_p = rbtree_finddata(pl, &packet);
1592 rad_child_state_t child_state;
1594 request = fr_packet2myptr(REQUEST, packet, packet_p);
1595 rad_assert(request->in_request_hash);
1596 child_state = request->child_state;
1599 * Same src/dst ip/port, length, and
1600 * authentication vector: must be a duplicate.
1602 if ((request->packet->data_len == packet->data_len) &&
1603 (memcmp(request->packet->vector, packet->vector,
1604 sizeof(packet->vector)) == 0)) {
1607 switch (packet->code) {
1608 case PW_CODE_ACCESS_REQUEST:
1609 FR_STATS_INC(auth, total_dup_requests);
1612 #ifdef WITH_ACCOUNTING
1613 case PW_CODE_ACCOUNTING_REQUEST:
1614 FR_STATS_INC(acct, total_dup_requests);
1618 case PW_CODE_COA_REQUEST:
1619 FR_STATS_INC(coa, total_dup_requests);
1622 case PW_CODE_DISCONNECT_REQUEST:
1623 FR_STATS_INC(dsc, total_dup_requests);
1630 #endif /* WITH_STATS */
1633 * Tell the state machine that there's a
1634 * duplicate request.
1636 request->process(request, FR_ACTION_DUP);
1637 return 0; /* duplicate of live request */
1641 * Mark the request as done ASAP, and before we
1642 * log anything. The child may stop processing
1643 * the request just as we're logging the
1646 request_done(request, FR_ACTION_DONE);
1650 * It's a new request, not a duplicate. If the
1651 * old one is done, then we can clean it up.
1653 if (child_state <= REQUEST_RUNNING) {
1655 * The request is still QUEUED or RUNNING. That's a problem.
1657 ERROR("Received conflicting packet from "
1658 "client %s port %d - ID: %u due to "
1659 "unfinished request. Giving up on old request.",
1661 packet->src_port, packet->id);
1665 * Mark the old request as done. If there's no
1666 * child, the request will be cleaned up
1667 * immediately. If there is a child, we'll set a
1668 * timer to go clean up the request.
1670 } /* else the new packet is unique */
1673 * Quench maximum number of outstanding requests.
1675 if (main_config.max_requests &&
1676 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1677 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1679 packet->src_port, packet->id);
1680 WARN("Please check the configuration file.\n"
1681 "\tThe value for 'max_requests' is probably set too low.\n"));
1683 exec_trigger(NULL, NULL, "server.max_requests", true);
1689 * Rate-limit the incoming packets
1691 if (sock && sock->max_rate) {
1694 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1695 if (pps > sock->max_rate) {
1696 DEBUG("Dropping request due to rate limiting");
1699 sock->rate_pps_now++;
1703 * Allocate a pool for the request.
1706 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1710 * The packet is still allocated from a different
1711 * context, but oh well.
1713 (void) talloc_steal(ctx, packet);
1716 request = request_setup(ctx, listener, packet, client, fun);
1723 * Mark it as a "real" request with a context.
1725 request->options |= RAD_REQUEST_OPTION_CTX;
1728 * Remember the request in the list.
1730 if (!listener->nodup) {
1731 if (!rbtree_insert(pl, &request->packet)) {
1732 RERROR("Failed to insert request in the list of live requests: discarding it");
1733 request_done(request, FR_ACTION_DONE);
1737 request->in_request_hash = true;
1741 * Process it. Send a response, and free it.
1743 if (listener->synchronous) {
1745 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1748 request->listener->decode(request->listener, request);
1749 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1750 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1754 if (request->reply->code != 0) {
1755 request->listener->send(request->listener, request);
1757 RDEBUG("Not sending reply");
1759 request_free(request);
1764 * Otherwise, insert it into the state machine.
1765 * The child threads will take care of processing it.
1767 request_queue_or_run(request, request_running);
1773 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1774 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1779 * Create and initialize the new request.
1781 request = request_alloc(ctx);
1786 request->reply = rad_alloc(request, false);
1787 if (!request->reply) {
1789 talloc_free(request);
1793 request->listener = listener;
1794 request->client = client;
1795 request->packet = talloc_steal(request, packet);
1796 request->number = request_num_counter++;
1797 request->priority = listener->type;
1798 request->master_state = REQUEST_ACTIVE;
1799 #ifdef DEBUG_STATE_MACHINE
1800 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1801 request->number, __FUNCTION__,
1802 child_state_names[request->child_state],
1803 child_state_names[REQUEST_RUNNING]);
1805 #ifdef HAVE_PTHREAD_H
1806 request->child_pid = NO_SUCH_CHILD_PID;
1808 request->child_state = REQUEST_RUNNING;
1809 request->handle = fun;
1813 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1814 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1815 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1816 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1817 #ifdef WITH_ACCOUNTING
1818 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1819 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1820 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1823 #endif /* WITH_STATS */
1826 * Status-Server packets go to the head of the queue.
1828 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1831 * Set virtual server identity
1833 if (client->server) {
1834 request->server = client->server;
1835 } else if (listener->server) {
1836 request->server = listener->server;
1838 request->server = NULL;
1841 request->root = &main_config;
1843 request->listener->count++;
1847 * The request passes many of our sanity checks.
1848 * From here on in, if anything goes wrong, we
1849 * send a reject message, instead of dropping the
1854 * Build the reply template from the request.
1857 request->reply->sockfd = request->packet->sockfd;
1858 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1859 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1860 request->reply->dst_port = request->packet->src_port;
1861 request->reply->src_port = request->packet->dst_port;
1862 request->reply->id = request->packet->id;
1863 request->reply->code = 0; /* UNKNOWN code */
1864 memcpy(request->reply->vector, request->packet->vector,
1865 sizeof(request->reply->vector));
1866 request->reply->vps = NULL;
1867 request->reply->data = NULL;
1868 request->reply->data_len = 0;
1874 /***********************************************************************
1878 ***********************************************************************/
1881 * Timer function for all TCP sockets.
1883 static void tcp_socket_timer(void *ctx)
1885 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1886 listen_socket_t *sock = listener->data;
1887 struct timeval end, now;
1889 fr_socket_limit_t *limit;
1893 fr_event_now(el, &now);
1895 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1897 switch (listener->type) {
1899 case RAD_LISTEN_PROXY:
1900 limit = &sock->home->limit;
1904 case RAD_LISTEN_AUTH:
1905 #ifdef WITH_ACCOUNTING
1906 case RAD_LISTEN_ACCT:
1908 limit = &sock->limit;
1916 * If we enforce a lifetime, do it now.
1918 if (limit->lifetime > 0) {
1919 end.tv_sec = sock->opened + limit->lifetime;
1922 if (timercmp(&end, &now, <=)) {
1923 listener->print(listener, buffer, sizeof(buffer));
1924 DEBUG("Reached maximum lifetime on socket %s", buffer);
1928 listener->status = RAD_LISTEN_STATUS_EOL;
1929 event_new_fd(listener);
1938 * Enforce an idle timeout.
1940 if (limit->idle_timeout > 0) {
1941 struct timeval idle;
1943 rad_assert(sock->last_packet != 0);
1944 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1947 if (timercmp(&idle, &now, <=)) {
1948 listener->print(listener, buffer, sizeof(buffer));
1949 DEBUG("Reached idle timeout on socket %s", buffer);
1954 * Enforce the minimum of idle timeout or lifetime.
1956 if (timercmp(&idle, &end, <)) {
1962 * Wake up at t + 0.5s. The code above checks if the timers
1963 * are <= t. This addition gives us a bit of leeway.
1965 end.tv_usec = USEC / 2;
1968 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1969 rad_panic("Failed to insert event");
1976 * Add +/- 2s of jitter, as suggested in RFC 3539
1979 static void add_jitter(struct timeval *when)
1986 jitter ^= (jitter >> 10);
1987 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1990 * Add in ~ (4 * USEC) of jitter.
1992 tv_add(when, jitter);
1996 * Called by socket_del to remove requests with this socket
1998 static int eol_proxy_listener(void *ctx, void *data)
2000 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2001 RADIUS_PACKET **proxy_p = data;
2004 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2005 if (request->proxy_listener != this) return 0;
2008 * The normal "remove_from_proxy_hash" tries to grab the
2009 * proxy mutex. We already have it held, so grabbing it
2010 * again will cause a deadlock. Instead, call the "no
2011 * lock" version of the function.
2013 rad_assert(request->in_proxy_hash == true);
2014 remove_from_proxy_hash_nl(request, false);
2017 * Don't mark it as DONE. The client can retransmit, and
2018 * the packet SHOULD be re-proxied somewhere else.
2020 * Return "2" means that the rbtree code will remove it
2021 * from the tree, and we don't need to do it ourselves.
2025 #endif /* WITH_PROXY */
2027 static int eol_listener(void *ctx, void *data)
2029 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2030 RADIUS_PACKET **packet_p = data;
2033 request = fr_packet2myptr(REQUEST, packet, packet_p);
2034 if (request->listener != this) return 0;
2036 request->master_state = REQUEST_STOP_PROCESSING;
2040 #endif /* WITH_TCP */
2043 /***********************************************************************
2045 * Proxy handlers for the state machine.
2047 ***********************************************************************/
2050 * Called with the proxy mutex held
2052 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2054 VERIFY_REQUEST(request);
2056 if (!request->in_proxy_hash) return;
2058 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2059 request->in_proxy_hash = false;
2062 * On the FIRST reply, decrement the count of outstanding
2063 * requests. Note that this is NOT the count of sent
2064 * packets, but whether or not the home server has
2067 if (request->home_server &&
2068 request->home_server->currently_outstanding) {
2069 request->home_server->currently_outstanding--;
2072 * If we're NOT sending it packets, AND it's been
2073 * a while since we got a response, then we don't
2074 * know if it's alive or dead.
2076 if ((request->home_server->currently_outstanding == 0) &&
2077 (request->home_server->state == HOME_STATE_ALIVE)) {
2078 struct timeval when, now;
2080 when.tv_sec = request->home_server->last_packet_recv ;
2083 timeradd(&when, request_response_window(request), &when);
2084 gettimeofday(&now, NULL);
2087 * last_packet + response_window
2089 * We *administratively* mark the home
2090 * server as "unknown" state, because we
2091 * haven't seen a packet for a while.
2093 if (timercmp(&now, &when, >)) {
2094 request->home_server->state = HOME_STATE_UNKNOWN;
2095 request->home_server->last_packet_sent = 0;
2096 request->home_server->last_packet_recv = 0;
2102 rad_assert(request->proxy_listener != NULL);
2103 request->proxy_listener->count--;
2105 request->proxy_listener = NULL;
2108 * Got from YES in hash, to NO, not in hash while we hold
2109 * the mutex. This guarantees that when another thread
2110 * grabs the mutex, the "not in hash" flag is correct.
2112 RDEBUG3("proxy: request is no longer in proxy hash");
2115 static void remove_from_proxy_hash(REQUEST *request)
2117 VERIFY_REQUEST(request);
2120 * Check this without grabbing the mutex because it's a
2121 * lot faster that way.
2123 if (!request->in_proxy_hash) return;
2126 * The "not in hash" flag is definitive. However, if the
2127 * flag says that it IS in the hash, there might still be
2128 * a race condition where it isn't.
2130 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2132 if (!request->in_proxy_hash) {
2133 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2137 remove_from_proxy_hash_nl(request, true);
2139 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2142 static int insert_into_proxy_hash(REQUEST *request)
2146 bool success = false;
2147 void *proxy_listener;
2149 VERIFY_REQUEST(request);
2151 rad_assert(request->proxy != NULL);
2152 rad_assert(request->home_server != NULL);
2153 rad_assert(proxy_list != NULL);
2156 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2157 proxy_listener = NULL;
2158 request->num_proxied_requests = 1;
2159 request->num_proxied_responses = 0;
2161 for (tries = 0; tries < 2; tries++) {
2163 listen_socket_t *sock;
2165 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2166 success = fr_packet_list_id_alloc(proxy_list,
2167 request->home_server->proto,
2168 &request->proxy, &proxy_listener);
2171 if (tries > 0) continue; /* try opening new socket only once */
2173 #ifdef HAVE_PTHREAD_H
2174 if (proxy_no_new_sockets) break;
2177 RDEBUG3("proxy: Trying to open a new listener to the home server");
2178 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2180 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2184 request->proxy->src_port = 0; /* Use any new socket */
2185 proxy_listener = this;
2188 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2190 &sock->other_ipaddr, sock->other_port,
2193 #ifdef HAVE_PTHREAD_H
2194 proxy_no_new_sockets = true;
2196 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2199 * This is bad. However, the
2200 * packet list now supports 256
2201 * open sockets, which should
2202 * minimize this problem.
2204 ERROR("Failed adding proxy socket: %s",
2210 * Add it to the event loop. Ensure that we have
2211 * only one mutex locked at a time.
2213 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2214 radius_update_listener(this);
2215 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2218 if (!proxy_listener || !success) {
2219 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2220 REDEBUG2("proxy: Failed allocating Id for proxied request");
2222 request->proxy_listener = NULL;
2223 request->in_proxy_hash = false;
2227 rad_assert(request->proxy->id >= 0);
2229 request->proxy_listener = proxy_listener;
2230 request->in_proxy_hash = true;
2231 RDEBUG3("proxy: request is now in proxy hash");
2234 * Keep track of maximum outstanding requests to a
2235 * particular home server. 'max_outstanding' is
2236 * enforced in home_server_ldb(), in realms.c.
2238 request->home_server->currently_outstanding++;
2241 request->proxy_listener->count++;
2244 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2246 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2247 inet_ntop(request->proxy->dst_ipaddr.af,
2248 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2249 request->proxy->dst_port,
2250 request->proxy->id);
2255 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2258 int post_proxy_type = 0;
2261 VERIFY_REQUEST(request);
2264 * There may be a proxy reply, but it may be too late.
2266 if (!request->home_server->server && !request->proxy_listener) return 0;
2269 * Delete any reply we had accumulated until now.
2271 RDEBUG2("Clearing existing &reply: attributes");
2272 pairfree(&request->reply->vps);
2275 * Run the packet through the post-proxy stage,
2276 * BEFORE playing games with the attributes.
2278 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2280 post_proxy_type = vp->vp_integer;
2282 * If we have a proxy_reply, and it was a reject, or a NAK
2283 * setup Post-Proxy <type>.
2285 * If the <type> doesn't have a section, then the Post-Proxy
2286 * section is ignored.
2289 DICT_VALUE *dval = NULL;
2291 switch (reply->code) {
2292 case PW_CODE_ACCESS_REJECT:
2293 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2294 if (dval) post_proxy_type = dval->value;
2297 case PW_CODE_DISCONNECT_NAK:
2298 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2299 if (dval) post_proxy_type = dval->value;
2302 case PW_CODE_COA_NAK:
2303 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2304 if (dval) post_proxy_type = dval->value;
2312 * Create config:Post-Proxy-Type
2315 vp = radius_paircreate(request, &request->config_items, PW_POST_PROXY_TYPE, 0);
2316 vp->vp_integer = dval->value;
2320 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2321 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2324 VERIFY_PACKET(reply);
2327 * Decode the packet if required.
2329 if (request->proxy_listener) {
2330 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2331 debug_packet(request, reply, true);
2334 * Pro-actively remove it from the proxy hash.
2335 * This is later than in 2.1.x, but it means that
2336 * the replies are authenticated before being
2337 * removed from the hash.
2340 (request->num_proxied_requests <= request->num_proxied_responses)) {
2341 remove_from_proxy_hash(request);
2344 rad_assert(!request->in_proxy_hash);
2346 } else if (request->in_proxy_hash) {
2347 remove_from_proxy_hash(request);
2350 if (request->home_pool && request->home_pool->virtual_server) {
2351 char const *old_server = request->server;
2353 request->server = request->home_pool->virtual_server;
2354 RDEBUG2("server %s {", request->server);
2356 rcode = process_post_proxy(post_proxy_type, request);
2359 request->server = old_server;
2361 rcode = process_post_proxy(post_proxy_type, request);
2365 if (request->packet->code == request->proxy->code)
2367 * Don't run the next bit if we originated a CoA
2368 * packet, after receiving an Access-Request or
2369 * Accounting-Request.
2374 * There may NOT be a proxy reply, as we may be
2375 * running Post-Proxy-Type = Fail.
2378 pairadd(&request->reply->vps, paircopy(request->reply, reply->vps));
2381 * Delete the Proxy-State Attributes from
2382 * the reply. These include Proxy-State
2383 * attributes from us and remote server.
2385 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2389 default: /* Don't do anything */
2391 case RLM_MODULE_FAIL:
2394 case RLM_MODULE_HANDLED:
2401 int request_proxy_reply(RADIUS_PACKET *packet)
2403 RADIUS_PACKET **proxy_p;
2408 VERIFY_PACKET(packet);
2410 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2411 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2414 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2415 PROXY("No outstanding request was found for reply from host %s port %d - ID %u",
2416 inet_ntop(packet->src_ipaddr.af,
2417 &packet->src_ipaddr.ipaddr,
2418 buffer, sizeof(buffer)),
2419 packet->src_port, packet->id);
2423 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2424 request->num_proxied_responses++; /* needs to be protected by lock */
2426 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2429 * No reply, BUT the current packet fails verification:
2430 * ignore it. This does the MD5 calculations in the
2431 * server core, but I guess we can fix that later.
2433 if (!request->proxy_reply &&
2434 (rad_verify(packet, request->proxy,
2435 request->home_server->secret) != 0)) {
2436 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2441 * The home server sent us a packet which doesn't match
2442 * something we have: ignore it. This is done only to
2443 * catch the case of broken systems.
2445 if (request->proxy_reply &&
2446 (memcmp(request->proxy_reply->vector,
2448 sizeof(request->proxy_reply->vector)) != 0)) {
2449 RDEBUG2("Ignoring conflicting proxy reply");
2453 gettimeofday(&now, NULL);
2456 * Status-Server packets don't count as real packets.
2458 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2459 listen_socket_t *sock = request->proxy_listener->data;
2461 request->home_server->last_packet_recv = now.tv_sec;
2462 sock->last_packet = now.tv_sec;
2466 * If we have previously seen a reply, ignore the
2469 if (request->proxy_reply) {
2470 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2471 inet_ntop(packet->src_ipaddr.af,
2472 &packet->src_ipaddr.ipaddr,
2473 buffer, sizeof(buffer)),
2474 packet->src_port, packet->id);
2479 * Call the state machine to do something useful with the
2482 request->proxy_reply = talloc_steal(request, packet);
2483 packet->timestamp = now;
2484 request->priority = RAD_LISTEN_PROXY;
2487 * We've received a reply. If we hadn't been sending it
2488 * packets for a while, just mark it alive.
2490 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2491 request->home_server->state = HOME_STATE_ALIVE;
2492 request->home_server->response_timeouts = 0;
2496 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2497 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2499 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2500 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2501 #ifdef WITH_ACCOUNTING
2502 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2503 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2506 #endif /* WITH_STATS */
2509 * Tell the request state machine that we have a proxy
2510 * reply. Depending on the function, this should either
2511 * ignore it, or process it.
2513 request->process(request, FR_ACTION_PROXY_REPLY);
2519 static int setup_post_proxy_fail(REQUEST *request)
2521 DICT_VALUE const *dval = NULL;
2524 VERIFY_REQUEST(request);
2526 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2527 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2528 "Fail-Authentication");
2530 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2531 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2534 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2535 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2537 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2538 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2541 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2545 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2548 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2552 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2553 if (!vp) vp = radius_paircreate(request, &request->config_items,
2554 PW_POST_PROXY_TYPE, 0);
2555 vp->vp_integer = dval->value;
2560 STATE_MACHINE_DECL(proxy_no_reply)
2562 VERIFY_REQUEST(request);
2564 TRACE_STATE_MACHINE;
2568 case FR_ACTION_TIMER:
2569 case FR_ACTION_PROXY_REPLY:
2570 request_common(request, action);
2574 if (process_proxy_reply(request, NULL)) {
2575 request_finish(request, action);
2577 request_done(request, FR_ACTION_DONE);
2581 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2586 STATE_MACHINE_DECL(proxy_running)
2588 VERIFY_REQUEST(request);
2590 TRACE_STATE_MACHINE;
2594 * Silently ignore duplicate proxy replies.
2596 case FR_ACTION_PROXY_REPLY:
2600 case FR_ACTION_TIMER:
2601 request_common(request, action);
2605 if (process_proxy_reply(request, request->proxy_reply)) {
2606 request->handle(request);
2607 request_finish(request, action);
2609 request_done(request, FR_ACTION_DONE);
2614 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2619 static int request_will_proxy(REQUEST *request)
2621 int rcode, pre_proxy_type = 0;
2622 char const *realmname = NULL;
2623 VALUE_PAIR *vp, *strippedname;
2624 home_server_t *home;
2625 REALM *realm = NULL;
2626 home_pool_t *pool = NULL;
2628 VERIFY_REQUEST(request);
2630 if (!request->root->proxy_requests) return 0;
2631 if (request->packet->dst_port == 0) return 0;
2632 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2633 if (request->in_proxy_hash) return 0;
2636 * FIXME: for 3.0, allow this only for rejects?
2638 if (request->reply->code != 0) return 0;
2640 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2642 realm = realm_find2(vp->vp_strvalue);
2644 REDEBUG2("Cannot proxy to unknown realm %s",
2649 realmname = vp->vp_strvalue;
2652 * Figure out which pool to use.
2654 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2655 pool = realm->auth_pool;
2657 #ifdef WITH_ACCOUNTING
2658 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2659 pool = realm->acct_pool;
2663 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2664 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2665 pool = realm->coa_pool;
2672 } else if ((vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2675 switch (request->packet->code) {
2676 case PW_CODE_ACCESS_REQUEST:
2677 pool_type = HOME_TYPE_AUTH;
2680 #ifdef WITH_ACCOUNTING
2681 case PW_CODE_ACCOUNTING_REQUEST:
2682 pool_type = HOME_TYPE_ACCT;
2687 case PW_CODE_COA_REQUEST:
2688 case PW_CODE_DISCONNECT_REQUEST:
2689 pool_type = HOME_TYPE_COA;
2697 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2700 * Send it directly to a home server (i.e. NAS)
2702 } else if (((vp = pairfind(request->config_items, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2703 ((vp = pairfind(request->config_items, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2706 fr_ipaddr_t dst_ipaddr;
2708 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2710 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2711 dst_ipaddr.af = AF_INET;
2712 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2713 dst_ipaddr.prefix = 32;
2715 dst_ipaddr.af = AF_INET6;
2716 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2717 dst_ipaddr.prefix = 128;
2720 port = pairfind(request->config_items, PW_PACKET_DST_PORT, 0, TAG_ANY);
2722 dst_port = PW_COA_UDP_PORT;
2724 dst_port = vp->vp_integer;
2728 * Nothing does CoA over TCP.
2730 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2734 WARN("No such CoA home server %s port %u",
2735 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2736 (unsigned int) dst_port);
2747 RWDEBUG2("Cancelling proxy as no home pool exists");
2751 if (request->listener->synchronous) {
2752 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2756 request->home_pool = pool;
2758 home = home_server_ldb(realmname, pool, request);
2761 REDEBUG2("Failed to find live home server: Cancelling proxy");
2766 home_server_update_request(home, request);
2770 * Once we've decided to proxy a request, we cannot send
2771 * a CoA packet. So we free up any CoA packet here.
2773 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2777 * Remember that we sent the request to a Realm.
2779 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2782 * Strip the name, if told to.
2784 * Doing it here catches the case of proxied tunneled
2787 if (realm && (realm->strip_realm == true) &&
2788 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2790 * If there's a Stripped-User-Name attribute in
2791 * the request, then use THAT as the User-Name
2792 * for the proxied request, instead of the
2795 * This is done by making a copy of the
2796 * Stripped-User-Name attribute, turning it into
2797 * a User-Name attribute, deleting the
2798 * Stripped-User-Name and User-Name attributes
2799 * from the vps list, and making the new
2800 * User-Name the head of the vps list.
2802 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2805 vp = radius_paircreate(NULL, NULL,
2807 rad_assert(vp != NULL); /* handled by above function */
2808 /* Insert at the START of the list */
2809 /* FIXME: Can't make assumptions about ordering */
2810 fr_cursor_init(&cursor, &vp);
2811 fr_cursor_merge(&cursor, request->proxy->vps);
2812 request->proxy->vps = vp;
2814 pairstrcpy(vp, strippedname->vp_strvalue);
2817 * Do NOT delete Stripped-User-Name.
2822 * If there is no PW_CHAP_CHALLENGE attribute but
2823 * there is a PW_CHAP_PASSWORD we need to add it
2824 * since we can't use the request authenticator
2825 * anymore - we changed it.
2827 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2828 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2829 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2830 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2831 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2835 * The RFC's say we have to do this, but FreeRADIUS
2838 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2839 pairsprintf(vp, "%u", request->packet->id);
2842 * Should be done BEFORE inserting into proxy hash, as
2843 * pre-proxy may use this information, or change it.
2845 request->proxy->code = request->packet->code;
2848 * Call the pre-proxy routines.
2850 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2852 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2853 /* Must be a validation issue */
2855 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2856 pre_proxy_type = vp->vp_integer;
2860 * home_pool may be NULL when originating CoA packets,
2861 * because they go directly to an IP address.
2863 if (request->home_pool && request->home_pool->virtual_server) {
2864 char const *old_server = request->server;
2866 request->server = request->home_pool->virtual_server;
2868 RDEBUG2("server %s {", request->server);
2870 rcode = process_pre_proxy(pre_proxy_type, request);
2874 request->server = old_server;
2876 rcode = process_pre_proxy(pre_proxy_type, request);
2879 case RLM_MODULE_FAIL:
2880 case RLM_MODULE_INVALID:
2881 case RLM_MODULE_NOTFOUND:
2882 case RLM_MODULE_USERLOCK:
2884 /* FIXME: debug print failed stuff */
2887 case RLM_MODULE_REJECT:
2888 case RLM_MODULE_HANDLED:
2892 * Only proxy the packet if the pre-proxy code succeeded.
2894 case RLM_MODULE_NOOP:
2896 case RLM_MODULE_UPDATED:
2903 static int request_proxy(REQUEST *request, int retransmit)
2907 VERIFY_REQUEST(request);
2909 rad_assert(request->parent == NULL);
2910 rad_assert(request->home_server != NULL);
2912 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2916 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2917 request_done(request->coa, FR_ACTION_DONE);
2922 * The request may need sending to a virtual server.
2923 * This code is more than a little screwed up. The rest
2924 * of the state machine doesn't handle parent / child
2925 * relationships well. i.e. if the child request takes
2926 * too long, the core will mark the *parent* as "stop
2927 * processing". And the child will continue without
2928 * knowing anything...
2930 * So, we have some horrible hacks to get around that.
2932 if (request->home_server->server) {
2935 if (request->packet->dst_port == 0) {
2936 WARN("Cannot proxy an internal request");
2940 DEBUG("Proxying to virtual server %s",
2941 request->home_server->server);
2944 * Packets to virtual serrers don't get
2945 * retransmissions sent to them. And the virtual
2946 * server is run ONLY if we have no child
2947 * threads, or we're running in a child thread.
2949 rad_assert(retransmit == 0);
2950 rad_assert(!spawn_flag || !we_are_master());
2952 fake = request_alloc_fake(request);
2954 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
2955 talloc_free(request->proxy);
2957 fake->server = request->home_server->server;
2958 fake->handle = request->handle;
2959 fake->process = NULL; /* should never be run for anything */
2962 * Run the virtual server.
2964 request_running(fake, FR_ACTION_RUN);
2966 request->proxy = talloc_steal(request, fake->packet);
2967 fake->packet = NULL;
2968 request->proxy_reply = talloc_steal(request, fake->reply);
2974 * No reply code, toss the reply we have,
2975 * and do post-proxy-type Fail.
2977 if (!request->proxy_reply->code) {
2978 TALLOC_FREE(request->proxy_reply);
2979 setup_post_proxy_fail(request);
2983 * Just do the work here, rather than trying to
2984 * run the "decode proxy reply" stuff...
2986 process_proxy_reply(request, request->proxy_reply);
2989 * If we have a reply, run it through the handler.
2991 if (request->proxy_reply) {
2992 request->handle(request); /* to do more post-proxy stuff */
2995 return -1; /* so we call request_finish */
2999 * We're actually sending a proxied packet. Do that now.
3001 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3002 ERROR("Failed to insert request into the proxy list");
3006 rad_assert(request->proxy->id >= 0);
3009 struct timeval *response_window;
3011 response_window = request_response_window(request);
3014 if (request->home_server->tls) {
3015 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3016 inet_ntop(request->proxy->dst_ipaddr.af,
3017 &request->proxy->dst_ipaddr.ipaddr,
3018 buffer, sizeof(buffer)),
3019 request->proxy->dst_port,
3020 (int) response_window->tv_sec, (int) response_window->tv_usec);
3023 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3024 inet_ntop(request->proxy->dst_ipaddr.af,
3025 &request->proxy->dst_ipaddr.ipaddr,
3026 buffer, sizeof(buffer)),
3027 request->proxy->dst_port,
3028 (int) response_window->tv_sec, (int) response_window->tv_usec);
3033 gettimeofday(&request->proxy_retransmit, NULL);
3035 request->proxy->timestamp = request->proxy_retransmit;
3037 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3039 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3042 * Encode the packet before we do anything else.
3044 request->proxy_listener->encode(request->proxy_listener, request);
3045 debug_packet(request, request->proxy, false);
3048 * Set the state function, then the state, no child, and
3051 request->process = proxy_wait_for_reply;
3052 request->child_state = REQUEST_PROXIED;
3056 * And send the packet.
3058 request->proxy_listener->send(request->proxy_listener, request);
3063 * Proxy the packet as if it was new.
3065 static int request_proxy_anew(REQUEST *request)
3067 home_server_t *home;
3069 VERIFY_REQUEST(request);
3072 * Delete the request from the proxy list.
3074 * The packet list code takes care of ensuring that IDs
3075 * aren't reused until all 256 IDs have been used. So
3076 * there's a 1/256 chance of re-using the same ID when
3077 * we're sending to the same home server. Which is
3080 remove_from_proxy_hash(request);
3083 * Find a live home server for the request.
3085 home = home_server_ldb(NULL, request->home_pool, request);
3087 REDEBUG2("Failed to find live home server for request");
3089 if (setup_post_proxy_fail(request)) {
3090 request_queue_or_run(request, proxy_running);
3092 gettimeofday(&request->reply->timestamp, NULL);
3093 request_cleanup_delay_init(request, NULL);
3097 home_server_update_request(home, request);
3099 if (!insert_into_proxy_hash(request)) {
3100 RPROXY("Failed to insert retransmission into the proxy list");
3101 goto post_proxy_fail;
3105 * Free the old packet, to force re-encoding
3107 talloc_free(request->proxy->data);
3108 request->proxy->data = NULL;
3109 request->proxy->data_len = 0;
3111 #ifdef WITH_ACCOUNTING
3113 * Update the Acct-Delay-Time attribute.
3115 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3118 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3119 if (!vp) vp = radius_paircreate(request->proxy,
3120 &request->proxy->vps,
3121 PW_ACCT_DELAY_TIME, 0);
3125 gettimeofday(&now, NULL);
3126 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3131 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3136 STATE_MACHINE_DECL(request_ping)
3138 home_server_t *home = request->home_server;
3141 VERIFY_REQUEST(request);
3143 TRACE_STATE_MACHINE;
3147 case FR_ACTION_TIMER:
3148 ERROR("No response to status check %d for home server %s port %d",
3150 inet_ntop(request->proxy->dst_ipaddr.af,
3151 &request->proxy->dst_ipaddr.ipaddr,
3152 buffer, sizeof(buffer)),
3153 request->proxy->dst_port);
3156 case FR_ACTION_PROXY_REPLY:
3157 rad_assert(request->in_proxy_hash);
3159 request->home_server->num_received_pings++;
3160 RPROXY("Received response to status check %d (%d in current sequence)",
3161 request->number, home->num_received_pings);
3164 * Remove the request from any hashes
3167 fr_event_delete(el, &request->ev);
3168 remove_from_proxy_hash(request);
3171 * The control socket may have marked the home server as
3172 * alive. OR, it may have suddenly started responding to
3173 * requests again. If so, don't re-do the "make alive"
3176 if (home->state == HOME_STATE_ALIVE) break;
3179 * It's dead, and we haven't received enough ping
3180 * responses to mark it "alive". Wait a bit.
3182 * If it's zombie, we mark it alive immediately.
3184 if ((home->state == HOME_STATE_IS_DEAD) &&
3185 (home->num_received_pings < home->num_pings_to_alive)) {
3190 * Mark it alive and delete any outstanding
3193 home->state = HOME_STATE_ALIVE;
3194 home->response_timeouts = 0;
3195 exec_trigger(request, home->cs, "home_server.alive", false);
3196 home->currently_outstanding = 0;
3197 home->num_sent_pings = 0;
3198 home->num_received_pings = 0;
3199 gettimeofday(&home->revive_time, NULL);
3202 fr_event_delete(el, &home->ev);
3204 RPROXY("Marking home server %s port %d alive",
3205 inet_ntop(request->proxy->dst_ipaddr.af,
3206 &request->proxy->dst_ipaddr.ipaddr,
3207 buffer, sizeof(buffer)),
3208 request->proxy->dst_port);
3212 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3216 rad_assert(!request->in_request_hash);
3217 rad_assert(request->ev == NULL);
3218 request_done(request, FR_ACTION_DONE);
3222 * Called from start of zombie period, OR after control socket
3223 * marks the home server dead.
3225 static void ping_home_server(void *ctx)
3227 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3230 struct timeval when, now;
3232 if ((home->state == HOME_STATE_ALIVE) ||
3234 (home->proto == IPPROTO_TCP) ||
3236 (home->ev != NULL)) {
3240 gettimeofday(&now, NULL);
3243 * We've run out of zombie time. Mark it dead.
3245 if (home->state == HOME_STATE_ZOMBIE) {
3246 when = home->zombie_period_start;
3247 when.tv_sec += home->zombie_period;
3249 if (timercmp(&when, &now, <)) {
3250 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3251 mark_home_server_dead(home, &now);
3256 * We're not supposed to be pinging it. Just wake up
3257 * when we're supposed to mark it dead.
3259 if (home->ping_check == HOME_PING_CHECK_NONE) {
3260 if (home->state == HOME_STATE_ZOMBIE) {
3261 when = home->zombie_period_start;
3262 when.tv_sec += home->zombie_period;
3264 INSERT_EVENT(ping_home_server, home);
3268 * Else mark_home_server_dead will set a timer
3269 * for revive_interval.
3275 request = request_alloc(NULL);
3276 if (!request) return;
3277 request->number = request_num_counter++;
3280 request->proxy = rad_alloc(request, true);
3281 rad_assert(request->proxy != NULL);
3283 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3284 request->proxy->code = PW_CODE_STATUS_SERVER;
3286 pairmake(request->proxy, &request->proxy->vps,
3287 "Message-Authenticator", "0x00", T_OP_SET);
3289 } else if (home->type == HOME_TYPE_AUTH) {
3290 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3292 pairmake(request->proxy, &request->proxy->vps,
3293 "User-Name", home->ping_user_name, T_OP_SET);
3294 pairmake(request->proxy, &request->proxy->vps,
3295 "User-Password", home->ping_user_password, T_OP_SET);
3296 pairmake(request->proxy, &request->proxy->vps,
3297 "Service-Type", "Authenticate-Only", T_OP_SET);
3298 pairmake(request->proxy, &request->proxy->vps,
3299 "Message-Authenticator", "0x00", T_OP_SET);
3302 #ifdef WITH_ACCOUNTING
3303 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3305 pairmake(request->proxy, &request->proxy->vps,
3306 "User-Name", home->ping_user_name, T_OP_SET);
3307 pairmake(request->proxy, &request->proxy->vps,
3308 "Acct-Status-Type", "Stop", T_OP_SET);
3309 pairmake(request->proxy, &request->proxy->vps,
3310 "Acct-Session-Id", "00000000", T_OP_SET);
3311 vp = pairmake(request->proxy, &request->proxy->vps,
3312 "Event-Timestamp", "0", T_OP_SET);
3313 vp->vp_date = now.tv_sec;
3315 rad_assert("Internal sanity check failed");
3319 vp = pairmake(request->proxy, &request->proxy->vps,
3320 "NAS-Identifier", "", T_OP_SET);
3322 pairsprintf(vp, "Status Check %u. Are you alive?",
3323 home->num_sent_pings);
3326 request->proxy->src_ipaddr = home->src_ipaddr;
3327 request->proxy->dst_ipaddr = home->ipaddr;
3328 request->proxy->dst_port = home->port;
3329 request->home_server = home;
3330 #ifdef DEBUG_STATE_MACHINE
3331 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3332 child_state_names[request->child_state],
3333 child_state_names[REQUEST_DONE]);
3334 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3336 #ifdef HAVE_PTHREAD_H
3337 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3339 request->child_state = REQUEST_DONE;
3340 request->process = request_ping;
3342 rad_assert(request->proxy_listener == NULL);
3344 if (!insert_into_proxy_hash(request)) {
3345 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3348 rad_assert(!request->in_request_hash);
3349 rad_assert(!request->in_proxy_hash);
3350 rad_assert(request->ev == NULL);
3351 talloc_free(request);
3356 * Set up the timer callback.
3359 when.tv_sec += home->ping_timeout;
3361 DEBUG("PING: Waiting %u seconds for response to ping",
3362 home->ping_timeout);
3364 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3365 home->num_sent_pings++;
3367 rad_assert(request->proxy_listener != NULL);
3368 request->proxy_listener->send(request->proxy_listener,
3372 * Add +/- 2s of jitter, as suggested in RFC 3539
3373 * and in the Issues and Fixes draft.
3376 home->when.tv_sec += home->ping_interval;
3378 add_jitter(&home->when);
3380 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3382 INSERT_EVENT(ping_home_server, home);
3385 static void home_trigger(home_server_t *home, char const *trigger)
3387 REQUEST *my_request;
3388 RADIUS_PACKET *my_packet;
3390 my_request = talloc_zero(NULL, REQUEST);
3391 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3392 my_request->proxy = my_packet;
3393 my_packet->dst_ipaddr = home->ipaddr;
3394 my_packet->src_ipaddr = home->src_ipaddr;
3396 exec_trigger(my_request, home->cs, trigger, false);
3397 talloc_free(my_request);
3400 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3407 rad_assert((home->state == HOME_STATE_ALIVE) ||
3408 (home->state == HOME_STATE_UNKNOWN));
3411 if (home->proto == IPPROTO_TCP) {
3412 WARN("Not marking TCP server %s zombie", home->log_name);
3418 * We've received a real packet recently. Don't mark the
3419 * server as zombie until we've received NO packets for a
3420 * while. The "1/4" of zombie period was chosen rather
3421 * arbitrarily. It's a balance between too short, which
3422 * gives quick fail-over and fail-back, or too long,
3423 * where the proxy still sends packets to an unresponsive
3426 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3427 if (home->last_packet_recv >= start) {
3428 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3429 (int) (now->tv_sec - home->last_packet_recv));
3433 home->state = HOME_STATE_ZOMBIE;
3434 home_trigger(home, "home_server.zombie");
3437 * Set the home server to "zombie", as of the time
3440 home->zombie_period_start.tv_sec = start;
3441 home->zombie_period_start.tv_usec = USEC / 2;
3444 fr_event_delete(el, &home->ev);
3445 home->num_sent_pings = 0;
3446 home->num_received_pings = 0;
3448 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3449 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3450 buffer, sizeof(buffer)),
3451 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3453 ping_home_server(home);
3457 void revive_home_server(void *ctx)
3459 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3463 rad_assert(home->proto != IPPROTO_TCP);
3466 home->state = HOME_STATE_ALIVE;
3467 home->response_timeouts = 0;
3468 home_trigger(home, "home_server.alive");
3469 home->currently_outstanding = 0;
3470 gettimeofday(&home->revive_time, NULL);
3473 * Delete any outstanding events.
3476 if (home->ev) fr_event_delete(el, &home->ev);
3478 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3479 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3480 buffer, sizeof(buffer)),
3484 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3486 int previous_state = home->state;
3490 if (home->proto == IPPROTO_TCP) {
3491 WARN("Not marking TCP server dead");
3496 PROXY( "Marking home server %s port %d as dead.",
3497 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3498 buffer, sizeof(buffer)),
3501 home->state = HOME_STATE_IS_DEAD;
3502 home_trigger(home, "home_server.dead");
3504 if (home->ping_check != HOME_PING_CHECK_NONE) {
3506 * If the control socket marks us dead, start
3507 * pinging. Otherwise, we already started
3508 * pinging when it was marked "zombie".
3510 if (previous_state == HOME_STATE_ALIVE) {
3511 ping_home_server(home);
3513 DEBUG("PING: Already pinging home server %s", home->log_name);
3518 * Revive it after a fixed period of time. This
3519 * is very, very, bad.
3522 home->when.tv_sec += home->revive_interval;
3524 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3526 INSERT_EVENT(revive_home_server, home);
3530 STATE_MACHINE_DECL(proxy_wait_for_reply)
3532 struct timeval now, when;
3533 struct timeval *response_window = NULL;
3534 home_server_t *home = request->home_server;
3537 VERIFY_REQUEST(request);
3539 TRACE_STATE_MACHINE;
3541 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3542 rad_assert(request->home_server != NULL);
3544 if (request->master_state == REQUEST_STOP_PROCESSING) {
3545 request->child_state = REQUEST_DONE;
3549 gettimeofday(&now, NULL);
3554 * We have a reply, ignore the retransmit.
3556 if (request->proxy_reply) return;
3559 * The request was proxied to a virtual server.
3560 * Ignore the retransmit.
3562 if (request->home_server->server) return;
3564 if ((home->state == HOME_STATE_IS_DEAD) ||
3565 !request->proxy_listener ||
3566 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3567 request_proxy_anew(request);
3572 if (home->proto == IPPROTO_TCP) {
3573 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3574 inet_ntop(request->proxy->dst_ipaddr.af,
3575 &request->proxy->dst_ipaddr.ipaddr,
3576 buffer, sizeof(buffer)),
3577 request->proxy->dst_port,
3578 request->proxy->id);
3584 * More than one retransmit a second is stupid,
3585 * and should be suppressed by the proxy.
3587 when = request->proxy_retransmit;
3590 if (timercmp(&now, &when, <)) {
3591 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3592 inet_ntop(request->proxy->dst_ipaddr.af,
3593 &request->proxy->dst_ipaddr.ipaddr,
3594 buffer, sizeof(buffer)),
3595 request->proxy->dst_port,
3596 request->proxy->id);
3600 #ifdef WITH_ACCOUNTING
3602 * If we update the Acct-Delay-Time, we need to
3605 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3606 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3607 request_proxy_anew(request);
3612 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3613 inet_ntop(request->proxy->dst_ipaddr.af,
3614 &request->proxy->dst_ipaddr.ipaddr,
3615 buffer, sizeof(buffer)),
3616 request->proxy->dst_port,
3617 request->proxy->id);
3618 request->num_proxied_requests++;
3620 rad_assert(request->proxy_listener != NULL);
3621 FR_STATS_TYPE_INC(home->stats.total_requests);
3622 home->last_packet_sent = now.tv_sec;
3623 request->proxy_retransmit = now;
3624 request->proxy_listener->send(request->proxy_listener, request);
3625 debug_packet(request, request->proxy, false);
3628 case FR_ACTION_TIMER:
3629 response_window = request_response_window(request);
3632 if (!request->proxy_listener ||
3633 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3634 remove_from_proxy_hash(request);
3636 when = request->packet->timestamp;
3637 when.tv_sec += request->root->max_request_time;
3639 if (timercmp(&when, &now, >)) {
3640 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3641 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3648 * Wake up "response_window" time in the future.
3649 * i.e. when MY packet hasn't received a response.
3651 * Note that we DO NOT mark the home server as
3652 * zombie if it doesn't respond to us. It may be
3653 * responding to other (better looking) packets.
3655 when = request->proxy->timestamp;
3656 timeradd(&when, response_window, &when);
3659 * Not at the response window. Set the timer for
3662 if (timercmp(&when, &now, >)) {
3663 struct timeval diff;
3664 timersub(&when, &now, &diff);
3666 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3667 (int) diff.tv_sec, (int) diff.tv_usec);
3668 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3673 RDEBUG("No proxy response, giving up on request and marking it done");
3676 * If we haven't received any packets for
3677 * "response_window", then mark the home server
3680 * If the connection is TCP, then another
3681 * "watchdog timer" function takes care of pings,
3682 * etc. So we don't need to do it here.
3684 * This check should really be part of a home
3685 * server state machine.
3687 if (((home->state == HOME_STATE_ALIVE) ||
3688 (home->state == HOME_STATE_UNKNOWN))
3690 && (home->proto != IPPROTO_TCP)
3693 home->response_timeouts++;
3694 if (home->response_timeouts >= home->max_response_timeouts)
3695 mark_home_server_zombie(home, &now, response_window);
3698 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3699 if (home->type == HOME_TYPE_AUTH) {
3700 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3701 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3704 else if (home->type == HOME_TYPE_ACCT) {
3705 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3706 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3711 * There was no response within the window. Stop
3712 * the request. If the client retransmitted, it
3713 * may have failed over to another home server.
3714 * But that one may be dead, too.
3716 * The extra verbose message if we have a username,
3717 * is extremely useful if the proxy is part of a chain
3718 * and the final home server, is not the one we're
3721 if (request->username) {
3722 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3723 "server %s port %d",
3724 request->username->vp_strvalue,
3725 inet_ntop(request->proxy->dst_ipaddr.af,
3726 &request->proxy->dst_ipaddr.ipaddr,
3727 buffer, sizeof(buffer)),
3728 request->proxy->dst_port);
3730 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3731 inet_ntop(request->proxy->dst_ipaddr.af,
3732 &request->proxy->dst_ipaddr.ipaddr,
3733 buffer, sizeof(buffer)),
3734 request->proxy->dst_port);
3737 if (setup_post_proxy_fail(request)) {
3738 request_queue_or_run(request, proxy_no_reply);
3740 gettimeofday(&request->reply->timestamp, NULL);
3741 request_cleanup_delay_init(request, NULL);
3746 * We received a new reply. Go process it.
3748 case FR_ACTION_PROXY_REPLY:
3749 request_queue_or_run(request, proxy_running);
3753 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3757 #endif /* WITH_PROXY */
3759 /***********************************************************************
3763 ***********************************************************************/
3765 static int null_handler(UNUSED REQUEST *request)
3771 * See if we need to originate a CoA request.
3773 static void request_coa_originate(REQUEST *request)
3775 int rcode, pre_proxy_type = 0;
3781 VERIFY_REQUEST(request);
3783 rad_assert(request->coa != NULL);
3784 rad_assert(request->proxy == NULL);
3785 rad_assert(!request->in_proxy_hash);
3786 rad_assert(request->proxy_reply == NULL);
3789 * Check whether we want to originate one, or cancel one.
3791 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3793 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3797 if (vp->vp_integer == 0) {
3799 TALLOC_FREE(request->coa);
3807 * src_ipaddr will be set up in proxy_encode.
3809 memset(&ipaddr, 0, sizeof(ipaddr));
3810 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3812 ipaddr.af = AF_INET;
3813 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3815 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3816 ipaddr.af = AF_INET6;
3817 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3818 ipaddr.prefix = 128;
3819 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3820 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3822 if (!coa->home_pool) {
3823 RWDEBUG2("No such home_server_pool %s",
3829 * Prefer the pool to one server
3831 } else if (request->client->coa_pool) {
3832 coa->home_pool = request->client->coa_pool;
3834 } else if (request->client->coa_server) {
3835 coa->home_server = request->client->coa_server;
3839 * If all else fails, send it to the client that
3840 * originated this request.
3842 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3846 * Use the pool, if it exists.
3848 if (coa->home_pool) {
3849 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3850 if (!coa->home_server) {
3851 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3854 home_server_update_request(coa->home_server, coa);
3856 } else if (!coa->home_server) {
3857 uint16_t port = PW_COA_UDP_PORT;
3859 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3860 if (vp) port = vp->vp_integer;
3862 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3863 if (!coa->home_server) {
3864 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3865 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3866 buffer, sizeof(buffer)), port);
3871 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3873 switch (vp->vp_integer) {
3874 case PW_CODE_COA_REQUEST:
3875 case PW_CODE_DISCONNECT_REQUEST:
3876 coa->proxy->code = vp->vp_integer;
3880 DEBUG("Cannot set CoA Packet-Type to code %d",
3886 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3889 * The rest of the server code assumes that
3890 * request->packet && request->reply exist. Copy them
3891 * from the original request.
3893 rad_assert(coa->packet != NULL);
3894 rad_assert(coa->packet->vps == NULL);
3896 coa->packet = rad_copy_packet(coa, request->packet);
3897 coa->reply = rad_copy_packet(coa, request->reply);
3899 coa->config_items = paircopy(coa, request->config_items);
3900 coa->num_coa_requests = 0;
3901 coa->handle = null_handler;
3902 coa->number = request->number; /* it's associated with the same request */
3905 * Call the pre-proxy routines.
3907 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3909 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3910 /* Must be a validation issue */
3912 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3913 pre_proxy_type = vp->vp_integer;
3916 if (coa->home_pool && coa->home_pool->virtual_server) {
3917 char const *old_server = coa->server;
3919 coa->server = coa->home_pool->virtual_server;
3920 RDEBUG2("server %s {", coa->server);
3922 rcode = process_pre_proxy(pre_proxy_type, coa);
3925 coa->server = old_server;
3927 rcode = process_pre_proxy(pre_proxy_type, coa);
3934 * Only send the CoA packet if the pre-proxy code succeeded.
3936 case RLM_MODULE_NOOP:
3938 case RLM_MODULE_UPDATED:
3943 * Source IP / port is set when the proxy socket
3946 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3947 coa->proxy->dst_port = coa->home_server->port;
3949 if (!insert_into_proxy_hash(coa)) {
3950 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
3955 * We CANNOT divorce the CoA request from the parent
3956 * request. This function is running in a child thread,
3957 * and we need access to the main event loop in order to
3958 * to add the timers for the CoA packet.
3960 * Instead, we wait for the timer on the parent request
3963 gettimeofday(&coa->proxy->timestamp, NULL);
3964 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3965 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3966 coa->delay = 0; /* need to calculate a new delay */
3969 * If requested, put a State attribute into the packet,
3970 * and cache the VPS.
3972 fr_state_put_vps(coa, NULL, coa->packet);
3974 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3977 * Encode the packet before we do anything else.
3979 coa->proxy_listener->encode(coa->proxy_listener, coa);
3980 debug_packet(coa, coa->proxy, false);
3982 #ifdef DEBUG_STATE_MACHINE
3983 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3984 child_state_names[request->child_state],
3985 child_state_names[REQUEST_PROXIED]);
3989 * Set the state function, then the state, no child, and
3992 coa->process = coa_wait_for_reply;
3993 coa->child_state = REQUEST_PROXIED;
3995 #ifdef HAVE_PTHREAD_H
3996 coa->child_pid = NO_SUCH_CHILD_PID;
4000 * And send the packet.
4002 coa->proxy_listener->send(coa->proxy_listener, coa);
4006 static void coa_timer(REQUEST *request)
4008 uint32_t delay, frac;
4009 struct timeval now, when, mrd;
4011 VERIFY_REQUEST(request);
4013 rad_assert(request->parent == NULL);
4015 if (request->proxy_reply) {
4016 request_process_timer(request);
4019 gettimeofday(&now, NULL);
4021 if (request->delay == 0) {
4023 * Implement re-transmit algorithm as per RFC 5080
4026 * We want IRT + RAND*IRT
4027 * or 0.9 IRT + rand(0,.2) IRT
4029 * 2^20 ~ USEC, and we want 2.
4030 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4032 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4033 request->delay = delay * request->home_server->coa_irt;
4034 delay = request->home_server->coa_irt * USEC;
4035 delay -= delay / 10;
4036 delay += request->delay;
4037 request->delay = delay;
4039 when = request->proxy->timestamp;
4040 tv_add(&when, delay);
4042 if (timercmp(&when, &now, >)) {
4043 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4049 * Retransmit CoA request.
4053 * Cap count at MRC, if it is non-zero.
4055 if (request->home_server->coa_mrc &&
4056 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4059 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4061 inet_ntop(request->proxy->dst_ipaddr.af,
4062 &request->proxy->dst_ipaddr.ipaddr,
4063 buffer, sizeof(buffer)),
4064 request->proxy->dst_port);
4066 if (setup_post_proxy_fail(request)) {
4067 request_queue_or_run(request, coa_no_reply);
4069 request_done(request, FR_ACTION_DONE);
4075 * RFC 5080 Section 2.2.1
4077 * RT = 2*RTprev + RAND*RTprev
4078 * = 1.9 * RTprev + rand(0,.2) * RTprev
4079 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4082 delay ^= (delay >> 16);
4084 frac = request->delay / 5;
4085 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4087 delay += (2 * request->delay) - (request->delay / 10);
4090 * Cap delay at MRT, if MRT is non-zero.
4092 if (request->home_server->coa_mrt &&
4093 (delay > (request->home_server->coa_mrt * USEC))) {
4094 int mrt_usec = request->home_server->coa_mrt * USEC;
4097 * delay = MRT + RAND * MRT
4098 * = 0.9 MRT + rand(0,.2) * MRT
4101 delay ^= (delay >> 15);
4103 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4104 delay += mrt_usec - (mrt_usec / 10);
4107 request->delay = delay;
4109 tv_add(&when, request->delay);
4110 mrd = request->proxy->timestamp;
4111 mrd.tv_sec += request->home_server->coa_mrd;
4114 * Cap duration at MRD.
4116 if (timercmp(&mrd, &when, <)) {
4119 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4121 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4123 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4126 * Status servers don't count as real packets sent.
4128 request->proxy_listener->send(request->proxy_listener,
4132 STATE_MACHINE_DECL(coa_wait_for_reply)
4134 VERIFY_REQUEST(request);
4136 TRACE_STATE_MACHINE;
4139 case FR_ACTION_TIMER:
4141 * This is big enough to be in it's own function.
4146 case FR_ACTION_PROXY_REPLY:
4147 rad_assert(request->parent != NULL);
4148 rad_assert(request->parent->coa == request);
4149 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
4150 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
4151 rad_assert(request->process != NULL);
4153 coa_separate(request, FR_ACTION_PROXY_REPLY);
4155 rad_assert(request->parent == NULL);
4158 * Do NOT get the session-state VPs. The request
4159 * already contains the packet and the reply, so
4160 * there's no more state we need to maintain.
4162 * The state for "originate CoA" is for the next
4163 * Access-Request, not for the CoA ACK/BAK
4166 request_queue_or_run(request, coa_running);
4170 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4175 STATE_MACHINE_DECL(coa_separate)
4177 VERIFY_REQUEST(request);
4179 TRACE_STATE_MACHINE;
4181 rad_assert(request->parent != NULL);
4182 rad_assert(request->parent->coa == request);
4183 rad_assert(request->ev == NULL);
4184 rad_assert(!request->in_request_hash);
4185 rad_assert(request->coa == NULL);
4187 rad_assert(request->proxy_reply || request->proxy_listener);
4189 (void) talloc_steal(NULL, request);
4190 request->parent->coa = NULL;
4191 request->parent = NULL;
4194 * Most of the time we're called for timers.
4197 case FR_ACTION_TIMER:
4198 request->process(request, FR_ACTION_TIMER);
4202 * Set up the main timers.
4204 case FR_ACTION_PROXY_REPLY:
4205 request->child_state = REQUEST_QUEUED;
4206 request_process_timer(request);
4210 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4215 STATE_MACHINE_DECL(coa_no_reply)
4219 VERIFY_REQUEST(request);
4221 TRACE_STATE_MACHINE;
4224 case FR_ACTION_TIMER:
4225 request_common(request, action);
4228 case FR_ACTION_PROXY_REPLY: /* too late! */
4229 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4230 inet_ntop(request->proxy->src_ipaddr.af,
4231 &request->proxy->src_ipaddr.ipaddr,
4232 buffer, sizeof(buffer)),
4233 request->proxy->dst_port, request->proxy->id);
4238 * FIXME: do recv_coa Fail
4240 (void) process_proxy_reply(request, NULL);
4241 request_done(request, FR_ACTION_DONE);
4245 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4250 STATE_MACHINE_DECL(coa_running)
4252 VERIFY_REQUEST(request);
4254 TRACE_STATE_MACHINE;
4258 * Silently ignore duplicate proxy replies.
4260 case FR_ACTION_PROXY_REPLY:
4263 case FR_ACTION_TIMER:
4264 request_process_timer(request);
4268 if (process_proxy_reply(request, request->proxy_reply)) {
4269 request->handle(request);
4270 request_finish(request, action);
4272 request_done(request, FR_ACTION_DONE);
4277 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4281 #endif /* WITH_COA */
4283 /***********************************************************************
4285 * End of the State machine. Start of additional helper code.
4287 ***********************************************************************/
4289 /***********************************************************************
4293 ***********************************************************************/
4294 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4296 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4298 rad_assert(xel == el);
4300 if ((listener->fd < 0)
4302 #ifndef WITH_DETAIL_THREAD
4303 && (listener->type != RAD_LISTEN_DETAIL)
4309 listener->print(listener, buffer, sizeof(buffer));
4310 ERROR("FATAL: Asked to read from closed socket: %s",
4313 rad_panic("Socket was closed on us!");
4317 listener->recv(listener);
4321 #ifdef WITH_DETAIL_THREAD
4324 * This function is called periodically to see if this detail
4325 * file is available for reading.
4327 static void event_poll_detail(void *ctx)
4330 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4331 struct timeval when, now;
4332 listen_detail_t *detail = this->data;
4334 rad_assert(this->type == RAD_LISTEN_DETAIL);
4337 event_socket_handler(el, this->fd, this);
4339 fr_event_now(el, &now);
4343 * Backdoor API to get the delay until the next poll
4346 delay = this->encode(this, NULL);
4347 if (delay == 0) goto redo;
4349 tv_add(&when, delay);
4352 if (!fr_event_insert(el, event_poll_detail, this,
4353 &when, &detail->ev)) {
4354 ERROR("Failed creating handler");
4358 #endif /* WITH_DETAIL_THREAD */
4359 #endif /* WITH_DETAIL */
4361 static void event_status(struct timeval *wake)
4363 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4367 if (debug_flag == 0) {
4369 INFO("Ready to process requests");
4370 just_started = false;
4376 INFO("Ready to process requests");
4378 } else if ((wake->tv_sec != 0) ||
4379 (wake->tv_usec >= 100000)) {
4380 DEBUG("Waking up in %d.%01u seconds.",
4381 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4386 * FIXME: Put this somewhere else, where it isn't called
4387 * all of the time...
4390 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4392 * If there are no child threads, then there may
4393 * be child processes. In that case, wait for
4394 * their exit status, and throw that exit status
4395 * away. This helps get rid of zxombie children.
4397 while (waitpid(-1, &argval, WNOHANG) > 0) {
4405 static void listener_free_cb(void *ctx)
4407 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4410 if (this->count > 0) {
4411 struct timeval when;
4412 listen_socket_t *sock = this->data;
4414 fr_event_now(el, &when);
4418 if (!fr_event_insert(el, listener_free_cb, this, &when,
4420 rad_panic("Failed to insert event");
4427 * It's all free, close the socket.
4430 this->print(this, buffer, sizeof(buffer));
4431 DEBUG("... cleaning up socket %s", buffer);
4432 rad_assert(this->next == NULL);
4438 static int proxy_eol_cb(void *ctx, void *data)
4440 struct timeval when;
4441 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4443 if (request->proxy_listener != ctx) return 0;
4446 * We don't care if it's being processed in a child thread.
4449 #ifdef WITH_ACCOUNTING
4451 * Accounting packets should be deleted immediately.
4452 * They will never be retransmitted by the client.
4454 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4455 RDEBUG("Stopping request due to failed connection to home server");
4456 request->master_state = REQUEST_STOP_PROCESSING;
4461 * Reset the timer to be now, so that the request is
4462 * quickly updated. But spread the requests randomly
4463 * over the next second, so that we don't overload the
4466 fr_event_now(el, &when);
4467 tv_add(&when, fr_rand() % USEC);
4468 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4471 * Don't delete it from the list.
4477 static int event_new_fd(rad_listen_t *this)
4483 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4485 this->print(this, buffer, sizeof(buffer));
4487 if (this->status == RAD_LISTEN_STATUS_INIT) {
4488 listen_socket_t *sock = this->data;
4490 rad_assert(sock != NULL);
4492 DEBUG("Listening on %s", buffer);
4495 } else if (this->type == RAD_LISTEN_PROXY) {
4496 home_server_t *home;
4499 if (!home || !home->limit.max_connections) {
4500 INFO(" ... adding new socket %s", buffer);
4502 INFO(" ... adding new socket %s (%u of %u)", buffer,
4503 home->limit.num_connections, home->limit.max_connections);
4508 INFO(" ... adding new socket %s", buffer);
4511 switch (this->type) {
4514 * Detail files are always known, and aren't
4515 * put into the socket event loop.
4517 case RAD_LISTEN_DETAIL:
4518 this->status = RAD_LISTEN_STATUS_KNOWN;
4520 #ifndef WITH_DETAIL_THREAD
4522 * Set up the first poll interval.
4524 event_poll_detail(this);
4527 break; /* add the FD to the list */
4529 #endif /* WITH_DETAIL */
4533 * Add it to the list of sockets we can use.
4534 * Server sockets (i.e. auth/acct) are never
4535 * added to the packet list.
4537 case RAD_LISTEN_PROXY:
4539 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4542 * Add timers to outgoing child sockets, if necessary.
4544 if (sock->proto == IPPROTO_TCP && sock->opened &&
4545 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4546 struct timeval when;
4548 when.tv_sec = sock->opened + 1;
4552 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4554 rad_panic("Failed to insert event");
4559 #endif /* WITH_PROXY */
4562 * FIXME: put idle timers on command sockets.
4568 * Add timers to incoming child sockets, if necessary.
4570 if (sock->proto == IPPROTO_TCP && sock->opened &&
4571 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4572 struct timeval when;
4574 when.tv_sec = sock->opened + 1;
4578 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4580 ERROR("Failed adding timer for socket: %s", fr_strerror());
4586 } /* switch over listener types */
4589 * All sockets: add the FD to the event handler.
4591 if (!fr_event_fd_insert(el, 0, this->fd,
4592 event_socket_handler, this)) {
4593 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4597 this->status = RAD_LISTEN_STATUS_KNOWN;
4603 * Stop using this socket, if at all possible.
4605 if (this->status == RAD_LISTEN_STATUS_EOL) {
4607 * Remove it from the list of live FD's.
4609 fr_event_fd_delete(el, 0, this->fd);
4613 * Proxy sockets get frozen, so that we don't use
4614 * them for new requests. But we do keep them
4615 * open to listen for replies to requests we had
4618 if (this->type == RAD_LISTEN_PROXY) {
4619 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4620 if (!fr_packet_list_socket_freeze(proxy_list,
4622 ERROR("Fatal error freezing socket: %s", fr_strerror());
4626 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4627 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4632 * Requests are still using the socket. Wait for
4635 if (this->count > 0) {
4636 struct timeval when;
4637 listen_socket_t *sock = this->data;
4640 * Try again to clean up the socket in 30
4643 gettimeofday(&when, NULL);
4647 if (!fr_event_insert(el,
4648 (fr_event_callback_t) event_new_fd,
4649 this, &when, &sock->ev)) {
4650 rad_panic("Failed to insert event");
4657 * No one is using the socket. We can remove it now.
4659 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4660 } /* socket is at EOL */
4666 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4669 listen_socket_t *sock = this->data;
4671 struct timeval when;
4674 * Re-open the socket, pointing it to /dev/null.
4675 * This means that all writes proceed without
4676 * blocking, and all reads return "no data".
4678 * This leaves the socket active, so any child
4679 * threads won't go insane. But it means that
4680 * they cannot send or receive any packets.
4682 * This is EXTRA work in the normal case, when
4683 * sockets are closed without error. But it lets
4684 * us have one simple processing method for all
4687 devnull = open("/dev/null", O_RDWR);
4689 ERROR("FATAL failure opening /dev/null: %s",
4690 fr_syserror(errno));
4693 if (dup2(devnull, this->fd) < 0) {
4694 ERROR("FATAL failure closing socket: %s",
4695 fr_syserror(errno));
4701 rad_assert(this->type != RAD_LISTEN_DETAIL);
4707 * The socket is dead. Force all proxied packets
4708 * to stop using it. And then remove it from the
4709 * list of outgoing sockets.
4711 if (this->type == RAD_LISTEN_PROXY) {
4712 home_server_t *home;
4715 if (!home || !home->limit.max_connections) {
4716 INFO(" ... shutting down socket %s", buffer);
4718 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4719 home->limit.num_connections, home->limit.max_connections);
4722 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4723 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4725 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4726 ERROR("Fatal error removing socket %s: %s",
4727 buffer, fr_strerror());
4730 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4734 INFO(" ... shutting down socket %s", buffer);
4737 * EOL all requests using this socket.
4739 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4743 * No child threads, clean it up now.
4747 if (sock->ev) fr_event_delete(el, &sock->ev);
4753 * Wait until all requests using this socket are done.
4755 gettimeofday(&when, NULL);
4759 if (!fr_event_insert(el, listener_free_cb, this, &when,
4761 rad_panic("Failed to insert event");
4764 #endif /* WITH_TCP */
4769 /***********************************************************************
4773 ***********************************************************************/
4775 static void handle_signal_self(int flag)
4779 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4780 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4781 INFO("Signalled to exit");
4782 fr_event_loop_exit(el, 1);
4784 INFO("Signalled to terminate");
4785 fr_event_loop_exit(el, 2);
4789 } /* else exit/term flags weren't set */
4792 * Tell the even loop to stop processing.
4794 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4796 static time_t last_hup = 0;
4799 if ((int) (when - last_hup) < 5) {
4800 INFO("Ignoring HUP (less than 5s since last one)");
4804 INFO("Received HUP signal");
4808 exec_trigger(NULL, NULL, "server.signal.hup", true);
4809 fr_event_loop_exit(el, 0x80);
4813 #ifndef WITH_DETAIL_THREAD
4814 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4818 * FIXME: O(N) loops suck.
4820 for (this = main_config.listen;
4822 this = this->next) {
4823 if (this->type != RAD_LISTEN_DETAIL) continue;
4826 * This one didn't send the signal, skip
4829 if (!this->decode(this, NULL)) continue;
4832 * Go service the interrupt.
4834 event_poll_detail(this);
4842 #ifdef HAVE_PTHREAD_H
4844 * There are new listeners in the list. Run
4845 * event_new_fd() on them.
4847 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4848 rad_listen_t *this, *next;
4850 FD_MUTEX_LOCK(&fd_mutex);
4853 * FIXME: unlock the mutex before calling
4856 for (this = new_listeners; this != NULL; this = next) {
4863 new_listeners = NULL;
4864 FD_MUTEX_UNLOCK(&fd_mutex);
4866 #endif /* HAVE_PTHREAD_H */
4867 #endif /* WITH_PROXY */
4868 #endif /* WITH_TCP */
4871 #ifndef HAVE_PTHREAD_H
4872 void radius_signal_self(int flag)
4874 return handle_signal_self(flag);
4878 static int self_pipe[2] = { -1, -1 };
4881 * Inform ourselves that we received a signal.
4883 void radius_signal_self(int flag)
4889 * The read MUST be non-blocking for this to work.
4891 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4895 for (i = 0; i < rcode; i++) {
4896 buffer[0] |= buffer[i];
4904 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4908 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4909 UNUSED int fd, UNUSED void *ctx)
4914 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4915 if (rcode <= 0) return;
4918 * Merge pending signals.
4920 for (i = 0; i < rcode; i++) {
4921 buffer[0] |= buffer[i];
4924 handle_signal_self(buffer[0]);
4926 #endif /* HAVE_PTHREAD_H */
4928 /***********************************************************************
4930 * Bootstrapping code.
4932 ***********************************************************************/
4935 * Externally-visibly functions.
4937 int radius_event_init(TALLOC_CTX *ctx) {
4938 el = fr_event_list_create(ctx, event_status);
4944 static int packet_entry_cmp(void const *one, void const *two)
4946 RADIUS_PACKET const * const *a = one;
4947 RADIUS_PACKET const * const *b = two;
4949 return fr_packet_cmp(*a, *b);
4953 int radius_event_start(CONF_SECTION *cs, bool have_children)
4955 rad_listen_t *head = NULL;
4957 if (fr_start_time != (time_t)-1) return 0;
4959 time(&fr_start_time);
4961 if (!check_config) {
4963 * radius_event_init() must be called first
4967 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
4968 if (!pl) return 0; /* leak el */
4971 request_num_counter = 0;
4974 if (main_config.proxy_requests) {
4976 * Create the tree for managing proxied requests and
4979 proxy_list = fr_packet_list_create(1);
4980 if (!proxy_list) return 0;
4982 #ifdef HAVE_PTHREAD_H
4983 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4984 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4985 fr_syserror(errno));
4991 * The "init_delay" is set to "response_window".
4992 * Reset it to half of "response_window" in order
4993 * to give the event loop enough time to service
4994 * the event before hitting "response_window".
4996 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
4997 main_config.init_delay.tv_usec >>= 1;
4998 main_config.init_delay.tv_sec >>= 1;
5000 proxy_ctx = talloc_init("proxy");
5005 * Move all of the thread calls to this file?
5007 * It may be best for the mutexes to be in this file...
5009 spawn_flag = have_children;
5011 #ifdef HAVE_PTHREAD_H
5012 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5015 * Initialize the threads ONLY if we're spawning, AND
5016 * we're running normally.
5018 if (have_children && !check_config &&
5019 (thread_pool_init(cs, &spawn_flag) < 0)) {
5025 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5027 if (listen_init(cs, &head, spawn_flag) < 0) {
5034 #ifdef HAVE_PTHREAD_H
5036 * Child threads need a pipe to signal us, as do the
5039 if (pipe(self_pipe) < 0) {
5040 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5043 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5044 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5045 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5048 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5049 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5050 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5053 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5055 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5056 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5061 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5064 * The server temporarily switches to an unprivileged
5065 * user very early in the bootstrapping process.
5066 * However, some sockets MAY require privileged access
5067 * (bind to device, or to port < 1024, or to raw
5068 * sockets). Those sockets need to call suid up/down
5069 * themselves around the functions that need a privileged
5072 if (listen_init(cs, &head, spawn_flag) < 0) {
5076 main_config.listen = head;
5079 * At this point, no one has any business *ever* going
5082 rad_suid_down_permanent();
5089 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5091 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5093 VERIFY_REQUEST(request);
5095 request->master_state = REQUEST_STOP_PROCESSING;
5097 #ifdef HAVE_PTHREAD_H
5098 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5102 * If it's queued we can't delete it from the queue.
5104 * Otherwise, it's OK to delete it. Even RUNNING, because
5105 * that will get caught by the check above.
5107 if (request->child_state == REQUEST_QUEUED) return 0;
5109 request->in_proxy_hash = false;
5111 if (!request->in_request_hash) {
5112 request_done(request, FR_ACTION_DONE);
5116 * Delete it from the list.
5123 static int request_delete_cb(UNUSED void *ctx, void *data)
5125 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5127 VERIFY_REQUEST(request);
5129 request->master_state = REQUEST_STOP_PROCESSING;
5132 * Not done, or the child thread is still processing it.
5134 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5136 #ifdef HAVE_PTHREAD_H
5137 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5141 rad_assert(request->in_proxy_hash == false);
5144 request->in_request_hash = false;
5146 if (request->ev) fr_event_delete(el, &request->ev);
5148 if (main_config.memory_report) {
5149 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5150 request->packet->id,
5151 (unsigned int) (request->timestamp - fr_start_time));
5156 rad_assert(!request->coa->in_proxy_hash);
5160 request_free(request);
5163 * Delete it from the list, and continue;
5169 void radius_event_free(void)
5175 * There are requests in the proxy hash that aren't
5176 * referenced from anywhere else. Remove them first.
5179 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5183 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5187 * Now that all requests have been marked "please stop",
5188 * ensure that all of the threads have exited.
5190 #ifdef HAVE_PTHREAD_H
5195 * Walk the lists again, ensuring that all
5196 * requests are done.
5198 if (main_config.memory_report) {
5203 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5204 num = fr_packet_list_num_elements(proxy_list);
5206 ERROR("Proxy list has %d requests still in it.", num);
5211 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5212 num = rbtree_num_elements(pl);
5214 ERROR("Request list has %d requests still in it.", num);
5223 fr_packet_list_free(proxy_list);
5226 if (proxy_ctx) talloc_free(proxy_ctx);
5231 if (debug_condition) talloc_free(debug_condition);
5234 int radius_event_process(void)
5238 return fr_event_loop(el);