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, struct timeval const *pnow)
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;
759 gettimeofday(&now, NULL);
762 rad_assert(request->reply->timestamp.tv_sec != 0);
763 when = request->reply->timestamp;
765 request->delay = request->root->cleanup_delay;
766 when.tv_sec += request->delay;
769 * Set timer for when we need to clean it up.
771 if (timercmp(&when, &now, >)) {
772 #ifdef DEBUG_STATE_MACHINE
773 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
775 request->process = request_cleanup_delay;
776 request->child_state = REQUEST_DONE;
777 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
782 * Otherwise just clean it up.
785 request_done(request, FR_ACTION_DONE);
790 * Function to do all time-related events.
792 static void request_process_timer(REQUEST *request)
794 struct timeval now, when;
795 rad_assert(request->magic == REQUEST_MAGIC);
796 #ifdef DEBUG_STATE_MACHINE
797 int action = FR_ACTION_TIMER;
800 VERIFY_REQUEST(request);
807 * If we originated a CoA request, divorce it from the
808 * parent. Then, set up the timers so that we can clean
809 * it up as appropriate.
811 if (request->coa) coa_separate(request->coa, FR_ACTION_TIMER);
814 * If we're the request, OR it isn't originating a CoA
815 * request, check more things.
817 if (!request->proxy || (request->packet->code == request->proxy->code))
820 rad_assert(request->listener != NULL);
823 * The socket was closed. Tell the request that
824 * there is no point in continuing.
826 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
827 if ((request->master_state == REQUEST_ACTIVE) &&
828 (request->child_state < REQUEST_RESPONSE_DELAY)) {
829 WARN("Socket was closed while processing request %u: Stopping it.", request->number);
830 request->master_state = REQUEST_STOP_PROCESSING;
835 gettimeofday(&now, NULL);
838 * The request was forcibly stopped.
840 if (request->master_state == REQUEST_STOP_PROCESSING) {
841 switch (request->child_state) {
843 case REQUEST_RUNNING:
844 #ifdef HAVE_PTHREAD_H
845 rad_assert(spawn_flag == true);
850 * Sleep for some more. We HOPE that the
851 * child will become responsive at some
852 * point in the future.
855 tv_add(&when, request->delay);
856 request->delay += request->delay >> 1;
857 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
861 * These should all be managed by the master thread
864 case REQUEST_PROXIED:
866 case REQUEST_RESPONSE_DELAY:
867 case REQUEST_CLEANUP_DELAY:
870 request_done(request, FR_ACTION_DONE);
875 rad_assert(request->master_state == REQUEST_ACTIVE);
878 * It's still supposed to be running.
880 switch (request->child_state) {
882 case REQUEST_RUNNING:
883 when = request->packet->timestamp;
884 when.tv_sec += request->root->max_request_time;
887 * Taking too long: tell it to die.
889 if (timercmp(&now, &when, >=)) {
890 #ifdef HAVE_PTHREAD_H
892 * If there's a child thread processing it,
896 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
897 ERROR("Unresponsive child for request %u, in component %s module %s",
899 request->component ? request->component : "<core>",
900 request->module ? request->module : "<core>");
901 exec_trigger(request, NULL, "server.thread.unresponsive", true);
904 request->master_state = REQUEST_STOP_PROCESSING;
906 goto delay; /* sleep some more */
909 case REQUEST_PROXIED:
910 when = request->packet->timestamp;
911 when.tv_sec += request->root->max_request_time;
913 if (timercmp(&now, &when, >=)) {
914 RWDEBUG("No response to proxied request in 'max_request_time'. Stopping it.");
915 request->master_state = REQUEST_STOP_PROCESSING;
916 request_done(request, FR_ACTION_DONE);
920 rad_assert(request->proxy != NULL);
923 * Delay some more, hoping that we get a response.
925 when = request->proxy->timestamp;
926 tv_add(&when, request->delay);
928 if (timercmp(&now, &when, >=)) {
929 request->process(request, FR_ACTION_TIMER);
934 * Otherwise set the timer for the future.
936 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
938 #endif /* WITH_PROXY */
940 case REQUEST_RESPONSE_DELAY:
941 rad_assert(request->response_delay.tv_sec > 0);
943 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
946 request->process = request_response_delay;
948 when = request->reply->timestamp;
950 tv_add(&when, request->response_delay.tv_sec * USEC);
951 tv_add(&when, request->response_delay.tv_usec);
953 if (timercmp(&when, &now, >)) {
954 #ifdef DEBUG_STATE_MACHINE
955 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
957 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
959 } /* else it's time to send the reject */
961 RDEBUG2("Sending delayed response");
962 request->listener->send(request->listener, request);
963 debug_packet(request, request->reply, false);
964 request->child_state = REQUEST_CLEANUP_DELAY;
967 case REQUEST_CLEANUP_DELAY:
968 rad_assert(request->root->cleanup_delay > 0);
971 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
974 request->process = request_cleanup_delay;
976 when = request->reply->timestamp;
977 when.tv_sec += request->root->cleanup_delay;
979 if (timercmp(&when, &now, >)) {
980 #ifdef DEBUG_STATE_MACHINE
981 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
983 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
985 } /* else it's time to clean up */
994 static void request_queue_or_run(REQUEST *request,
995 fr_request_process_t process)
997 #ifdef DEBUG_STATE_MACHINE
998 int action = FR_ACTION_TIMER;
1001 VERIFY_REQUEST(request);
1003 TRACE_STATE_MACHINE;
1006 * Do this here so that fewer other functions need to do
1009 if (request->master_state == REQUEST_STOP_PROCESSING) {
1010 #ifdef DEBUG_STATE_MACHINE
1011 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
1012 request->number, __FUNCTION__,
1013 master_state_names[request->master_state],
1014 child_state_names[request->child_state],
1015 child_state_names[REQUEST_DONE]);
1017 request_done(request, FR_ACTION_DONE);
1021 request->process = process;
1023 if (we_are_master()) {
1024 struct timeval when;
1027 * (re) set the initial delay.
1029 request->delay = request_init_delay(request);
1030 if (request->delay > USEC) request->delay = USEC;
1031 gettimeofday(&when, NULL);
1032 tv_add(&when, request->delay);
1033 request->delay += request->delay >> 1;
1035 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1037 #ifdef HAVE_PTHREAD_H
1040 * A child thread will eventually pick it up.
1042 if (request_enqueue(request)) return;
1045 * Otherwise we're not going to do anything with
1048 request_done(request, FR_ACTION_DONE);
1054 request->child_state = REQUEST_RUNNING;
1055 request->process(request, FR_ACTION_RUN);
1059 * Requests that care about child process exit
1060 * codes have already either called
1061 * rad_waitpid(), or they've given up.
1063 while (waitpid(-1, NULL, WNOHANG) > 0);
1067 STATE_MACHINE_DECL(request_common)
1073 VERIFY_REQUEST(request);
1075 TRACE_STATE_MACHINE;
1079 * Bail out as early as possible.
1081 if (request->master_state == REQUEST_STOP_PROCESSING) {
1082 request_done(request, FR_ACTION_DONE);
1088 ERROR("(%u) Ignoring duplicate packet from "
1089 "client %s port %d - ID: %u due to unfinished request "
1090 "in component %s module %s",
1091 request->number, request->client->shortname,
1092 request->packet->src_port,request->packet->id,
1093 request->component, request->module);
1096 case FR_ACTION_TIMER:
1097 request_process_timer(request);
1101 case FR_ACTION_PROXY_REPLY:
1102 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
1103 inet_ntop(request->proxy->dst_ipaddr.af,
1104 &request->proxy->dst_ipaddr.ipaddr,
1105 buffer, sizeof(buffer)),
1106 request->proxy->dst_port, request->proxy->id);
1111 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1116 STATE_MACHINE_DECL(request_cleanup_delay)
1118 struct timeval when;
1120 VERIFY_REQUEST(request);
1122 TRACE_STATE_MACHINE;
1127 if (request->reply->code != 0) {
1128 request->listener->send(request->listener, request);
1130 RDEBUG("No reply. Ignoring retransmit");
1134 * Double the cleanup_delay to catch retransmits.
1136 when = request->reply->timestamp;
1137 request->delay += request->delay ;
1138 when.tv_sec += request->delay;
1140 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1144 case FR_ACTION_PROXY_REPLY:
1146 case FR_ACTION_TIMER:
1147 request_common(request, action);
1151 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1156 STATE_MACHINE_DECL(request_response_delay)
1158 VERIFY_REQUEST(request);
1160 TRACE_STATE_MACHINE;
1165 ERROR("(%u) Discarding duplicate request from "
1166 "client %s port %d - ID: %u due to delayed response",
1167 request->number, request->client->shortname,
1168 request->packet->src_port,request->packet->id);
1172 case FR_ACTION_PROXY_REPLY:
1174 case FR_ACTION_TIMER:
1175 request_common(request, action);
1179 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1185 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1189 VERIFY_REQUEST(request);
1191 TRACE_STATE_MACHINE;
1193 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1196 * Don't decode the packet if it's an internal "fake"
1197 * request. Instead, just return so that the caller can
1200 if (request->packet->dst_port == 0) {
1201 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1202 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1206 if (!request->packet->vps) { /* FIXME: check for correct state */
1207 rcode = request->listener->decode(request->listener, request);
1210 if (debug_condition) {
1212 * Ignore parse errors.
1214 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1215 request->log.lvl = L_DBG_LVL_2;
1216 request->log.func = vradlog_request;
1221 debug_packet(request, request->packet, true);
1227 RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1228 request->reply->offset = -2; /* bad authenticator */
1232 if (!request->username) {
1233 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1239 STATE_MACHINE_DECL(request_finish)
1243 VERIFY_REQUEST(request);
1245 TRACE_STATE_MACHINE;
1247 (void) action; /* -Wunused */
1249 if (request->master_state == REQUEST_STOP_PROCESSING) {
1252 * Always send a reply to the detail listener.
1254 if (request->listener->type == RAD_LISTEN_DETAIL) {
1259 request->child_state = REQUEST_DONE;
1265 * Don't do post-auth if we're a CoA request originated
1266 * from an Access-Request. See request_alloc_coa() for
1269 if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1273 * Override the response code if a control:Response-Packet-Type attribute is present.
1275 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1277 if (vp->vp_integer == 256) {
1278 RDEBUG2("Not responding to request");
1279 request->reply->code = 0;
1281 request->reply->code = vp->vp_integer;
1285 * Catch Auth-Type := Reject BEFORE proxying the packet.
1287 else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1288 if (request->reply->code == 0) {
1289 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1291 if (!vp || (vp->vp_integer != PW_CODE_ACCESS_REJECT)) {
1292 RDEBUG2("There was no response configured: "
1293 "rejecting request");
1296 request->reply->code = PW_CODE_ACCESS_REJECT;
1301 * Copy Proxy-State from the request to the reply.
1303 vp = paircopy_by_num(request->reply, request->packet->vps,
1304 PW_PROXY_STATE, 0, TAG_ANY);
1305 if (vp) pairadd(&request->reply->vps, vp);
1308 * Call Post-Auth for Access-Request packets.
1310 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1311 rad_postauth(request);
1316 * Clean up. These are no longer needed.
1318 gettimeofday(&request->reply->timestamp, NULL);
1321 * Fake packets get marked as "done", and have the
1322 * proxy-reply section deal with the reply attributes.
1323 * We therefore don't free the reply attributes.
1325 if (request->packet->dst_port == 0) {
1326 RDEBUG("Finished internally proxied request.");
1328 request->child_state = REQUEST_DONE;
1334 * Always send the reply to the detail listener.
1336 if (request->listener->type == RAD_LISTEN_DETAIL) {
1338 request->simul_max = 1;
1339 request->listener->send(request->listener, request);
1341 * But only print the reply if there is one.
1343 if (request->reply->code != 0) {
1344 debug_packet(request, request->reply, false);
1351 * Ignore all "do not respond" packets.
1352 * Except for the detail ones, which need to ping
1353 * the detail file reader so that it will retransmit.
1355 if (!request->reply->code) {
1356 RDEBUG("Not sending reply to client.");
1361 * If it's not in the request hash, we MIGHT not want to
1364 * If duplicate packets are allowed, then then only
1365 * reason to NOT be in the request hash is because we
1366 * don't want to send a reply.
1368 * FIXME: this is crap. The rest of the state handling
1369 * should use a different field so that we don't have two
1372 * Otherwise duplicates are forbidden, and the request is
1373 * SUPPOSED to avoid the request hash.
1375 * In that case, we need to send a reply.
1377 if (!request->in_request_hash &&
1378 !request->listener->nodup) {
1379 RDEBUG("Suppressing reply to client.");
1384 * See if we need to delay an Access-Reject packet.
1386 if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1387 (request->root->reject_delay.tv_sec > 0)) {
1388 request->response_delay = request->root->reject_delay;
1392 * If we timed out a proxy packet, don't delay
1393 * the reject any more.
1395 if (request->proxy && !request->proxy_reply) {
1396 request->response_delay.tv_sec = 0;
1397 request->response_delay.tv_usec = 0;
1405 if (request->response_delay.tv_sec == 0) {
1406 rad_assert(request->response_delay.tv_usec == 0);
1409 * Don't print a reply if there's none to send.
1411 if (request->reply->code != 0) {
1412 request->listener->send(request->listener, request);
1413 debug_packet(request, request->reply, false);
1417 RDEBUG2("Finished request");
1418 request->component = "<core>";
1419 request->module = "<done>";
1421 #ifdef WITH_ACCOUNTING
1423 * Accounting packets can be cleaned up now.
1425 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1427 request->child_state = REQUEST_DONE;
1434 * If the packets are from the detail file, we can clean them up now.
1436 if (request->listener->type == RAD_LISTEN_DETAIL) {
1438 request->child_state = REQUEST_DONE;
1445 * If we've originated this CoA request, it gets
1448 if (request->proxy &&
1449 ((request->proxy->code == PW_CODE_COA_REQUEST) ||
1450 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
1451 (request->packet->code != request->proxy->code)) {
1453 request->child_state = REQUEST_DONE;
1459 * No cleanup, mark the request as done.
1461 * Otherwise, mark it as "please do cleanup delay".
1463 if (request->root->cleanup_delay == 0) {
1465 request->child_state = REQUEST_DONE;
1468 request->child_state = REQUEST_CLEANUP_DELAY;
1472 * Encode and sign it here, so that the master
1473 * thread can just send the encoded data, which
1474 * means it does less work.
1476 RDEBUG2("Delaying response for %d.%06d seconds",
1477 (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1478 request->listener->encode(request->listener, request);
1479 request->component = "<core>";
1480 request->module = "<delay>";
1482 request->child_state = REQUEST_RESPONSE_DELAY;
1486 STATE_MACHINE_DECL(request_running)
1488 VERIFY_REQUEST(request);
1490 TRACE_STATE_MACHINE;
1493 case FR_ACTION_TIMER:
1494 request_process_timer(request);
1498 request_common(request, action);
1502 if (!request_pre_handler(request, action)) {
1503 #ifdef DEBUG_STATE_MACHINE
1504 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1505 request->number, __FUNCTION__,
1506 child_state_names[request->child_state],
1507 child_state_names[REQUEST_DONE]);
1511 request->child_state = REQUEST_DONE;
1515 rad_assert(request->handle != NULL);
1516 request->handle(request);
1520 * We may need to send a proxied request.
1522 if ((action == FR_ACTION_RUN) &&
1523 request_will_proxy(request)) {
1524 #ifdef DEBUG_STATE_MACHINE
1525 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1529 * takes care of setting
1530 * up the post proxy fail
1533 if (request_proxy(request, 0) < 0) goto req_finished;
1537 #ifdef DEBUG_STATE_MACHINE
1538 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1543 * Maybe originate a CoA request.
1545 if ((action == FR_ACTION_RUN) && request->coa) {
1546 request_coa_originate(request);
1553 request_finish(request, action);
1558 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1563 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1564 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1567 RADIUS_PACKET **packet_p;
1568 REQUEST *request = NULL;
1570 listen_socket_t *sock = NULL;
1572 VERIFY_PACKET(packet);
1575 * Set the last packet received.
1577 gettimeofday(&now, NULL);
1579 packet->timestamp = now;
1581 #ifdef WITH_ACCOUNTING
1582 if (listener->type != RAD_LISTEN_DETAIL)
1585 sock = listener->data;
1586 sock->last_packet = now.tv_sec;
1590 * Skip everything if required.
1592 if (listener->nodup) goto skip_dup;
1594 packet_p = rbtree_finddata(pl, &packet);
1596 rad_child_state_t child_state;
1598 request = fr_packet2myptr(REQUEST, packet, packet_p);
1599 rad_assert(request->in_request_hash);
1600 child_state = request->child_state;
1603 * Same src/dst ip/port, length, and
1604 * authentication vector: must be a duplicate.
1606 if ((request->packet->data_len == packet->data_len) &&
1607 (memcmp(request->packet->vector, packet->vector,
1608 sizeof(packet->vector)) == 0)) {
1611 switch (packet->code) {
1612 case PW_CODE_ACCESS_REQUEST:
1613 FR_STATS_INC(auth, total_dup_requests);
1616 #ifdef WITH_ACCOUNTING
1617 case PW_CODE_ACCOUNTING_REQUEST:
1618 FR_STATS_INC(acct, total_dup_requests);
1622 case PW_CODE_COA_REQUEST:
1623 FR_STATS_INC(coa, total_dup_requests);
1626 case PW_CODE_DISCONNECT_REQUEST:
1627 FR_STATS_INC(dsc, total_dup_requests);
1634 #endif /* WITH_STATS */
1637 * Tell the state machine that there's a
1638 * duplicate request.
1640 request->process(request, FR_ACTION_DUP);
1641 return 0; /* duplicate of live request */
1645 * Mark the request as done ASAP, and before we
1646 * log anything. The child may stop processing
1647 * the request just as we're logging the
1650 request_done(request, FR_ACTION_DONE);
1654 * It's a new request, not a duplicate. If the
1655 * old one is done, then we can clean it up.
1657 if (child_state <= REQUEST_RUNNING) {
1659 * The request is still QUEUED or RUNNING. That's a problem.
1661 ERROR("Received conflicting packet from "
1662 "client %s port %d - ID: %u due to "
1663 "unfinished request. Giving up on old request.",
1665 packet->src_port, packet->id);
1669 * Mark the old request as done. If there's no
1670 * child, the request will be cleaned up
1671 * immediately. If there is a child, we'll set a
1672 * timer to go clean up the request.
1674 } /* else the new packet is unique */
1677 * Quench maximum number of outstanding requests.
1679 if (main_config.max_requests &&
1680 ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1681 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1683 packet->src_port, packet->id);
1684 WARN("Please check the configuration file.\n"
1685 "\tThe value for 'max_requests' is probably set too low.\n"));
1687 exec_trigger(NULL, NULL, "server.max_requests", true);
1693 * Rate-limit the incoming packets
1695 if (sock && sock->max_rate) {
1698 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1699 if (pps > sock->max_rate) {
1700 DEBUG("Dropping request due to rate limiting");
1703 sock->rate_pps_now++;
1707 * Allocate a pool for the request.
1710 ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1714 * The packet is still allocated from a different
1715 * context, but oh well.
1717 (void) talloc_steal(ctx, packet);
1720 request = request_setup(ctx, listener, packet, client, fun);
1727 * Mark it as a "real" request with a context.
1729 request->options |= RAD_REQUEST_OPTION_CTX;
1732 * Remember the request in the list.
1734 if (!listener->nodup) {
1735 if (!rbtree_insert(pl, &request->packet)) {
1736 RERROR("Failed to insert request in the list of live requests: discarding it");
1737 request_done(request, FR_ACTION_DONE);
1741 request->in_request_hash = true;
1745 * Process it. Send a response, and free it.
1747 if (listener->synchronous) {
1749 rad_assert(listener->type != RAD_LISTEN_DETAIL);
1752 request->listener->decode(request->listener, request);
1753 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1754 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1758 if (request->reply->code != 0) {
1759 request->listener->send(request->listener, request);
1761 RDEBUG("Not sending reply");
1765 * Don't do delayed reject. Oh well.
1767 request_free(request);
1772 * Otherwise, insert it into the state machine.
1773 * The child threads will take care of processing it.
1775 request_queue_or_run(request, request_running);
1781 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1782 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1787 * Create and initialize the new request.
1789 request = request_alloc(ctx);
1794 request->reply = rad_alloc(request, false);
1795 if (!request->reply) {
1797 talloc_free(request);
1801 request->listener = listener;
1802 request->client = client;
1803 request->packet = talloc_steal(request, packet);
1804 request->number = request_num_counter++;
1805 request->priority = listener->type;
1806 request->master_state = REQUEST_ACTIVE;
1807 #ifdef DEBUG_STATE_MACHINE
1808 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1809 request->number, __FUNCTION__,
1810 child_state_names[request->child_state],
1811 child_state_names[REQUEST_RUNNING]);
1813 #ifdef HAVE_PTHREAD_H
1814 request->child_pid = NO_SUCH_CHILD_PID;
1816 request->child_state = REQUEST_RUNNING;
1817 request->handle = fun;
1821 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1822 if (packet->code == PW_CODE_ACCESS_REQUEST) {
1823 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1824 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1825 #ifdef WITH_ACCOUNTING
1826 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1827 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1828 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1831 #endif /* WITH_STATS */
1834 * Status-Server packets go to the head of the queue.
1836 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1839 * Set virtual server identity
1841 if (client->server) {
1842 request->server = client->server;
1843 } else if (listener->server) {
1844 request->server = listener->server;
1846 request->server = NULL;
1849 request->root = &main_config;
1851 request->listener->count++;
1855 * The request passes many of our sanity checks.
1856 * From here on in, if anything goes wrong, we
1857 * send a reject message, instead of dropping the
1862 * Build the reply template from the request.
1865 request->reply->sockfd = request->packet->sockfd;
1866 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1867 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1868 request->reply->dst_port = request->packet->src_port;
1869 request->reply->src_port = request->packet->dst_port;
1870 request->reply->id = request->packet->id;
1871 request->reply->code = 0; /* UNKNOWN code */
1872 memcpy(request->reply->vector, request->packet->vector,
1873 sizeof(request->reply->vector));
1874 request->reply->vps = NULL;
1875 request->reply->data = NULL;
1876 request->reply->data_len = 0;
1882 /***********************************************************************
1886 ***********************************************************************/
1889 * Timer function for all TCP sockets.
1891 static void tcp_socket_timer(void *ctx)
1893 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1894 listen_socket_t *sock = listener->data;
1895 struct timeval end, now;
1897 fr_socket_limit_t *limit;
1901 fr_event_now(el, &now);
1903 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1905 switch (listener->type) {
1907 case RAD_LISTEN_PROXY:
1908 limit = &sock->home->limit;
1912 case RAD_LISTEN_AUTH:
1913 #ifdef WITH_ACCOUNTING
1914 case RAD_LISTEN_ACCT:
1916 limit = &sock->limit;
1924 * If we enforce a lifetime, do it now.
1926 if (limit->lifetime > 0) {
1927 end.tv_sec = sock->opened + limit->lifetime;
1930 if (timercmp(&end, &now, <=)) {
1931 listener->print(listener, buffer, sizeof(buffer));
1932 DEBUG("Reached maximum lifetime on socket %s", buffer);
1936 listener->status = RAD_LISTEN_STATUS_EOL;
1937 event_new_fd(listener);
1946 * Enforce an idle timeout.
1948 if (limit->idle_timeout > 0) {
1949 struct timeval idle;
1951 rad_assert(sock->last_packet != 0);
1952 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1955 if (timercmp(&idle, &now, <=)) {
1956 listener->print(listener, buffer, sizeof(buffer));
1957 DEBUG("Reached idle timeout on socket %s", buffer);
1962 * Enforce the minimum of idle timeout or lifetime.
1964 if (timercmp(&idle, &end, <)) {
1970 * Wake up at t + 0.5s. The code above checks if the timers
1971 * are <= t. This addition gives us a bit of leeway.
1973 end.tv_usec = USEC / 2;
1976 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1977 rad_panic("Failed to insert event");
1984 * Add +/- 2s of jitter, as suggested in RFC 3539
1987 static void add_jitter(struct timeval *when)
1994 jitter ^= (jitter >> 10);
1995 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1998 * Add in ~ (4 * USEC) of jitter.
2000 tv_add(when, jitter);
2004 * Called by socket_del to remove requests with this socket
2006 static int eol_proxy_listener(void *ctx, void *data)
2008 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2009 RADIUS_PACKET **proxy_p = data;
2012 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2013 if (request->proxy_listener != this) return 0;
2016 * The normal "remove_from_proxy_hash" tries to grab the
2017 * proxy mutex. We already have it held, so grabbing it
2018 * again will cause a deadlock. Instead, call the "no
2019 * lock" version of the function.
2021 rad_assert(request->in_proxy_hash == true);
2022 remove_from_proxy_hash_nl(request, false);
2025 * Don't mark it as DONE. The client can retransmit, and
2026 * the packet SHOULD be re-proxied somewhere else.
2028 * Return "2" means that the rbtree code will remove it
2029 * from the tree, and we don't need to do it ourselves.
2033 #endif /* WITH_PROXY */
2035 static int eol_listener(void *ctx, void *data)
2037 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2038 RADIUS_PACKET **packet_p = data;
2041 request = fr_packet2myptr(REQUEST, packet, packet_p);
2042 if (request->listener != this) return 0;
2044 request->master_state = REQUEST_STOP_PROCESSING;
2048 #endif /* WITH_TCP */
2051 /***********************************************************************
2053 * Proxy handlers for the state machine.
2055 ***********************************************************************/
2058 * Called with the proxy mutex held
2060 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2062 VERIFY_REQUEST(request);
2064 if (!request->in_proxy_hash) return;
2066 fr_packet_list_id_free(proxy_list, request->proxy, yank);
2067 request->in_proxy_hash = false;
2070 * On the FIRST reply, decrement the count of outstanding
2071 * requests. Note that this is NOT the count of sent
2072 * packets, but whether or not the home server has
2075 if (request->home_server &&
2076 request->home_server->currently_outstanding) {
2077 request->home_server->currently_outstanding--;
2080 * If we're NOT sending it packets, AND it's been
2081 * a while since we got a response, then we don't
2082 * know if it's alive or dead.
2084 if ((request->home_server->currently_outstanding == 0) &&
2085 (request->home_server->state == HOME_STATE_ALIVE)) {
2086 struct timeval when, now;
2088 when.tv_sec = request->home_server->last_packet_recv ;
2091 timeradd(&when, request_response_window(request), &when);
2092 gettimeofday(&now, NULL);
2095 * last_packet + response_window
2097 * We *administratively* mark the home
2098 * server as "unknown" state, because we
2099 * haven't seen a packet for a while.
2101 if (timercmp(&now, &when, >)) {
2102 request->home_server->state = HOME_STATE_UNKNOWN;
2103 request->home_server->last_packet_sent = 0;
2104 request->home_server->last_packet_recv = 0;
2110 rad_assert(request->proxy_listener != NULL);
2111 request->proxy_listener->count--;
2113 request->proxy_listener = NULL;
2116 * Got from YES in hash, to NO, not in hash while we hold
2117 * the mutex. This guarantees that when another thread
2118 * grabs the mutex, the "not in hash" flag is correct.
2120 RDEBUG3("proxy: request is no longer in proxy hash");
2123 static void remove_from_proxy_hash(REQUEST *request)
2125 VERIFY_REQUEST(request);
2128 * Check this without grabbing the mutex because it's a
2129 * lot faster that way.
2131 if (!request->in_proxy_hash) return;
2134 * The "not in hash" flag is definitive. However, if the
2135 * flag says that it IS in the hash, there might still be
2136 * a race condition where it isn't.
2138 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2140 if (!request->in_proxy_hash) {
2141 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2145 remove_from_proxy_hash_nl(request, true);
2147 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2150 static int insert_into_proxy_hash(REQUEST *request)
2154 bool success = false;
2155 void *proxy_listener;
2157 VERIFY_REQUEST(request);
2159 rad_assert(request->proxy != NULL);
2160 rad_assert(request->home_server != NULL);
2161 rad_assert(proxy_list != NULL);
2164 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2165 proxy_listener = NULL;
2166 request->num_proxied_requests = 1;
2167 request->num_proxied_responses = 0;
2169 for (tries = 0; tries < 2; tries++) {
2171 listen_socket_t *sock;
2173 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2174 success = fr_packet_list_id_alloc(proxy_list,
2175 request->home_server->proto,
2176 &request->proxy, &proxy_listener);
2179 if (tries > 0) continue; /* try opening new socket only once */
2181 #ifdef HAVE_PTHREAD_H
2182 if (proxy_no_new_sockets) break;
2185 RDEBUG3("proxy: Trying to open a new listener to the home server");
2186 this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2188 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2192 request->proxy->src_port = 0; /* Use any new socket */
2193 proxy_listener = this;
2196 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2198 &sock->other_ipaddr, sock->other_port,
2201 #ifdef HAVE_PTHREAD_H
2202 proxy_no_new_sockets = true;
2204 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2207 * This is bad. However, the
2208 * packet list now supports 256
2209 * open sockets, which should
2210 * minimize this problem.
2212 ERROR("Failed adding proxy socket: %s",
2218 * Add it to the event loop. Ensure that we have
2219 * only one mutex locked at a time.
2221 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2222 radius_update_listener(this);
2223 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2226 if (!proxy_listener || !success) {
2227 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2228 REDEBUG2("proxy: Failed allocating Id for proxied request");
2230 request->proxy_listener = NULL;
2231 request->in_proxy_hash = false;
2235 rad_assert(request->proxy->id >= 0);
2237 request->proxy_listener = proxy_listener;
2238 request->in_proxy_hash = true;
2239 RDEBUG3("proxy: request is now in proxy hash");
2242 * Keep track of maximum outstanding requests to a
2243 * particular home server. 'max_outstanding' is
2244 * enforced in home_server_ldb(), in realms.c.
2246 request->home_server->currently_outstanding++;
2249 request->proxy_listener->count++;
2252 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2254 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2255 inet_ntop(request->proxy->dst_ipaddr.af,
2256 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2257 request->proxy->dst_port,
2258 request->proxy->id);
2263 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2266 int post_proxy_type = 0;
2269 VERIFY_REQUEST(request);
2272 * There may be a proxy reply, but it may be too late.
2274 if (!request->home_server->server && !request->proxy_listener) return 0;
2277 * Delete any reply we had accumulated until now.
2279 RDEBUG2("Clearing existing &reply: attributes");
2280 pairfree(&request->reply->vps);
2283 * Run the packet through the post-proxy stage,
2284 * BEFORE playing games with the attributes.
2286 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2288 post_proxy_type = vp->vp_integer;
2290 * If we have a proxy_reply, and it was a reject, or a NAK
2291 * setup Post-Proxy <type>.
2293 * If the <type> doesn't have a section, then the Post-Proxy
2294 * section is ignored.
2297 DICT_VALUE *dval = NULL;
2299 switch (reply->code) {
2300 case PW_CODE_ACCESS_REJECT:
2301 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2302 if (dval) post_proxy_type = dval->value;
2305 case PW_CODE_DISCONNECT_NAK:
2306 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2307 if (dval) post_proxy_type = dval->value;
2310 case PW_CODE_COA_NAK:
2311 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, fr_packet_codes[reply->code]);
2312 if (dval) post_proxy_type = dval->value;
2320 * Create config:Post-Proxy-Type
2323 vp = radius_paircreate(request, &request->config_items, PW_POST_PROXY_TYPE, 0);
2324 vp->vp_integer = dval->value;
2328 if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2329 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2332 VERIFY_PACKET(reply);
2335 * Decode the packet if required.
2337 if (request->proxy_listener) {
2338 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2339 debug_packet(request, reply, true);
2342 * Pro-actively remove it from the proxy hash.
2343 * This is later than in 2.1.x, but it means that
2344 * the replies are authenticated before being
2345 * removed from the hash.
2348 (request->num_proxied_requests <= request->num_proxied_responses)) {
2349 remove_from_proxy_hash(request);
2352 rad_assert(!request->in_proxy_hash);
2354 } else if (request->in_proxy_hash) {
2355 remove_from_proxy_hash(request);
2358 if (request->home_pool && request->home_pool->virtual_server) {
2359 char const *old_server = request->server;
2361 request->server = request->home_pool->virtual_server;
2362 RDEBUG2("server %s {", request->server);
2364 rcode = process_post_proxy(post_proxy_type, request);
2367 request->server = old_server;
2369 rcode = process_post_proxy(post_proxy_type, request);
2373 if (request->packet->code == request->proxy->code)
2375 * Don't run the next bit if we originated a CoA
2376 * packet, after receiving an Access-Request or
2377 * Accounting-Request.
2382 * There may NOT be a proxy reply, as we may be
2383 * running Post-Proxy-Type = Fail.
2386 pairadd(&request->reply->vps, paircopy(request->reply, reply->vps));
2389 * Delete the Proxy-State Attributes from
2390 * the reply. These include Proxy-State
2391 * attributes from us and remote server.
2393 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2397 default: /* Don't do anything */
2399 case RLM_MODULE_FAIL:
2402 case RLM_MODULE_HANDLED:
2409 int request_proxy_reply(RADIUS_PACKET *packet)
2411 RADIUS_PACKET **proxy_p;
2416 VERIFY_PACKET(packet);
2418 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2419 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2422 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2423 PROXY("No outstanding request was found for reply from host %s port %d - ID %u",
2424 inet_ntop(packet->src_ipaddr.af,
2425 &packet->src_ipaddr.ipaddr,
2426 buffer, sizeof(buffer)),
2427 packet->src_port, packet->id);
2431 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2432 request->num_proxied_responses++; /* needs to be protected by lock */
2434 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2437 * No reply, BUT the current packet fails verification:
2438 * ignore it. This does the MD5 calculations in the
2439 * server core, but I guess we can fix that later.
2441 if (!request->proxy_reply &&
2442 (rad_verify(packet, request->proxy,
2443 request->home_server->secret) != 0)) {
2444 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2449 * The home server sent us a packet which doesn't match
2450 * something we have: ignore it. This is done only to
2451 * catch the case of broken systems.
2453 if (request->proxy_reply &&
2454 (memcmp(request->proxy_reply->vector,
2456 sizeof(request->proxy_reply->vector)) != 0)) {
2457 RDEBUG2("Ignoring conflicting proxy reply");
2461 gettimeofday(&now, NULL);
2464 * Status-Server packets don't count as real packets.
2466 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2467 listen_socket_t *sock = request->proxy_listener->data;
2469 request->home_server->last_packet_recv = now.tv_sec;
2470 sock->last_packet = now.tv_sec;
2474 * If we have previously seen a reply, ignore the
2477 if (request->proxy_reply) {
2478 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2479 inet_ntop(packet->src_ipaddr.af,
2480 &packet->src_ipaddr.ipaddr,
2481 buffer, sizeof(buffer)),
2482 packet->src_port, packet->id);
2487 * Call the state machine to do something useful with the
2490 request->proxy_reply = talloc_steal(request, packet);
2491 packet->timestamp = now;
2492 request->priority = RAD_LISTEN_PROXY;
2496 * Update the proxy listener stats here, because only one
2497 * thread accesses that at a time. The home_server and
2498 * main proxy_*_stats structures are updated once the
2499 * request is cleaned up.
2501 request->proxy_listener->stats.total_responses++;
2503 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2504 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2506 switch (request->proxy->code) {
2507 case PW_CODE_ACCESS_REQUEST:
2508 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2510 if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2511 request->proxy_listener->stats.total_access_accepts++;
2513 } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2514 request->proxy_listener->stats.total_access_rejects++;
2516 } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2517 request->proxy_listener->stats.total_access_challenges++;
2521 #ifdef WITH_ACCOUNTING
2522 case PW_CODE_ACCOUNTING_REQUEST:
2523 request->proxy_listener->stats.total_responses++;
2524 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2530 case PW_CODE_COA_REQUEST:
2531 request->proxy_listener->stats.total_responses++;
2532 proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2535 case PW_CODE_DISCONNECT_REQUEST:
2536 request->proxy_listener->stats.total_responses++;
2537 proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2547 * We've received a reply. If we hadn't been sending it
2548 * packets for a while, just mark it alive.
2550 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2551 request->home_server->state = HOME_STATE_ALIVE;
2552 request->home_server->response_timeouts = 0;
2556 * Tell the request state machine that we have a proxy
2557 * reply. Depending on the function, this should either
2558 * ignore it, or process it.
2560 request->process(request, FR_ACTION_PROXY_REPLY);
2566 static int setup_post_proxy_fail(REQUEST *request)
2568 DICT_VALUE const *dval = NULL;
2571 VERIFY_REQUEST(request);
2573 if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2574 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2575 "Fail-Authentication");
2577 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2578 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2581 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2582 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2584 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2585 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2588 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2592 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2595 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2599 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2600 if (!vp) vp = radius_paircreate(request, &request->config_items,
2601 PW_POST_PROXY_TYPE, 0);
2602 vp->vp_integer = dval->value;
2607 STATE_MACHINE_DECL(proxy_no_reply)
2609 VERIFY_REQUEST(request);
2611 TRACE_STATE_MACHINE;
2615 case FR_ACTION_TIMER:
2616 case FR_ACTION_PROXY_REPLY:
2617 request_common(request, action);
2621 if (process_proxy_reply(request, NULL)) {
2622 request_finish(request, action);
2624 request_done(request, FR_ACTION_DONE);
2628 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2633 STATE_MACHINE_DECL(proxy_running)
2635 VERIFY_REQUEST(request);
2637 TRACE_STATE_MACHINE;
2641 * Silently ignore duplicate proxy replies.
2643 case FR_ACTION_PROXY_REPLY:
2647 case FR_ACTION_TIMER:
2648 request_common(request, action);
2652 if (process_proxy_reply(request, request->proxy_reply)) {
2653 request->handle(request);
2654 request_finish(request, action);
2656 request_done(request, FR_ACTION_DONE);
2661 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2666 static int request_will_proxy(REQUEST *request)
2668 int rcode, pre_proxy_type = 0;
2669 char const *realmname = NULL;
2670 VALUE_PAIR *vp, *strippedname;
2671 home_server_t *home;
2672 REALM *realm = NULL;
2673 home_pool_t *pool = NULL;
2675 VERIFY_REQUEST(request);
2677 if (!request->root->proxy_requests) return 0;
2678 if (request->packet->dst_port == 0) return 0;
2679 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2680 if (request->in_proxy_hash) return 0;
2683 * FIXME: for 3.0, allow this only for rejects?
2685 if (request->reply->code != 0) return 0;
2687 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2689 realm = realm_find2(vp->vp_strvalue);
2691 REDEBUG2("Cannot proxy to unknown realm %s",
2696 realmname = vp->vp_strvalue;
2699 * Figure out which pool to use.
2701 if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2702 pool = realm->auth_pool;
2704 #ifdef WITH_ACCOUNTING
2705 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2706 pool = realm->acct_pool;
2710 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2711 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2712 pool = realm->coa_pool;
2719 } else if ((vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
2722 switch (request->packet->code) {
2723 case PW_CODE_ACCESS_REQUEST:
2724 pool_type = HOME_TYPE_AUTH;
2727 #ifdef WITH_ACCOUNTING
2728 case PW_CODE_ACCOUNTING_REQUEST:
2729 pool_type = HOME_TYPE_ACCT;
2734 case PW_CODE_COA_REQUEST:
2735 case PW_CODE_DISCONNECT_REQUEST:
2736 pool_type = HOME_TYPE_COA;
2744 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2747 * Send it directly to a home server (i.e. NAS)
2749 } else if (((vp = pairfind(request->config_items, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY)) != NULL) ||
2750 ((vp = pairfind(request->config_items, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL)) {
2753 fr_ipaddr_t dst_ipaddr;
2755 memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2757 if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2758 dst_ipaddr.af = AF_INET;
2759 dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2760 dst_ipaddr.prefix = 32;
2762 dst_ipaddr.af = AF_INET6;
2763 memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2764 dst_ipaddr.prefix = 128;
2767 port = pairfind(request->config_items, PW_PACKET_DST_PORT, 0, TAG_ANY);
2769 dst_port = PW_COA_UDP_PORT;
2771 dst_port = vp->vp_integer;
2775 * Nothing does CoA over TCP.
2777 home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2781 WARN("No such CoA home server %s port %u",
2782 inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2783 (unsigned int) dst_port);
2794 RWDEBUG2("Cancelling proxy as no home pool exists");
2798 if (request->listener->synchronous) {
2799 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2803 request->home_pool = pool;
2805 home = home_server_ldb(realmname, pool, request);
2808 REDEBUG2("Failed to find live home server: Cancelling proxy");
2813 home_server_update_request(home, request);
2817 * Once we've decided to proxy a request, we cannot send
2818 * a CoA packet. So we free up any CoA packet here.
2820 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2824 * Remember that we sent the request to a Realm.
2826 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2829 * Strip the name, if told to.
2831 * Doing it here catches the case of proxied tunneled
2834 if (realm && (realm->strip_realm == true) &&
2835 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2837 * If there's a Stripped-User-Name attribute in
2838 * the request, then use THAT as the User-Name
2839 * for the proxied request, instead of the
2842 * This is done by making a copy of the
2843 * Stripped-User-Name attribute, turning it into
2844 * a User-Name attribute, deleting the
2845 * Stripped-User-Name and User-Name attributes
2846 * from the vps list, and making the new
2847 * User-Name the head of the vps list.
2849 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2852 vp = radius_paircreate(NULL, NULL,
2854 rad_assert(vp != NULL); /* handled by above function */
2855 /* Insert at the START of the list */
2856 /* FIXME: Can't make assumptions about ordering */
2857 fr_cursor_init(&cursor, &vp);
2858 fr_cursor_merge(&cursor, request->proxy->vps);
2859 request->proxy->vps = vp;
2861 pairstrcpy(vp, strippedname->vp_strvalue);
2864 * Do NOT delete Stripped-User-Name.
2869 * If there is no PW_CHAP_CHALLENGE attribute but
2870 * there is a PW_CHAP_PASSWORD we need to add it
2871 * since we can't use the request authenticator
2872 * anymore - we changed it.
2874 if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2875 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2876 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2877 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2878 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2882 * The RFC's say we have to do this, but FreeRADIUS
2885 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2886 pairsprintf(vp, "%u", request->packet->id);
2889 * Should be done BEFORE inserting into proxy hash, as
2890 * pre-proxy may use this information, or change it.
2892 request->proxy->code = request->packet->code;
2895 * Call the pre-proxy routines.
2897 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2899 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2900 /* Must be a validation issue */
2902 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2903 pre_proxy_type = vp->vp_integer;
2907 * home_pool may be NULL when originating CoA packets,
2908 * because they go directly to an IP address.
2910 if (request->home_pool && request->home_pool->virtual_server) {
2911 char const *old_server = request->server;
2913 request->server = request->home_pool->virtual_server;
2915 RDEBUG2("server %s {", request->server);
2917 rcode = process_pre_proxy(pre_proxy_type, request);
2921 request->server = old_server;
2923 rcode = process_pre_proxy(pre_proxy_type, request);
2926 case RLM_MODULE_FAIL:
2927 case RLM_MODULE_INVALID:
2928 case RLM_MODULE_NOTFOUND:
2929 case RLM_MODULE_USERLOCK:
2931 /* FIXME: debug print failed stuff */
2934 case RLM_MODULE_REJECT:
2935 case RLM_MODULE_HANDLED:
2939 * Only proxy the packet if the pre-proxy code succeeded.
2941 case RLM_MODULE_NOOP:
2943 case RLM_MODULE_UPDATED:
2950 static int request_proxy(REQUEST *request, int retransmit)
2954 VERIFY_REQUEST(request);
2956 rad_assert(request->parent == NULL);
2957 rad_assert(request->home_server != NULL);
2959 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2963 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2964 request_done(request->coa, FR_ACTION_DONE);
2969 * The request may need sending to a virtual server.
2970 * This code is more than a little screwed up. The rest
2971 * of the state machine doesn't handle parent / child
2972 * relationships well. i.e. if the child request takes
2973 * too long, the core will mark the *parent* as "stop
2974 * processing". And the child will continue without
2975 * knowing anything...
2977 * So, we have some horrible hacks to get around that.
2979 if (request->home_server->server) {
2982 if (request->packet->dst_port == 0) {
2983 WARN("Cannot proxy an internal request");
2987 DEBUG("Proxying to virtual server %s",
2988 request->home_server->server);
2991 * Packets to virtual serrers don't get
2992 * retransmissions sent to them. And the virtual
2993 * server is run ONLY if we have no child
2994 * threads, or we're running in a child thread.
2996 rad_assert(retransmit == 0);
2997 rad_assert(!spawn_flag || !we_are_master());
2999 fake = request_alloc_fake(request);
3001 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
3002 talloc_free(request->proxy);
3004 fake->server = request->home_server->server;
3005 fake->handle = request->handle;
3006 fake->process = NULL; /* should never be run for anything */
3009 * Run the virtual server.
3011 request_running(fake, FR_ACTION_RUN);
3013 request->proxy = talloc_steal(request, fake->packet);
3014 fake->packet = NULL;
3015 request->proxy_reply = talloc_steal(request, fake->reply);
3021 * No reply code, toss the reply we have,
3022 * and do post-proxy-type Fail.
3024 if (!request->proxy_reply->code) {
3025 TALLOC_FREE(request->proxy_reply);
3026 setup_post_proxy_fail(request);
3030 * Just do the work here, rather than trying to
3031 * run the "decode proxy reply" stuff...
3033 process_proxy_reply(request, request->proxy_reply);
3036 * If we have a reply, run it through the handler.
3038 if (request->proxy_reply) {
3039 request->handle(request); /* to do more post-proxy stuff */
3042 return -1; /* so we call request_finish */
3046 * We're actually sending a proxied packet. Do that now.
3048 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3049 ERROR("Failed to insert request into the proxy list");
3053 rad_assert(request->proxy->id >= 0);
3056 struct timeval *response_window;
3058 response_window = request_response_window(request);
3061 if (request->home_server->tls) {
3062 RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3063 inet_ntop(request->proxy->dst_ipaddr.af,
3064 &request->proxy->dst_ipaddr.ipaddr,
3065 buffer, sizeof(buffer)),
3066 request->proxy->dst_port,
3067 (int) response_window->tv_sec, (int) response_window->tv_usec);
3070 RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3071 inet_ntop(request->proxy->dst_ipaddr.af,
3072 &request->proxy->dst_ipaddr.ipaddr,
3073 buffer, sizeof(buffer)),
3074 request->proxy->dst_port,
3075 (int) response_window->tv_sec, (int) response_window->tv_usec);
3080 gettimeofday(&request->proxy_retransmit, NULL);
3082 request->proxy->timestamp = request->proxy_retransmit;
3084 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3087 * Encode the packet before we do anything else.
3089 request->proxy_listener->encode(request->proxy_listener, request);
3090 debug_packet(request, request->proxy, false);
3093 * Set the state function, then the state, no child, and
3096 request->process = proxy_wait_for_reply;
3097 request->child_state = REQUEST_PROXIED;
3101 * And send the packet.
3103 request->proxy_listener->send(request->proxy_listener, request);
3108 * Proxy the packet as if it was new.
3110 static int request_proxy_anew(REQUEST *request)
3112 home_server_t *home;
3114 VERIFY_REQUEST(request);
3117 * Delete the request from the proxy list.
3119 * The packet list code takes care of ensuring that IDs
3120 * aren't reused until all 256 IDs have been used. So
3121 * there's a 1/256 chance of re-using the same ID when
3122 * we're sending to the same home server. Which is
3125 remove_from_proxy_hash(request);
3128 * Find a live home server for the request.
3130 home = home_server_ldb(NULL, request->home_pool, request);
3132 REDEBUG2("Failed to find live home server for request");
3134 if (setup_post_proxy_fail(request)) {
3135 request_queue_or_run(request, proxy_running);
3137 gettimeofday(&request->reply->timestamp, NULL);
3138 request_cleanup_delay_init(request, NULL);
3142 home_server_update_request(home, request);
3144 if (!insert_into_proxy_hash(request)) {
3145 RPROXY("Failed to insert retransmission into the proxy list");
3146 goto post_proxy_fail;
3150 * Free the old packet, to force re-encoding
3152 talloc_free(request->proxy->data);
3153 request->proxy->data = NULL;
3154 request->proxy->data_len = 0;
3156 #ifdef WITH_ACCOUNTING
3158 * Update the Acct-Delay-Time attribute.
3160 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3163 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
3164 if (!vp) vp = radius_paircreate(request->proxy,
3165 &request->proxy->vps,
3166 PW_ACCT_DELAY_TIME, 0);
3170 gettimeofday(&now, NULL);
3171 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3176 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3181 STATE_MACHINE_DECL(request_ping)
3183 home_server_t *home = request->home_server;
3186 VERIFY_REQUEST(request);
3188 TRACE_STATE_MACHINE;
3192 case FR_ACTION_TIMER:
3193 ERROR("No response to status check %d for home server %s port %d",
3195 inet_ntop(request->proxy->dst_ipaddr.af,
3196 &request->proxy->dst_ipaddr.ipaddr,
3197 buffer, sizeof(buffer)),
3198 request->proxy->dst_port);
3201 case FR_ACTION_PROXY_REPLY:
3202 rad_assert(request->in_proxy_hash);
3204 request->home_server->num_received_pings++;
3205 RPROXY("Received response to status check %d (%d in current sequence)",
3206 request->number, home->num_received_pings);
3209 * Remove the request from any hashes
3212 fr_event_delete(el, &request->ev);
3213 remove_from_proxy_hash(request);
3216 * The control socket may have marked the home server as
3217 * alive. OR, it may have suddenly started responding to
3218 * requests again. If so, don't re-do the "make alive"
3221 if (home->state == HOME_STATE_ALIVE) break;
3224 * It's dead, and we haven't received enough ping
3225 * responses to mark it "alive". Wait a bit.
3227 * If it's zombie, we mark it alive immediately.
3229 if ((home->state == HOME_STATE_IS_DEAD) &&
3230 (home->num_received_pings < home->num_pings_to_alive)) {
3235 * Mark it alive and delete any outstanding
3238 home->state = HOME_STATE_ALIVE;
3239 home->response_timeouts = 0;
3240 exec_trigger(request, home->cs, "home_server.alive", false);
3241 home->currently_outstanding = 0;
3242 home->num_sent_pings = 0;
3243 home->num_received_pings = 0;
3244 gettimeofday(&home->revive_time, NULL);
3247 fr_event_delete(el, &home->ev);
3249 RPROXY("Marking home server %s port %d alive",
3250 inet_ntop(request->proxy->dst_ipaddr.af,
3251 &request->proxy->dst_ipaddr.ipaddr,
3252 buffer, sizeof(buffer)),
3253 request->proxy->dst_port);
3257 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3261 rad_assert(!request->in_request_hash);
3262 rad_assert(request->ev == NULL);
3263 request_done(request, FR_ACTION_DONE);
3267 * Called from start of zombie period, OR after control socket
3268 * marks the home server dead.
3270 static void ping_home_server(void *ctx)
3272 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3275 struct timeval when, now;
3277 if ((home->state == HOME_STATE_ALIVE) ||
3279 (home->proto == IPPROTO_TCP) ||
3281 (home->ev != NULL)) {
3285 gettimeofday(&now, NULL);
3288 * We've run out of zombie time. Mark it dead.
3290 if (home->state == HOME_STATE_ZOMBIE) {
3291 when = home->zombie_period_start;
3292 when.tv_sec += home->zombie_period;
3294 if (timercmp(&when, &now, <)) {
3295 DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3296 mark_home_server_dead(home, &now);
3301 * We're not supposed to be pinging it. Just wake up
3302 * when we're supposed to mark it dead.
3304 if (home->ping_check == HOME_PING_CHECK_NONE) {
3305 if (home->state == HOME_STATE_ZOMBIE) {
3306 when = home->zombie_period_start;
3307 when.tv_sec += home->zombie_period;
3309 INSERT_EVENT(ping_home_server, home);
3313 * Else mark_home_server_dead will set a timer
3314 * for revive_interval.
3320 request = request_alloc(NULL);
3321 if (!request) return;
3322 request->number = request_num_counter++;
3325 request->proxy = rad_alloc(request, true);
3326 rad_assert(request->proxy != NULL);
3328 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
3329 request->proxy->code = PW_CODE_STATUS_SERVER;
3331 pairmake(request->proxy, &request->proxy->vps,
3332 "Message-Authenticator", "0x00", T_OP_SET);
3334 } else if (home->type == HOME_TYPE_AUTH) {
3335 request->proxy->code = PW_CODE_ACCESS_REQUEST;
3337 pairmake(request->proxy, &request->proxy->vps,
3338 "User-Name", home->ping_user_name, T_OP_SET);
3339 pairmake(request->proxy, &request->proxy->vps,
3340 "User-Password", home->ping_user_password, T_OP_SET);
3341 pairmake(request->proxy, &request->proxy->vps,
3342 "Service-Type", "Authenticate-Only", T_OP_SET);
3343 pairmake(request->proxy, &request->proxy->vps,
3344 "Message-Authenticator", "0x00", T_OP_SET);
3347 #ifdef WITH_ACCOUNTING
3348 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
3350 pairmake(request->proxy, &request->proxy->vps,
3351 "User-Name", home->ping_user_name, T_OP_SET);
3352 pairmake(request->proxy, &request->proxy->vps,
3353 "Acct-Status-Type", "Stop", T_OP_SET);
3354 pairmake(request->proxy, &request->proxy->vps,
3355 "Acct-Session-Id", "00000000", T_OP_SET);
3356 vp = pairmake(request->proxy, &request->proxy->vps,
3357 "Event-Timestamp", "0", T_OP_SET);
3358 vp->vp_date = now.tv_sec;
3360 rad_assert("Internal sanity check failed");
3364 vp = pairmake(request->proxy, &request->proxy->vps,
3365 "NAS-Identifier", "", T_OP_SET);
3367 pairsprintf(vp, "Status Check %u. Are you alive?",
3368 home->num_sent_pings);
3371 request->proxy->src_ipaddr = home->src_ipaddr;
3372 request->proxy->dst_ipaddr = home->ipaddr;
3373 request->proxy->dst_port = home->port;
3374 request->home_server = home;
3375 #ifdef DEBUG_STATE_MACHINE
3376 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3377 child_state_names[request->child_state],
3378 child_state_names[REQUEST_DONE]);
3379 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3381 #ifdef HAVE_PTHREAD_H
3382 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3384 request->child_state = REQUEST_DONE;
3385 request->process = request_ping;
3387 rad_assert(request->proxy_listener == NULL);
3389 if (!insert_into_proxy_hash(request)) {
3390 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3393 rad_assert(!request->in_request_hash);
3394 rad_assert(!request->in_proxy_hash);
3395 rad_assert(request->ev == NULL);
3396 talloc_free(request);
3401 * Set up the timer callback.
3404 when.tv_sec += home->ping_timeout;
3406 DEBUG("PING: Waiting %u seconds for response to ping",
3407 home->ping_timeout);
3409 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3410 home->num_sent_pings++;
3412 rad_assert(request->proxy_listener != NULL);
3413 request->proxy_listener->send(request->proxy_listener,
3417 * Add +/- 2s of jitter, as suggested in RFC 3539
3418 * and in the Issues and Fixes draft.
3421 home->when.tv_sec += home->ping_interval;
3423 add_jitter(&home->when);
3425 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3427 INSERT_EVENT(ping_home_server, home);
3430 static void home_trigger(home_server_t *home, char const *trigger)
3432 REQUEST *my_request;
3433 RADIUS_PACKET *my_packet;
3435 my_request = talloc_zero(NULL, REQUEST);
3436 my_packet = talloc_zero(my_request, RADIUS_PACKET);
3437 my_request->proxy = my_packet;
3438 my_packet->dst_ipaddr = home->ipaddr;
3439 my_packet->src_ipaddr = home->src_ipaddr;
3441 exec_trigger(my_request, home->cs, trigger, false);
3442 talloc_free(my_request);
3445 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3452 rad_assert((home->state == HOME_STATE_ALIVE) ||
3453 (home->state == HOME_STATE_UNKNOWN));
3456 if (home->proto == IPPROTO_TCP) {
3457 WARN("Not marking TCP server %s zombie", home->log_name);
3463 * We've received a real packet recently. Don't mark the
3464 * server as zombie until we've received NO packets for a
3465 * while. The "1/4" of zombie period was chosen rather
3466 * arbitrarily. It's a balance between too short, which
3467 * gives quick fail-over and fail-back, or too long,
3468 * where the proxy still sends packets to an unresponsive
3471 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3472 if (home->last_packet_recv >= start) {
3473 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3474 (int) (now->tv_sec - home->last_packet_recv));
3478 home->state = HOME_STATE_ZOMBIE;
3479 home_trigger(home, "home_server.zombie");
3482 * Set the home server to "zombie", as of the time
3485 home->zombie_period_start.tv_sec = start;
3486 home->zombie_period_start.tv_usec = USEC / 2;
3489 fr_event_delete(el, &home->ev);
3490 home->num_sent_pings = 0;
3491 home->num_received_pings = 0;
3493 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3494 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3495 buffer, sizeof(buffer)),
3496 home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3498 ping_home_server(home);
3502 void revive_home_server(void *ctx)
3504 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3508 rad_assert(home->proto != IPPROTO_TCP);
3511 home->state = HOME_STATE_ALIVE;
3512 home->response_timeouts = 0;
3513 home_trigger(home, "home_server.alive");
3514 home->currently_outstanding = 0;
3515 gettimeofday(&home->revive_time, NULL);
3518 * Delete any outstanding events.
3521 if (home->ev) fr_event_delete(el, &home->ev);
3523 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3524 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3525 buffer, sizeof(buffer)),
3529 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3531 int previous_state = home->state;
3535 if (home->proto == IPPROTO_TCP) {
3536 WARN("Not marking TCP server dead");
3541 PROXY( "Marking home server %s port %d as dead.",
3542 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3543 buffer, sizeof(buffer)),
3546 home->state = HOME_STATE_IS_DEAD;
3547 home_trigger(home, "home_server.dead");
3549 if (home->ping_check != HOME_PING_CHECK_NONE) {
3551 * If the control socket marks us dead, start
3552 * pinging. Otherwise, we already started
3553 * pinging when it was marked "zombie".
3555 if (previous_state == HOME_STATE_ALIVE) {
3556 ping_home_server(home);
3558 DEBUG("PING: Already pinging home server %s", home->log_name);
3563 * Revive it after a fixed period of time. This
3564 * is very, very, bad.
3567 home->when.tv_sec += home->revive_interval;
3569 DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3571 INSERT_EVENT(revive_home_server, home);
3575 STATE_MACHINE_DECL(proxy_wait_for_reply)
3577 struct timeval now, when;
3578 struct timeval *response_window = NULL;
3579 home_server_t *home = request->home_server;
3582 VERIFY_REQUEST(request);
3584 TRACE_STATE_MACHINE;
3586 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3587 rad_assert(request->home_server != NULL);
3589 if (request->master_state == REQUEST_STOP_PROCESSING) {
3590 request->child_state = REQUEST_DONE;
3594 gettimeofday(&now, NULL);
3599 * We have a reply, ignore the retransmit.
3601 if (request->proxy_reply) return;
3604 * The request was proxied to a virtual server.
3605 * Ignore the retransmit.
3607 if (request->home_server->server) return;
3609 if ((home->state == HOME_STATE_IS_DEAD) ||
3610 !request->proxy_listener ||
3611 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3612 request_proxy_anew(request);
3617 if (home->proto == IPPROTO_TCP) {
3618 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3619 inet_ntop(request->proxy->dst_ipaddr.af,
3620 &request->proxy->dst_ipaddr.ipaddr,
3621 buffer, sizeof(buffer)),
3622 request->proxy->dst_port,
3623 request->proxy->id);
3629 * More than one retransmit a second is stupid,
3630 * and should be suppressed by the proxy.
3632 when = request->proxy_retransmit;
3635 if (timercmp(&now, &when, <)) {
3636 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3637 inet_ntop(request->proxy->dst_ipaddr.af,
3638 &request->proxy->dst_ipaddr.ipaddr,
3639 buffer, sizeof(buffer)),
3640 request->proxy->dst_port,
3641 request->proxy->id);
3645 #ifdef WITH_ACCOUNTING
3647 * If we update the Acct-Delay-Time, we need to
3650 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3651 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3652 request_proxy_anew(request);
3657 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3658 inet_ntop(request->proxy->dst_ipaddr.af,
3659 &request->proxy->dst_ipaddr.ipaddr,
3660 buffer, sizeof(buffer)),
3661 request->proxy->dst_port,
3662 request->proxy->id);
3663 request->num_proxied_requests++;
3665 rad_assert(request->proxy_listener != NULL);
3666 FR_STATS_TYPE_INC(home->stats.total_requests);
3667 home->last_packet_sent = now.tv_sec;
3668 request->proxy_retransmit = now;
3669 request->proxy_listener->send(request->proxy_listener, request);
3670 debug_packet(request, request->proxy, false);
3673 case FR_ACTION_TIMER:
3674 response_window = request_response_window(request);
3677 if (!request->proxy_listener ||
3678 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3679 remove_from_proxy_hash(request);
3681 when = request->packet->timestamp;
3682 when.tv_sec += request->root->max_request_time;
3684 if (timercmp(&when, &now, >)) {
3685 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3686 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3693 * Wake up "response_window" time in the future.
3694 * i.e. when MY packet hasn't received a response.
3696 * Note that we DO NOT mark the home server as
3697 * zombie if it doesn't respond to us. It may be
3698 * responding to other (better looking) packets.
3700 when = request->proxy->timestamp;
3701 timeradd(&when, response_window, &when);
3704 * Not at the response window. Set the timer for
3707 if (timercmp(&when, &now, >)) {
3708 struct timeval diff;
3709 timersub(&when, &now, &diff);
3711 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3712 (int) diff.tv_sec, (int) diff.tv_usec);
3713 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3718 RDEBUG("No proxy response, giving up on request and marking it done");
3721 * If we haven't received any packets for
3722 * "response_window", then mark the home server
3725 * If the connection is TCP, then another
3726 * "watchdog timer" function takes care of pings,
3727 * etc. So we don't need to do it here.
3729 * This check should really be part of a home
3730 * server state machine.
3732 if (((home->state == HOME_STATE_ALIVE) ||
3733 (home->state == HOME_STATE_UNKNOWN))
3735 && (home->proto != IPPROTO_TCP)
3738 home->response_timeouts++;
3739 if (home->response_timeouts >= home->max_response_timeouts)
3740 mark_home_server_zombie(home, &now, response_window);
3743 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3744 if (home->type == HOME_TYPE_AUTH) {
3745 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3746 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3749 else if (home->type == HOME_TYPE_ACCT) {
3750 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3751 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3756 * There was no response within the window. Stop
3757 * the request. If the client retransmitted, it
3758 * may have failed over to another home server.
3759 * But that one may be dead, too.
3761 * The extra verbose message if we have a username,
3762 * is extremely useful if the proxy is part of a chain
3763 * and the final home server, is not the one we're
3766 if (request->username) {
3767 RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3768 "server %s port %d",
3769 request->username->vp_strvalue,
3770 inet_ntop(request->proxy->dst_ipaddr.af,
3771 &request->proxy->dst_ipaddr.ipaddr,
3772 buffer, sizeof(buffer)),
3773 request->proxy->dst_port);
3775 RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3776 inet_ntop(request->proxy->dst_ipaddr.af,
3777 &request->proxy->dst_ipaddr.ipaddr,
3778 buffer, sizeof(buffer)),
3779 request->proxy->dst_port);
3782 if (setup_post_proxy_fail(request)) {
3783 request_queue_or_run(request, proxy_no_reply);
3785 gettimeofday(&request->reply->timestamp, NULL);
3786 request_cleanup_delay_init(request, NULL);
3791 * We received a new reply. Go process it.
3793 case FR_ACTION_PROXY_REPLY:
3794 request_queue_or_run(request, proxy_running);
3798 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3802 #endif /* WITH_PROXY */
3804 /***********************************************************************
3808 ***********************************************************************/
3810 static int null_handler(UNUSED REQUEST *request)
3816 * See if we need to originate a CoA request.
3818 static void request_coa_originate(REQUEST *request)
3820 int rcode, pre_proxy_type = 0;
3826 VERIFY_REQUEST(request);
3828 rad_assert(request->coa != NULL);
3829 rad_assert(request->proxy == NULL);
3830 rad_assert(!request->in_proxy_hash);
3831 rad_assert(request->proxy_reply == NULL);
3834 * Check whether we want to originate one, or cancel one.
3836 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3838 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3842 if (vp->vp_integer == 0) {
3844 TALLOC_FREE(request->coa);
3852 * src_ipaddr will be set up in proxy_encode.
3854 memset(&ipaddr, 0, sizeof(ipaddr));
3855 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3857 ipaddr.af = AF_INET;
3858 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3860 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3861 ipaddr.af = AF_INET6;
3862 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3863 ipaddr.prefix = 128;
3864 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3865 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3867 if (!coa->home_pool) {
3868 RWDEBUG2("No such home_server_pool %s",
3874 * Prefer the pool to one server
3876 } else if (request->client->coa_pool) {
3877 coa->home_pool = request->client->coa_pool;
3879 } else if (request->client->coa_server) {
3880 coa->home_server = request->client->coa_server;
3884 * If all else fails, send it to the client that
3885 * originated this request.
3887 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3891 * Use the pool, if it exists.
3893 if (coa->home_pool) {
3894 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3895 if (!coa->home_server) {
3896 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3899 home_server_update_request(coa->home_server, coa);
3901 } else if (!coa->home_server) {
3902 uint16_t port = PW_COA_UDP_PORT;
3904 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3905 if (vp) port = vp->vp_integer;
3907 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3908 if (!coa->home_server) {
3909 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3910 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3911 buffer, sizeof(buffer)), port);
3916 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3918 switch (vp->vp_integer) {
3919 case PW_CODE_COA_REQUEST:
3920 case PW_CODE_DISCONNECT_REQUEST:
3921 coa->proxy->code = vp->vp_integer;
3925 DEBUG("Cannot set CoA Packet-Type to code %d",
3931 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3934 * The rest of the server code assumes that
3935 * request->packet && request->reply exist. Copy them
3936 * from the original request.
3938 rad_assert(coa->packet != NULL);
3939 rad_assert(coa->packet->vps == NULL);
3941 coa->packet = rad_copy_packet(coa, request->packet);
3942 coa->reply = rad_copy_packet(coa, request->reply);
3944 coa->config_items = paircopy(coa, request->config_items);
3945 coa->num_coa_requests = 0;
3946 coa->handle = null_handler;
3947 coa->number = request->number; /* it's associated with the same request */
3950 * Call the pre-proxy routines.
3952 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3954 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3955 /* Must be a validation issue */
3957 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3958 pre_proxy_type = vp->vp_integer;
3961 if (coa->home_pool && coa->home_pool->virtual_server) {
3962 char const *old_server = coa->server;
3964 coa->server = coa->home_pool->virtual_server;
3965 RDEBUG2("server %s {", coa->server);
3967 rcode = process_pre_proxy(pre_proxy_type, coa);
3970 coa->server = old_server;
3972 rcode = process_pre_proxy(pre_proxy_type, coa);
3979 * Only send the CoA packet if the pre-proxy code succeeded.
3981 case RLM_MODULE_NOOP:
3983 case RLM_MODULE_UPDATED:
3988 * Source IP / port is set when the proxy socket
3991 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3992 coa->proxy->dst_port = coa->home_server->port;
3994 if (!insert_into_proxy_hash(coa)) {
3995 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4000 * We CANNOT divorce the CoA request from the parent
4001 * request. This function is running in a child thread,
4002 * and we need access to the main event loop in order to
4003 * to add the timers for the CoA packet.
4005 * Instead, we wait for the timer on the parent request
4008 gettimeofday(&coa->proxy->timestamp, NULL);
4009 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4010 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4011 coa->delay = 0; /* need to calculate a new delay */
4014 * If requested, put a State attribute into the packet,
4015 * and cache the VPS.
4017 fr_state_put_vps(coa, NULL, coa->packet);
4020 * Encode the packet before we do anything else.
4022 coa->proxy_listener->encode(coa->proxy_listener, coa);
4023 debug_packet(coa, coa->proxy, false);
4025 #ifdef DEBUG_STATE_MACHINE
4026 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4027 child_state_names[request->child_state],
4028 child_state_names[REQUEST_PROXIED]);
4032 * Set the state function, then the state, no child, and
4035 coa->process = coa_wait_for_reply;
4036 coa->child_state = REQUEST_PROXIED;
4038 #ifdef HAVE_PTHREAD_H
4039 coa->child_pid = NO_SUCH_CHILD_PID;
4043 * And send the packet.
4045 coa->proxy_listener->send(coa->proxy_listener, coa);
4049 static void coa_timer(REQUEST *request)
4051 uint32_t delay, frac;
4052 struct timeval now, when, mrd;
4054 VERIFY_REQUEST(request);
4056 rad_assert(request->parent == NULL);
4058 if (request->proxy_reply) {
4059 request_process_timer(request);
4062 gettimeofday(&now, NULL);
4064 if (request->delay == 0) {
4066 * Implement re-transmit algorithm as per RFC 5080
4069 * We want IRT + RAND*IRT
4070 * or 0.9 IRT + rand(0,.2) IRT
4072 * 2^20 ~ USEC, and we want 2.
4073 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4075 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4076 request->delay = delay * request->home_server->coa_irt;
4077 delay = request->home_server->coa_irt * USEC;
4078 delay -= delay / 10;
4079 delay += request->delay;
4080 request->delay = delay;
4082 when = request->proxy->timestamp;
4083 tv_add(&when, delay);
4085 if (timercmp(&when, &now, >)) {
4086 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4092 * Retransmit CoA request.
4096 * Cap count at MRC, if it is non-zero.
4098 if (request->home_server->coa_mrc &&
4099 (request->num_coa_requests >= request->home_server->coa_mrc)) {
4102 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4104 inet_ntop(request->proxy->dst_ipaddr.af,
4105 &request->proxy->dst_ipaddr.ipaddr,
4106 buffer, sizeof(buffer)),
4107 request->proxy->dst_port);
4109 if (setup_post_proxy_fail(request)) {
4110 request_queue_or_run(request, coa_no_reply);
4112 request_done(request, FR_ACTION_DONE);
4118 * RFC 5080 Section 2.2.1
4120 * RT = 2*RTprev + RAND*RTprev
4121 * = 1.9 * RTprev + rand(0,.2) * RTprev
4122 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4125 delay ^= (delay >> 16);
4127 frac = request->delay / 5;
4128 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4130 delay += (2 * request->delay) - (request->delay / 10);
4133 * Cap delay at MRT, if MRT is non-zero.
4135 if (request->home_server->coa_mrt &&
4136 (delay > (request->home_server->coa_mrt * USEC))) {
4137 int mrt_usec = request->home_server->coa_mrt * USEC;
4140 * delay = MRT + RAND * MRT
4141 * = 0.9 MRT + rand(0,.2) * MRT
4144 delay ^= (delay >> 15);
4146 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4147 delay += mrt_usec - (mrt_usec / 10);
4150 request->delay = delay;
4152 tv_add(&when, request->delay);
4153 mrd = request->proxy->timestamp;
4154 mrd.tv_sec += request->home_server->coa_mrd;
4157 * Cap duration at MRD.
4159 if (timercmp(&mrd, &when, <)) {
4162 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4164 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4166 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
4169 * Status servers don't count as real packets sent.
4171 request->proxy_listener->send(request->proxy_listener,
4175 STATE_MACHINE_DECL(coa_wait_for_reply)
4177 VERIFY_REQUEST(request);
4179 TRACE_STATE_MACHINE;
4182 case FR_ACTION_TIMER:
4184 * This is big enough to be in it's own function.
4189 case FR_ACTION_PROXY_REPLY:
4190 rad_assert(request->parent != NULL);
4191 rad_assert(request->parent->coa == request);
4192 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
4193 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
4194 rad_assert(request->process != NULL);
4196 coa_separate(request, FR_ACTION_PROXY_REPLY);
4198 rad_assert(request->parent == NULL);
4201 * Do NOT get the session-state VPs. The request
4202 * already contains the packet and the reply, so
4203 * there's no more state we need to maintain.
4205 * The state for "originate CoA" is for the next
4206 * Access-Request, not for the CoA ACK/BAK
4209 request_queue_or_run(request, coa_running);
4213 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4218 STATE_MACHINE_DECL(coa_separate)
4220 VERIFY_REQUEST(request);
4222 TRACE_STATE_MACHINE;
4224 rad_assert(request->parent != NULL);
4225 rad_assert(request->parent->coa == request);
4226 rad_assert(request->ev == NULL);
4227 rad_assert(!request->in_request_hash);
4228 rad_assert(request->coa == NULL);
4230 rad_assert(request->proxy_reply || request->proxy_listener);
4232 (void) talloc_steal(NULL, request);
4233 request->parent->coa = NULL;
4234 request->parent = NULL;
4237 * Most of the time we're called for timers.
4240 case FR_ACTION_TIMER:
4241 request->process(request, FR_ACTION_TIMER);
4245 * Set up the main timers.
4247 case FR_ACTION_PROXY_REPLY:
4248 request->child_state = REQUEST_QUEUED;
4249 request_process_timer(request);
4253 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4258 STATE_MACHINE_DECL(coa_no_reply)
4262 VERIFY_REQUEST(request);
4264 TRACE_STATE_MACHINE;
4267 case FR_ACTION_TIMER:
4268 request_common(request, action);
4271 case FR_ACTION_PROXY_REPLY: /* too late! */
4272 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4273 inet_ntop(request->proxy->src_ipaddr.af,
4274 &request->proxy->src_ipaddr.ipaddr,
4275 buffer, sizeof(buffer)),
4276 request->proxy->dst_port, request->proxy->id);
4281 * FIXME: do recv_coa Fail
4283 (void) process_proxy_reply(request, NULL);
4284 request_done(request, FR_ACTION_DONE);
4288 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4293 STATE_MACHINE_DECL(coa_running)
4295 VERIFY_REQUEST(request);
4297 TRACE_STATE_MACHINE;
4301 * Silently ignore duplicate proxy replies.
4303 case FR_ACTION_PROXY_REPLY:
4306 case FR_ACTION_TIMER:
4307 request_process_timer(request);
4311 if (process_proxy_reply(request, request->proxy_reply)) {
4312 request->handle(request);
4313 request_finish(request, action);
4315 request_done(request, FR_ACTION_DONE);
4320 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4324 #endif /* WITH_COA */
4326 /***********************************************************************
4328 * End of the State machine. Start of additional helper code.
4330 ***********************************************************************/
4332 /***********************************************************************
4336 ***********************************************************************/
4337 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4339 rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4341 rad_assert(xel == el);
4343 if ((listener->fd < 0)
4345 #ifndef WITH_DETAIL_THREAD
4346 && (listener->type != RAD_LISTEN_DETAIL)
4352 listener->print(listener, buffer, sizeof(buffer));
4353 ERROR("FATAL: Asked to read from closed socket: %s",
4356 rad_panic("Socket was closed on us!");
4360 listener->recv(listener);
4364 #ifdef WITH_DETAIL_THREAD
4367 * This function is called periodically to see if this detail
4368 * file is available for reading.
4370 static void event_poll_detail(void *ctx)
4373 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4374 struct timeval when, now;
4375 listen_detail_t *detail = this->data;
4377 rad_assert(this->type == RAD_LISTEN_DETAIL);
4380 event_socket_handler(el, this->fd, this);
4382 fr_event_now(el, &now);
4386 * Backdoor API to get the delay until the next poll
4389 delay = this->encode(this, NULL);
4390 if (delay == 0) goto redo;
4392 tv_add(&when, delay);
4395 if (!fr_event_insert(el, event_poll_detail, this,
4396 &when, &detail->ev)) {
4397 ERROR("Failed creating handler");
4401 #endif /* WITH_DETAIL_THREAD */
4402 #endif /* WITH_DETAIL */
4404 static void event_status(struct timeval *wake)
4406 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4410 if (debug_flag == 0) {
4412 INFO("Ready to process requests");
4413 just_started = false;
4419 INFO("Ready to process requests");
4421 } else if ((wake->tv_sec != 0) ||
4422 (wake->tv_usec >= 100000)) {
4423 DEBUG("Waking up in %d.%01u seconds.",
4424 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4429 * FIXME: Put this somewhere else, where it isn't called
4430 * all of the time...
4433 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4435 * If there are no child threads, then there may
4436 * be child processes. In that case, wait for
4437 * their exit status, and throw that exit status
4438 * away. This helps get rid of zxombie children.
4440 while (waitpid(-1, &argval, WNOHANG) > 0) {
4448 static void listener_free_cb(void *ctx)
4450 rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4453 if (this->count > 0) {
4454 struct timeval when;
4455 listen_socket_t *sock = this->data;
4457 fr_event_now(el, &when);
4461 if (!fr_event_insert(el, listener_free_cb, this, &when,
4463 rad_panic("Failed to insert event");
4470 * It's all free, close the socket.
4473 this->print(this, buffer, sizeof(buffer));
4474 DEBUG("... cleaning up socket %s", buffer);
4475 rad_assert(this->next == NULL);
4481 static int proxy_eol_cb(void *ctx, void *data)
4483 struct timeval when;
4484 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4486 if (request->proxy_listener != ctx) return 0;
4489 * We don't care if it's being processed in a child thread.
4492 #ifdef WITH_ACCOUNTING
4494 * Accounting packets should be deleted immediately.
4495 * They will never be retransmitted by the client.
4497 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4498 RDEBUG("Stopping request due to failed connection to home server");
4499 request->master_state = REQUEST_STOP_PROCESSING;
4504 * Reset the timer to be now, so that the request is
4505 * quickly updated. But spread the requests randomly
4506 * over the next second, so that we don't overload the
4509 fr_event_now(el, &when);
4510 tv_add(&when, fr_rand() % USEC);
4511 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4514 * Don't delete it from the list.
4520 static int event_new_fd(rad_listen_t *this)
4526 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4528 this->print(this, buffer, sizeof(buffer));
4530 if (this->status == RAD_LISTEN_STATUS_INIT) {
4531 listen_socket_t *sock = this->data;
4533 rad_assert(sock != NULL);
4535 DEBUG("Listening on %s", buffer);
4538 } else if (this->type == RAD_LISTEN_PROXY) {
4539 home_server_t *home;
4542 if (!home || !home->limit.max_connections) {
4543 INFO(" ... adding new socket %s", buffer);
4545 INFO(" ... adding new socket %s (%u of %u)", buffer,
4546 home->limit.num_connections, home->limit.max_connections);
4551 INFO(" ... adding new socket %s", buffer);
4554 switch (this->type) {
4557 * Detail files are always known, and aren't
4558 * put into the socket event loop.
4560 case RAD_LISTEN_DETAIL:
4561 this->status = RAD_LISTEN_STATUS_KNOWN;
4563 #ifndef WITH_DETAIL_THREAD
4565 * Set up the first poll interval.
4567 event_poll_detail(this);
4570 break; /* add the FD to the list */
4572 #endif /* WITH_DETAIL */
4576 * Add it to the list of sockets we can use.
4577 * Server sockets (i.e. auth/acct) are never
4578 * added to the packet list.
4580 case RAD_LISTEN_PROXY:
4582 rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4585 * Add timers to outgoing child sockets, if necessary.
4587 if (sock->proto == IPPROTO_TCP && sock->opened &&
4588 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4589 struct timeval when;
4591 when.tv_sec = sock->opened + 1;
4595 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4597 rad_panic("Failed to insert event");
4602 #endif /* WITH_PROXY */
4605 * FIXME: put idle timers on command sockets.
4611 * Add timers to incoming child sockets, if necessary.
4613 if (sock->proto == IPPROTO_TCP && sock->opened &&
4614 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4615 struct timeval when;
4617 when.tv_sec = sock->opened + 1;
4621 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4623 ERROR("Failed adding timer for socket: %s", fr_strerror());
4629 } /* switch over listener types */
4632 * All sockets: add the FD to the event handler.
4634 if (!fr_event_fd_insert(el, 0, this->fd,
4635 event_socket_handler, this)) {
4636 ERROR("Failed adding event handler for socket: %s", fr_strerror());
4640 this->status = RAD_LISTEN_STATUS_KNOWN;
4646 * Stop using this socket, if at all possible.
4648 if (this->status == RAD_LISTEN_STATUS_EOL) {
4650 * Remove it from the list of live FD's.
4652 fr_event_fd_delete(el, 0, this->fd);
4656 * Proxy sockets get frozen, so that we don't use
4657 * them for new requests. But we do keep them
4658 * open to listen for replies to requests we had
4661 if (this->type == RAD_LISTEN_PROXY) {
4662 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4663 if (!fr_packet_list_socket_freeze(proxy_list,
4665 ERROR("Fatal error freezing socket: %s", fr_strerror());
4669 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4670 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4675 * Requests are still using the socket. Wait for
4678 if (this->count > 0) {
4679 struct timeval when;
4680 listen_socket_t *sock = this->data;
4683 * Try again to clean up the socket in 30
4686 gettimeofday(&when, NULL);
4690 if (!fr_event_insert(el,
4691 (fr_event_callback_t) event_new_fd,
4692 this, &when, &sock->ev)) {
4693 rad_panic("Failed to insert event");
4700 * No one is using the socket. We can remove it now.
4702 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4703 } /* socket is at EOL */
4709 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4712 listen_socket_t *sock = this->data;
4714 struct timeval when;
4717 * Re-open the socket, pointing it to /dev/null.
4718 * This means that all writes proceed without
4719 * blocking, and all reads return "no data".
4721 * This leaves the socket active, so any child
4722 * threads won't go insane. But it means that
4723 * they cannot send or receive any packets.
4725 * This is EXTRA work in the normal case, when
4726 * sockets are closed without error. But it lets
4727 * us have one simple processing method for all
4730 devnull = open("/dev/null", O_RDWR);
4732 ERROR("FATAL failure opening /dev/null: %s",
4733 fr_syserror(errno));
4736 if (dup2(devnull, this->fd) < 0) {
4737 ERROR("FATAL failure closing socket: %s",
4738 fr_syserror(errno));
4744 rad_assert(this->type != RAD_LISTEN_DETAIL);
4750 * The socket is dead. Force all proxied packets
4751 * to stop using it. And then remove it from the
4752 * list of outgoing sockets.
4754 if (this->type == RAD_LISTEN_PROXY) {
4755 home_server_t *home;
4758 if (!home || !home->limit.max_connections) {
4759 INFO(" ... shutting down socket %s", buffer);
4761 INFO(" ... shutting down socket %s (%u of %u)", buffer,
4762 home->limit.num_connections, home->limit.max_connections);
4765 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4766 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4768 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4769 ERROR("Fatal error removing socket %s: %s",
4770 buffer, fr_strerror());
4773 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4777 INFO(" ... shutting down socket %s", buffer);
4780 * EOL all requests using this socket.
4782 rbtree_walk(pl, RBTREE_DELETE_ORDER, eol_listener, this);
4786 * No child threads, clean it up now.
4790 if (sock->ev) fr_event_delete(el, &sock->ev);
4796 * Wait until all requests using this socket are done.
4798 gettimeofday(&when, NULL);
4802 if (!fr_event_insert(el, listener_free_cb, this, &when,
4804 rad_panic("Failed to insert event");
4807 #endif /* WITH_TCP */
4812 /***********************************************************************
4816 ***********************************************************************/
4818 static void handle_signal_self(int flag)
4822 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4823 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4824 INFO("Signalled to exit");
4825 fr_event_loop_exit(el, 1);
4827 INFO("Signalled to terminate");
4828 fr_event_loop_exit(el, 2);
4832 } /* else exit/term flags weren't set */
4835 * Tell the even loop to stop processing.
4837 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4839 static time_t last_hup = 0;
4842 if ((int) (when - last_hup) < 5) {
4843 INFO("Ignoring HUP (less than 5s since last one)");
4847 INFO("Received HUP signal");
4851 exec_trigger(NULL, NULL, "server.signal.hup", true);
4852 fr_event_loop_exit(el, 0x80);
4856 #ifndef WITH_DETAIL_THREAD
4857 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4861 * FIXME: O(N) loops suck.
4863 for (this = main_config.listen;
4865 this = this->next) {
4866 if (this->type != RAD_LISTEN_DETAIL) continue;
4869 * This one didn't send the signal, skip
4872 if (!this->decode(this, NULL)) continue;
4875 * Go service the interrupt.
4877 event_poll_detail(this);
4885 #ifdef HAVE_PTHREAD_H
4887 * There are new listeners in the list. Run
4888 * event_new_fd() on them.
4890 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4891 rad_listen_t *this, *next;
4893 FD_MUTEX_LOCK(&fd_mutex);
4896 * FIXME: unlock the mutex before calling
4899 for (this = new_listeners; this != NULL; this = next) {
4906 new_listeners = NULL;
4907 FD_MUTEX_UNLOCK(&fd_mutex);
4909 #endif /* HAVE_PTHREAD_H */
4910 #endif /* WITH_PROXY */
4911 #endif /* WITH_TCP */
4914 #ifndef HAVE_PTHREAD_H
4915 void radius_signal_self(int flag)
4917 return handle_signal_self(flag);
4921 static int self_pipe[2] = { -1, -1 };
4924 * Inform ourselves that we received a signal.
4926 void radius_signal_self(int flag)
4932 * The read MUST be non-blocking for this to work.
4934 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4938 for (i = 0; i < rcode; i++) {
4939 buffer[0] |= buffer[i];
4947 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4951 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4952 UNUSED int fd, UNUSED void *ctx)
4957 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4958 if (rcode <= 0) return;
4961 * Merge pending signals.
4963 for (i = 0; i < rcode; i++) {
4964 buffer[0] |= buffer[i];
4967 handle_signal_self(buffer[0]);
4969 #endif /* HAVE_PTHREAD_H */
4971 /***********************************************************************
4973 * Bootstrapping code.
4975 ***********************************************************************/
4978 * Externally-visibly functions.
4980 int radius_event_init(TALLOC_CTX *ctx) {
4981 el = fr_event_list_create(ctx, event_status);
4987 static int packet_entry_cmp(void const *one, void const *two)
4989 RADIUS_PACKET const * const *a = one;
4990 RADIUS_PACKET const * const *b = two;
4992 return fr_packet_cmp(*a, *b);
4996 int radius_event_start(CONF_SECTION *cs, bool have_children)
4998 rad_listen_t *head = NULL;
5000 if (fr_start_time != (time_t)-1) return 0;
5002 time(&fr_start_time);
5004 if (!check_config) {
5006 * radius_event_init() must be called first
5010 pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5011 if (!pl) return 0; /* leak el */
5014 request_num_counter = 0;
5017 if (main_config.proxy_requests) {
5019 * Create the tree for managing proxied requests and
5022 proxy_list = fr_packet_list_create(1);
5023 if (!proxy_list) return 0;
5025 #ifdef HAVE_PTHREAD_H
5026 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5027 ERROR("FATAL: Failed to initialize proxy mutex: %s",
5028 fr_syserror(errno));
5034 * The "init_delay" is set to "response_window".
5035 * Reset it to half of "response_window" in order
5036 * to give the event loop enough time to service
5037 * the event before hitting "response_window".
5039 main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5040 main_config.init_delay.tv_usec >>= 1;
5041 main_config.init_delay.tv_sec >>= 1;
5043 proxy_ctx = talloc_init("proxy");
5048 * Move all of the thread calls to this file?
5050 * It may be best for the mutexes to be in this file...
5052 spawn_flag = have_children;
5054 #ifdef HAVE_PTHREAD_H
5055 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5058 * Initialize the threads ONLY if we're spawning, AND
5059 * we're running normally.
5061 if (have_children && !check_config &&
5062 (thread_pool_init(cs, &spawn_flag) < 0)) {
5068 DEBUG("%s: #### Skipping IP addresses and Ports ####",
5070 if (listen_init(cs, &head, spawn_flag) < 0) {
5077 #ifdef HAVE_PTHREAD_H
5079 * Child threads need a pipe to signal us, as do the
5082 if (pipe(self_pipe) < 0) {
5083 ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5086 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5087 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5088 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5091 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5092 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5093 ERROR("Error setting internal flags: %s", fr_syserror(errno));
5096 DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5098 if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5099 ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5104 DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5107 * The server temporarily switches to an unprivileged
5108 * user very early in the bootstrapping process.
5109 * However, some sockets MAY require privileged access
5110 * (bind to device, or to port < 1024, or to raw
5111 * sockets). Those sockets need to call suid up/down
5112 * themselves around the functions that need a privileged
5115 if (listen_init(cs, &head, spawn_flag) < 0) {
5119 main_config.listen = head;
5122 * At this point, no one has any business *ever* going
5125 rad_suid_down_permanent();
5132 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5134 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5136 VERIFY_REQUEST(request);
5138 request->master_state = REQUEST_STOP_PROCESSING;
5140 #ifdef HAVE_PTHREAD_H
5141 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5145 * If it's queued we can't delete it from the queue.
5147 * Otherwise, it's OK to delete it. Even RUNNING, because
5148 * that will get caught by the check above.
5150 if (request->child_state == REQUEST_QUEUED) return 0;
5152 request->in_proxy_hash = false;
5154 if (!request->in_request_hash) {
5155 request_done(request, FR_ACTION_DONE);
5159 * Delete it from the list.
5166 static int request_delete_cb(UNUSED void *ctx, void *data)
5168 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5170 VERIFY_REQUEST(request);
5172 request->master_state = REQUEST_STOP_PROCESSING;
5175 * Not done, or the child thread is still processing it.
5177 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5179 #ifdef HAVE_PTHREAD_H
5180 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5184 rad_assert(request->in_proxy_hash == false);
5187 request->in_request_hash = false;
5189 if (request->ev) fr_event_delete(el, &request->ev);
5191 if (main_config.memory_report) {
5192 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5193 request->packet->id,
5194 (unsigned int) (request->timestamp - fr_start_time));
5199 rad_assert(!request->coa->in_proxy_hash);
5203 request_free(request);
5206 * Delete it from the list, and continue;
5212 void radius_event_free(void)
5218 * There are requests in the proxy hash that aren't
5219 * referenced from anywhere else. Remove them first.
5222 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5226 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5230 * Now that all requests have been marked "please stop",
5231 * ensure that all of the threads have exited.
5233 #ifdef HAVE_PTHREAD_H
5238 * Walk the lists again, ensuring that all
5239 * requests are done.
5241 if (main_config.memory_report) {
5246 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5247 num = fr_packet_list_num_elements(proxy_list);
5249 ERROR("Proxy list has %d requests still in it.", num);
5254 rbtree_walk(pl, RBTREE_DELETE_ORDER, request_delete_cb, NULL);
5255 num = rbtree_num_elements(pl);
5257 ERROR("Request list has %d requests still in it.", num);
5266 fr_packet_list_free(proxy_list);
5269 if (proxy_ctx) talloc_free(proxy_ctx);
5274 if (debug_condition) talloc_free(debug_condition);
5277 int radius_event_process(void)
5281 return fr_event_loop(el);