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 rad_assert(request->ev == NULL);
489 rad_assert(!request->in_request_hash);
490 rad_assert(!request->in_proxy_hash);
492 if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
493 talloc_free(request);
497 ptr = talloc_parent(request);
498 rad_assert(ptr != NULL);
504 * Only ever called from the master thread.
506 STATE_MACHINE_DECL(request_done)
508 struct timeval now, when;
513 VERIFY_REQUEST(request);
518 * Force this no matter what.
520 request->process = request_done;
524 * Tell the detail listener that we're done.
526 if (request->listener &&
527 (request->listener->type == RAD_LISTEN_DETAIL) &&
528 (request->simul_max != 1)) {
529 request->simul_max = 1;
530 request->listener->send(request->listener,
535 #ifdef HAVE_PTHREAD_H
537 * If called from a child thread, mark ourselves as done,
538 * and wait for the master thread timer to clean us up.
540 if (!we_are_master()) {
542 request->child_state = REQUEST_DONE;
548 * Mark the request as STOP.
550 request->master_state = REQUEST_STOP_PROCESSING;
554 * Move the CoA request to its own handler.
557 coa_separate(request->coa, FR_ACTION_TIMER);
558 } else if (request->parent && (request->parent->coa == request)) {
559 coa_separate(request, FR_ACTION_TIMER);
564 * It doesn't hurt to send duplicate replies. All other
565 * signals are ignored, as the request will be cleaned up
571 rad_assert(request->listener != NULL);
573 if (request->reply->code != 0) {
574 request->listener->send(request->listener, request);
577 RDEBUG("No reply. Ignoring retransmit");
582 * Mark the request as done.
585 #ifdef HAVE_PTHREAD_H
587 * If the child is still running, leave it alone.
589 if (spawn_flag && (request->child_state <= REQUEST_RUNNING)) {
594 #ifdef DEBUG_STATE_MACHINE
595 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
596 request->number, __FUNCTION__,
597 child_state_names[request->child_state],
598 child_state_names[REQUEST_DONE]);
600 request->child_state = REQUEST_DONE;
604 * Called when the child is taking too long to
605 * finish. We've already marked it "please
606 * stop", so we don't complain any more.
608 case FR_ACTION_TIMER:
613 * Child is still alive, and we're receiving more
614 * packets from the home server.
616 case FR_ACTION_PROXY_REPLY:
617 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
618 inet_ntop(request->proxy->src_ipaddr.af,
619 &request->proxy->src_ipaddr.ipaddr,
620 buffer, sizeof(buffer)),
621 request->proxy->dst_port, request->proxy->id);
630 * Remove it from the request hash.
632 if (request->in_request_hash) {
633 if (!rbtree_deletebydata(pl, &request->packet)) {
636 request->in_request_hash = false;
641 * Wait for the proxy ID to expire. This allows us to
642 * avoid re-use of proxy IDs for a while.
644 if (request->in_proxy_hash) {
645 rad_assert(request->proxy != NULL);
647 fr_event_now(el, &now);
648 when = request->proxy->timestamp;
651 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
652 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
653 (request->packet->code != request->proxy->code)) {
654 when.tv_sec += request->home_server->coa_mrd;
657 timeradd(&when, request_response_window(request), &when);
660 * We haven't received all responses, AND there's still
661 * time to wait. Do so.
663 if ((request->num_proxied_requests > request->num_proxied_responses) &&
665 (request->home_server->proto != IPPROTO_TCP) &&
667 timercmp(&now, &when, <)) {
668 RDEBUG("Waiting for more responses from the home server");
675 remove_from_proxy_hash(request);
679 #ifdef HAVE_PTHREAD_H
681 * If there's no children, we can mark the request as done.
683 if (!spawn_flag) request->child_state = REQUEST_DONE;
687 * If the child is still running, wait for it to be finished.
689 if (request->child_state <= REQUEST_RUNNING) {
690 gettimeofday(&now, NULL);
695 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
696 tv_add(&when, request->delay);
697 request->delay += request->delay >> 1;
698 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
700 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
704 #ifdef HAVE_PTHREAD_H
705 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
709 * @todo: do final states for TCP sockets, too?
711 request_stats_final(request);
713 if (request->listener) {
714 request->listener->count--;
717 * If we're the last one, remove the listener now.
719 if ((request->listener->count == 0) &&
720 (request->listener->status == RAD_LISTEN_STATUS_EOL)) {
721 request->listener->status = RAD_LISTEN_STATUS_REMOVE_NOW;
722 event_new_fd(request->listener);
727 if (request->packet) {
728 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
730 (unsigned int) (request->timestamp - fr_start_time));
731 } /* else don't print anything */
734 fr_event_delete(el, &request->ev);
735 request_free(request);
739 static void request_cleanup_delay_init(REQUEST *request)
741 struct timeval now, when;
743 VERIFY_REQUEST(request);
745 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
749 * If the packets are from the detail file, we can clean them up now.
751 if (request->listener->type == RAD_LISTEN_DETAIL) goto done;
754 if (!request->root->cleanup_delay) goto done;
756 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_CLEANUP_DELAY;
775 * Update this if we can, otherwise let the timers pick it up.
777 if (we_are_master()) {
778 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
786 * Otherwise just clean it up.
789 request_done(request, FR_ACTION_DONE);
794 * Function to do all time-related events.
796 static void request_process_timer(REQUEST *request)
798 struct timeval now, when;
799 rad_assert(request->magic == REQUEST_MAGIC);
800 #ifdef DEBUG_STATE_MACHINE
801 int action = FR_ACTION_TIMER;
804 VERIFY_REQUEST(request);
811 * If we originated a CoA request, divorce it from the
812 * parent. Then, set up the timers so that we can clean
813 * it up as appropriate.
815 if (request->coa) coa_separate(request->coa, FR_ACTION_TIMER);
818 * If we're the request, OR it isn't originating a CoA
819 * request, check more things.
821 if (!request->proxy || (request->packet->code == request->proxy->code))
824 rad_assert(request->listener != NULL);
827 * The socket was closed. Tell the request that
828 * there is no point in continuing.
830 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
831 if ((request->master_state == REQUEST_ACTIVE) &&
832 (request->child_state < REQUEST_RESPONSE_DELAY)) {
833 WARN("Socket was closed while processing request %u: Stopping it.", request->number);
834 request->master_state = REQUEST_STOP_PROCESSING;
839 gettimeofday(&now, NULL);
842 * The request was forcibly stopped.
844 if (request->master_state == REQUEST_STOP_PROCESSING) {
845 switch (request->child_state) {
847 case REQUEST_RUNNING:
848 #ifdef HAVE_PTHREAD_H
849 rad_assert(spawn_flag == true);
854 * Sleep for some more. We HOPE that the
855 * child will become responsive at some
856 * point in the future.
859 tv_add(&when, request->delay);
860 request->delay += request->delay >> 1;
861 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
865 * These should all be managed by the master thread
868 case REQUEST_PROXIED:
870 case REQUEST_RESPONSE_DELAY:
871 case REQUEST_CLEANUP_DELAY:
874 request_done(request, FR_ACTION_DONE);
879 rad_assert(request->master_state == REQUEST_ACTIVE);
882 * It's still supposed to be running.
884 switch (request->child_state) {
886 case REQUEST_RUNNING:
887 when = request->packet->timestamp;
888 when.tv_sec += request->root->max_request_time;
891 * Taking too long: tell it to die.
893 if (timercmp(&now, &when, >=)) {
894 #ifdef HAVE_PTHREAD_H
896 * If there's a child thread processing it,
900 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
901 ERROR("Unresponsive child for request %u, in component %s module %s",
903 request->component ? request->component : "<core>",
904 request->module ? request->module : "<core>");
905 exec_trigger(request, NULL, "server.thread.unresponsive", true);
908 request->master_state = REQUEST_STOP_PROCESSING;
910 goto delay; /* sleep some more */
913 case REQUEST_PROXIED:
914 when = request->packet->timestamp;
915 when.tv_sec += request->root->max_request_time;
917 if (timercmp(&now, &when, >=)) {
918 RWDEBUG("No response to proxied request in 'max_request_time'. Stopping it.");
919 request->master_state = REQUEST_STOP_PROCESSING;
920 request_done(request, FR_ACTION_DONE);
924 rad_assert(request->proxy != NULL);
927 * Delay some more, hoping that we get a response.
929 when = request->proxy->timestamp;
930 tv_add(&when, request->delay);
932 if (timercmp(&now, &when, >=)) {
933 request->process(request, FR_ACTION_TIMER);
938 * Otherwise set the timer for the future.
940 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
942 #endif /* WITH_PROXY */
944 case REQUEST_RESPONSE_DELAY:
945 rad_assert(request->response_delay.tv_sec > 0);
947 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
950 request->process = request_response_delay;
952 when = request->reply->timestamp;
954 tv_add(&when, request->response_delay.tv_sec * USEC);
955 tv_add(&when, request->response_delay.tv_usec);
957 if (timercmp(&when, &now, >)) {
958 #ifdef DEBUG_STATE_MACHINE
959 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
961 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
963 } /* else it's time to send the reject */
965 RDEBUG2("Sending delayed response");
966 request->listener->send(request->listener, request);
967 debug_packet(request, request->reply, false);
969 request->process = request_cleanup_delay;
970 request->child_state = REQUEST_CLEANUP_DELAY;
973 case REQUEST_CLEANUP_DELAY:
974 rad_assert(request->root->cleanup_delay > 0);
977 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
980 when = request->reply->timestamp;
981 when.tv_sec += request->root->cleanup_delay;
983 if (timercmp(&when, &now, >)) {
984 #ifdef DEBUG_STATE_MACHINE
985 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
987 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
989 } /* else it's time to clean up */
998 static void request_queue_or_run(REQUEST *request,
999 fr_request_process_t process)
1001 #ifdef DEBUG_STATE_MACHINE
1002 int action = FR_ACTION_TIMER;
1005 VERIFY_REQUEST(request);
1007 TRACE_STATE_MACHINE;
1010 * Do this here so that fewer other functions need to do
1013 if (request->master_state == REQUEST_STOP_PROCESSING) {
1014 #ifdef DEBUG_STATE_MACHINE
1015 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
1016 request->number, __FUNCTION__,
1017 master_state_names[request->master_state],
1018 child_state_names[request->child_state],
1019 child_state_names[REQUEST_DONE]);
1021 request_done(request, FR_ACTION_DONE);
1025 request->process = process;
1027 if (we_are_master()) {
1028 struct timeval when;
1031 * (re) set the initial delay.
1033 request->delay = request_init_delay(request);
1034 if (request->delay > USEC) request->delay = USEC;
1035 gettimeofday(&when, NULL);
1036 tv_add(&when, request->delay);
1037 request->delay += request->delay >> 1;
1039 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1041 #ifdef HAVE_PTHREAD_H
1044 * A child thread will eventually pick it up.
1046 if (request_enqueue(request)) return;
1049 * Otherwise we're not going to do anything with
1052 request_done(request, FR_ACTION_DONE);
1058 request->child_state = REQUEST_RUNNING;
1059 request->process(request, FR_ACTION_RUN);
1063 * Requests that care about child process exit
1064 * codes have already either called
1065 * rad_waitpid(), or they've given up.
1067 while (waitpid(-1, NULL, WNOHANG) > 0);
1071 STATE_MACHINE_DECL(request_common)
1077 VERIFY_REQUEST(request);
1079 TRACE_STATE_MACHINE;
1083 * Bail out as early as possible.
1085 if (request->master_state == REQUEST_STOP_PROCESSING) {
1086 request_done(request, FR_ACTION_DONE);
1092 ERROR("(%u) Ignoring duplicate packet from "
1093 "client %s port %d - ID: %u due to unfinished request "
1094 "in component %s module %s",
1095 request->number, request->client->shortname,
1096 request->packet->src_port,request->packet->id,
1097 request->component, request->module);
1100 case FR_ACTION_TIMER:
1101 request_process_timer(request);
1105 case FR_ACTION_PROXY_REPLY:
1106 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
1107 inet_ntop(request->proxy->dst_ipaddr.af,
1108 &request->proxy->dst_ipaddr.ipaddr,
1109 buffer, sizeof(buffer)),
1110 request->proxy->dst_port, request->proxy->id);
1115 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1120 STATE_MACHINE_DECL(request_cleanup_delay)
1122 struct timeval when;
1124 VERIFY_REQUEST(request);
1126 TRACE_STATE_MACHINE;
1131 if (request->reply->code != 0) {
1132 request->listener->send(request->listener, request);
1134 RDEBUG("No reply. Ignoring retransmit");
1138 * Double the cleanup_delay to catch retransmits.
1140 when = request->reply->timestamp;
1141 request->delay += request->delay ;
1142 when.tv_sec += request->delay;
1144 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1148 case FR_ACTION_PROXY_REPLY:
1150 case FR_ACTION_TIMER:
1151 request_common(request, action);
1155 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1160 STATE_MACHINE_DECL(request_response_delay)
1162 VERIFY_REQUEST(request);
1164 TRACE_STATE_MACHINE;
1169 ERROR("(%u) Discarding duplicate request from "
1170 "client %s port %d - ID: %u due to delayed response",
1171 request->number, request->client->shortname,
1172 request->packet->src_port,request->packet->id);
1176 case FR_ACTION_PROXY_REPLY:
1178 case FR_ACTION_TIMER:
1179 request_common(request, action);
1183 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1189 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1193 VERIFY_REQUEST(request);
1195 TRACE_STATE_MACHINE;
1197 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1200 * Don't decode the packet if it's an internal "fake"
1201 * request. Instead, just return so that the caller can
1204 if (request->packet->dst_port == 0) {
1205 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1206 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1210 if (!request->packet->vps) { /* FIXME: check for correct state */
1211 rcode = request->listener->decode(request->listener, request);
1214 if (debug_condition) {
1216 * Ignore parse errors.
1218 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1219 request->log.lvl = L_DBG_LVL_2;
1220 request->log.func = vradlog_request;
1225 debug_packet(request, request->packet, true);
1231 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1232 request->reply->offset = -2; /* bad authenticator */
1236 if (!request->username) {
1237 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1243 STATE_MACHINE_DECL(request_finish)
1247 VERIFY_REQUEST(request);
1249 TRACE_STATE_MACHINE;
1251 (void) action; /* -Wunused */
1253 if (request->master_state == REQUEST_STOP_PROCESSING) {
1256 * Always send a reply to the detail listener.
1258 if (request->listener->type == RAD_LISTEN_DETAIL) {
1263 request->child_state = REQUEST_DONE;
1269 * Don't do post-auth if we're a CoA request originated
1270 * from an Access-Request. See request_alloc_coa() for
1273 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1277 * Override the response code if a control:Response-Packet-Type attribute is present.
1279 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1281 if (vp->vp_integer == 256) {
1282 RDEBUG2("Not responding to request");
1283 request->reply->code = 0;
1285 request->reply->code = vp->vp_integer;
1289 * Catch Auth-Type := Reject BEFORE proxying the packet.
1291 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1292 if (request->reply->code == 0) {
1293 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1295 if (!vp || (vp->vp_integer != 5)) {
1296 RDEBUG2("There was no response configured: "
1297 "rejecting request");
1300 request->reply->code = PW_CODE_ACCESS_REJECT;
1305 * Copy Proxy-State from the request to the reply.
1307 vp = paircopy_by_num(request->reply, request->packet->vps,
1308 PW_PROXY_STATE, 0, TAG_ANY);
1309 if (vp) pairadd(&request->reply->vps, vp);
1312 * Call Post-Auth for Access-Request packets.
1314 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1315 rad_postauth(request);
1320 * Clean up. These are no longer needed.
1322 gettimeofday(&request->reply->timestamp, NULL);
1325 * Fake packets get marked as "done", and have the
1326 * proxy-reply section deal with the reply attributes.
1327 * We therefore don't free the reply attributes.
1329 if (request->packet->dst_port == 0) {
1330 RDEBUG("Finished internally proxied request.");
1332 request->child_state = REQUEST_DONE;
1338 * Always send the reply to the detail listener.
1340 if (request->listener->type == RAD_LISTEN_DETAIL) {
1342 request->simul_max = 1;
1343 request->listener->send(request->listener, request);
1345 * But only print the reply if there is one.
1347 if (request->reply->code != 0) {
1348 debug_packet(request, request->reply, false);
1355 * Ignore all "do not respond" packets.
1356 * Except for the detail ones, which need to ping
1357 * the detail file reader so that it will retransmit.
1359 if (!request->reply->code) {
1360 RDEBUG("Not sending reply to client.");
1365 * If it's not in the request hash, we MIGHT not want to
1368 * If duplicate packets are allowed, then then only
1369 * reason to NOT be in the request hash is because we
1370 * don't want to send a reply.
1372 * FIXME: this is crap. The rest of the state handling
1373 * should use a different field so that we don't have two
1376 * Otherwise duplicates are forbidden, and the request is
1377 * SUPPOSED to avoid the request hash.
1379 * In that case, we need to send a reply.
1381 if (!request->in_request_hash &&
1382 !request->listener->nodup) {
1383 RDEBUG("Suppressing reply to client.");
1388 * See if we need to delay an Access-Reject packet.
1390 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1391 (request->root->reject_delay.tv_sec > 0)) {
1392 request->response_delay = request->root->reject_delay;
1396 * If we timed out a proxy packet, don't delay
1397 * the reject any more.
1399 if (request->proxy && !request->proxy_reply) {
1400 request->response_delay.tv_sec = 0;
1401 request->response_delay.tv_usec = 0;
1409 if (request->response_delay.tv_sec == 0) {
1410 rad_assert(request->response_delay.tv_usec == 0);
1413 * Don't print a reply if there's none to send.
1415 if (request->reply->code != 0) {
1416 request->listener->send(request->listener, request);
1417 debug_packet(request, request->reply, false);
1421 RDEBUG2("Finished request");
1422 request->component = "<core>";
1423 request->module = "<done>";
1425 #ifdef WITH_ACCOUNTING
1427 * Accounting packets can be cleaned up now.
1429 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1431 request->child_state = REQUEST_DONE;
1438 * If the packets are from the detail file, we can clean them up now.
1440 if (request->listener->type == RAD_LISTEN_DETAIL) {
1442 request->child_state = REQUEST_DONE;
1449 * If we've originated this CoA request, it gets
1452 if (request->proxy &&
1453 ((request->proxy->code == PW_CODE_COA_REQUEST) ||
1454 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
1455 (request->packet->code != request->proxy->code)) {
1457 request->child_state = REQUEST_DONE;
1463 * Clean up the request.
1465 request_cleanup_delay_init(request);
1469 * Encode and sign it here, so that the master
1470 * thread can just send the encoded data, which
1471 * means it does less work.
1473 RDEBUG2("Delaying response for %d.%06d seconds",
1474 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1475 request->listener->encode(request->listener, request);
1476 request->component = "<core>";
1477 request->module = "<delay>";
1479 request->child_state = REQUEST_RESPONSE_DELAY;
1483 STATE_MACHINE_DECL(request_running)
1485 VERIFY_REQUEST(request);
1487 TRACE_STATE_MACHINE;
1490 case FR_ACTION_TIMER:
1491 request_process_timer(request);
1495 request_common(request, action);
1499 if (!request_pre_handler(request, action)) {
1500 #ifdef DEBUG_STATE_MACHINE
1501 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1502 request->number, __FUNCTION__,
1503 child_state_names[request->child_state],
1504 child_state_names[REQUEST_DONE]);
1508 request->child_state = REQUEST_DONE;
1512 rad_assert(request->handle != NULL);
1513 request->handle(request);
1517 * We may need to send a proxied request.
1519 if ((action == FR_ACTION_RUN) &&
1520 request_will_proxy(request)) {
1521 #ifdef DEBUG_STATE_MACHINE
1522 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1526 * takes care of setting
1527 * up the post proxy fail
1530 if (request_proxy(request, 0) < 0) goto req_finished;
1534 #ifdef DEBUG_STATE_MACHINE
1535 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1540 * Maybe originate a CoA request.
1542 if ((action == FR_ACTION_RUN) && request->coa) {
1543 request_coa_originate(request);
1550 request_finish(request, action);
1555 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1560 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1561 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1564 RADIUS_PACKET **packet_p;
1565 REQUEST *request = NULL;
1567 listen_socket_t *sock = NULL;
1569 VERIFY_PACKET(packet);
1572 * Set the last packet received.
1574 gettimeofday(&now, NULL);
1576 packet->timestamp = now;
1578 #ifdef WITH_ACCOUNTING
1579 if (listener->type != RAD_LISTEN_DETAIL)
1582 sock = listener->data;
1583 sock->last_packet = now.tv_sec;
1587 * Skip everything if required.
1589 if (listener->nodup) goto skip_dup;
1591 packet_p = rbtree_finddata(pl, &packet);
1593 rad_child_state_t child_state;
1595 request = fr_packet2myptr(REQUEST, packet, packet_p);
1596 rad_assert(request->in_request_hash);
1597 child_state = request->child_state;
1600 * Same src/dst ip/port, length, and
1601 * authentication vector: must be a duplicate.
1603 if ((request->packet->data_len == packet->data_len) &&
1604 (memcmp(request->packet->vector, packet->vector,
1605 sizeof(packet->vector)) == 0)) {
1608 switch (packet->code) {
1609 case PW_CODE_ACCESS_REQUEST:
1610 FR_STATS_INC(auth, total_dup_requests);
1613 #ifdef WITH_ACCOUNTING
1614 case PW_CODE_ACCOUNTING_REQUEST:
1615 FR_STATS_INC(acct, total_dup_requests);
1619 case PW_CODE_COA_REQUEST:
1620 FR_STATS_INC(coa, total_dup_requests);
1623 case PW_CODE_DISCONNECT_REQUEST:
1624 FR_STATS_INC(dsc, total_dup_requests);
1631 #endif /* WITH_STATS */
1634 * Tell the state machine that there's a
1635 * duplicate request.
1637 request->process(request, FR_ACTION_DUP);
1638 return 0; /* duplicate of live request */
1642 * Mark the request as done ASAP, and before we
1643 * log anything. The child may stop processing
1644 * the request just as we're logging the
1647 request_done(request, FR_ACTION_DONE);
1651 * It's a new request, not a duplicate. If the
1652 * old one is done, then we can clean it up.
1654 if (child_state <= REQUEST_RUNNING) {
1656 * The request is still QUEUED or RUNNING. That's a problem.
1658 ERROR("Received conflicting packet from "
1659 "client %s port %d - ID: %u due to "
1660 "unfinished request. Giving up on old request.",
1662 packet->src_port, packet->id);
1666 * Mark the old request as done. If there's no
1667 * child, the request will be cleaned up
1668 * immediately. If there is a child, we'll set a
1669 * timer to go clean up the request.
1671 } /* else the new packet is unique */
1674 * Quench maximum number of outstanding requests.
1676 if (main_config.max_requests &&
1677 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1678 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1680 packet->src_port, packet->id);
1681 WARN("Please check the configuration file.\n"
1682 "\tThe value for 'max_requests' is probably set too low.\n"));
1684 exec_trigger(NULL, NULL, "server.max_requests", true);
1690 * Rate-limit the incoming packets
1692 if (sock && sock->max_rate) {
1695 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1696 if (pps > sock->max_rate) {
1697 DEBUG("Dropping request due to rate limiting");
1700 sock->rate_pps_now++;
1704 * Allocate a pool for the request.
1707 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1711 * The packet is still allocated from a different
1712 * context, but oh well.
1714 (void) talloc_steal(ctx, packet);
1717 request = request_setup(ctx, listener, packet, client, fun);
1724 * Mark it as a "real" request with a context.
1726 request->options |= RAD_REQUEST_OPTION_CTX;
1729 * Remember the request in the list.
1731 if (!listener->nodup) {
1732 if (!rbtree_insert(pl, &request->packet)) {
1733 RERROR("Failed to insert request in the list of live requests: discarding it");
1734 request_done(request, FR_ACTION_DONE);
1738 request->in_request_hash = true;
1742 * Process it. Send a response, and free it.
1744 if (listener->synchronous) {
1746 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1749 request->listener->decode(request->listener, request);
1750 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1751 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1755 if (request->reply->code != 0) {
1756 request->listener->send(request->listener, request);
1758 RDEBUG("Not sending reply");
1762 * Don't do delayed reject. Oh well.
1764 request_free(request);
1769 * Otherwise, insert it into the state machine.
1770 * The child threads will take care of processing it.
1772 request_queue_or_run(request, request_running);
1778 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1779 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1784 * Create and initialize the new request.
1786 request = request_alloc(ctx);
1791 request->reply = rad_alloc(request, false);
1792 if (!request->reply) {
1794 talloc_free(request);
1798 request->listener = listener;
1799 request->client = client;
1800 request->packet = talloc_steal(request, packet);
1801 request->number = request_num_counter++;
1802 request->priority = listener->type;
1803 request->master_state = REQUEST_ACTIVE;
1804 #ifdef DEBUG_STATE_MACHINE
1805 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1806 request->number, __FUNCTION__,
1807 child_state_names[request->child_state],
1808 child_state_names[REQUEST_RUNNING]);
1810 #ifdef HAVE_PTHREAD_H
1811 request->child_pid = NO_SUCH_CHILD_PID;
1813 request->child_state = REQUEST_RUNNING;
1814 request->handle = fun;
1818 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1819 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1820 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1821 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1822 #ifdef WITH_ACCOUNTING
1823 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1824 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1825 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1828 #endif /* WITH_STATS */
1831 * Status-Server packets go to the head of the queue.
1833 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1836 * Set virtual server identity
1838 if (client->server) {
1839 request->server = client->server;
1840 } else if (listener->server) {
1841 request->server = listener->server;
1843 request->server = NULL;
1846 request->root = &main_config;
1848 request->listener->count++;
1852 * The request passes many of our sanity checks.
1853 * From here on in, if anything goes wrong, we
1854 * send a reject message, instead of dropping the
1859 * Build the reply template from the request.
1862 request->reply->sockfd = request->packet->sockfd;
1863 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1864 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1865 request->reply->dst_port = request->packet->src_port;
1866 request->reply->src_port = request->packet->dst_port;
1867 request->reply->id = request->packet->id;
1868 request->reply->code = 0; /* UNKNOWN code */
1869 memcpy(request->reply->vector, request->packet->vector,
1870 sizeof(request->reply->vector));
1871 request->reply->vps = NULL;
1872 request->reply->data = NULL;
1873 request->reply->data_len = 0;
1879 /***********************************************************************
1883 ***********************************************************************/
1886 * Timer function for all TCP sockets.
1888 static void tcp_socket_timer(void *ctx)
1890 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1891 listen_socket_t *sock = listener->data;
1892 struct timeval end, now;
1894 fr_socket_limit_t *limit;
1898 fr_event_now(el, &now);
1900 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1902 switch (listener->type) {
1904 case RAD_LISTEN_PROXY:
1905 limit = &sock->home->limit;
1909 case RAD_LISTEN_AUTH:
1910 #ifdef WITH_ACCOUNTING
1911 case RAD_LISTEN_ACCT:
1913 limit = &sock->limit;
1921 * If we enforce a lifetime, do it now.
1923 if (limit->lifetime > 0) {
1924 end.tv_sec = sock->opened + limit->lifetime;
1927 if (timercmp(&end, &now, <=)) {
1928 listener->print(listener, buffer, sizeof(buffer));
1929 DEBUG("Reached maximum lifetime on socket %s", buffer);
1933 listener->status = RAD_LISTEN_STATUS_EOL;
1934 event_new_fd(listener);
1943 * Enforce an idle timeout.
1945 if (limit->idle_timeout > 0) {
1946 struct timeval idle;
1948 rad_assert(sock->last_packet != 0);
1949 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1952 if (timercmp(&idle, &now, <=)) {
1953 listener->print(listener, buffer, sizeof(buffer));
1954 DEBUG("Reached idle timeout on socket %s", buffer);
1959 * Enforce the minimum of idle timeout or lifetime.
1961 if (timercmp(&idle, &end, <)) {
1967 * Wake up at t + 0.5s. The code above checks if the timers
1968 * are <= t. This addition gives us a bit of leeway.
1970 end.tv_usec = USEC / 2;
1973 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1974 rad_panic("Failed to insert event");
1981 * Add +/- 2s of jitter, as suggested in RFC 3539
1984 static void add_jitter(struct timeval *when)
1991 jitter ^= (jitter >> 10);
1992 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1995 * Add in ~ (4 * USEC) of jitter.
1997 tv_add(when, jitter);
2001 * Called by socket_del to remove requests with this socket
2003 static int eol_proxy_listener(void *ctx, void *data)
2005 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2006 RADIUS_PACKET **proxy_p = data;
2009 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2010 if (request->proxy_listener != this) return 0;
2013 * The normal "remove_from_proxy_hash" tries to grab the
2014 * proxy mutex. We already have it held, so grabbing it
2015 * again will cause a deadlock. Instead, call the "no
2016 * lock" version of the function.
2018 rad_assert(request->in_proxy_hash == true);
2019 remove_from_proxy_hash_nl(request, false);
2022 * Don't mark it as DONE. The client can retransmit, and
2023 * the packet SHOULD be re-proxied somewhere else.
2025 * Return "2" means that the rbtree code will remove it
2026 * from the tree, and we don't need to do it ourselves.
2030 #endif /* WITH_PROXY */
2032 static int eol_listener(void *ctx, void *data)
2034 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2035 RADIUS_PACKET **packet_p = data;
2038 request = fr_packet2myptr(REQUEST, packet, packet_p);
2039 if (request->listener != this) return 0;
2041 request->master_state = REQUEST_STOP_PROCESSING;
2045 #endif /* WITH_TCP */
2048 /***********************************************************************
2050 * Proxy handlers for the state machine.
2052 ***********************************************************************/
2055 * Called with the proxy mutex held
2057 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2059 VERIFY_REQUEST(request);
2061 if (!request->in_proxy_hash) return;
2063 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2064 request->in_proxy_hash = false;
2067 * On the FIRST reply, decrement the count of outstanding
2068 * requests. Note that this is NOT the count of sent
2069 * packets, but whether or not the home server has
2072 if (request->home_server &&
2073 request->home_server->currently_outstanding) {
2074 request->home_server->currently_outstanding--;
2077 * If we're NOT sending it packets, AND it's been
2078 * a while since we got a response, then we don't
2079 * know if it's alive or dead.
2081 if ((request->home_server->currently_outstanding == 0) &&
2082 (request->home_server->state == HOME_STATE_ALIVE)) {
2083 struct timeval when, now;
2085 when.tv_sec = request->home_server->last_packet_recv ;
2088 timeradd(&when, request_response_window(request), &when);
2089 gettimeofday(&now, NULL);
2092 * last_packet + response_window
2094 * We *administratively* mark the home
2095 * server as "unknown" state, because we
2096 * haven't seen a packet for a while.
2098 if (timercmp(&now, &when, >)) {
2099 request->home_server->state = HOME_STATE_UNKNOWN;
2100 request->home_server->last_packet_sent = 0;
2101 request->home_server->last_packet_recv = 0;
2107 rad_assert(request->proxy_listener != NULL);
2108 request->proxy_listener->count--;
2110 request->proxy_listener = NULL;
2113 * Got from YES in hash, to NO, not in hash while we hold
2114 * the mutex. This guarantees that when another thread
2115 * grabs the mutex, the "not in hash" flag is correct.
2117 RDEBUG3("proxy: request is no longer in proxy hash");
2120 static void remove_from_proxy_hash(REQUEST *request)
2122 VERIFY_REQUEST(request);
2125 * Check this without grabbing the mutex because it's a
2126 * lot faster that way.
2128 if (!request->in_proxy_hash) return;
2131 * The "not in hash" flag is definitive. However, if the
2132 * flag says that it IS in the hash, there might still be
2133 * a race condition where it isn't.
2135 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2137 if (!request->in_proxy_hash) {
2138 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2142 remove_from_proxy_hash_nl(request, true);
2144 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2147 static int insert_into_proxy_hash(REQUEST *request)
2151 bool success = false;
2152 void *proxy_listener;
2154 VERIFY_REQUEST(request);
2156 rad_assert(request->proxy != NULL);
2157 rad_assert(request->home_server != NULL);
2158 rad_assert(proxy_list != NULL);
2161 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2162 proxy_listener = NULL;
2163 request->num_proxied_requests = 1;
2164 request->num_proxied_responses = 0;
2166 for (tries = 0; tries < 2; tries++) {
2168 listen_socket_t *sock;
2170 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2171 success = fr_packet_list_id_alloc(proxy_list,
2172 request->home_server->proto,
2173 &request->proxy, &proxy_listener);
2176 if (tries > 0) continue; /* try opening new socket only once */
2178 #ifdef HAVE_PTHREAD_H
2179 if (proxy_no_new_sockets) break;
2182 RDEBUG3("proxy: Trying to open a new listener to the home server");
2183 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2185 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2189 request->proxy->src_port = 0; /* Use any new socket */
2190 proxy_listener = this;
2193 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2195 &sock->other_ipaddr, sock->other_port,
2198 #ifdef HAVE_PTHREAD_H
2199 proxy_no_new_sockets = true;
2201 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2204 * This is bad. However, the
2205 * packet list now supports 256
2206 * open sockets, which should
2207 * minimize this problem.
2209 ERROR("Failed adding proxy socket: %s",
2215 * Add it to the event loop. Ensure that we have
2216 * only one mutex locked at a time.
2218 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2219 radius_update_listener(this);
2220 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2223 if (!proxy_listener || !success) {
2224 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2225 REDEBUG2("proxy: Failed allocating Id for proxied request");
2227 request->proxy_listener = NULL;
2228 request->in_proxy_hash = false;
2232 rad_assert(request->proxy->id >= 0);
2234 request->proxy_listener = proxy_listener;
2235 request->in_proxy_hash = true;
2236 RDEBUG3("proxy: request is now in proxy hash");
2239 * Keep track of maximum outstanding requests to a
2240 * particular home server. 'max_outstanding' is
2241 * enforced in home_server_ldb(), in realms.c.
2243 request->home_server->currently_outstanding++;
2246 request->proxy_listener->count++;
2249 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2251 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2252 inet_ntop(request->proxy->dst_ipaddr.af,
2253 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2254 request->proxy->dst_port,
2255 request->proxy->id);
2260 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2263 int post_proxy_type = 0;
2266 VERIFY_REQUEST(request);
2269 * There may be a proxy reply, but it may be too late.
2271 if (!request->home_server->server && !request->proxy_listener) return 0;
2274 * Delete any reply we had accumulated until now.
2276 RDEBUG2("Clearing existing &reply: attributes");
2277 pairfree(&request->reply->vps);
2280 * Run the packet through the post-proxy stage,
2281 * BEFORE playing games with the attributes.
2283 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2285 post_proxy_type = vp->vp_integer;
2287 * If we have a proxy_reply, and it was a reject, or a NAK
2288 * setup Post-Proxy <type>.
2290 * If the <type> doesn't have a section, then the Post-Proxy
2291 * section is ignored.
2294 DICT_VALUE *dval = NULL;
2296 switch (reply->code) {
2297 case PW_CODE_ACCESS_REJECT:
2298 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2299 if (dval) post_proxy_type = dval->value;
2302 case PW_CODE_DISCONNECT_NAK:
2303 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2304 if (dval) post_proxy_type = dval->value;
2307 case PW_CODE_COA_NAK:
2308 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2309 if (dval) post_proxy_type = dval->value;
2317 * Create config:Post-Proxy-Type
2320 vp = radius_paircreate(request, &request->config_items, PW_POST_PROXY_TYPE, 0);
2321 vp->vp_integer = dval->value;
2325 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2326 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2329 VERIFY_PACKET(reply);
2332 * Decode the packet if required.
2334 if (request->proxy_listener) {
2335 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2336 debug_packet(request, reply, true);
2339 * Pro-actively remove it from the proxy hash.
2340 * This is later than in 2.1.x, but it means that
2341 * the replies are authenticated before being
2342 * removed from the hash.
2345 (request->num_proxied_requests <= request->num_proxied_responses)) {
2346 remove_from_proxy_hash(request);
2349 rad_assert(!request->in_proxy_hash);
2351 } else if (request->in_proxy_hash) {
2352 remove_from_proxy_hash(request);
2355 if (request->home_pool && request->home_pool->virtual_server) {
2356 char const *old_server = request->server;
2358 request->server = request->home_pool->virtual_server;
2359 RDEBUG2("server %s {", request->server);
2361 rcode = process_post_proxy(post_proxy_type, request);
2364 request->server = old_server;
2366 rcode = process_post_proxy(post_proxy_type, request);
2370 if (request->packet->code == request->proxy->code)
2372 * Don't run the next bit if we originated a CoA
2373 * packet, after receiving an Access-Request or
2374 * Accounting-Request.
2379 * There may NOT be a proxy reply, as we may be
2380 * running Post-Proxy-Type = Fail.
2383 pairadd(&request->reply->vps, paircopy(request->reply, reply->vps));
2386 * Delete the Proxy-State Attributes from
2387 * the reply. These include Proxy-State
2388 * attributes from us and remote server.
2390 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2394 default: /* Don't do anything */
2396 case RLM_MODULE_FAIL:
2399 case RLM_MODULE_HANDLED:
2406 int request_proxy_reply(RADIUS_PACKET *packet)
2408 RADIUS_PACKET **proxy_p;
2413 VERIFY_PACKET(packet);
2415 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2416 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2419 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2420 PROXY("No outstanding request was found for reply from host %s port %d - ID %u",
2421 inet_ntop(packet->src_ipaddr.af,
2422 &packet->src_ipaddr.ipaddr,
2423 buffer, sizeof(buffer)),
2424 packet->src_port, packet->id);
2428 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2429 request->num_proxied_responses++; /* needs to be protected by lock */
2431 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2434 * No reply, BUT the current packet fails verification:
2435 * ignore it. This does the MD5 calculations in the
2436 * server core, but I guess we can fix that later.
2438 if (!request->proxy_reply &&
2439 (rad_verify(packet, request->proxy,
2440 request->home_server->secret) != 0)) {
2441 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2446 * The home server sent us a packet which doesn't match
2447 * something we have: ignore it. This is done only to
2448 * catch the case of broken systems.
2450 if (request->proxy_reply &&
2451 (memcmp(request->proxy_reply->vector,
2453 sizeof(request->proxy_reply->vector)) != 0)) {
2454 RDEBUG2("Ignoring conflicting proxy reply");
2458 gettimeofday(&now, NULL);
2461 * Status-Server packets don't count as real packets.
2463 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2464 listen_socket_t *sock = request->proxy_listener->data;
2466 request->home_server->last_packet_recv = now.tv_sec;
2467 sock->last_packet = now.tv_sec;
2471 * If we have previously seen a reply, ignore the
2474 if (request->proxy_reply) {
2475 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2476 inet_ntop(packet->src_ipaddr.af,
2477 &packet->src_ipaddr.ipaddr,
2478 buffer, sizeof(buffer)),
2479 packet->src_port, packet->id);
2484 * Call the state machine to do something useful with the
2487 request->proxy_reply = talloc_steal(request, packet);
2488 packet->timestamp = now;
2489 request->priority = RAD_LISTEN_PROXY;
2493 * Update the proxy listener stats here, because only one
2494 * thread accesses that at a time. The home_server and
2495 * main proxy_*_stats structures are updated once the
2496 * request is cleaned up.
2498 request->proxy_listener->stats.total_responses++;
2500 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2501 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2503 switch (request->proxy->code) {
2504 case PW_CODE_ACCESS_REQUEST:
2505 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2507 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2508 request->proxy_listener->stats.total_access_accepts++;
2510 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2511 request->proxy_listener->stats.total_access_rejects++;
2513 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2514 request->proxy_listener->stats.total_access_challenges++;
2518 #ifdef WITH_ACCOUNTING
2519 case PW_CODE_ACCOUNTING_REQUEST:
2520 request->proxy_listener->stats.total_responses++;
2521 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2527 case PW_CODE_COA_REQUEST:
2528 request->proxy_listener->stats.total_responses++;
2529 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2532 case PW_CODE_DISCONNECT_REQUEST:
2533 request->proxy_listener->stats.total_responses++;
2534 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2544 * We've received a reply. If we hadn't been sending it
2545 * packets for a while, just mark it alive.
2547 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2548 request->home_server->state = HOME_STATE_ALIVE;
2549 request->home_server->response_timeouts = 0;
2553 * Tell the request state machine that we have a proxy
2554 * reply. Depending on the function, this should either
2555 * ignore it, or process it.
2557 request->process(request, FR_ACTION_PROXY_REPLY);
2563 static int setup_post_proxy_fail(REQUEST *request)
2565 DICT_VALUE const *dval = NULL;
2568 VERIFY_REQUEST(request);
2570 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2571 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2572 "Fail-Authentication");
2574 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2575 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2578 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2579 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2581 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2582 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2585 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2589 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2592 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2596 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2597 if (!vp) vp = radius_paircreate(request, &request->config_items,
2598 PW_POST_PROXY_TYPE, 0);
2599 vp->vp_integer = dval->value;
2604 STATE_MACHINE_DECL(proxy_no_reply)
2606 VERIFY_REQUEST(request);
2608 TRACE_STATE_MACHINE;
2612 case FR_ACTION_TIMER:
2613 case FR_ACTION_PROXY_REPLY:
2614 request_common(request, action);
2618 if (process_proxy_reply(request, NULL)) {
2619 request_finish(request, action);
2621 request_done(request, FR_ACTION_DONE);
2626 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2631 STATE_MACHINE_DECL(proxy_running)
2633 VERIFY_REQUEST(request);
2635 TRACE_STATE_MACHINE;
2639 * Silently ignore duplicate proxy replies.
2641 case FR_ACTION_PROXY_REPLY:
2645 case FR_ACTION_TIMER:
2646 request_common(request, action);
2650 if (process_proxy_reply(request, request->proxy_reply)) {
2651 request->handle(request);
2652 request_finish(request, action);
2654 request_done(request, FR_ACTION_DONE);
2659 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2664 static int request_will_proxy(REQUEST *request)
2666 int rcode, pre_proxy_type = 0;
2667 char const *realmname = NULL;
2668 VALUE_PAIR *vp, *strippedname;
2669 home_server_t *home;
2670 REALM *realm = NULL;
2671 home_pool_t *pool = NULL;
2673 VERIFY_REQUEST(request);
2675 if (!request->root->proxy_requests) return 0;
2676 if (request->packet->dst_port == 0) return 0;
2677 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2678 if (request->in_proxy_hash) return 0;
2681 * FIXME: for 3.0, allow this only for rejects?
2683 if (request->reply->code != 0) return 0;
2685 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2687 realm = realm_find2(vp->vp_strvalue);
2689 REDEBUG2("Cannot proxy to unknown realm %s",
2694 realmname = vp->vp_strvalue;
2697 * Figure out which pool to use.
2699 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2700 pool = realm->auth_pool;
2702 #ifdef WITH_ACCOUNTING
2703 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2704 pool = realm->acct_pool;
2708 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2709 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2710 pool = realm->coa_pool;
2717 } else if ((vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2720 switch (request->packet->code) {
2721 case PW_CODE_ACCESS_REQUEST:
2722 pool_type = HOME_TYPE_AUTH;
2725 #ifdef WITH_ACCOUNTING
2726 case PW_CODE_ACCOUNTING_REQUEST:
2727 pool_type = HOME_TYPE_ACCT;
2732 case PW_CODE_COA_REQUEST:
2733 case PW_CODE_DISCONNECT_REQUEST:
2734 pool_type = HOME_TYPE_COA;
2742 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2745 * Send it directly to a home server (i.e. NAS)
2747 } else if (((vp = pairfind(request->config_items, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2748 ((vp = pairfind(request->config_items, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2751 fr_ipaddr_t dst_ipaddr;
2753 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2755 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2756 dst_ipaddr.af = AF_INET;
2757 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2758 dst_ipaddr.prefix = 32;
2760 dst_ipaddr.af = AF_INET6;
2761 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2762 dst_ipaddr.prefix = 128;
2765 port = pairfind(request->config_items, PW_PACKET_DST_PORT, 0, TAG_ANY);
2767 dst_port = PW_COA_UDP_PORT;
2769 dst_port = vp->vp_integer;
2773 * Nothing does CoA over TCP.
2775 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2779 WARN("No such CoA home server %s port %u",
2780 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2781 (unsigned int) dst_port);
2792 RWDEBUG2("Cancelling proxy as no home pool exists");
2796 if (request->listener->synchronous) {
2797 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2801 request->home_pool = pool;
2803 home = home_server_ldb(realmname, pool, request);
2806 REDEBUG2("Failed to find live home server: Cancelling proxy");
2811 home_server_update_request(home, request);
2815 * Once we've decided to proxy a request, we cannot send
2816 * a CoA packet. So we free up any CoA packet here.
2818 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2822 * Remember that we sent the request to a Realm.
2824 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2827 * Strip the name, if told to.
2829 * Doing it here catches the case of proxied tunneled
2832 if (realm && (realm->strip_realm == true) &&
2833 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2835 * If there's a Stripped-User-Name attribute in
2836 * the request, then use THAT as the User-Name
2837 * for the proxied request, instead of the
2840 * This is done by making a copy of the
2841 * Stripped-User-Name attribute, turning it into
2842 * a User-Name attribute, deleting the
2843 * Stripped-User-Name and User-Name attributes
2844 * from the vps list, and making the new
2845 * User-Name the head of the vps list.
2847 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2850 vp = radius_paircreate(NULL, NULL,
2852 rad_assert(vp != NULL); /* handled by above function */
2853 /* Insert at the START of the list */
2854 /* FIXME: Can't make assumptions about ordering */
2855 fr_cursor_init(&cursor, &vp);
2856 fr_cursor_merge(&cursor, request->proxy->vps);
2857 request->proxy->vps = vp;
2859 pairstrcpy(vp, strippedname->vp_strvalue);
2862 * Do NOT delete Stripped-User-Name.
2867 * If there is no PW_CHAP_CHALLENGE attribute but
2868 * there is a PW_CHAP_PASSWORD we need to add it
2869 * since we can't use the request authenticator
2870 * anymore - we changed it.
2872 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2873 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2874 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2875 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2876 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2880 * The RFC's say we have to do this, but FreeRADIUS
2883 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2884 pairsprintf(vp, "%u", request->packet->id);
2887 * Should be done BEFORE inserting into proxy hash, as
2888 * pre-proxy may use this information, or change it.
2890 request->proxy->code = request->packet->code;
2893 * Call the pre-proxy routines.
2895 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2897 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2898 /* Must be a validation issue */
2900 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2901 pre_proxy_type = vp->vp_integer;
2905 * home_pool may be NULL when originating CoA packets,
2906 * because they go directly to an IP address.
2908 if (request->home_pool && request->home_pool->virtual_server) {
2909 char const *old_server = request->server;
2911 request->server = request->home_pool->virtual_server;
2913 RDEBUG2("server %s {", request->server);
2915 rcode = process_pre_proxy(pre_proxy_type, request);
2919 request->server = old_server;
2921 rcode = process_pre_proxy(pre_proxy_type, request);
2924 case RLM_MODULE_FAIL:
2925 case RLM_MODULE_INVALID:
2926 case RLM_MODULE_NOTFOUND:
2927 case RLM_MODULE_USERLOCK:
2929 /* FIXME: debug print failed stuff */
2932 case RLM_MODULE_REJECT:
2933 case RLM_MODULE_HANDLED:
2937 * Only proxy the packet if the pre-proxy code succeeded.
2939 case RLM_MODULE_NOOP:
2941 case RLM_MODULE_UPDATED:
2948 static int request_proxy(REQUEST *request, int retransmit)
2952 VERIFY_REQUEST(request);
2954 rad_assert(request->parent == NULL);
2955 rad_assert(request->home_server != NULL);
2957 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2961 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2962 request_done(request->coa, FR_ACTION_DONE);
2967 * The request may need sending to a virtual server.
2968 * This code is more than a little screwed up. The rest
2969 * of the state machine doesn't handle parent / child
2970 * relationships well. i.e. if the child request takes
2971 * too long, the core will mark the *parent* as "stop
2972 * processing". And the child will continue without
2973 * knowing anything...
2975 * So, we have some horrible hacks to get around that.
2977 if (request->home_server->server) {
2980 if (request->packet->dst_port == 0) {
2981 WARN("Cannot proxy an internal request");
2985 DEBUG("Proxying to virtual server %s",
2986 request->home_server->server);
2989 * Packets to virtual serrers don't get
2990 * retransmissions sent to them. And the virtual
2991 * server is run ONLY if we have no child
2992 * threads, or we're running in a child thread.
2994 rad_assert(retransmit == 0);
2995 rad_assert(!spawn_flag || !we_are_master());
2997 fake = request_alloc_fake(request);
2999 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
3000 talloc_free(request->proxy);
3002 fake->server = request->home_server->server;
3003 fake->handle = request->handle;
3004 fake->process = NULL; /* should never be run for anything */
3007 * Run the virtual server.
3009 request_running(fake, FR_ACTION_RUN);
3011 request->proxy = talloc_steal(request, fake->packet);
3012 fake->packet = NULL;
3013 request->proxy_reply = talloc_steal(request, fake->reply);
3019 * No reply code, toss the reply we have,
3020 * and do post-proxy-type Fail.
3022 if (!request->proxy_reply->code) {
3023 TALLOC_FREE(request->proxy_reply);
3024 setup_post_proxy_fail(request);
3028 * Just do the work here, rather than trying to
3029 * run the "decode proxy reply" stuff...
3031 process_proxy_reply(request, request->proxy_reply);
3034 * If we have a reply, run it through the handler.
3036 if (request->proxy_reply) {
3037 request->handle(request); /* to do more post-proxy stuff */
3040 return -1; /* so we call request_finish */
3044 * We're actually sending a proxied packet. Do that now.
3046 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3047 ERROR("Failed to insert request into the proxy list");
3051 rad_assert(request->proxy->id >= 0);
3054 struct timeval *response_window;
3056 response_window = request_response_window(request);
3059 if (request->home_server->tls) {
3060 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3061 inet_ntop(request->proxy->dst_ipaddr.af,
3062 &request->proxy->dst_ipaddr.ipaddr,
3063 buffer, sizeof(buffer)),
3064 request->proxy->dst_port,
3065 (int) response_window->tv_sec, (int) response_window->tv_usec);
3068 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3069 inet_ntop(request->proxy->dst_ipaddr.af,
3070 &request->proxy->dst_ipaddr.ipaddr,
3071 buffer, sizeof(buffer)),
3072 request->proxy->dst_port,
3073 (int) response_window->tv_sec, (int) response_window->tv_usec);
3078 gettimeofday(&request->proxy_retransmit, NULL);
3080 request->proxy->timestamp = request->proxy_retransmit;
3082 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3085 * Encode the packet before we do anything else.
3087 request->proxy_listener->encode(request->proxy_listener, request);
3088 debug_packet(request, request->proxy, false);
3091 * Set the state function, then the state, no child, and
3094 request->process = proxy_wait_for_reply;
3095 request->child_state = REQUEST_PROXIED;
3099 * And send the packet.
3101 request->proxy_listener->send(request->proxy_listener, request);
3106 * Proxy the packet as if it was new.
3108 static int request_proxy_anew(REQUEST *request)
3110 home_server_t *home;
3112 VERIFY_REQUEST(request);
3115 * Delete the request from the proxy list.
3117 * The packet list code takes care of ensuring that IDs
3118 * aren't reused until all 256 IDs have been used. So
3119 * there's a 1/256 chance of re-using the same ID when
3120 * we're sending to the same home server. Which is
3123 remove_from_proxy_hash(request);
3126 * Find a live home server for the request.
3128 home = home_server_ldb(NULL, request->home_pool, request);
3130 REDEBUG2("Failed to find live home server for request");
3132 if (setup_post_proxy_fail(request)) {
3133 request_queue_or_run(request, proxy_running);
3135 gettimeofday(&request->reply->timestamp, NULL);
3136 request_cleanup_delay_init(request);
3140 home_server_update_request(home, request);
3142 if (!insert_into_proxy_hash(request)) {
3143 RPROXY("Failed to insert retransmission into the proxy list");
3144 goto post_proxy_fail;
3148 * Free the old packet, to force re-encoding
3150 talloc_free(request->proxy->data);
3151 request->proxy->data = NULL;
3152 request->proxy->data_len = 0;
3154 #ifdef WITH_ACCOUNTING
3156 * Update the Acct-Delay-Time attribute.
3158 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3161 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3162 if (!vp) vp = radius_paircreate(request->proxy,
3163 &request->proxy->vps,
3164 PW_ACCT_DELAY_TIME, 0);
3168 gettimeofday(&now, NULL);
3169 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3174 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3179 STATE_MACHINE_DECL(request_ping)
3181 home_server_t *home = request->home_server;
3184 VERIFY_REQUEST(request);
3186 TRACE_STATE_MACHINE;
3190 case FR_ACTION_TIMER:
3191 ERROR("No response to status check %d for home server %s port %d",
3193 inet_ntop(request->proxy->dst_ipaddr.af,
3194 &request->proxy->dst_ipaddr.ipaddr,
3195 buffer, sizeof(buffer)),
3196 request->proxy->dst_port);
3199 case FR_ACTION_PROXY_REPLY:
3200 rad_assert(request->in_proxy_hash);
3202 request->home_server->num_received_pings++;
3203 RPROXY("Received response to status check %d (%d in current sequence)",
3204 request->number, home->num_received_pings);
3207 * Remove the request from any hashes
3209 fr_event_delete(el, &request->ev);
3210 remove_from_proxy_hash(request);
3213 * The control socket may have marked the home server as
3214 * alive. OR, it may have suddenly started responding to
3215 * requests again. If so, don't re-do the "make alive"
3218 if (home->state == HOME_STATE_ALIVE) break;
3221 * It's dead, and we haven't received enough ping
3222 * responses to mark it "alive". Wait a bit.
3224 * If it's zombie, we mark it alive immediately.
3226 if ((home->state == HOME_STATE_IS_DEAD) &&
3227 (home->num_received_pings < home->num_pings_to_alive)) {
3232 * Mark it alive and delete any outstanding
3235 home->state = HOME_STATE_ALIVE;
3236 home->response_timeouts = 0;
3237 exec_trigger(request, home->cs, "home_server.alive", false);
3238 home->currently_outstanding = 0;
3239 home->num_sent_pings = 0;
3240 home->num_received_pings = 0;
3241 gettimeofday(&home->revive_time, NULL);
3243 fr_event_delete(el, &home->ev);
3245 RPROXY("Marking home server %s port %d alive",
3246 inet_ntop(request->proxy->dst_ipaddr.af,
3247 &request->proxy->dst_ipaddr.ipaddr,
3248 buffer, sizeof(buffer)),
3249 request->proxy->dst_port);
3253 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3257 rad_assert(!request->in_request_hash);
3258 rad_assert(request->ev == NULL);
3260 request_done(request, FR_ACTION_DONE);
3264 * Called from start of zombie period, OR after control socket
3265 * marks the home server dead.
3267 static void ping_home_server(void *ctx)
3269 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3272 struct timeval when, now;
3274 if ((home->state == HOME_STATE_ALIVE) ||
3276 (home->proto == IPPROTO_TCP) ||
3278 (home->ev != NULL)) {
3282 gettimeofday(&now, NULL);
3286 * We've run out of zombie time. Mark it dead.
3288 if (home->state == HOME_STATE_ZOMBIE) {
3289 when = home->zombie_period_start;
3290 when.tv_sec += home->zombie_period;
3292 if (timercmp(&when, &now, <)) {
3293 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3294 mark_home_server_dead(home, &now);
3299 * We're not supposed to be pinging it. Just wake up
3300 * when we're supposed to mark it dead.
3302 if (home->ping_check == HOME_PING_CHECK_NONE) {
3303 if (home->state == HOME_STATE_ZOMBIE) {
3304 when = home->zombie_period_start;
3305 when.tv_sec += home->zombie_period;
3306 INSERT_EVENT(ping_home_server, home);
3310 * Else mark_home_server_dead will set a timer
3311 * for revive_interval.
3317 request = request_alloc(NULL);
3318 if (!request) return;
3319 request->number = request_num_counter++;
3322 request->proxy = rad_alloc(request, true);
3323 rad_assert(request->proxy != NULL);
3325 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3326 request->proxy->code = PW_CODE_STATUS_SERVER;
3328 pairmake(request->proxy, &request->proxy->vps,
3329 "Message-Authenticator", "0x00", T_OP_SET);
3331 } else if (home->type == HOME_TYPE_AUTH) {
3332 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3334 pairmake(request->proxy, &request->proxy->vps,
3335 "User-Name", home->ping_user_name, T_OP_SET);
3336 pairmake(request->proxy, &request->proxy->vps,
3337 "User-Password", home->ping_user_password, T_OP_SET);
3338 pairmake(request->proxy, &request->proxy->vps,
3339 "Service-Type", "Authenticate-Only", T_OP_SET);
3340 pairmake(request->proxy, &request->proxy->vps,
3341 "Message-Authenticator", "0x00", T_OP_SET);
3344 #ifdef WITH_ACCOUNTING
3345 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3347 pairmake(request->proxy, &request->proxy->vps,
3348 "User-Name", home->ping_user_name, T_OP_SET);
3349 pairmake(request->proxy, &request->proxy->vps,
3350 "Acct-Status-Type", "Stop", T_OP_SET);
3351 pairmake(request->proxy, &request->proxy->vps,
3352 "Acct-Session-Id", "00000000", T_OP_SET);
3353 vp = pairmake(request->proxy, &request->proxy->vps,
3354 "Event-Timestamp", "0", T_OP_SET);
3355 vp->vp_date = now.tv_sec;
3357 rad_assert("Internal sanity check failed");
3361 vp = pairmake(request->proxy, &request->proxy->vps,
3362 "NAS-Identifier", "", T_OP_SET);
3364 pairsprintf(vp, "Status Check %u. Are you alive?",
3365 home->num_sent_pings);
3368 request->proxy->src_ipaddr = home->src_ipaddr;
3369 request->proxy->dst_ipaddr = home->ipaddr;
3370 request->proxy->dst_port = home->port;
3371 request->home_server = home;
3372 #ifdef DEBUG_STATE_MACHINE
3373 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3374 child_state_names[request->child_state],
3375 child_state_names[REQUEST_DONE]);
3376 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3378 #ifdef HAVE_PTHREAD_H
3379 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3381 request->child_state = REQUEST_PROXIED;
3382 request->process = request_ping;
3384 rad_assert(request->proxy_listener == NULL);
3386 if (!insert_into_proxy_hash(request)) {
3387 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3390 rad_assert(!request->in_request_hash);
3391 rad_assert(!request->in_proxy_hash);
3392 rad_assert(request->ev == NULL);
3393 talloc_free(request);
3398 * Set up the timer callback.
3401 when.tv_sec += home->ping_timeout;
3403 DEBUG("PING: Waiting %u seconds for response to ping",
3404 home->ping_timeout);
3406 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3407 home->num_sent_pings++;
3409 rad_assert(request->proxy_listener != NULL);
3410 request->proxy_listener->send(request->proxy_listener,
3414 * Add +/- 2s of jitter, as suggested in RFC 3539
3415 * and in the Issues and Fixes draft.
3418 home->when.tv_sec += home->ping_interval;
3420 add_jitter(&home->when);
3422 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3423 INSERT_EVENT(ping_home_server, home);
3426 static void home_trigger(home_server_t *home, char const *trigger)
3428 REQUEST *my_request;
3429 RADIUS_PACKET *my_packet;
3431 my_request = talloc_zero(NULL, REQUEST);
3432 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3433 my_request->proxy = my_packet;
3434 my_packet->dst_ipaddr = home->ipaddr;
3435 my_packet->src_ipaddr = home->src_ipaddr;
3437 exec_trigger(my_request, home->cs, trigger, false);
3438 talloc_free(my_request);
3441 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3448 rad_assert((home->state == HOME_STATE_ALIVE) ||
3449 (home->state == HOME_STATE_UNKNOWN));
3452 if (home->proto == IPPROTO_TCP) {
3453 WARN("Not marking TCP server %s zombie", home->log_name);
3459 * We've received a real packet recently. Don't mark the
3460 * server as zombie until we've received NO packets for a
3461 * while. The "1/4" of zombie period was chosen rather
3462 * arbitrarily. It's a balance between too short, which
3463 * gives quick fail-over and fail-back, or too long,
3464 * where the proxy still sends packets to an unresponsive
3467 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3468 if (home->last_packet_recv >= start) {
3469 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3470 (int) (now->tv_sec - home->last_packet_recv));
3474 home->state = HOME_STATE_ZOMBIE;
3475 home_trigger(home, "home_server.zombie");
3478 * Set the home server to "zombie", as of the time
3481 home->zombie_period_start.tv_sec = start;
3482 home->zombie_period_start.tv_usec = USEC / 2;
3484 fr_event_delete(el, &home->ev);
3486 home->num_sent_pings = 0;
3487 home->num_received_pings = 0;
3489 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3490 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3491 buffer, sizeof(buffer)),
3492 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3494 ping_home_server(home);
3498 void revive_home_server(void *ctx)
3500 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3504 rad_assert(home->proto != IPPROTO_TCP);
3507 home->state = HOME_STATE_ALIVE;
3508 home->response_timeouts = 0;
3509 home_trigger(home, "home_server.alive");
3510 home->currently_outstanding = 0;
3511 gettimeofday(&home->revive_time, NULL);
3514 * Delete any outstanding events.
3517 if (home->ev) fr_event_delete(el, &home->ev);
3519 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3520 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3521 buffer, sizeof(buffer)),
3525 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3527 int previous_state = home->state;
3531 if (home->proto == IPPROTO_TCP) {
3532 WARN("Not marking TCP server dead");
3537 PROXY( "Marking home server %s port %d as dead.",
3538 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3539 buffer, sizeof(buffer)),
3542 home->state = HOME_STATE_IS_DEAD;
3543 home_trigger(home, "home_server.dead");
3545 if (home->ping_check != HOME_PING_CHECK_NONE) {
3547 * If the control socket marks us dead, start
3548 * pinging. Otherwise, we already started
3549 * pinging when it was marked "zombie".
3551 if (previous_state == HOME_STATE_ALIVE) {
3552 ping_home_server(home);
3554 DEBUG("PING: Already pinging home server %s", home->log_name);
3559 * Revive it after a fixed period of time. This
3560 * is very, very, bad.
3563 home->when.tv_sec += home->revive_interval;
3565 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3567 INSERT_EVENT(revive_home_server, home);
3571 STATE_MACHINE_DECL(proxy_wait_for_reply)
3573 struct timeval now, when;
3574 struct timeval *response_window = NULL;
3575 home_server_t *home = request->home_server;
3578 VERIFY_REQUEST(request);
3580 TRACE_STATE_MACHINE;
3582 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3583 rad_assert(request->home_server != NULL);
3585 if (request->master_state == REQUEST_STOP_PROCESSING) {
3586 request->child_state = REQUEST_DONE;
3590 gettimeofday(&now, NULL);
3595 * We have a reply, ignore the retransmit.
3597 if (request->proxy_reply) return;
3600 * The request was proxied to a virtual server.
3601 * Ignore the retransmit.
3603 if (request->home_server->server) return;
3605 if ((home->state == HOME_STATE_IS_DEAD) ||
3606 !request->proxy_listener ||
3607 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3608 request_proxy_anew(request);
3613 if (home->proto == IPPROTO_TCP) {
3614 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3615 inet_ntop(request->proxy->dst_ipaddr.af,
3616 &request->proxy->dst_ipaddr.ipaddr,
3617 buffer, sizeof(buffer)),
3618 request->proxy->dst_port,
3619 request->proxy->id);
3625 * More than one retransmit a second is stupid,
3626 * and should be suppressed by the proxy.
3628 when = request->proxy_retransmit;
3631 if (timercmp(&now, &when, <)) {
3632 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3633 inet_ntop(request->proxy->dst_ipaddr.af,
3634 &request->proxy->dst_ipaddr.ipaddr,
3635 buffer, sizeof(buffer)),
3636 request->proxy->dst_port,
3637 request->proxy->id);
3641 #ifdef WITH_ACCOUNTING
3643 * If we update the Acct-Delay-Time, we need to
3646 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3647 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3648 request_proxy_anew(request);
3653 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3654 inet_ntop(request->proxy->dst_ipaddr.af,
3655 &request->proxy->dst_ipaddr.ipaddr,
3656 buffer, sizeof(buffer)),
3657 request->proxy->dst_port,
3658 request->proxy->id);
3659 request->num_proxied_requests++;
3661 rad_assert(request->proxy_listener != NULL);
3662 FR_STATS_TYPE_INC(home->stats.total_requests);
3663 home->last_packet_sent = now.tv_sec;
3664 request->proxy_retransmit = now;
3665 request->proxy_listener->send(request->proxy_listener, request);
3666 debug_packet(request, request->proxy, false);
3669 case FR_ACTION_TIMER:
3670 response_window = request_response_window(request);
3673 if (!request->proxy_listener ||
3674 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3675 remove_from_proxy_hash(request);
3677 when = request->packet->timestamp;
3678 when.tv_sec += request->root->max_request_time;
3680 if (timercmp(&when, &now, >)) {
3681 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3682 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3689 * Wake up "response_window" time in the future.
3690 * i.e. when MY packet hasn't received a response.
3692 * Note that we DO NOT mark the home server as
3693 * zombie if it doesn't respond to us. It may be
3694 * responding to other (better looking) packets.
3696 when = request->proxy->timestamp;
3697 timeradd(&when, response_window, &when);
3700 * Not at the response window. Set the timer for
3703 if (timercmp(&when, &now, >)) {
3704 struct timeval diff;
3705 timersub(&when, &now, &diff);
3707 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3708 (int) diff.tv_sec, (int) diff.tv_usec);
3709 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3714 RDEBUG("No proxy response, giving up on request and marking it done");
3717 * If we haven't received any packets for
3718 * "response_window", then mark the home server
3721 * If the connection is TCP, then another
3722 * "watchdog timer" function takes care of pings,
3723 * etc. So we don't need to do it here.
3725 * This check should really be part of a home
3726 * server state machine.
3728 if (((home->state == HOME_STATE_ALIVE) ||
3729 (home->state == HOME_STATE_UNKNOWN))
3731 && (home->proto != IPPROTO_TCP)
3734 home->response_timeouts++;
3735 if (home->response_timeouts >= home->max_response_timeouts)
3736 mark_home_server_zombie(home, &now, response_window);
3739 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3740 if (home->type == HOME_TYPE_AUTH) {
3741 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3742 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3745 else if (home->type == HOME_TYPE_ACCT) {
3746 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3747 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3752 * There was no response within the window. Stop
3753 * the request. If the client retransmitted, it
3754 * may have failed over to another home server.
3755 * But that one may be dead, too.
3757 * The extra verbose message if we have a username,
3758 * is extremely useful if the proxy is part of a chain
3759 * and the final home server, is not the one we're
3762 if (request->username) {
3763 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3764 "server %s port %d",
3765 request->username->vp_strvalue,
3766 inet_ntop(request->proxy->dst_ipaddr.af,
3767 &request->proxy->dst_ipaddr.ipaddr,
3768 buffer, sizeof(buffer)),
3769 request->proxy->dst_port);
3771 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3772 inet_ntop(request->proxy->dst_ipaddr.af,
3773 &request->proxy->dst_ipaddr.ipaddr,
3774 buffer, sizeof(buffer)),
3775 request->proxy->dst_port);
3778 if (setup_post_proxy_fail(request)) {
3779 request_queue_or_run(request, proxy_no_reply);
3781 gettimeofday(&request->reply->timestamp, NULL);
3782 request_cleanup_delay_init(request);
3787 * We received a new reply. Go process it.
3789 case FR_ACTION_PROXY_REPLY:
3790 request_queue_or_run(request, proxy_running);
3794 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3798 #endif /* WITH_PROXY */
3800 /***********************************************************************
3804 ***********************************************************************/
3806 static int null_handler(UNUSED REQUEST *request)
3812 * See if we need to originate a CoA request.
3814 static void request_coa_originate(REQUEST *request)
3816 int rcode, pre_proxy_type = 0;
3822 VERIFY_REQUEST(request);
3824 rad_assert(request->coa != NULL);
3825 rad_assert(request->proxy == NULL);
3826 rad_assert(!request->in_proxy_hash);
3827 rad_assert(request->proxy_reply == NULL);
3830 * Check whether we want to originate one, or cancel one.
3832 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3834 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3838 if (vp->vp_integer == 0) {
3840 TALLOC_FREE(request->coa);
3848 * src_ipaddr will be set up in proxy_encode.
3850 memset(&ipaddr, 0, sizeof(ipaddr));
3851 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3853 ipaddr.af = AF_INET;
3854 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3856 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3857 ipaddr.af = AF_INET6;
3858 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3859 ipaddr.prefix = 128;
3860 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3861 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3863 if (!coa->home_pool) {
3864 RWDEBUG2("No such home_server_pool %s",
3870 * Prefer the pool to one server
3872 } else if (request->client->coa_pool) {
3873 coa->home_pool = request->client->coa_pool;
3875 } else if (request->client->coa_server) {
3876 coa->home_server = request->client->coa_server;
3880 * If all else fails, send it to the client that
3881 * originated this request.
3883 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3887 * Use the pool, if it exists.
3889 if (coa->home_pool) {
3890 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3891 if (!coa->home_server) {
3892 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3895 home_server_update_request(coa->home_server, coa);
3897 } else if (!coa->home_server) {
3898 uint16_t port = PW_COA_UDP_PORT;
3900 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3901 if (vp) port = vp->vp_integer;
3903 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3904 if (!coa->home_server) {
3905 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3906 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3907 buffer, sizeof(buffer)), port);
3912 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3914 switch (vp->vp_integer) {
3915 case PW_CODE_COA_REQUEST:
3916 case PW_CODE_DISCONNECT_REQUEST:
3917 coa->proxy->code = vp->vp_integer;
3921 DEBUG("Cannot set CoA Packet-Type to code %d",
3927 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3930 * The rest of the server code assumes that
3931 * request->packet && request->reply exist. Copy them
3932 * from the original request.
3934 rad_assert(coa->packet != NULL);
3935 rad_assert(coa->packet->vps == NULL);
3937 coa->packet = rad_copy_packet(coa, request->packet);
3938 coa->reply = rad_copy_packet(coa, request->reply);
3940 coa->config_items = paircopy(coa, request->config_items);
3941 coa->num_coa_requests = 0;
3942 coa->handle = null_handler;
3943 coa->number = request->number; /* it's associated with the same request */
3946 * Call the pre-proxy routines.
3948 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3950 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3951 /* Must be a validation issue */
3953 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3954 pre_proxy_type = vp->vp_integer;
3957 if (coa->home_pool && coa->home_pool->virtual_server) {
3958 char const *old_server = coa->server;
3960 coa->server = coa->home_pool->virtual_server;
3961 RDEBUG2("server %s {", coa->server);
3963 rcode = process_pre_proxy(pre_proxy_type, coa);
3966 coa->server = old_server;
3968 rcode = process_pre_proxy(pre_proxy_type, coa);
3975 * Only send the CoA packet if the pre-proxy code succeeded.
3977 case RLM_MODULE_NOOP:
3979 case RLM_MODULE_UPDATED:
3984 * Source IP / port is set when the proxy socket
3987 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3988 coa->proxy->dst_port = coa->home_server->port;
3990 if (!insert_into_proxy_hash(coa)) {
3991 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
3996 * We CANNOT divorce the CoA request from the parent
3997 * request. This function is running in a child thread,
3998 * and we need access to the main event loop in order to
3999 * to add the timers for the CoA packet.
4001 * Instead, we wait for the timer on the parent request
4004 gettimeofday(&coa->proxy->timestamp, NULL);
4005 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4006 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4007 coa->delay = 0; /* need to calculate a new delay */
4010 * If requested, put a State attribute into the packet,
4011 * and cache the VPS.
4013 fr_state_put_vps(coa, NULL, coa->packet);
4016 * Encode the packet before we do anything else.
4018 coa->proxy_listener->encode(coa->proxy_listener, coa);
4019 debug_packet(coa, coa->proxy, false);
4021 #ifdef DEBUG_STATE_MACHINE
4022 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4023 child_state_names[request->child_state],
4024 child_state_names[REQUEST_PROXIED]);
4028 * Set the state function, then the state, no child, and
4031 coa->process = coa_wait_for_reply;
4032 coa->child_state = REQUEST_PROXIED;
4034 #ifdef HAVE_PTHREAD_H
4035 coa->child_pid = NO_SUCH_CHILD_PID;
4039 * And send the packet.
4041 coa->proxy_listener->send(coa->proxy_listener, coa);
4045 static void coa_timer(REQUEST *request)
4047 uint32_t delay, frac;
4048 struct timeval now, when, mrd;
4050 VERIFY_REQUEST(request);
4052 rad_assert(request->parent == NULL);
4054 if (request->proxy_reply) {
4055 request_process_timer(request);
4058 gettimeofday(&now, NULL);
4060 if (request->delay == 0) {
4062 * Implement re-transmit algorithm as per RFC 5080
4065 * We want IRT + RAND*IRT
4066 * or 0.9 IRT + rand(0,.2) IRT
4068 * 2^20 ~ USEC, and we want 2.
4069 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4071 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4072 request->delay = delay * request->home_server->coa_irt;
4073 delay = request->home_server->coa_irt * USEC;
4074 delay -= delay / 10;
4075 delay += request->delay;
4076 request->delay = delay;
4078 when = request->proxy->timestamp;
4079 tv_add(&when, delay);
4081 if (timercmp(&when, &now, >)) {
4082 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4088 * Retransmit CoA request.
4092 * Cap count at MRC, if it is non-zero.
4094 if (request->home_server->coa_mrc &&
4095 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4098 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4100 inet_ntop(request->proxy->dst_ipaddr.af,
4101 &request->proxy->dst_ipaddr.ipaddr,
4102 buffer, sizeof(buffer)),
4103 request->proxy->dst_port);
4105 if (setup_post_proxy_fail(request)) {
4106 request_queue_or_run(request, coa_no_reply);
4108 request_done(request, FR_ACTION_DONE);
4114 * RFC 5080 Section 2.2.1
4116 * RT = 2*RTprev + RAND*RTprev
4117 * = 1.9 * RTprev + rand(0,.2) * RTprev
4118 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4121 delay ^= (delay >> 16);
4123 frac = request->delay / 5;
4124 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4126 delay += (2 * request->delay) - (request->delay / 10);
4129 * Cap delay at MRT, if MRT is non-zero.
4131 if (request->home_server->coa_mrt &&
4132 (delay > (request->home_server->coa_mrt * USEC))) {
4133 int mrt_usec = request->home_server->coa_mrt * USEC;
4136 * delay = MRT + RAND * MRT
4137 * = 0.9 MRT + rand(0,.2) * MRT
4140 delay ^= (delay >> 15);
4142 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4143 delay += mrt_usec - (mrt_usec / 10);
4146 request->delay = delay;
4148 tv_add(&when, request->delay);
4149 mrd = request->proxy->timestamp;
4150 mrd.tv_sec += request->home_server->coa_mrd;
4153 * Cap duration at MRD.
4155 if (timercmp(&mrd, &when, <)) {
4158 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4160 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4162 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4165 * Status servers don't count as real packets sent.
4167 request->proxy_listener->send(request->proxy_listener,
4171 STATE_MACHINE_DECL(coa_wait_for_reply)
4173 VERIFY_REQUEST(request);
4175 TRACE_STATE_MACHINE;
4178 case FR_ACTION_TIMER:
4180 * This is big enough to be in it's own function.
4185 case FR_ACTION_PROXY_REPLY:
4186 rad_assert(request->parent != NULL);
4187 rad_assert(request->parent->coa == request);
4188 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
4189 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
4190 rad_assert(request->process != NULL);
4192 coa_separate(request, FR_ACTION_PROXY_REPLY);
4194 rad_assert(request->parent == NULL);
4197 * Do NOT get the session-state VPs. The request
4198 * already contains the packet and the reply, so
4199 * there's no more state we need to maintain.
4201 * The state for "originate CoA" is for the next
4202 * Access-Request, not for the CoA ACK/BAK
4205 request_queue_or_run(request, coa_running);
4209 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4214 STATE_MACHINE_DECL(coa_separate)
4216 VERIFY_REQUEST(request);
4218 TRACE_STATE_MACHINE;
4220 rad_assert(request->parent != NULL);
4221 rad_assert(request->parent->coa == request);
4222 rad_assert(request->ev == NULL);
4223 rad_assert(!request->in_request_hash);
4224 rad_assert(request->coa == NULL);
4226 rad_assert(request->proxy_reply || request->proxy_listener);
4228 (void) talloc_steal(NULL, request);
4229 request->parent->coa = NULL;
4230 request->parent = NULL;
4233 * Most of the time we're called for timers.
4236 case FR_ACTION_TIMER:
4237 request->process(request, FR_ACTION_TIMER);
4241 * Set up the main timers.
4243 case FR_ACTION_PROXY_REPLY:
4244 request->child_state = REQUEST_QUEUED;
4245 request_process_timer(request);
4249 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4254 STATE_MACHINE_DECL(coa_no_reply)
4258 VERIFY_REQUEST(request);
4260 TRACE_STATE_MACHINE;
4263 case FR_ACTION_TIMER:
4264 request_common(request, action);
4267 case FR_ACTION_PROXY_REPLY: /* too late! */
4268 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4269 inet_ntop(request->proxy->src_ipaddr.af,
4270 &request->proxy->src_ipaddr.ipaddr,
4271 buffer, sizeof(buffer)),
4272 request->proxy->dst_port, request->proxy->id);
4276 (void) process_proxy_reply(request, NULL);
4277 request_done(request, FR_ACTION_DONE);
4281 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4286 STATE_MACHINE_DECL(coa_running)
4288 VERIFY_REQUEST(request);
4290 TRACE_STATE_MACHINE;
4294 * Silently ignore duplicate proxy replies.
4296 case FR_ACTION_PROXY_REPLY:
4299 case FR_ACTION_TIMER:
4300 request_process_timer(request);
4304 if (process_proxy_reply(request, request->proxy_reply)) {
4305 request->handle(request);
4307 request_done(request, FR_ACTION_DONE);
4311 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4315 #endif /* WITH_COA */
4317 /***********************************************************************
4319 * End of the State machine. Start of additional helper code.
4321 ***********************************************************************/
4323 /***********************************************************************
4327 ***********************************************************************/
4328 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4330 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4332 rad_assert(xel == el);
4334 if ((listener->fd < 0)
4336 #ifndef WITH_DETAIL_THREAD
4337 && (listener->type != RAD_LISTEN_DETAIL)
4343 listener->print(listener, buffer, sizeof(buffer));
4344 ERROR("FATAL: Asked to read from closed socket: %s",
4347 rad_panic("Socket was closed on us!");
4351 listener->recv(listener);
4355 #ifdef WITH_DETAIL_THREAD
4358 * This function is called periodically to see if this detail
4359 * file is available for reading.
4361 static void event_poll_detail(void *ctx)
4364 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4365 struct timeval when, now;
4366 listen_detail_t *detail = this->data;
4368 rad_assert(this->type == RAD_LISTEN_DETAIL);
4371 event_socket_handler(el, this->fd, this);
4373 fr_event_now(el, &now);
4377 * Backdoor API to get the delay until the next poll
4380 delay = this->encode(this, NULL);
4381 if (delay == 0) goto redo;
4383 tv_add(&when, delay);
4386 if (!fr_event_insert(el, event_poll_detail, this,
4387 &when, &detail->ev)) {
4388 ERROR("Failed creating handler");
4392 #endif /* WITH_DETAIL_THREAD */
4393 #endif /* WITH_DETAIL */
4395 static void event_status(struct timeval *wake)
4397 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4401 if (debug_flag == 0) {
4403 INFO("Ready to process requests");
4404 just_started = false;
4410 INFO("Ready to process requests");
4412 } else if ((wake->tv_sec != 0) ||
4413 (wake->tv_usec >= 100000)) {
4414 DEBUG("Waking up in %d.%01u seconds.",
4415 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4420 * FIXME: Put this somewhere else, where it isn't called
4421 * all of the time...
4424 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4426 * If there are no child threads, then there may
4427 * be child processes. In that case, wait for
4428 * their exit status, and throw that exit status
4429 * away. This helps get rid of zxombie children.
4431 while (waitpid(-1, &argval, WNOHANG) > 0) {
4439 static void listener_free_cb(void *ctx)
4441 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4444 if (this->count > 0) {
4445 struct timeval when;
4446 listen_socket_t *sock = this->data;
4448 fr_event_now(el, &when);
4452 if (!fr_event_insert(el, listener_free_cb, this, &when,
4454 rad_panic("Failed to insert event");
4461 * It's all free, close the socket.
4464 this->print(this, buffer, sizeof(buffer));
4465 DEBUG("... cleaning up socket %s", buffer);
4466 rad_assert(this->next == NULL);
4472 static int proxy_eol_cb(void *ctx, void *data)
4474 struct timeval when;
4475 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4477 if (request->proxy_listener != ctx) return 0;
4480 * We don't care if it's being processed in a child thread.
4483 #ifdef WITH_ACCOUNTING
4485 * Accounting packets should be deleted immediately.
4486 * They will never be retransmitted by the client.
4488 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4489 RDEBUG("Stopping request due to failed connection to home server");
4490 request->master_state = REQUEST_STOP_PROCESSING;
4495 * Reset the timer to be now, so that the request is
4496 * quickly updated. But spread the requests randomly
4497 * over the next second, so that we don't overload the
4500 fr_event_now(el, &when);
4501 tv_add(&when, fr_rand() % USEC);
4502 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4505 * Don't delete it from the list.
4511 static int event_new_fd(rad_listen_t *this)
4517 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4519 this->print(this, buffer, sizeof(buffer));
4521 if (this->status == RAD_LISTEN_STATUS_INIT) {
4522 listen_socket_t *sock = this->data;
4524 rad_assert(sock != NULL);
4526 DEBUG("Listening on %s", buffer);
4529 } else if (this->type == RAD_LISTEN_PROXY) {
4530 home_server_t *home;
4533 if (!home || !home->limit.max_connections) {
4534 INFO(" ... adding new socket %s", buffer);
4536 INFO(" ... adding new socket %s (%u of %u)", buffer,
4537 home->limit.num_connections, home->limit.max_connections);
4542 INFO(" ... adding new socket %s", buffer);
4545 switch (this->type) {
4548 * Detail files are always known, and aren't
4549 * put into the socket event loop.
4551 case RAD_LISTEN_DETAIL:
4552 this->status = RAD_LISTEN_STATUS_KNOWN;
4554 #ifndef WITH_DETAIL_THREAD
4556 * Set up the first poll interval.
4558 event_poll_detail(this);
4561 break; /* add the FD to the list */
4563 #endif /* WITH_DETAIL */
4567 * Add it to the list of sockets we can use.
4568 * Server sockets (i.e. auth/acct) are never
4569 * added to the packet list.
4571 case RAD_LISTEN_PROXY:
4573 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4576 * Add timers to outgoing child sockets, if necessary.
4578 if (sock->proto == IPPROTO_TCP && sock->opened &&
4579 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4580 struct timeval when;
4582 when.tv_sec = sock->opened + 1;
4586 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4588 rad_panic("Failed to insert event");
4593 #endif /* WITH_PROXY */
4596 * FIXME: put idle timers on command sockets.
4602 * Add timers to incoming child sockets, if necessary.
4604 if (sock->proto == IPPROTO_TCP && sock->opened &&
4605 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4606 struct timeval when;
4608 when.tv_sec = sock->opened + 1;
4612 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4614 ERROR("Failed adding timer for socket: %s", fr_strerror());
4620 } /* switch over listener types */
4623 * All sockets: add the FD to the event handler.
4625 if (!fr_event_fd_insert(el, 0, this->fd,
4626 event_socket_handler, this)) {
4627 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4631 this->status = RAD_LISTEN_STATUS_KNOWN;
4637 * Stop using this socket, if at all possible.
4639 if (this->status == RAD_LISTEN_STATUS_EOL) {
4641 * Remove it from the list of live FD's.
4643 fr_event_fd_delete(el, 0, this->fd);
4647 * Proxy sockets get frozen, so that we don't use
4648 * them for new requests. But we do keep them
4649 * open to listen for replies to requests we had
4652 if (this->type == RAD_LISTEN_PROXY) {
4653 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4654 if (!fr_packet_list_socket_freeze(proxy_list,
4656 ERROR("Fatal error freezing socket: %s", fr_strerror());
4660 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4661 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4666 * Requests are still using the socket. Wait for
4669 if (this->count > 0) {
4670 struct timeval when;
4671 listen_socket_t *sock = this->data;
4674 * Try again to clean up the socket in 30
4677 gettimeofday(&when, NULL);
4681 if (!fr_event_insert(el,
4682 (fr_event_callback_t) event_new_fd,
4683 this, &when, &sock->ev)) {
4684 rad_panic("Failed to insert event");
4691 * No one is using the socket. We can remove it now.
4693 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4694 } /* socket is at EOL */
4700 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4703 listen_socket_t *sock = this->data;
4705 struct timeval when;
4708 * Re-open the socket, pointing it to /dev/null.
4709 * This means that all writes proceed without
4710 * blocking, and all reads return "no data".
4712 * This leaves the socket active, so any child
4713 * threads won't go insane. But it means that
4714 * they cannot send or receive any packets.
4716 * This is EXTRA work in the normal case, when
4717 * sockets are closed without error. But it lets
4718 * us have one simple processing method for all
4721 devnull = open("/dev/null", O_RDWR);
4723 ERROR("FATAL failure opening /dev/null: %s",
4724 fr_syserror(errno));
4727 if (dup2(devnull, this->fd) < 0) {
4728 ERROR("FATAL failure closing socket: %s",
4729 fr_syserror(errno));
4735 rad_assert(this->type != RAD_LISTEN_DETAIL);
4741 * The socket is dead. Force all proxied packets
4742 * to stop using it. And then remove it from the
4743 * list of outgoing sockets.
4745 if (this->type == RAD_LISTEN_PROXY) {
4746 home_server_t *home;
4749 if (!home || !home->limit.max_connections) {
4750 INFO(" ... shutting down socket %s", buffer);
4752 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4753 home->limit.num_connections, home->limit.max_connections);
4756 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4757 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4759 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4760 ERROR("Fatal error removing socket %s: %s",
4761 buffer, fr_strerror());
4764 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4768 INFO(" ... shutting down socket %s", buffer);
4771 * EOL all requests using this socket.
4773 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4777 * No child threads, clean it up now.
4781 if (sock->ev) fr_event_delete(el, &sock->ev);
4787 * Wait until all requests using this socket are done.
4789 gettimeofday(&when, NULL);
4793 if (!fr_event_insert(el, listener_free_cb, this, &when,
4795 rad_panic("Failed to insert event");
4798 #endif /* WITH_TCP */
4803 /***********************************************************************
4807 ***********************************************************************/
4809 static void handle_signal_self(int flag)
4813 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4814 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4815 INFO("Signalled to exit");
4816 fr_event_loop_exit(el, 1);
4818 INFO("Signalled to terminate");
4819 fr_event_loop_exit(el, 2);
4823 } /* else exit/term flags weren't set */
4826 * Tell the even loop to stop processing.
4828 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4830 static time_t last_hup = 0;
4833 if ((int) (when - last_hup) < 5) {
4834 INFO("Ignoring HUP (less than 5s since last one)");
4838 INFO("Received HUP signal");
4842 exec_trigger(NULL, NULL, "server.signal.hup", true);
4843 fr_event_loop_exit(el, 0x80);
4847 #ifndef WITH_DETAIL_THREAD
4848 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4852 * FIXME: O(N) loops suck.
4854 for (this = main_config.listen;
4856 this = this->next) {
4857 if (this->type != RAD_LISTEN_DETAIL) continue;
4860 * This one didn't send the signal, skip
4863 if (!this->decode(this, NULL)) continue;
4866 * Go service the interrupt.
4868 event_poll_detail(this);
4876 #ifdef HAVE_PTHREAD_H
4878 * There are new listeners in the list. Run
4879 * event_new_fd() on them.
4881 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4882 rad_listen_t *this, *next;
4884 FD_MUTEX_LOCK(&fd_mutex);
4887 * FIXME: unlock the mutex before calling
4890 for (this = new_listeners; this != NULL; this = next) {
4897 new_listeners = NULL;
4898 FD_MUTEX_UNLOCK(&fd_mutex);
4900 #endif /* HAVE_PTHREAD_H */
4901 #endif /* WITH_PROXY */
4902 #endif /* WITH_TCP */
4905 #ifndef HAVE_PTHREAD_H
4906 void radius_signal_self(int flag)
4908 return handle_signal_self(flag);
4912 static int self_pipe[2] = { -1, -1 };
4915 * Inform ourselves that we received a signal.
4917 void radius_signal_self(int flag)
4923 * The read MUST be non-blocking for this to work.
4925 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4929 for (i = 0; i < rcode; i++) {
4930 buffer[0] |= buffer[i];
4938 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4942 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4943 UNUSED int fd, UNUSED void *ctx)
4948 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4949 if (rcode <= 0) return;
4952 * Merge pending signals.
4954 for (i = 0; i < rcode; i++) {
4955 buffer[0] |= buffer[i];
4958 handle_signal_self(buffer[0]);
4960 #endif /* HAVE_PTHREAD_H */
4962 /***********************************************************************
4964 * Bootstrapping code.
4966 ***********************************************************************/
4969 * Externally-visibly functions.
4971 int radius_event_init(TALLOC_CTX *ctx) {
4972 el = fr_event_list_create(ctx, event_status);
4978 static int packet_entry_cmp(void const *one, void const *two)
4980 RADIUS_PACKET const * const *a = one;
4981 RADIUS_PACKET const * const *b = two;
4983 return fr_packet_cmp(*a, *b);
4987 int radius_event_start(CONF_SECTION *cs, bool have_children)
4989 rad_listen_t *head = NULL;
4991 if (fr_start_time != (time_t)-1) return 0;
4993 time(&fr_start_time);
4995 if (!check_config) {
4997 * radius_event_init() must be called first
5001 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5002 if (!pl) return 0; /* leak el */
5005 request_num_counter = 0;
5008 if (main_config.proxy_requests) {
5010 * Create the tree for managing proxied requests and
5013 proxy_list = fr_packet_list_create(1);
5014 if (!proxy_list) return 0;
5016 #ifdef HAVE_PTHREAD_H
5017 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5018 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5019 fr_syserror(errno));
5025 * The "init_delay" is set to "response_window".
5026 * Reset it to half of "response_window" in order
5027 * to give the event loop enough time to service
5028 * the event before hitting "response_window".
5030 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5031 main_config.init_delay.tv_usec >>= 1;
5032 main_config.init_delay.tv_sec >>= 1;
5034 proxy_ctx = talloc_init("proxy");
5039 * Move all of the thread calls to this file?
5041 * It may be best for the mutexes to be in this file...
5043 spawn_flag = have_children;
5045 #ifdef HAVE_PTHREAD_H
5046 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5049 * Initialize the threads ONLY if we're spawning, AND
5050 * we're running normally.
5052 if (have_children && !check_config &&
5053 (thread_pool_init(cs, &spawn_flag) < 0)) {
5059 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5061 if (listen_init(cs, &head, spawn_flag) < 0) {
5068 #ifdef HAVE_PTHREAD_H
5070 * Child threads need a pipe to signal us, as do the
5073 if (pipe(self_pipe) < 0) {
5074 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5077 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5078 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5079 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5082 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5083 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5084 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5087 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5089 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5090 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5095 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5098 * The server temporarily switches to an unprivileged
5099 * user very early in the bootstrapping process.
5100 * However, some sockets MAY require privileged access
5101 * (bind to device, or to port < 1024, or to raw
5102 * sockets). Those sockets need to call suid up/down
5103 * themselves around the functions that need a privileged
5106 if (listen_init(cs, &head, spawn_flag) < 0) {
5110 main_config.listen = head;
5113 * At this point, no one has any business *ever* going
5116 rad_suid_down_permanent();
5123 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5125 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5127 VERIFY_REQUEST(request);
5129 request->master_state = REQUEST_STOP_PROCESSING;
5131 #ifdef HAVE_PTHREAD_H
5132 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5136 * If it's queued we can't delete it from the queue.
5138 * Otherwise, it's OK to delete it. Even RUNNING, because
5139 * that will get caught by the check above.
5141 if (request->child_state == REQUEST_QUEUED) return 0;
5143 request->in_proxy_hash = false;
5145 if (!request->in_request_hash) {
5146 request_done(request, FR_ACTION_DONE);
5150 * Delete it from the list.
5157 static int request_delete_cb(UNUSED void *ctx, void *data)
5159 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5161 VERIFY_REQUEST(request);
5163 request->master_state = REQUEST_STOP_PROCESSING;
5166 * Not done, or the child thread is still processing it.
5168 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5170 #ifdef HAVE_PTHREAD_H
5171 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5175 rad_assert(request->in_proxy_hash == false);
5178 request->in_request_hash = false;
5180 if (request->ev) fr_event_delete(el, &request->ev);
5182 if (main_config.memory_report) {
5183 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5184 request->packet->id,
5185 (unsigned int) (request->timestamp - fr_start_time));
5190 rad_assert(!request->coa->in_proxy_hash);
5194 request_free(request);
5197 * Delete it from the list, and continue;
5203 void radius_event_free(void)
5209 * There are requests in the proxy hash that aren't
5210 * referenced from anywhere else. Remove them first.
5213 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5217 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5221 * Now that all requests have been marked "please stop",
5222 * ensure that all of the threads have exited.
5224 #ifdef HAVE_PTHREAD_H
5229 * Walk the lists again, ensuring that all
5230 * requests are done.
5232 if (main_config.memory_report) {
5237 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5238 num = fr_packet_list_num_elements(proxy_list);
5240 ERROR("Proxy list has %d requests still in it.", num);
5245 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5246 num = rbtree_num_elements(pl);
5248 ERROR("Request list has %d requests still in it.", num);
5257 fr_packet_list_free(proxy_list);
5260 if (proxy_ctx) talloc_free(proxy_ctx);
5265 if (debug_condition) talloc_free(debug_condition);
5268 int radius_event_process(void)
5272 return fr_event_loop(el);