2 * event.c Server event handling
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2007 The FreeRADIUS server project
21 * Copyright 2007 Alan DeKok <aland@deployingradius.com>
24 #include <freeradius-devel/ident.h>
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/detail.h>
32 #include <freeradius-devel/rad_assert.h>
37 #ifdef HAVE_SYS_WAIT_H
38 # include <sys/wait.h>
41 #define USEC (1000000)
43 extern pid_t radius_pid;
45 extern int check_config;
46 extern char *debug_condition;
49 * Ridiculous amounts of local state.
51 static fr_event_list_t *el = NULL;
52 static fr_packet_list_t *pl = NULL;
53 static int request_num_counter = 0;
54 static struct timeval now;
56 static int have_children;
57 static int just_started = TRUE;
61 #define WITH_SELF_PIPE (1)
66 static int self_pipe[2];
71 static pthread_mutex_t proxy_mutex;
74 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
75 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
77 #define NO_CHILD_THREAD (0)
80 * This is easier than ifdef's throughout the code.
82 #define PTHREAD_MUTEX_LOCK(_x)
83 #define PTHREAD_MUTEX_UNLOCK(_x)
84 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
86 radius_handle_request(request, fun);
91 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
94 static fr_packet_list_t *proxy_list = NULL;
97 * We keep the proxy FD's here. The RADIUS Id's are marked
98 * "allocated" per Id, via a bit per proxy FD.
100 static int proxy_all_used = FALSE;
101 static int proxy_fds[32];
102 static rad_listen_t *proxy_listeners[32];
103 static void check_for_zombie_home_server(REQUEST *request);
104 static void remove_from_proxy_hash(REQUEST *request);
106 #define remove_from_proxy_hash(foo)
109 static void request_post_handler(REQUEST *request);
110 static void wait_a_bit(void *ctx);
111 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
113 static void event_poll_detail(void *ctx);
116 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
119 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
123 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
126 static void tv_add(struct timeval *tv, int usec_delay)
128 if (usec_delay >= USEC) {
129 tv->tv_sec += usec_delay / USEC;
132 tv->tv_usec += usec_delay;
134 if (tv->tv_usec >= USEC) {
135 tv->tv_sec += tv->tv_usec / USEC;
140 static void remove_from_request_hash(REQUEST *request)
142 if (!request->in_request_hash) return;
144 fr_packet_list_yank(pl, request->packet);
145 request->in_request_hash = FALSE;
147 request_stats_final(request);
151 static void ev_request_free(REQUEST **prequest)
155 if (!prequest || !*prequest) return;
162 * Divorce the child from the parent first,
163 * then clean up the child.
165 request->coa->parent = NULL;
166 ev_request_free(&request->coa);
170 * Divorce the parent from the child, and leave the
171 * parent still alive.
173 if (request->parent && (request->parent->coa == request)) {
174 request->parent->coa = NULL;
178 if (request->ev) fr_event_delete(el, &request->ev);
180 if (request->in_proxy_hash) remove_from_proxy_hash(request);
182 if (request->in_request_hash) remove_from_request_hash(request);
184 rad_assert(request->child_state != REQUEST_QUEUED);
186 request_free(prequest);
190 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
192 RADIUS_PACKET **proxy_p;
195 PTHREAD_MUTEX_LOCK(&proxy_mutex);
196 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
199 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
203 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
206 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
210 request->num_proxied_responses++;
213 * Catch the most common case of everything working
216 if (request->num_proxied_requests == request->num_proxied_responses) {
217 fr_packet_list_yank(proxy_list, request->proxy);
218 fr_packet_list_id_free(proxy_list, request->proxy);
219 request->in_proxy_hash = FALSE;
223 * On the FIRST reply, decrement the count of outstanding
224 * requests. Note that this is NOT the count of sent
225 * packets, but whether or not the home server has
228 if (!request->proxy_reply &&
229 request->home_server &&
230 request->home_server->currently_outstanding) {
231 request->home_server->currently_outstanding--;
234 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
240 static void remove_from_proxy_hash(REQUEST *request)
243 * Check this without grabbing the mutex because it's a
244 * lot faster that way.
246 if (!request->in_proxy_hash) return;
249 * The "not in hash" flag is definitive. However, if the
250 * flag says that it IS in the hash, there might still be
251 * a race condition where it isn't.
253 PTHREAD_MUTEX_LOCK(&proxy_mutex);
255 if (!request->in_proxy_hash) {
256 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
260 fr_packet_list_yank(proxy_list, request->proxy);
261 fr_packet_list_id_free(proxy_list, request->proxy);
264 * The home server hasn't replied, but we've given up on
265 * this request. Don't count this request against the
268 if (!request->proxy_reply &&
269 request->home_server &&
270 request->home_server->currently_outstanding) {
271 request->home_server->currently_outstanding--;
275 * Got from YES in hash, to NO, not in hash while we hold
276 * the mutex. This guarantees that when another thread
277 * grans the mutex, the "not in hash" flag is correct.
279 request->in_proxy_hash = FALSE;
281 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
284 static int proxy_add_fds(rad_listen_t *proxy_listener)
286 int i, proxy, found = -1;
288 proxy = proxy_listener->fd;
289 for (i = 0; i < 32; i++) {
291 * Found a free entry. Save the socket,
292 * and remember where we saved it.
294 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
295 found = (proxy + i) & 0x1f;
296 proxy_fds[found] = proxy;
297 proxy_listeners[found] = proxy_listener;
305 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
307 rad_listen_t *proxy_listener;
309 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
311 if (proxy_all_used) return 0;
314 * Allocate a new proxy fd. This function adds
315 * it to the tail of the list of listeners. With
316 * some care, this can be thread-safe.
318 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
319 if (!proxy_listener) {
320 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
327 if (proxy_add_fds(proxy_listener) < 0) {
328 proxy_all_used = TRUE;
329 listen_free(&proxy_listener);
330 radlog(L_ERR, "Failed creating new proxy socket: server is too busy and home servers appear to be down");
335 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
336 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
341 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
342 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
347 * Signal the main thread to add the new FD to the list
350 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
355 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
360 rad_assert(request->proxy != NULL);
361 rad_assert(proxy_list != NULL);
363 PTHREAD_MUTEX_LOCK(&proxy_mutex);
366 * Keep track of maximum outstanding requests to a
367 * particular home server. 'max_outstanding' is
368 * enforced in home_server_ldb(), in realms.c.
370 if (request->home_server) {
371 request->home_server->currently_outstanding++;
375 RADIUS_PACKET packet;
377 packet = *request->proxy;
379 if (!proxy_id_alloc(request, &packet)) {
380 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
385 * Yank the request, free the old Id, and
386 * remember the new Id.
388 fr_packet_list_yank(proxy_list, request->proxy);
389 fr_packet_list_id_free(proxy_list, request->proxy);
390 *request->proxy = packet;
392 } else if (!proxy_id_alloc(request, request->proxy)) {
393 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
397 rad_assert(request->proxy->sockfd >= 0);
400 * FIXME: Hack until we get rid of rad_listen_t, and put
401 * the information into the packet_list.
404 for (i = 0; i < 32; i++) {
405 if (proxy_fds[i] == request->proxy->sockfd) {
412 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
413 RDEBUG2("ERROR: All sockets are full.");
417 rad_assert(proxy_fds[proxy] != -1);
418 rad_assert(proxy_listeners[proxy] != NULL);
419 request->proxy_listener = proxy_listeners[proxy];
421 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
422 fr_packet_list_yank(proxy_list, request->proxy);
423 fr_packet_list_id_free(proxy_list, request->proxy);
424 request->proxy_listener = NULL;
425 request->in_proxy_hash = FALSE;
426 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
427 RDEBUG2("ERROR: Failed to insert entry into proxy list.");
431 request->in_proxy_hash = TRUE;
433 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
435 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
436 inet_ntop(request->proxy->dst_ipaddr.af,
437 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
438 request->proxy->dst_port,
446 * Called as BOTH an event, and in-line from other functions.
448 static void wait_for_proxy_id_to_expire(void *ctx)
450 REQUEST *request = ctx;
452 rad_assert(request->magic == REQUEST_MAGIC);
453 rad_assert(request->proxy != NULL);
455 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
456 request->when = request->proxy_when;
459 if (((request->proxy->code == PW_COA_REQUEST) ||
460 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
461 (request->packet->code != request->proxy->code)) {
462 request->when.tv_sec += request->home_server->coa_mrd;
465 request->when.tv_sec += request->home_server->response_window;
467 if ((request->num_proxied_requests == request->num_proxied_responses) ||
468 timercmp(&now, &request->when, >)) {
469 if (request->packet) {
470 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
471 request->number, request->packet->id,
472 (unsigned int) (request->timestamp - fr_start_time));
474 RDEBUG2("Cleaning up request %u with timestamp +%d",
476 (unsigned int) (request->timestamp - fr_start_time));
479 ev_request_free(&request);
483 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
487 #ifdef HAVE_PTHREAD_H
488 static void wait_for_child_to_die(void *ctx)
490 REQUEST *request = ctx;
492 rad_assert(request->magic == REQUEST_MAGIC);
493 remove_from_request_hash(request);
496 * If it's still queued (waiting for a thread to pick it
497 * up) OR, it's running AND there's still a child thread
498 * handling it, THEN delay some more.
500 if ((request->child_state == REQUEST_QUEUED) ||
501 ((request->child_state == REQUEST_RUNNING) &&
502 (request->thread_id == NO_CHILD_THREAD))) {
505 * Cap delay at max_request_time
507 if (request->delay < (USEC * request->root->max_request_time)) {
508 request->delay += (request->delay >> 1);
509 radlog(L_INFO, "WARNING: Child is hung for request %u in component %s module %s.",
510 request->number, request->component, request->module);
512 request->delay = USEC * request->root->max_request_time;
513 RDEBUG2("WARNING: Child is hung after \"max_request_time\" for request %u",
516 tv_add(&request->when, request->delay);
518 INSERT_EVENT(wait_for_child_to_die, request);
522 RDEBUG2("Child is finally responsive for request %u", request->number);
525 if (request->proxy) {
526 wait_for_proxy_id_to_expire(request);
531 ev_request_free(&request);
535 static void cleanup_delay(void *ctx)
537 REQUEST *request = ctx;
539 rad_assert(request->magic == REQUEST_MAGIC);
540 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
541 (request->child_state == REQUEST_DONE));
543 remove_from_request_hash(request);
546 if (request->proxy && request->in_proxy_hash) {
547 wait_for_proxy_id_to_expire(request);
552 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
553 request->number, request->packet->id,
554 (unsigned int) (request->timestamp - fr_start_time));
556 ev_request_free(&request);
561 * In daemon mode, AND this request has debug flags set.
563 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
565 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
569 const char *received, *from;
570 const fr_ipaddr_t *ip;
575 rad_assert(request->radlog != NULL);
577 if (direction == 0) {
578 received = "Received";
579 from = "from"; /* what else? */
580 ip = &packet->src_ipaddr;
581 port = packet->src_port;
584 received = "Sending";
585 from = "to"; /* hah! */
586 ip = &packet->dst_ipaddr;
587 port = packet->dst_port;
591 * Client-specific debugging re-prints the input
592 * packet into the client log.
594 * This really belongs in a utility library
596 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
597 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
598 received, fr_packet_codes[packet->code], from,
599 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
600 port, packet->id, packet->data_len);
602 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
604 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
606 packet->code, packet->id, packet->data_len);
609 for (vp = packet->vps; vp != NULL; vp = vp->next) {
610 vp_prints(buffer, sizeof(buffer), vp);
611 request->radlog(L_DBG, 0, request, "\t%s", buffer);
615 static void reject_delay(void *ctx)
617 REQUEST *request = ctx;
619 rad_assert(request->magic == REQUEST_MAGIC);
620 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
622 RDEBUG2("Sending delayed reject for request %u", request->number);
624 DEBUG_PACKET(request, request->reply, 1);
626 request->listener->send(request->listener, request);
628 request->when.tv_sec += request->root->cleanup_delay;
629 request->child_state = REQUEST_CLEANUP_DELAY;
631 INSERT_EVENT(cleanup_delay, request);
636 void revive_home_server(void *ctx)
638 home_server *home = ctx;
641 home->state = HOME_STATE_ALIVE;
642 home->currently_outstanding = 0;
643 home->revive_time = now;
646 * Delete any outstanding events.
648 if (home->ev) fr_event_delete(el, &home->ev);
650 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
651 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
652 buffer, sizeof(buffer)),
658 static void no_response_to_ping(void *ctx)
660 REQUEST *request = ctx;
664 rad_assert(request->home_server != NULL);
666 home = request->home_server;
667 home->num_received_pings = 0;
669 radlog(L_ERR, "No response to status check %d for home server %s port %d",
671 inet_ntop(request->proxy->dst_ipaddr.af,
672 &request->proxy->dst_ipaddr.ipaddr,
673 buffer, sizeof(buffer)),
674 request->proxy->dst_port);
676 check_for_zombie_home_server(request);
678 wait_for_proxy_id_to_expire(request);
682 static void received_response_to_ping(REQUEST *request)
687 rad_assert(request->home_server != NULL);
689 home = request->home_server;
690 home->num_received_pings++;
692 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
693 request->number, home->num_received_pings);
696 * Remove the request from any hashes
698 fr_event_delete(el, &request->ev);
699 remove_from_proxy_hash(request);
700 rad_assert(request->in_request_hash == FALSE);
703 * The control socket may have marked the home server as
704 * alive. OR, it may have suddenly started responding to
705 * requests again. If so, don't re-do the "make alive"
708 if (home->state == HOME_STATE_ALIVE) return;
711 * We haven't received enough ping responses to mark it
712 * "alive". Wait a bit.
714 if (home->num_received_pings < home->num_pings_to_alive) {
718 home->state = HOME_STATE_ALIVE;
719 home->currently_outstanding = 0;
720 home->revive_time = now;
722 if (!fr_event_delete(el, &home->ev)) {
723 RDEBUG2("Hmm... no event for home server. Oh well.");
726 radlog(L_PROXY, "Marking home server %s port %d alive",
727 inet_ntop(request->proxy->dst_ipaddr.af,
728 &request->proxy->dst_ipaddr.ipaddr,
729 buffer, sizeof(buffer)),
730 request->proxy->dst_port);
735 * Called from start of zombie period, OR after control socket
736 * marks the home server dead.
738 static void ping_home_server(void *ctx)
741 home_server *home = ctx;
745 if ((home->state == HOME_STATE_ALIVE) ||
746 (home->ping_check == HOME_PING_CHECK_NONE) ||
747 (home->ev != NULL)) {
751 request = request_alloc();
752 request->number = request_num_counter++;
754 request->proxy = rad_alloc(1);
755 rad_assert(request->proxy != NULL);
757 fr_event_now(el, &request->when);
758 home->when = request->when;
760 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
761 request->proxy->code = PW_STATUS_SERVER;
763 radius_pairmake(request, &request->proxy->vps,
764 "Message-Authenticator", "0x00", T_OP_SET);
766 } else if (home->type == HOME_TYPE_AUTH) {
767 request->proxy->code = PW_AUTHENTICATION_REQUEST;
769 radius_pairmake(request, &request->proxy->vps,
770 "User-Name", home->ping_user_name, T_OP_SET);
771 radius_pairmake(request, &request->proxy->vps,
772 "User-Password", home->ping_user_password, T_OP_SET);
773 radius_pairmake(request, &request->proxy->vps,
774 "Service-Type", "Authenticate-Only", T_OP_SET);
775 radius_pairmake(request, &request->proxy->vps,
776 "Message-Authenticator", "0x00", T_OP_SET);
779 #ifdef WITH_ACCOUNTING
780 request->proxy->code = PW_ACCOUNTING_REQUEST;
782 radius_pairmake(request, &request->proxy->vps,
783 "User-Name", home->ping_user_name, T_OP_SET);
784 radius_pairmake(request, &request->proxy->vps,
785 "Acct-Status-Type", "Stop", T_OP_SET);
786 radius_pairmake(request, &request->proxy->vps,
787 "Acct-Session-Id", "00000000", T_OP_SET);
788 vp = radius_pairmake(request, &request->proxy->vps,
789 "Event-Timestamp", "0", T_OP_SET);
790 vp->vp_date = now.tv_sec;
792 rad_assert("Internal sanity check failed");
796 radius_pairmake(request, &request->proxy->vps,
797 "NAS-Identifier", "Status Check. Are you alive?",
800 request->proxy->src_ipaddr = home->src_ipaddr;
801 request->proxy->dst_ipaddr = home->ipaddr;
802 request->proxy->dst_port = home->port;
803 request->home_server = home;
805 rad_assert(request->proxy_listener == NULL);
807 if (!insert_into_proxy_hash(request, FALSE)) {
808 RDEBUG2("ERROR: Failed to insert status check %d into proxy list. Discarding it.",
810 ev_request_free(&request);
813 rad_assert(request->proxy_listener != NULL);
814 request->proxy_listener->send(request->proxy_listener,
817 request->next_callback = NULL;
818 request->child_state = REQUEST_PROXIED;
819 gettimeofday(&request->when, NULL);
820 home->when = request->when;
821 request->when.tv_sec += home->ping_timeout;;
823 INSERT_EVENT(no_response_to_ping, request);
826 * Add +/- 2s of jitter, as suggested in RFC 3539
827 * and in the Issues and Fixes draft.
829 home->when.tv_sec += home->ping_interval - 2;
832 jitter ^= (jitter >> 10);
833 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
835 tv_add(&home->when, jitter);
837 INSERT_EVENT(ping_home_server, home);
841 void mark_home_server_dead(home_server *home, struct timeval *when)
843 int previous_state = home->state;
846 radlog(L_PROXY, "Marking home server %s port %d as dead.",
847 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
848 buffer, sizeof(buffer)),
851 home->state = HOME_STATE_IS_DEAD;
852 home->num_received_pings = 0;
854 if (home->ping_check != HOME_PING_CHECK_NONE) {
856 * If the control socket marks us dead, start
857 * pinging. Otherwise, we already started
858 * pinging when it was marked "zombie".
860 if (previous_state == HOME_STATE_ALIVE) {
861 ping_home_server(home);
866 * Revive it after a fixed period of time. This
867 * is very, very, bad.
870 home->when.tv_sec += home->revive_interval;
872 INSERT_EVENT(revive_home_server, home);
876 static void check_for_zombie_home_server(REQUEST *request)
881 home = request->home_server;
883 if (home->state != HOME_STATE_ZOMBIE) return;
885 when = home->zombie_period_start;
886 when.tv_sec += home->zombie_period;
888 fr_event_now(el, &now);
889 if (timercmp(&now, &when, <)) {
893 mark_home_server_dead(home, &request->when);
896 static int proxy_to_virtual_server(REQUEST *request);
898 static int virtual_server_handler(UNUSED REQUEST *request)
900 proxy_to_virtual_server(request);
904 static void proxy_fallback_handler(REQUEST *request)
907 * A proper time is required for wait_a_bit.
909 request->delay = USEC / 10;
910 gettimeofday(&now, NULL);
911 request->next_when = now;
912 tv_add(&request->next_when, request->delay);
913 request->next_callback = wait_a_bit;
916 * Re-queue the request.
918 request->child_state = REQUEST_QUEUED;
920 rad_assert(request->proxy != NULL);
921 if (!thread_pool_addrequest(request, virtual_server_handler)) {
922 request->child_state = REQUEST_DONE;
925 #ifdef HAVE_PTHREAD_H
927 * MAY free the request if we're over max_request_time,
928 * AND we're not in threaded mode!
930 * Note that we call this ONLY if we're threaded, as
931 * if we're NOT threaded, request_post_handler() calls
932 * wait_a_bit(), which means that "request" may not
935 if (have_children) wait_a_bit(request);
940 static int setup_post_proxy_fail(REQUEST *request)
942 DICT_VALUE *dval = NULL;
945 request->child_state = REQUEST_RUNNING;
947 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
948 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
950 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
951 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
955 * See no_response_to_coa_request
957 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
958 request->packet->code &= 0xff; /* restore it */
960 if (request->proxy->code == PW_COA_REQUEST) {
961 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
963 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
964 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
974 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
977 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
981 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
982 if (!vp) vp = radius_paircreate(request, &request->config_items,
983 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
984 vp->vp_integer = dval->value;
986 rad_assert(request->proxy_reply == NULL);
992 static int null_handler(UNUSED REQUEST *request)
997 static void post_proxy_fail_handler(REQUEST *request)
1000 * A proper time is required for wait_a_bit.
1002 request->delay = USEC / 10;
1003 gettimeofday(&now, NULL);
1006 * Not set up to run Post-Proxy-Type = Fail.
1008 * Mark the request as still running, and figure out what
1011 if (!setup_post_proxy_fail(request)) {
1012 request_post_handler(request);
1016 * Re-queue the request.
1018 request->child_state = REQUEST_QUEUED;
1021 * There is a post-proxy-type of fail. We run
1022 * the request through the pre/post proxy
1023 * handlers, just like it was a real proxied
1024 * request. However, we set the per-request
1025 * handler to NULL, as we don't want to do
1028 * Note that when we're not threaded, this will
1029 * process the request even if it's greater than
1030 * max_request_time. That's not fatal.
1032 request->priority = 0;
1033 rad_assert(request->proxy != NULL);
1034 thread_pool_addrequest(request, null_handler);
1038 * MAY free the request if we're over max_request_time,
1039 * AND we're not in threaded mode!
1041 * Note that we call this ONLY if we're threaded, as
1042 * if we're NOT threaded, request_post_handler() calls
1043 * wait_a_bit(), which means that "request" may not
1046 if (have_children) wait_a_bit(request);
1050 /* maybe check this against wait_for_proxy_id_to_expire? */
1051 static void no_response_to_proxied_request(void *ctx)
1053 REQUEST *request = ctx;
1057 rad_assert(request->magic == REQUEST_MAGIC);
1058 rad_assert(request->child_state == REQUEST_PROXIED);
1061 * If we've failed over to an internal home server,
1062 * replace the callback with the correct one. This
1063 * is due to locking issues with child threads...
1065 if (request->home_server->server) {
1066 wait_a_bit(request);
1070 check_for_zombie_home_server(request);
1072 home = request->home_server;
1075 * The default as of 2.1.7 is to allow requests to
1076 * fail-over to a backup home server when this one does
1077 * not respond. The old behavior can be configured as
1080 if (home->no_response_fail) {
1081 radlog(L_ERR, "Rejecting request %u (proxy Id %d) due to lack of any response from home server %s port %d",
1082 request->number, request->proxy->id,
1083 inet_ntop(request->proxy->dst_ipaddr.af,
1084 &request->proxy->dst_ipaddr.ipaddr,
1085 buffer, sizeof(buffer)),
1086 request->proxy->dst_port);
1088 post_proxy_fail_handler(request);
1090 rad_assert(request->ev == NULL);
1091 request->child_state = REQUEST_RUNNING;
1092 wait_a_bit(request);
1096 * Don't touch request due to race conditions
1100 * If it's not alive, don't try to make it a zombie.
1102 if (home->state != HOME_STATE_ALIVE) {
1104 * Don't check home->ev due to race conditions.
1110 * We've received a real packet recently. Don't mark the
1111 * server as zombie until we've received NO packets for a
1112 * while. The "1/4" of zombie period was chosen rather
1113 * arbitrarily. It's a balance between too short, which
1114 * gives quick fail-over and fail-back, or too long,
1115 * where the proxy still sends packets to an unresponsive
1118 if ((home->last_packet + ((home->zombie_period + 3) / 4)) >= now.tv_sec) {
1123 * Enable the zombie period when we notice that the home
1124 * server hasn't responded for a while. We back-date the
1125 * zombie period to when we last received a response from
1128 home->state = HOME_STATE_ZOMBIE;
1130 home->zombie_period_start.tv_sec = home->last_packet;
1131 home->zombie_period_start.tv_usec = USEC / 2;
1133 fr_event_delete(el, &home->ev);
1134 home->currently_outstanding = 0;
1135 home->num_received_pings = 0;
1137 radlog(L_PROXY, "Marking home server %s port %d as zombie (it looks like it is dead).",
1138 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1139 buffer, sizeof(buffer)),
1143 * Start pinging the home server.
1145 ping_home_server(home);
1149 static void wait_a_bit(void *ctx)
1151 struct timeval when;
1152 REQUEST *request = ctx;
1153 fr_event_callback_t callback = NULL;
1155 rad_assert(request->magic == REQUEST_MAGIC);
1159 * The CoA request is a new (internally generated)
1160 * request, created in a child thread. We therefore need
1161 * some way to tie its events back into the main event
1164 if (request->coa && !request->coa->proxy_reply &&
1165 request->coa->next_callback) {
1166 request->coa->when = request->coa->next_when;
1167 INSERT_EVENT(request->coa->next_callback, request->coa);
1168 request->coa->next_callback = NULL;
1169 request->coa->parent = NULL;
1170 request->coa = NULL;
1174 switch (request->child_state) {
1175 case REQUEST_QUEUED:
1176 case REQUEST_RUNNING:
1178 * If we're not thread-capable, OR we're capable,
1179 * but have been told to run without threads, and
1180 * the request is still running. This is usually
1181 * because the request was proxied, and the home
1182 * server didn't respond.
1184 #ifdef HAVE_PTHREAD_H
1188 request->child_state = REQUEST_DONE;
1192 #ifdef HAVE_PTHREAD_H
1194 * If we have threads, wait for the child thread
1197 when = request->received;
1198 when.tv_sec += request->root->max_request_time;
1201 * Normally called from the event loop with the
1202 * proper event loop time. Otherwise, called from
1203 * post proxy fail handler, which sets "now", and
1204 * this call won't re-set it, because we're not
1205 * in the event loop.
1207 fr_event_now(el, &now);
1210 * Request still has more time. Continue
1213 if (timercmp(&now, &when, <)) {
1214 if (request->delay < (USEC / 10)) {
1215 request->delay = USEC / 10;
1217 request->delay += request->delay >> 1;
1220 * Cap delays at something reasonable.
1222 if (request->delay > (request->root->max_request_time * USEC)) {
1223 request->delay = request->root->max_request_time * USEC;
1226 request->when = now;
1227 tv_add(&request->when, request->delay);
1228 callback = wait_a_bit;
1232 request->master_state = REQUEST_STOP_PROCESSING;
1235 * A child thread MAY still be running on the
1236 * request. Ask the thread to stop working on
1239 if (have_children &&
1240 (request->thread_id == NO_CHILD_THREAD)) {
1241 radlog(L_ERR, "WARNING: Unresponsive thread %d for request %u, in component %s module %s",
1242 request->number, request->thread_id,
1243 request->component ? request->component : "<server core>",
1244 request->module ? request->module : "<server core>");
1248 request->delay = USEC;
1249 tv_add(&request->when, request->delay);
1250 callback = wait_for_child_to_die;
1255 * Mark the request as no longer running,
1260 #ifdef HAVE_PTHREAD_H
1261 request->thread_id = NO_CHILD_THREAD;
1266 * This is a CoA request. It's been divorced
1267 * from everything else, so we clean it up now.
1269 if (!request->in_request_hash &&
1271 (request->packet->code != request->proxy->code) &&
1272 ((request->proxy->code == PW_COA_REQUEST) ||
1273 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1275 * FIXME: Do CoA MIBs
1277 ev_request_free(&request);
1281 request_stats_final(request);
1282 cleanup_delay(request);
1285 case REQUEST_REJECT_DELAY:
1286 case REQUEST_CLEANUP_DELAY:
1287 #ifdef HAVE_PTHREAD_H
1288 request->thread_id = NO_CHILD_THREAD;
1290 request_stats_final(request);
1293 case REQUEST_PROXIED:
1294 rad_assert(request->next_callback != NULL);
1295 rad_assert(request->next_callback != wait_a_bit);
1297 request->when = request->next_when;
1298 callback = request->next_callback;
1299 request->next_callback = NULL;
1303 rad_panic("Internal sanity check failure");
1308 * Something major went wrong. Discard the request, and
1311 * FIXME: No idea why this happens or how to fix it...
1312 * It seems to happen *only* when requests are proxied,
1313 * and where the home server doesn't respond. So it looks
1314 * like a race condition above, but it happens in debug
1315 * mode, with no threads...
1318 RDEBUG("WARNING: Internal sanity check failed in event handler for request %u: Discarding the request!", request->number);
1319 ev_request_free(&request);
1323 INSERT_EVENT(callback, request);
1327 static void no_response_to_coa_request(void *ctx)
1329 REQUEST *request = ctx;
1332 rad_assert(request->magic == REQUEST_MAGIC);
1333 rad_assert(request->child_state == REQUEST_PROXIED);
1334 rad_assert(request->home_server != NULL);
1335 rad_assert(!request->in_request_hash);
1337 radlog(L_ERR, "No response to CoA request sent to %s",
1338 inet_ntop(request->proxy->dst_ipaddr.af,
1339 &request->proxy->dst_ipaddr.ipaddr,
1340 buffer, sizeof(buffer)));
1345 request->packet->code |= (PW_COA_REQUEST << 8);
1346 post_proxy_fail_handler(request);
1350 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1354 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1361 packet->data = NULL;
1362 packet->data_len = 0;
1365 return 1; /* time stamp updated */
1370 * Called when we haven't received a response to a CoA request.
1372 static void retransmit_coa_request(void *ctx)
1376 REQUEST *request = ctx;
1378 rad_assert(request->magic == REQUEST_MAGIC);
1379 rad_assert(request->child_state == REQUEST_PROXIED);
1380 rad_assert(request->home_server != NULL);
1381 rad_assert(!request->in_request_hash);
1382 rad_assert(request->parent == NULL);
1384 fr_event_now(el, &now);
1387 * Cap count at MRC, if it is non-zero.
1389 if (request->home_server->coa_mrc &&
1390 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1391 no_response_to_coa_request(request);
1396 * RFC 5080 Section 2.2.1
1398 * RT = 2*RTprev + RAND*RTprev
1399 * = 1.9 * RTprev + rand(0,.2) * RTprev
1400 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1403 delay ^= (delay >> 16);
1405 frac = request->delay / 5;
1406 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1408 delay += (2 * request->delay) - (request->delay / 10);
1411 * Cap delay at MRT, if MRT is non-zero.
1413 if (request->home_server->coa_mrt &&
1414 (delay > (request->home_server->coa_mrt * USEC))) {
1415 int mrt_usec = request->home_server->coa_mrt * USEC;
1418 * delay = MRT + RAND * MRT
1419 * = 0.9 MRT + rand(0,.2) * MRT
1422 delay ^= (delay >> 15);
1424 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1425 delay += mrt_usec - (mrt_usec / 10);
1428 request->delay = delay;
1429 request->when = now;
1430 tv_add(&request->when, request->delay);
1431 mrd = request->proxy_when;
1432 mrd.tv_sec += request->home_server->coa_mrd;
1435 * Cap duration at MRD.
1437 if (timercmp(&mrd, &request->when, <)) {
1438 request->when = mrd;
1439 INSERT_EVENT(no_response_to_coa_request, request);
1442 INSERT_EVENT(retransmit_coa_request, request);
1445 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1446 if (!insert_into_proxy_hash(request, TRUE)) {
1447 DEBUG("ERROR: Failed to insert retransmission of CoA request into proxy list.");
1451 request->num_proxied_requests = 0;
1452 request->num_proxied_responses = 0;
1455 request->num_proxied_requests++;
1456 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1458 request->proxy_listener->send(request->proxy_listener,
1464 * The original request is either DONE, or in CLEANUP_DELAY.
1466 static int originated_coa_request(REQUEST *request)
1468 int delay, rcode, pre_proxy_type = 0;
1474 rad_assert(request->proxy == NULL);
1475 rad_assert(!request->in_proxy_hash);
1476 rad_assert(request->proxy_reply == NULL);
1479 * Check whether we want to originate one, or cancel one.
1481 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1482 if (!vp && request->coa) {
1483 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1487 if (vp->vp_integer == 0) {
1488 ev_request_free(&request->coa);
1489 return 1; /* success */
1493 if (!request->coa) request_alloc_coa(request);
1494 if (!request->coa) return 0;
1499 * src_ipaddr will be set up in proxy_encode.
1501 memset(&ipaddr, 0, sizeof(ipaddr));
1502 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1504 ipaddr.af = AF_INET;
1505 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1507 } else if ((vp = pairfind(coa->proxy->vps,
1508 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1509 ipaddr.af = AF_INET6;
1510 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1512 } else if ((vp = pairfind(coa->proxy->vps,
1513 PW_HOME_SERVER_POOL)) != NULL) {
1514 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1516 if (!coa->home_pool) {
1517 RDEBUG2("WARNING: No such home_server_pool %s",
1520 ev_request_free(&request->coa);
1527 } else if (request->client->coa_pool) {
1528 coa->home_pool = request->client->coa_pool;
1530 } else if (request->client->coa_server) {
1531 coa->home_server = request->client->coa_server;
1535 * If all else fails, send it to the client that
1536 * originated this request.
1538 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1542 * Use the pool, if it exists.
1544 if (coa->home_pool) {
1545 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1546 if (!coa->home_server) {
1547 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1551 } else if (!coa->home_server) {
1552 int port = PW_COA_UDP_PORT;
1554 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1555 if (vp) port = vp->vp_integer;
1557 coa->home_server = home_server_find(&ipaddr, port);
1558 if (!coa->home_server) {
1559 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1560 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1561 buffer, sizeof(buffer)), port);
1566 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1568 switch (vp->vp_integer) {
1569 case PW_COA_REQUEST:
1570 case PW_DISCONNECT_REQUEST:
1571 coa->proxy->code = vp->vp_integer;
1575 DEBUG("Cannot set CoA Packet-Type to code %d",
1581 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1584 * The rest of the server code assumes that
1585 * request->packet && request->reply exist. Copy them
1586 * from the original request.
1588 rad_assert(coa->packet != NULL);
1589 rad_assert(coa->packet->vps == NULL);
1590 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1591 coa->packet->vps = paircopy(request->packet->vps);
1592 coa->packet->data = NULL;
1593 rad_assert(coa->reply != NULL);
1594 rad_assert(coa->reply->vps == NULL);
1595 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1596 coa->reply->vps = paircopy(request->reply->vps);
1597 coa->reply->data = NULL;
1598 coa->config_items = paircopy(request->config_items);
1601 * Call the pre-proxy routines.
1603 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1605 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1606 pre_proxy_type = vp->vp_integer;
1609 if (coa->home_pool && coa->home_pool->virtual_server) {
1610 const char *old_server = coa->server;
1612 coa->server = coa->home_pool->virtual_server;
1613 RDEBUG2(" server %s {", coa->server);
1614 rcode = module_pre_proxy(pre_proxy_type, coa);
1616 coa->server = old_server;
1618 rcode = module_pre_proxy(pre_proxy_type, coa);
1625 * Only send the CoA packet if the pre-proxy code succeeded.
1627 case RLM_MODULE_NOOP:
1629 case RLM_MODULE_UPDATED:
1634 * Source IP / port is set when the proxy socket
1637 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1638 coa->proxy->dst_port = coa->home_server->port;
1640 if (!insert_into_proxy_hash(coa, FALSE)) {
1641 DEBUG("ERROR: Failed to insert CoA request into proxy list.");
1646 * We CANNOT divorce the CoA request from the parent
1647 * request. This function is running in a child thread,
1648 * and we need access to the main event loop in order to
1649 * to add the timers for the CoA packet. See
1654 * Forget about the original request completely at this
1659 gettimeofday(&request->proxy_when, NULL);
1660 request->received = request->next_when = request->proxy_when;
1661 rad_assert(request->proxy_reply == NULL);
1664 * Implement re-transmit algorithm as per RFC 5080
1667 * We want IRT + RAND*IRT
1668 * or 0.9 IRT + rand(0,.2) IRT
1670 * 2^20 ~ USEC, and we want 2.
1671 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1673 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1674 request->delay = delay * request->home_server->coa_irt;
1675 delay = request->home_server->coa_irt * USEC;
1676 delay -= delay / 10;
1677 delay += request->delay;
1679 request->delay = delay;
1680 tv_add(&request->next_when, delay);
1681 request->next_callback = retransmit_coa_request;
1684 * Note that we set proxied BEFORE sending the packet.
1686 * Once we send it, the request is tainted, as
1687 * another thread may have picked it up. Don't
1690 request->num_proxied_requests = 1;
1691 request->num_proxied_responses = 0;
1693 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1695 request->child_state = REQUEST_PROXIED;
1697 DEBUG_PACKET(request, request->proxy, 1);
1699 #ifdef HAVE_PTHREAD_H
1700 request->thread_id = NO_CHILD_THREAD;
1703 request->proxy_listener->send(request->proxy_listener,
1707 #endif /* WITH_COA */
1710 static int process_proxy_reply(REQUEST *request)
1713 int post_proxy_type = 0;
1717 * Delete any reply we had accumulated until now.
1719 pairfree(&request->reply->vps);
1722 * Run the packet through the post-proxy stage,
1723 * BEFORE playing games with the attributes.
1725 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1728 * If we have a proxy_reply, and it was a reject, setup
1729 * post-proxy-type Reject
1731 if (!vp && request->proxy_reply &&
1732 request->proxy_reply->code == PW_AUTHENTICATION_REJECT) {
1735 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Reject");
1736 if (!dval) return 0;
1738 vp = radius_paircreate(request, &request->config_items,
1739 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
1741 vp->vp_integer = dval->value;
1745 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1746 post_proxy_type = vp->vp_integer;
1749 if (request->home_pool && request->home_pool->virtual_server) {
1750 const char *old_server = request->server;
1752 request->server = request->home_pool->virtual_server;
1753 RDEBUG2(" server %s {", request->server);
1754 rcode = module_post_proxy(post_proxy_type, request);
1756 request->server = old_server;
1758 rcode = module_post_proxy(post_proxy_type, request);
1762 if (request->packet->code == request->proxy->code)
1764 * Don't run the next bit if we originated a CoA
1765 * packet, after receiving an Access-Request or
1766 * Accounting-Request.
1771 * There may NOT be a proxy reply, as we may be
1772 * running Post-Proxy-Type = Fail.
1774 if (request->proxy_reply) {
1776 * Delete the Proxy-State Attributes from
1777 * the reply. These include Proxy-State
1778 * attributes from us and remote server.
1780 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1783 * Add the attributes left in the proxy
1784 * reply to the reply list.
1786 pairadd(&request->reply->vps, request->proxy_reply->vps);
1787 request->proxy_reply->vps = NULL;
1790 * Free proxy request pairs.
1792 pairfree(&request->proxy->vps);
1796 default: /* Don't do anything */
1798 case RLM_MODULE_FAIL:
1799 case RLM_MODULE_HANDLED:
1800 /* FIXME: debug print stuff */
1801 request->child_state = REQUEST_DONE;
1802 #ifdef HAVE_PTHREAD_H
1803 request->thread_id = NO_CHILD_THREAD;
1812 static int request_pre_handler(REQUEST *request)
1816 rad_assert(request->magic == REQUEST_MAGIC);
1817 rad_assert(request->packet != NULL);
1819 request->child_state = REQUEST_RUNNING;
1822 * Don't decode the packet if it's an internal "fake"
1823 * request. Instead, just return so that the caller can
1826 if (request->packet->dst_port == 0) {
1827 request->username = pairfind(request->packet->vps,
1829 request->password = pairfind(request->packet->vps,
1836 * Put the decoded packet into it's proper place.
1838 if (request->proxy_reply != NULL) {
1839 rcode = request->proxy_listener->decode(request->proxy_listener,
1841 DEBUG_PACKET(request, request->proxy_reply, 0);
1844 if (request->packet->vps == NULL) {
1845 rcode = request->listener->decode(request->listener, request);
1847 if (debug_condition) {
1849 const char *my_debug = debug_condition;
1852 * Ignore parse errors.
1854 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1858 request->options = 2;
1859 request->radlog = radlog_request;
1863 DEBUG_PACKET(request, request->packet, 0);
1869 RDEBUG("%s Dropping packet without response.", fr_strerror());
1870 request->reply->offset = -2; /* bad authenticator */
1871 request->child_state = REQUEST_DONE;
1872 #ifdef HAVE_PTHREAD_H
1873 request->thread_id = NO_CHILD_THREAD;
1878 if (!request->username) {
1879 request->username = pairfind(request->packet->vps,
1884 if (request->proxy) {
1885 return process_proxy_reply(request);
1895 * Do state handling when we proxy a request.
1897 static int proxy_request(REQUEST *request)
1899 struct timeval when;
1904 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
1905 ev_request_free(&request->coa);
1909 if (request->home_server->server) {
1910 RDEBUG("ERROR: Cannot proxy to a virtual server.");
1914 if (!insert_into_proxy_hash(request, FALSE)) {
1915 RDEBUG("ERROR: Failed to insert entry into proxy list.");
1919 request->proxy_listener->encode(request->proxy_listener, request);
1921 when = request->received;
1922 when.tv_sec += request->root->max_request_time;
1924 gettimeofday(&request->proxy_when, NULL);
1926 request->next_when = request->proxy_when;
1927 request->next_when.tv_sec += request->home_server->response_window;
1929 rad_assert(request->home_server->response_window > 0);
1931 if (timercmp(&when, &request->next_when, <)) {
1932 request->next_when = when;
1934 request->next_callback = no_response_to_proxied_request;
1936 RDEBUG2("Proxying request %u to home server %s port %d",
1938 inet_ntop(request->proxy->dst_ipaddr.af,
1939 &request->proxy->dst_ipaddr.ipaddr,
1940 buffer, sizeof(buffer)),
1941 request->proxy->dst_port);
1944 * Note that we set proxied BEFORE sending the packet.
1946 * Once we send it, the request is tainted, as
1947 * another thread may have picked it up. Don't
1950 request->num_proxied_requests = 1;
1951 request->num_proxied_responses = 0;
1952 #ifdef HAVE_PTHREAD_H
1953 request->thread_id = NO_CHILD_THREAD;
1955 request->child_state = REQUEST_PROXIED;
1957 DEBUG_PACKET(request, request->proxy, 1);
1959 request->proxy_listener->send(request->proxy_listener,
1966 * "Proxy" the request by sending it to a new virtual server.
1968 static int proxy_to_virtual_server(REQUEST *request)
1971 RAD_REQUEST_FUNP fun;
1973 if (!request->home_server || !request->home_server->server) return 0;
1975 if (request->parent) {
1976 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1980 fake = request_alloc_fake(request);
1982 RDEBUG2("WARNING: Out of memory");
1986 fake->packet->vps = paircopy(request->proxy->vps);
1987 fake->server = request->home_server->server;
1989 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1990 fun = rad_virtual_server;
1992 #ifdef WITH_ACCOUNTING
1993 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1994 fun = rad_accounting;
1998 RDEBUG2("Unknown packet type %d", request->proxy->code);
1999 ev_request_free(&fake);
2003 RDEBUG2(">>> Sending proxied request internally to virtual server.");
2004 radius_handle_request(fake, fun);
2005 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
2007 if (fake->reply->code != 0) {
2008 request->proxy_reply = fake->reply;
2012 * There was no response
2014 setup_post_proxy_fail(request);
2017 ev_request_free(&fake);
2019 if (!process_proxy_reply(request)) {
2024 * Process it through the normal section again, but ONLY
2025 * if we received a proxy reply..
2027 if (request->proxy_reply) {
2028 if (request->server) RDEBUG("server %s {",
2029 request->server != NULL ?
2030 request->server : "");
2033 if (request->server) RDEBUG("} # server %s",
2034 request->server != NULL ?
2035 request->server : "");
2038 return 2; /* success, but NOT '1' !*/
2042 * Return 1 if we did proxy it, or the proxy attempt failed
2043 * completely. Either way, the caller doesn't touch the request
2044 * any more if we return 1.
2046 static int successfully_proxied_request(REQUEST *request)
2049 int pre_proxy_type = 0;
2050 VALUE_PAIR *realmpair;
2051 VALUE_PAIR *strippedname;
2053 char *realmname = NULL;
2055 REALM *realm = NULL;
2059 * If it was already proxied, do nothing.
2061 * FIXME: This should really be a serious error.
2063 if (request->in_proxy_hash ||
2064 (request->proxy_reply && (request->proxy_reply->code != 0))) {
2068 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
2069 if (!realmpair || (realmpair->length == 0)) {
2072 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
2075 switch (request->packet->code) {
2076 case PW_AUTHENTICATION_REQUEST:
2077 pool_type = HOME_TYPE_AUTH;
2080 #ifdef WITH_ACCOUNTING
2081 case PW_ACCOUNTING_REQUEST:
2082 pool_type = HOME_TYPE_ACCT;
2087 case PW_COA_REQUEST:
2088 case PW_DISCONNECT_REQUEST:
2089 pool_type = HOME_TYPE_COA;
2097 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2099 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2104 realmname = NULL; /* no realms */
2109 realmname = (char *) realmpair->vp_strvalue;
2111 realm = realm_find2(realmname);
2113 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2118 * Figure out which pool to use.
2120 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2121 pool = realm->auth_pool;
2123 #ifdef WITH_ACCOUNTING
2124 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2125 pool = realm->acct_pool;
2129 } else if ((request->packet->code == PW_COA_REQUEST) ||
2130 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2131 pool = realm->acct_pool;
2135 rad_panic("Internal sanity check failed");
2139 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2145 home = home_server_ldb(realmname, pool, request);
2147 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2151 request->home_pool = pool;
2155 * Once we've decided to proxy a request, we cannot send
2156 * a CoA packet. So we free up any CoA packet here.
2158 ev_request_free(&request->coa);
2161 * Remember that we sent the request to a Realm.
2163 if (realmname) pairadd(&request->packet->vps,
2164 pairmake("Realm", realmname, T_OP_EQ));
2167 * Strip the name, if told to.
2169 * Doing it here catches the case of proxied tunneled
2172 if (realm && (realm->striprealm == TRUE) &&
2173 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2175 * If there's a Stripped-User-Name attribute in
2176 * the request, then use THAT as the User-Name
2177 * for the proxied request, instead of the
2180 * This is done by making a copy of the
2181 * Stripped-User-Name attribute, turning it into
2182 * a User-Name attribute, deleting the
2183 * Stripped-User-Name and User-Name attributes
2184 * from the vps list, and making the new
2185 * User-Name the head of the vps list.
2187 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2189 vp = radius_paircreate(request, NULL,
2190 PW_USER_NAME, PW_TYPE_STRING);
2191 rad_assert(vp != NULL); /* handled by above function */
2192 /* Insert at the START of the list */
2193 vp->next = request->proxy->vps;
2194 request->proxy->vps = vp;
2196 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2197 sizeof(vp->vp_strvalue));
2198 vp->length = strippedname->length;
2201 * Do NOT delete Stripped-User-Name.
2206 * If there is no PW_CHAP_CHALLENGE attribute but
2207 * there is a PW_CHAP_PASSWORD we need to add it
2208 * since we can't use the request authenticator
2209 * anymore - we changed it.
2211 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2212 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2213 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2214 vp = radius_paircreate(request, &request->proxy->vps,
2215 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2216 vp->length = AUTH_VECTOR_LEN;
2217 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2221 * The RFC's say we have to do this, but FreeRADIUS
2224 vp = radius_paircreate(request, &request->proxy->vps,
2225 PW_PROXY_STATE, PW_TYPE_OCTETS);
2226 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2227 request->packet->id);
2228 vp->length = strlen(vp->vp_strvalue);
2231 * Should be done BEFORE inserting into proxy hash, as
2232 * pre-proxy may use this information, or change it.
2234 request->proxy->code = request->packet->code;
2237 * Call the pre-proxy routines.
2239 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2241 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2242 pre_proxy_type = vp->vp_integer;
2245 rad_assert(request->home_pool != NULL);
2247 if (request->home_pool->virtual_server) {
2248 const char *old_server = request->server;
2250 request->server = request->home_pool->virtual_server;
2251 RDEBUG2(" server %s {", request->server);
2252 rcode = module_pre_proxy(pre_proxy_type, request);
2254 request->server = old_server;
2256 rcode = module_pre_proxy(pre_proxy_type, request);
2259 case RLM_MODULE_FAIL:
2260 case RLM_MODULE_INVALID:
2261 case RLM_MODULE_NOTFOUND:
2262 case RLM_MODULE_USERLOCK:
2264 /* FIXME: debug print failed stuff */
2267 case RLM_MODULE_REJECT:
2268 case RLM_MODULE_HANDLED:
2272 * Only proxy the packet if the pre-proxy code succeeded.
2274 case RLM_MODULE_NOOP:
2276 case RLM_MODULE_UPDATED:
2281 * If it's a fake request, don't send the proxy
2282 * packet. The outer tunnel session will take
2283 * care of doing that.
2285 if (request->packet->dst_port == 0) {
2286 request->home_server = NULL;
2290 if (request->home_server->server) {
2291 return proxy_to_virtual_server(request);
2294 if (!proxy_request(request)) {
2295 RDEBUG("ERROR: Failed to proxy request %u", request->number);
2303 static void request_post_handler(REQUEST *request)
2305 int child_state = -1;
2306 struct timeval when;
2309 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2311 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2312 RDEBUG2("request %u was cancelled.", request->number);
2313 child_state = REQUEST_DONE;
2317 if (request->child_state != REQUEST_RUNNING) {
2318 rad_panic("Internal sanity check failed");
2323 * If it's not in the request hash, it's a CoA request.
2326 if (!request->in_request_hash &&
2328 ((request->proxy->code == PW_COA_REQUEST) ||
2329 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2330 request->next_callback = NULL;
2331 child_state = REQUEST_DONE;
2337 * Catch Auth-Type := Reject BEFORE proxying the packet.
2339 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2340 (request->reply->code == 0) &&
2341 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2342 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2343 request->reply->code = PW_AUTHENTICATION_REJECT;
2347 if (request->root->proxy_requests &&
2348 !request->in_proxy_hash &&
2349 (request->reply->code == 0) &&
2350 (request->packet->dst_port != 0) &&
2351 (request->packet->code != PW_STATUS_SERVER)) {
2352 int rcode = successfully_proxied_request(request);
2354 if (rcode == 1) return; /* "request" is now untouchable */
2357 * Failed proxying it (dead home servers, etc.)
2358 * Run it through Post-Proxy-Type = Fail, and
2359 * respond to the request.
2361 * Note that we're in a child thread here, so we
2362 * do NOT re-schedule the request. Instead, we
2363 * do what we would have done, which is run the
2364 * pre-handler, a NULL request handler, and then
2367 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2368 request_pre_handler(request);
2372 * Else we weren't supposed to proxy it,
2373 * OR we proxied it internally to a virutal server.
2378 else if (request->proxy && request->coa) {
2379 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2380 ev_request_free(&request->coa);
2386 * Fake requests don't get encoded or signed. The caller
2387 * also requires the reply VP's, so we don't free them
2390 if (request->packet->dst_port == 0) {
2391 /* FIXME: RDEBUG going to the next request */
2392 #ifdef HAVE_PTHREAD_H
2393 request->thread_id = NO_CHILD_THREAD;
2395 request->child_state = REQUEST_DONE;
2401 * Copy Proxy-State from the request to the reply.
2403 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2404 if (vp) pairadd(&request->reply->vps, vp);
2408 * Access-Requests get delayed or cached.
2410 switch (request->packet->code) {
2411 case PW_AUTHENTICATION_REQUEST:
2412 gettimeofday(&request->next_when, NULL);
2415 * Override the response code if a
2416 * control:Response-Packet-Type attribute is present.
2418 vp = pairfind(request->config_items,
2419 PW_RESPONSE_PACKET_TYPE);
2421 if (vp->vp_integer == 256) {
2422 RDEBUG2("Not responding to request %u",
2426 * Force cleanup after a long
2427 * time, so that we don't
2428 * re-process the packet.
2430 request->reply->code = 0;
2431 request->next_when.tv_sec += request->root->max_request_time;
2432 request->next_callback = cleanup_delay;
2433 child_state = REQUEST_CLEANUP_DELAY;
2437 request->reply->code = vp->vp_integer;
2439 } else if (request->reply->code == 0) {
2440 RDEBUG2("There was no response configured: rejecting "
2441 "request %u", request->number);
2443 request->reply->code = PW_AUTHENTICATION_REJECT;
2447 * Run rejected packets through
2449 * Post-Auth-Type = Reject
2451 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2452 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2453 vp = radius_pairmake(request, &request->config_items,
2454 "Post-Auth-Type", "Reject",
2456 if (vp) rad_postauth(request);
2459 * If configured, delay Access-Reject packets.
2461 * If request->root->reject_delay = 0, we discover
2462 * that we have to send the packet now.
2464 when = request->received;
2465 when.tv_sec += request->root->reject_delay;
2467 if (timercmp(&when, &request->next_when, >)) {
2468 RDEBUG2("Delaying reject of request %u for %d seconds",
2470 request->root->reject_delay);
2471 request->next_when = when;
2472 request->next_callback = reject_delay;
2473 #ifdef HAVE_PTHREAD_H
2474 request->thread_id = NO_CHILD_THREAD;
2476 request->child_state = REQUEST_REJECT_DELAY;
2481 if (request->reply->code == PW_AUTHENTICATION_ACK) {
2482 rad_postauth(request);
2488 case PW_COA_REQUEST:
2489 case PW_DISCONNECT_REQUEST:
2491 request->next_when.tv_sec += request->root->cleanup_delay;
2492 request->next_callback = cleanup_delay;
2493 child_state = REQUEST_CLEANUP_DELAY;
2496 case PW_ACCOUNTING_REQUEST:
2497 request->next_callback = NULL; /* just to be safe */
2498 child_state = REQUEST_DONE;
2502 * FIXME: Status-Server should probably not be
2505 case PW_STATUS_SERVER:
2506 request->next_callback = NULL;
2507 child_state = REQUEST_DONE;
2514 request->next_callback = NULL;
2515 child_state = REQUEST_DONE;
2520 * Suppress "no reply" packets here, unless we're reading
2521 * from the "detail" file. In that case, we've got to
2522 * tell the detail file handler that the request is dead,
2523 * and it should re-send it.
2524 * If configured, encode, sign, and send.
2526 if ((request->reply->code != 0) ||
2527 (request->listener->type == RAD_LISTEN_DETAIL)) {
2528 DEBUG_PACKET(request, request->reply, 1);
2529 request->listener->send(request->listener, request);
2534 * Now that we've completely processed the request,
2535 * see if we need to originate a CoA request. But ONLY
2536 * if it wasn't proxied.
2538 if (!request->proxy &&
2539 (request->packet->code != PW_COA_REQUEST) &&
2540 (request->packet->code != PW_DISCONNECT_REQUEST) &&
2542 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL))) {
2543 if (!originated_coa_request(request)) {
2544 RDEBUG2("Do CoA Fail handler here");
2546 /* request->coa is stil set, so we can update events */
2552 * Clean up. These are no longer needed.
2554 pairfree(&request->config_items);
2556 pairfree(&request->packet->vps);
2557 request->username = NULL;
2558 request->password = NULL;
2560 pairfree(&request->reply->vps);
2563 if (request->proxy) {
2564 pairfree(&request->proxy->vps);
2566 if (request->proxy_reply) {
2567 pairfree(&request->proxy_reply->vps);
2572 * We're not tracking responses from the home
2573 * server, we can therefore free this memory in
2576 if (!request->in_proxy_hash) {
2577 rad_free(&request->proxy);
2578 rad_free(&request->proxy_reply);
2579 request->home_server = NULL;
2585 RDEBUG2("Finished request %u.", request->number);
2586 rad_assert(child_state >= 0);
2587 request->child_state = child_state;
2589 if (have_children) {
2590 #ifdef HAVE_PTHREAD_H
2591 request->thread_id = NO_CHILD_THREAD;
2595 * Single threaded mode: update timers now.
2597 wait_a_bit(request);
2602 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2608 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2609 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2611 switch (request->child_state) {
2612 case REQUEST_QUEUED:
2613 case REQUEST_RUNNING:
2617 radlog(L_ERR, "Discarding duplicate request from "
2618 "client %s port %d - ID: %u due to unfinished request %u",
2620 request->packet->src_port,request->packet->id,
2625 case REQUEST_PROXIED:
2627 * We're not supposed to have duplicate
2628 * accounting packets. The other states handle
2629 * duplicates fine (discard, or send duplicate
2630 * reply). But we do NOT want to retransmit an
2631 * accounting request here, because that would
2632 * involve updating the Acct-Delay-Time, and
2633 * therefore changing the packet Id, etc.
2635 * Instead, we just discard the packet. We may
2636 * eventually respond, or the client will send a
2637 * new accounting packet.
2639 * The same comments go for Status-Server, and
2640 * other packet types.
2642 * FIXME: coa: when we proxy CoA && Disconnect
2643 * packets, this logic has to be fixed.
2645 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2649 check_for_zombie_home_server(request);
2652 * If we've just discovered that the home server is
2653 * dead, send the packet to another one.
2655 if ((request->packet->dst_port != 0) &&
2656 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2659 remove_from_proxy_hash(request);
2661 home = home_server_ldb(NULL, request->home_pool, request);
2663 RDEBUG2("ERROR: Failed to find live home server for request %u", request->number);
2666 * Do post-request processing,
2667 * and any insertion of necessary
2670 post_proxy_fail_handler(request);
2674 request->proxy->code = request->packet->code;
2677 * Free the old packet, to force re-encoding
2679 free(request->proxy->data);
2680 request->proxy->data = NULL;
2681 request->proxy->data_len = 0;
2684 * This request failed over to a virtual
2685 * server. Push it back onto the queue
2688 if (request->home_server->server) {
2689 proxy_fallback_handler(request);
2694 * Try to proxy the request.
2696 if (!proxy_request(request)) {
2697 RDEBUG("ERROR: Failed to re-proxy request %u", request->number);
2698 goto no_home_servers;
2702 * This code executes in the main server
2703 * thread, so there's no need for locking.
2705 rad_assert(request->next_callback != NULL);
2706 INSERT_EVENT(request->next_callback, request);
2707 request->next_callback = NULL;
2709 } /* else the home server is still alive */
2711 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2712 inet_ntop(request->proxy->dst_ipaddr.af,
2713 &request->proxy->dst_ipaddr.ipaddr,
2714 buffer, sizeof(buffer)),
2715 request->proxy->dst_port,
2716 request->proxy->id);
2717 request->num_proxied_requests++;
2719 DEBUG_PACKET(request, request->proxy, 1);
2720 request->proxy_listener->send(request->proxy_listener,
2725 case REQUEST_REJECT_DELAY:
2726 RDEBUG2("Waiting to send Access-Reject "
2727 "to client %s port %d - ID: %d",
2729 request->packet->src_port, request->packet->id);
2732 case REQUEST_CLEANUP_DELAY:
2734 if (request->reply->code == 0) {
2735 RDEBUG2("Ignoring retransmit from client %s port %d "
2736 "- ID: %d, no reply was configured",
2738 request->packet->src_port, request->packet->id);
2743 * FIXME: This sends duplicate replies to
2744 * accounting requests, even if Acct-Delay-Time
2745 * or Event-Timestamp is in the packet. In those
2746 * cases, the Id should be changed, and the packet
2749 RDEBUG2("Sending duplicate reply "
2750 "to client %s port %d - ID: %d",
2752 request->packet->src_port, request->packet->id);
2753 DEBUG_PACKET(request, request->reply, 1);
2754 request->listener->send(request->listener, request);
2760 static void received_conflicting_request(REQUEST *request,
2761 const RADCLIENT *client)
2763 radlog(L_ERR, "Received conflicting packet from "
2764 "client %s port %d - ID: %d due to unfinished request %u. Giving up on old request.",
2766 request->packet->src_port, request->packet->id,
2770 * Nuke it from the request hash, so we can receive new
2773 remove_from_request_hash(request);
2775 switch (request->child_state) {
2776 #ifdef HAVE_PTHREAD_H
2778 * It's queued or running. Tell it to stop, and
2779 * wait for it to do so.
2781 case REQUEST_QUEUED:
2782 case REQUEST_RUNNING:
2783 request->master_state = REQUEST_STOP_PROCESSING;
2784 request->delay += request->delay >> 1;
2786 tv_add(&request->when, request->delay);
2788 INSERT_EVENT(wait_for_child_to_die, request);
2793 * Catch race conditions. It may have switched
2794 * from running to done while this code is being
2797 case REQUEST_REJECT_DELAY:
2798 case REQUEST_CLEANUP_DELAY:
2803 * It's in some other state, and therefore also
2804 * in the event queue. At some point, the
2805 * child will notice, and we can then delete it.
2807 case REQUEST_PROXIED:
2814 static int can_handle_new_request(RADIUS_PACKET *packet,
2816 struct main_config_t *root)
2819 * Count the total number of requests, to see if
2820 * there are too many. If so, return with an
2823 if (root->max_requests) {
2824 int request_count = fr_packet_list_num_elements(pl);
2827 * This is a new request. Let's see if
2828 * it makes us go over our configured
2831 if (request_count > root->max_requests) {
2832 radlog(L_ERR, "Dropping request (%d is too many): "
2833 "from client %s port %d - ID: %d", request_count,
2835 packet->src_port, packet->id);
2836 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2837 "\tThe value for 'max_requests' is probably set too low.\n");
2839 } /* else there were a small number of requests */
2840 } /* else there was no configured limit for requests */
2843 * FIXME: Add per-client checks. If one client is sending
2844 * too many packets, start discarding them.
2846 * We increment the counters here, and decrement them
2847 * when the response is sent... somewhere in this file.
2851 * FUTURE: Add checks for system load. If the system is
2852 * busy, start dropping requests...
2854 * We can probably keep some statistics ourselves... if
2855 * there are more requests coming in than we can handle,
2856 * start dropping some.
2863 int received_request(rad_listen_t *listener,
2864 RADIUS_PACKET *packet, REQUEST **prequest,
2867 RADIUS_PACKET **packet_p;
2868 REQUEST *request = NULL;
2869 struct main_config_t *root = &mainconfig;
2871 packet_p = fr_packet_list_find(pl, packet);
2873 request = fr_packet2myptr(REQUEST, packet, packet_p);
2874 rad_assert(request->in_request_hash);
2876 if ((request->packet->data_len == packet->data_len) &&
2877 (memcmp(request->packet->vector, packet->vector,
2878 sizeof(packet->vector)) == 0)) {
2879 received_retransmit(request, client);
2884 * The new request is different from the old one,
2885 * but maybe the old is finished. If so, delete
2888 switch (request->child_state) {
2889 struct timeval when;
2893 * Special hacks for race conditions.
2894 * The reply is encoded, and therefore
2895 * likely sent. We received a *new*
2896 * packet from the client, likely before
2897 * the next line or two of code which
2898 * updated the child state. In this
2899 * case, just accept the new request.
2901 if ((request->reply->code != 0) &&
2902 request->reply->data) {
2903 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %u.",
2905 packet->src_port, packet->id,
2907 remove_from_request_hash(request);
2912 gettimeofday(&when, NULL);
2916 * If the cached request was received
2917 * within the last second, then we
2918 * discard the NEW request instead of the
2919 * old one. This will happen ONLY when
2920 * the client is severely broken, and is
2921 * sending conflicting packets very
2924 if (timercmp(&when, &request->received, <)) {
2925 radlog(L_ERR, "Discarding conflicting packet from "
2926 "client %s port %d - ID: %d due to recent request %u.",
2928 packet->src_port, packet->id,
2933 received_conflicting_request(request, client);
2937 case REQUEST_REJECT_DELAY:
2938 case REQUEST_CLEANUP_DELAY:
2939 request->child_state = REQUEST_DONE;
2943 cleanup_delay(request);
2950 * We may want to quench the new request.
2952 if ((listener->type != RAD_LISTEN_DETAIL) &&
2953 !can_handle_new_request(packet, client, root)) {
2958 * Create and initialize the new request.
2960 request = request_alloc(); /* never fails */
2962 if ((request->reply = rad_alloc(0)) == NULL) {
2963 radlog(L_ERR, "No memory");
2967 request->listener = listener;
2968 request->client = client;
2969 request->packet = packet;
2970 request->packet->timestamp = request->timestamp;
2971 request->number = request_num_counter++;
2972 request->priority = listener->type;
2973 #ifdef HAVE_PTHREAD_H
2974 request->thread_id = NO_CHILD_THREAD;
2978 * Status-Server packets go to the head of the queue.
2980 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2983 * Set virtual server identity
2985 if (client->server) {
2986 request->server = client->server;
2987 } else if (listener->server) {
2988 request->server = listener->server;
2990 request->server = NULL;
2994 * Remember the request in the list.
2996 if (!fr_packet_list_insert(pl, &request->packet)) {
2997 radlog(L_ERR, "Failed to insert request %u in the list of live requests: discarding", request->number);
2998 ev_request_free(&request);
3002 request->in_request_hash = TRUE;
3003 request->root = root;
3007 * The request passes many of our sanity checks.
3008 * From here on in, if anything goes wrong, we
3009 * send a reject message, instead of dropping the
3014 * Build the reply template from the request.
3017 request->reply->sockfd = request->packet->sockfd;
3018 request->reply->dst_ipaddr = request->packet->src_ipaddr;
3019 request->reply->src_ipaddr = request->packet->dst_ipaddr;
3020 request->reply->dst_port = request->packet->src_port;
3021 request->reply->src_port = request->packet->dst_port;
3022 request->reply->id = request->packet->id;
3023 request->reply->code = 0; /* UNKNOWN code */
3024 memcpy(request->reply->vector, request->packet->vector,
3025 sizeof(request->reply->vector));
3026 request->reply->vps = NULL;
3027 request->reply->data = NULL;
3028 request->reply->data_len = 0;
3030 request->master_state = REQUEST_ACTIVE;
3031 request->child_state = REQUEST_QUEUED;
3032 request->next_callback = NULL;
3034 gettimeofday(&request->received, NULL);
3035 request->timestamp = request->received.tv_sec;
3036 request->when = request->received;
3038 request->delay = USEC;
3040 tv_add(&request->when, request->delay);
3042 INSERT_EVENT(wait_a_bit, request);
3044 *prequest = request;
3050 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
3056 * Also removes from the proxy hash if responses == requests
3058 request = lookup_in_proxy_hash(packet);
3061 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
3062 inet_ntop(packet->src_ipaddr.af,
3063 &packet->src_ipaddr.ipaddr,
3064 buffer, sizeof(buffer)),
3065 packet->src_port, packet->id);
3070 * We haven't replied to the NAS, but we have seen an
3071 * earlier reply from the home server. Ignore this packet,
3072 * as we're likely still processing the previous reply.
3074 if (request->proxy_reply) {
3075 if (memcmp(request->proxy_reply->vector,
3077 sizeof(request->proxy_reply->vector)) == 0) {
3078 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %u",
3079 inet_ntop(packet->src_ipaddr.af,
3080 &packet->src_ipaddr.ipaddr,
3081 buffer, sizeof(buffer)),
3082 packet->src_port, packet->id,
3086 * ? The home server gave us a new proxy
3087 * reply which doesn't match the old
3090 RDEBUG2("Ignoring conflicting proxy reply");
3093 /* assert that there's an event queued for request? */
3098 * Verify the packet before doing ANYTHING with it. This
3099 * means we're doing more MD5 checks in the server core.
3100 * However, we can fix that by moving to multiple threads
3101 * listening on sockets.
3103 * We do this AFTER looking the request up in the hash,
3104 * and AFTER vhecking if we saw a previous request. This
3105 * helps minimize the DoS effect of people attacking us
3106 * with spoofed packets.
3108 if (rad_verify(packet, request->proxy,
3109 request->home_server->secret) != 0) {
3110 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3114 gettimeofday(&now, NULL);
3117 * "ping" packets have a different algorithm for marking
3118 * a home server alive. They also skip all of the CoA,
3121 if (!request->packet) {
3122 request->proxy_reply = packet;
3123 received_response_to_ping(request);
3124 request->proxy_reply = NULL; /* caller will free it */
3125 ev_request_free(&request);
3130 * Maybe move this earlier in the decision process?
3131 * Having it here means that late or duplicate proxy
3132 * replies no longer get the home server marked as
3133 * "alive". This might be good for stability, though.
3135 * FIXME: Do we really want to do this whenever we
3136 * receive a packet? Setting this here means that we
3137 * mark it alive on *any* packet, even if it's lost all
3138 * of the *other* packets in the last 10s.
3140 * This behavior could be configurable.
3142 request->home_server->state = HOME_STATE_ALIVE;
3143 request->home_server->last_packet = now.tv_sec;
3147 * When originating CoA, the "proxy" reply is the reply
3148 * to the CoA request that we originated. At this point,
3149 * the original request is finished, and it has a reply.
3151 * However, if we haven't separated the two requests, do
3152 * so now. This is done so that cleaning up the original
3153 * request won't cause the CoA request to be free'd. See
3154 * util.c, request_free()
3156 if (request->parent && (request->parent->coa == request)) {
3157 request->parent->coa = NULL;
3158 request->parent = NULL;
3161 * The proxied packet was different from the
3162 * original packet, AND the proxied packet was
3165 } else if ((request->packet->code != request->proxy->code) &&
3166 ((request->proxy->code == PW_COA_REQUEST) ||
3167 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
3169 * It's already divorced: do nothing.
3174 * Skip the next set of checks, as the original
3175 * reply is cached. We want to be able to still
3176 * process the CoA reply, AND to reference the
3177 * original request/reply.
3179 * This is getting to be really quite a bit of a
3185 * If there's a reply to the NAS, ignore everything
3186 * related to proxy responses
3188 if (request->reply && request->reply->code != 0) {
3189 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3195 * The average includes our time to receive packets and
3196 * look them up in the hashes, which should be the same
3199 * We update the response time only for the FIRST packet
3202 if (request->home_server->ema.window > 0) {
3203 radius_stats_ema(&request->home_server->ema,
3204 &now, &request->proxy_when);
3208 switch (request->child_state) {
3209 case REQUEST_QUEUED:
3210 case REQUEST_RUNNING:
3211 radlog(L_ERR, "Internal sanity check failed for child state");
3214 case REQUEST_REJECT_DELAY:
3215 case REQUEST_CLEANUP_DELAY:
3217 radlog(L_ERR, "Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
3218 inet_ntop(packet->src_ipaddr.af,
3219 &packet->src_ipaddr.ipaddr,
3220 buffer, sizeof(buffer)),
3221 packet->src_port, packet->id,
3223 /* assert that there's an event queued for request? */
3226 case REQUEST_PROXIED:
3230 request->proxy_reply = packet;
3234 * Perform RTT calculations, as per RFC 2988 (for TCP).
3235 * Note that we only do so on the first response.
3237 if ((request->num_proxied_responses == 1)
3239 home_server *home = request->home_server;
3241 rtt = now.tv_sec - request->proxy_when.tv_sec;
3244 rtt -= request->proxy_when.tv_usec;
3246 if (!home->has_rtt) {
3247 home->has_rtt = TRUE;
3250 home->rttvar = rtt / 2;
3253 home->rttvar -= home->rttvar >> 2;
3254 home->rttvar += (home->srtt - rtt);
3255 home->srtt -= home->srtt >> 3;
3256 home->srtt += rtt >> 3;
3259 home->rto = home->srtt;
3260 if (home->rttvar > (USEC / 4)) {
3261 home->rto += home->rttvar * 4;
3268 request->child_state = REQUEST_QUEUED;
3269 request->when = now;
3270 request->delay = USEC;
3271 request->priority = RAD_LISTEN_PROXY;
3272 tv_add(&request->when, request->delay);
3275 * Wait a bit will take care of max_request_time
3277 INSERT_EVENT(wait_a_bit, request);
3283 void event_new_fd(rad_listen_t *this)
3287 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3289 this->print(this, buffer, sizeof(buffer));
3291 if (this->status == RAD_LISTEN_STATUS_INIT) {
3293 DEBUG("Listening on %s", buffer);
3295 radlog(L_INFO, " ... adding new socket %s", buffer);
3297 if (!fr_event_fd_insert(el, 0, this->fd,
3298 event_socket_handler, this)) {
3299 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3303 this->status = RAD_LISTEN_STATUS_KNOWN;
3307 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3308 DEBUG(" ... closing socket %s", buffer);
3310 fr_event_fd_delete(el, 0, this->fd);
3311 this->status = RAD_LISTEN_STATUS_FINISH;
3314 * Close the fd AFTER fixing up the requests and
3315 * listeners, so that they don't send/recv on the
3316 * wrong socket (if someone manages to open
3324 static void handle_signal_self(int flag)
3326 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3327 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3328 radlog(L_INFO, "Signalled to exit");
3329 fr_event_loop_exit(el, 1);
3331 radlog(L_INFO, "Signalled to terminate");
3332 fr_event_loop_exit(el, 2);
3336 } /* else exit/term flags weren't set */
3339 * Tell the even loop to stop processing.
3341 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3343 static time_t last_hup = 0;
3346 if ((int) (when - last_hup) < 5) {
3347 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3351 radlog(L_INFO, "Received HUP signal.");
3355 fr_event_loop_exit(el, 0x80);
3359 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3363 * FIXME: O(N) loops suck.
3365 for (this = mainconfig.listen;
3367 this = this->next) {
3368 if (this->type != RAD_LISTEN_DETAIL) continue;
3371 * This one didn't send the signal, skip
3374 if (!this->decode(this, NULL)) continue;
3377 * Go service the interrupt.
3379 event_poll_detail(this);
3384 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3387 for (this = mainconfig.listen;
3389 this = this->next) {
3395 #ifndef WITH_SELF_PIPE
3396 void radius_signal_self(int flag)
3398 handle_signal_self(flag);
3402 * Inform ourselves that we received a signal.
3404 void radius_signal_self(int flag)
3410 * The read MUST be non-blocking for this to work.
3412 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3416 for (i = 0; i < rcode; i++) {
3417 buffer[0] |= buffer[i];
3425 write(self_pipe[1], buffer, 1);
3429 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3430 UNUSED int fd, UNUSED void *ctx)
3435 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3436 if (rcode <= 0) return;
3439 * Merge pending signals.
3441 for (i = 0; i < rcode; i++) {
3442 buffer[0] |= buffer[i];
3445 handle_signal_self(buffer[0]);
3450 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3453 rad_listen_t *listener = ctx;
3454 RAD_REQUEST_FUNP fun;
3457 rad_assert(xel == el);
3461 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3463 if (!listener->recv(listener, &fun, &request)) return;
3465 if (!thread_pool_addrequest(request, fun)) {
3466 request->child_state = REQUEST_DONE;
3472 * This function is called periodically to see if this detail
3473 * file is available for reading.
3475 static void event_poll_detail(void *ctx)
3478 RAD_REQUEST_FUNP fun;
3480 rad_listen_t *this = ctx;
3481 struct timeval when;
3482 listen_detail_t *detail = this->data;
3484 rad_assert(this->type == RAD_LISTEN_DETAIL);
3487 * Try to read something.
3489 * FIXME: This does poll AND receive.
3491 rcode = this->recv(this, &fun, &request);
3493 rad_assert(fun != NULL);
3494 rad_assert(request != NULL);
3496 if (!thread_pool_addrequest(request, fun)) {
3497 request->child_state = REQUEST_DONE;
3501 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3505 * Backdoor API to get the delay until the next poll
3508 delay = this->encode(this, NULL);
3509 tv_add(&when, delay);
3511 if (!fr_event_insert(el, event_poll_detail, this,
3512 &when, &detail->ev)) {
3513 radlog(L_ERR, "Failed creating handler");
3519 static void event_status(struct timeval *wake)
3521 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3525 if (debug_flag == 0) {
3527 radlog(L_INFO, "Ready to process requests.");
3528 just_started = FALSE;
3534 radlog(L_INFO, "Ready to process requests.");
3536 } else if ((wake->tv_sec != 0) ||
3537 (wake->tv_usec >= 100000)) {
3538 DEBUG("Waking up in %d.%01u seconds.",
3539 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3544 * FIXME: Put this somewhere else, where it isn't called
3545 * all of the time...
3548 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3550 * If there are no child threads, then there may
3551 * be child processes. In that case, wait for
3552 * their exit status, and throw that exit status
3553 * away. This helps get rid of zxombie children.
3555 while (waitpid(-1, &argval, WNOHANG) > 0) {
3563 * Externally-visibly functions.
3565 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3567 rad_listen_t *this, *head = NULL;
3571 time(&fr_start_time);
3573 el = fr_event_list_create(event_status);
3576 pl = fr_packet_list_create(0);
3577 if (!pl) return 0; /* leak el */
3579 request_num_counter = 0;
3582 if (mainconfig.proxy_requests) {
3584 * Create the tree for managing proxied requests and
3587 proxy_list = fr_packet_list_create(1);
3588 if (!proxy_list) return 0;
3590 #ifdef HAVE_PTHREAD_H
3591 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3592 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3600 #ifdef HAVE_PTHREAD_H
3602 * Initialize the threads ONLY if we're spawning, AND
3603 * we're running normally.
3605 if (spawn_flag && !check_config &&
3606 (thread_pool_init(cs, &spawn_flag) < 0)) {
3612 * Move all of the thread calls to this file?
3614 * It may be best for the mutexes to be in this file...
3616 have_children = spawn_flag;
3619 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3621 if (listen_init(cs, &head) < 0) {
3628 #ifdef WITH_SELF_PIPE
3630 * Child threads need a pipe to signal us, as do the
3633 if (pipe(self_pipe) < 0) {
3634 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3638 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
3639 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
3640 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3644 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
3645 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
3646 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3651 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3652 event_signal_handler, el)) {
3653 radlog(L_ERR, "Failed creating handler for signals");
3656 #endif /* WITH_SELF_PIPE */
3660 * Mark the proxy Fd's as unused.
3665 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3669 DEBUG("%s: #### Opening IP addresses and Ports ####",
3673 * The server temporarily switches to an unprivileged
3674 * user very early in the bootstrapping process.
3675 * However, some sockets MAY require privileged access
3676 * (bind to device, or to port < 1024, or to raw
3677 * sockets). Those sockets need to call suid up/down
3678 * themselves around the functions that need a privileged
3681 if (listen_init(cs, &head) < 0) {
3686 * At this point, no one has any business *ever* going
3689 fr_suid_down_permanent();
3692 * Add all of the sockets to the event loop.
3696 this = this->next) {
3699 this->print(this, buffer, sizeof(buffer));
3701 switch (this->type) {
3703 case RAD_LISTEN_DETAIL:
3704 DEBUG("Listening on %s", buffer);
3707 * Detail files are always known, and aren't
3708 * put into the socket event loop.
3710 this->status = RAD_LISTEN_STATUS_KNOWN;
3713 * Set up the first poll interval.
3715 event_poll_detail(this);
3720 case RAD_LISTEN_PROXY:
3721 if (proxy_add_fds(this) < 0) {
3722 radlog(L_ERR, "Failed creating new proxy socket");
3726 if (!fr_packet_list_socket_add(proxy_list,
3740 mainconfig.listen = head;
3746 static int request_hash_cb(UNUSED void *ctx, void *data)
3748 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3751 rad_assert(request->in_proxy_hash == FALSE);
3754 ev_request_free(&request);
3761 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3763 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3765 ev_request_free(&request);
3771 void radius_event_free(void)
3774 * Stop and join all threads.
3776 #ifdef HAVE_PTHREAD_H
3782 * There are requests in the proxy hash that aren't
3783 * referenced from anywhere else. Remove them first.
3786 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3787 fr_packet_list_free(proxy_list);
3792 fr_packet_list_walk(pl, NULL, request_hash_cb);
3794 fr_packet_list_free(pl);
3797 fr_event_list_free(el);
3800 int radius_event_process(void)
3804 return fr_event_loop(el);
3807 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3809 request->options = RAD_REQUEST_OPTION_DEBUG2;
3811 if (request_pre_handler(request)) {
3812 rad_assert(fun != NULL);
3813 rad_assert(request != NULL);
3815 if (request->server) RDEBUG("server %s {",
3816 request->server != NULL ?
3817 request->server : "");
3820 if (request->server) RDEBUG("} # server %s",
3821 request->server != NULL ?
3822 request->server : "");
3824 request_post_handler(request);
3827 DEBUG2("Going to the next request");