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 static pthread_t NO_SUCH_CHILD_PID;
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 request_free(prequest);
188 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
190 RADIUS_PACKET **proxy_p;
193 PTHREAD_MUTEX_LOCK(&proxy_mutex);
194 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
197 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
201 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
204 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
208 request->num_proxied_responses++;
211 * Catch the most common case of everything working
214 if (request->num_proxied_requests == request->num_proxied_responses) {
215 fr_packet_list_yank(proxy_list, request->proxy);
216 fr_packet_list_id_free(proxy_list, request->proxy);
217 request->in_proxy_hash = FALSE;
221 * On the FIRST reply, decrement the count of outstanding
222 * requests. Note that this is NOT the count of sent
223 * packets, but whether or not the home server has
226 if (!request->proxy_reply &&
227 request->home_server &&
228 request->home_server->currently_outstanding) {
229 request->home_server->currently_outstanding--;
232 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
238 static void remove_from_proxy_hash(REQUEST *request)
241 * Check this without grabbing the mutex because it's a
242 * lot faster that way.
244 if (!request->in_proxy_hash) return;
247 * The "not in hash" flag is definitive. However, if the
248 * flag says that it IS in the hash, there might still be
249 * a race condition where it isn't.
251 PTHREAD_MUTEX_LOCK(&proxy_mutex);
253 if (!request->in_proxy_hash) {
254 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
258 fr_packet_list_yank(proxy_list, request->proxy);
259 fr_packet_list_id_free(proxy_list, request->proxy);
262 * The home server hasn't replied, but we've given up on
263 * this request. Don't count this request against the
266 if (!request->proxy_reply &&
267 request->home_server &&
268 request->home_server->currently_outstanding) {
269 request->home_server->currently_outstanding--;
273 * Got from YES in hash, to NO, not in hash while we hold
274 * the mutex. This guarantees that when another thread
275 * grans the mutex, the "not in hash" flag is correct.
277 request->in_proxy_hash = FALSE;
279 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
282 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
285 rad_listen_t *proxy_listener;
287 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
289 if (proxy_all_used) return 0;
292 * Allocate a new proxy fd. This function adds
293 * it to the tail of the list of listeners. With
294 * some care, this can be thread-safe.
296 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
297 if (!proxy_listener) {
298 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
306 proxy = proxy_listener->fd;
307 for (i = 0; i < 32; i++) {
309 * Found a free entry. Save the socket,
310 * and remember where we saved it.
312 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
313 found = (proxy + i) & 0x1f;
314 proxy_fds[found] = proxy;
315 proxy_listeners[found] = proxy_listener;
320 proxy_all_used = TRUE;
321 listen_free(&proxy_listener);
322 radlog(L_ERR, "Failed creating new proxy socket: server is too busy and home servers appear to be down");
327 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
328 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
333 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
334 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
339 * Signal the main thread to add the new FD to the list
342 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
347 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
352 rad_assert(request->proxy != NULL);
353 rad_assert(proxy_list != NULL);
355 PTHREAD_MUTEX_LOCK(&proxy_mutex);
358 * Keep track of maximum outstanding requests to a
359 * particular home server. 'max_outstanding' is
360 * enforced in home_server_ldb(), in realms.c.
362 if (request->home_server) {
363 request->home_server->currently_outstanding++;
367 RADIUS_PACKET packet;
369 packet = *request->proxy;
371 if (!proxy_id_alloc(request, &packet)) {
372 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
377 * Yank the request, free the old Id, and
378 * remember the new Id.
380 fr_packet_list_yank(proxy_list, request->proxy);
381 fr_packet_list_id_free(proxy_list, request->proxy);
382 *request->proxy = packet;
384 } else if (!proxy_id_alloc(request, request->proxy)) {
385 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
389 rad_assert(request->proxy->sockfd >= 0);
392 * FIXME: Hack until we get rid of rad_listen_t, and put
393 * the information into the packet_list.
396 for (i = 0; i < 32; i++) {
397 if (proxy_fds[i] == request->proxy->sockfd) {
404 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
405 RDEBUG2("ERROR: All sockets are full.");
409 rad_assert(proxy_fds[proxy] != -1);
410 rad_assert(proxy_listeners[proxy] != NULL);
411 request->proxy_listener = proxy_listeners[proxy];
413 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
414 fr_packet_list_id_free(proxy_list, request->proxy);
415 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
416 RDEBUG2("ERROR: Failed to insert entry into proxy list.");
420 request->in_proxy_hash = TRUE;
422 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
424 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
425 inet_ntop(request->proxy->dst_ipaddr.af,
426 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
427 request->proxy->dst_port,
435 * Called as BOTH an event, and in-line from other functions.
437 static void wait_for_proxy_id_to_expire(void *ctx)
439 REQUEST *request = ctx;
441 rad_assert(request->magic == REQUEST_MAGIC);
442 rad_assert(request->proxy != NULL);
444 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
445 request->when = request->proxy_when;
448 if (((request->proxy->code == PW_COA_REQUEST) ||
449 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
450 (request->packet->code != request->proxy->code)) {
451 request->when.tv_sec += request->home_server->coa_mrd;
454 request->when.tv_sec += request->home_server->response_window;
456 if ((request->num_proxied_requests == request->num_proxied_responses) ||
457 timercmp(&now, &request->when, >)) {
458 if (request->packet) {
459 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
460 request->number, request->packet->id,
461 (unsigned int) (request->timestamp - fr_start_time));
463 RDEBUG2("Cleaning up request %u with timestamp +%d",
465 (unsigned int) (request->timestamp - fr_start_time));
468 ev_request_free(&request);
472 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
476 #ifdef HAVE_PTHREAD_H
477 static void wait_for_child_to_die(void *ctx)
479 REQUEST *request = ctx;
481 rad_assert(request->magic == REQUEST_MAGIC);
482 remove_from_request_hash(request);
485 * If it's still queued (waiting for a thread to pick it
486 * up) OR, it's running AND there's still a child thread
487 * handling it, THEN delay some more.
489 if ((request->child_state == REQUEST_QUEUED) ||
490 ((request->child_state == REQUEST_RUNNING) &&
491 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0))) {
494 * Cap delay at max_request_time
496 if (request->delay < (USEC * request->root->max_request_time)) {
497 request->delay += (request->delay >> 1);
498 radlog(L_INFO, "WARNING: Child is hung for request %u in component %s module %s.",
499 request->number, request->component, request->module);
501 request->delay = USEC * request->root->max_request_time;
502 RDEBUG2("WARNING: Child is still stuck for request %u",
505 tv_add(&request->when, request->delay);
507 INSERT_EVENT(wait_for_child_to_die, request);
511 RDEBUG2("Child is finally responsive for request %u", request->number);
514 if (request->proxy) {
515 wait_for_proxy_id_to_expire(request);
520 ev_request_free(&request);
524 static void cleanup_delay(void *ctx)
526 REQUEST *request = ctx;
528 rad_assert(request->magic == REQUEST_MAGIC);
529 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
530 (request->child_state == REQUEST_DONE));
532 remove_from_request_hash(request);
535 if (request->proxy && request->in_proxy_hash) {
536 wait_for_proxy_id_to_expire(request);
541 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
542 request->number, request->packet->id,
543 (unsigned int) (request->timestamp - fr_start_time));
545 ev_request_free(&request);
550 * In daemon mode, AND this request has debug flags set.
552 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
554 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
558 const char *received, *from;
559 const fr_ipaddr_t *ip;
564 rad_assert(request->radlog != NULL);
566 if (direction == 0) {
567 received = "Received";
568 from = "from"; /* what else? */
569 ip = &packet->src_ipaddr;
570 port = packet->src_port;
573 received = "Sending";
574 from = "to"; /* hah! */
575 ip = &packet->dst_ipaddr;
576 port = packet->dst_port;
580 * Client-specific debugging re-prints the input
581 * packet into the client log.
583 * This really belongs in a utility library
585 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
586 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
587 received, fr_packet_codes[packet->code], from,
588 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
589 port, packet->id, packet->data_len);
591 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
593 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
595 packet->code, packet->id, packet->data_len);
598 for (vp = packet->vps; vp != NULL; vp = vp->next) {
599 vp_prints(buffer, sizeof(buffer), vp);
600 request->radlog(L_DBG, 0, request, "\t%s", buffer);
604 static void reject_delay(void *ctx)
606 REQUEST *request = ctx;
608 rad_assert(request->magic == REQUEST_MAGIC);
609 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
611 RDEBUG2("Sending delayed reject for request %u", request->number);
613 DEBUG_PACKET(request, request->reply, 1);
615 request->listener->send(request->listener, request);
617 request->when.tv_sec += request->root->cleanup_delay;
618 request->child_state = REQUEST_CLEANUP_DELAY;
620 INSERT_EVENT(cleanup_delay, request);
625 void revive_home_server(void *ctx)
627 home_server *home = ctx;
630 home->state = HOME_STATE_ALIVE;
631 home->currently_outstanding = 0;
632 home->revive_time = now;
635 * Delete any outstanding events.
637 if (home->ev) fr_event_delete(el, &home->ev);
639 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
640 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
641 buffer, sizeof(buffer)),
647 static void no_response_to_ping(void *ctx)
649 REQUEST *request = ctx;
653 rad_assert(request->home_server != NULL);
655 home = request->home_server;
656 home->num_received_pings = 0;
658 radlog(L_ERR, "No response to status check %d for home server %s port %d",
660 inet_ntop(request->proxy->dst_ipaddr.af,
661 &request->proxy->dst_ipaddr.ipaddr,
662 buffer, sizeof(buffer)),
663 request->proxy->dst_port);
665 check_for_zombie_home_server(request);
667 wait_for_proxy_id_to_expire(request);
671 static void received_response_to_ping(REQUEST *request)
676 rad_assert(request->home_server != NULL);
678 home = request->home_server;
679 home->num_received_pings++;
681 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
682 request->number, home->num_received_pings);
685 * Remove the request from any hashes
687 fr_event_delete(el, &request->ev);
688 remove_from_proxy_hash(request);
689 rad_assert(request->in_request_hash == FALSE);
692 * The control socket may have marked the home server as
693 * alive. OR, it may have suddenly started responding to
694 * requests again. If so, don't re-do the "make alive"
697 if (home->state == HOME_STATE_ALIVE) return;
700 * We haven't received enough ping responses to mark it
701 * "alive". Wait a bit.
703 if (home->num_received_pings < home->num_pings_to_alive) {
707 home->state = HOME_STATE_ALIVE;
708 home->currently_outstanding = 0;
709 home->revive_time = now;
711 if (!fr_event_delete(el, &home->ev)) {
712 RDEBUG2("Hmm... no event for home server. Oh well.");
715 radlog(L_PROXY, "Marking home server %s port %d alive",
716 inet_ntop(request->proxy->dst_ipaddr.af,
717 &request->proxy->dst_ipaddr.ipaddr,
718 buffer, sizeof(buffer)),
719 request->proxy->dst_port);
724 * Called from start of zombie period, OR after control socket
725 * marks the home server dead.
727 static void ping_home_server(void *ctx)
730 home_server *home = ctx;
734 if ((home->state == HOME_STATE_ALIVE) ||
735 (home->ping_check == HOME_PING_CHECK_NONE) ||
736 (home->ev != NULL)) {
740 request = request_alloc();
741 request->number = request_num_counter++;
743 request->proxy = rad_alloc(1);
744 rad_assert(request->proxy != NULL);
746 fr_event_now(el, &request->when);
747 home->when = request->when;
749 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
750 request->proxy->code = PW_STATUS_SERVER;
752 radius_pairmake(request, &request->proxy->vps,
753 "Message-Authenticator", "0x00", T_OP_SET);
755 } else if (home->type == HOME_TYPE_AUTH) {
756 request->proxy->code = PW_AUTHENTICATION_REQUEST;
758 radius_pairmake(request, &request->proxy->vps,
759 "User-Name", home->ping_user_name, T_OP_SET);
760 radius_pairmake(request, &request->proxy->vps,
761 "User-Password", home->ping_user_password, T_OP_SET);
762 radius_pairmake(request, &request->proxy->vps,
763 "Service-Type", "Authenticate-Only", T_OP_SET);
764 radius_pairmake(request, &request->proxy->vps,
765 "Message-Authenticator", "0x00", T_OP_SET);
768 #ifdef WITH_ACCOUNTING
769 request->proxy->code = PW_ACCOUNTING_REQUEST;
771 radius_pairmake(request, &request->proxy->vps,
772 "User-Name", home->ping_user_name, T_OP_SET);
773 radius_pairmake(request, &request->proxy->vps,
774 "Acct-Status-Type", "Stop", T_OP_SET);
775 radius_pairmake(request, &request->proxy->vps,
776 "Acct-Session-Id", "00000000", T_OP_SET);
777 vp = radius_pairmake(request, &request->proxy->vps,
778 "Event-Timestamp", "0", T_OP_SET);
779 vp->vp_date = now.tv_sec;
781 rad_assert("Internal sanity check failed");
785 radius_pairmake(request, &request->proxy->vps,
786 "NAS-Identifier", "Status Check. Are you alive?",
789 request->proxy->dst_ipaddr = home->ipaddr;
790 request->proxy->dst_port = home->port;
791 request->home_server = home;
793 rad_assert(request->proxy_listener == NULL);
795 if (!insert_into_proxy_hash(request, FALSE)) {
796 RDEBUG2("ERROR: Failed to insert status check %d into proxy list. Discarding it.",
798 ev_request_free(&request);
801 rad_assert(request->proxy_listener != NULL);
802 request->proxy_listener->send(request->proxy_listener,
805 request->next_callback = NULL;
806 request->child_state = REQUEST_PROXIED;
807 gettimeofday(&request->when, NULL);
808 home->when = request->when;
809 request->when.tv_sec += home->ping_timeout;;
811 INSERT_EVENT(no_response_to_ping, request);
814 * Add +/- 2s of jitter, as suggested in RFC 3539
815 * and in the Issues and Fixes draft.
817 home->when.tv_sec += home->ping_interval - 2;
820 jitter ^= (jitter >> 10);
821 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
823 tv_add(&home->when, jitter);
825 INSERT_EVENT(ping_home_server, home);
829 void mark_home_server_dead(home_server *home, struct timeval *when)
831 int previous_state = home->state;
834 radlog(L_PROXY, "Marking home server %s port %d as dead.",
835 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
836 buffer, sizeof(buffer)),
839 home->state = HOME_STATE_IS_DEAD;
840 home->num_received_pings = 0;
842 if (home->ping_check != HOME_PING_CHECK_NONE) {
844 * If the control socket marks us dead, start
845 * pinging. Otherwise, we already started
846 * pinging when it was marked "zombie".
848 if (previous_state == HOME_STATE_ALIVE) {
849 ping_home_server(home);
854 * Revive it after a fixed period of time. This
855 * is very, very, bad.
858 home->when.tv_sec += home->revive_interval;
860 INSERT_EVENT(revive_home_server, home);
864 static void check_for_zombie_home_server(REQUEST *request)
869 home = request->home_server;
871 if (home->state != HOME_STATE_ZOMBIE) return;
873 when = home->zombie_period_start;
874 when.tv_sec += home->zombie_period;
876 fr_event_now(el, &now);
877 if (timercmp(&now, &when, <)) {
881 mark_home_server_dead(home, &request->when);
884 static int proxy_to_virtual_server(REQUEST *request);
886 static int virtual_server_handler(UNUSED REQUEST *request)
888 proxy_to_virtual_server(request);
892 static void proxy_fallback_handler(REQUEST *request)
895 * A proper time is required for wait_a_bit.
897 request->delay = USEC / 10;
898 gettimeofday(&now, NULL);
899 request->next_when = now;
900 tv_add(&request->next_when, request->delay);
901 request->next_callback = wait_a_bit;
904 * Re-queue the request.
906 request->child_state = REQUEST_QUEUED;
908 rad_assert(request->proxy != NULL);
909 if (!thread_pool_addrequest(request, virtual_server_handler)) {
910 request->child_state = REQUEST_DONE;
913 #ifdef HAVE_PTHREAD_H
915 * MAY free the request if we're over max_request_time,
916 * AND we're not in threaded mode!
918 * Note that we call this ONLY if we're threaded, as
919 * if we're NOT threaded, request_post_handler() calls
920 * wait_a_bit(), which means that "request" may not
923 if (have_children) wait_a_bit(request);
928 static int setup_post_proxy_fail(REQUEST *request)
930 DICT_VALUE *dval = NULL;
933 request->child_state = REQUEST_RUNNING;
935 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
936 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
938 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
939 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
943 * See no_response_to_coa_request
945 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
946 request->packet->code &= 0xff; /* restore it */
948 if (request->proxy->code == PW_COA_REQUEST) {
949 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
951 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
952 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
962 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
965 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
969 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
970 if (!vp) vp = radius_paircreate(request, &request->config_items,
971 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
972 vp->vp_integer = dval->value;
974 rad_assert(request->proxy_reply == NULL);
980 static int null_handler(UNUSED REQUEST *request)
985 static void post_proxy_fail_handler(REQUEST *request)
988 * A proper time is required for wait_a_bit.
990 request->delay = USEC / 10;
991 gettimeofday(&now, NULL);
994 * Not set up to run Post-Proxy-Type = Fail.
996 * Mark the request as still running, and figure out what
999 if (!setup_post_proxy_fail(request)) {
1000 request_post_handler(request);
1004 * Re-queue the request.
1006 request->child_state = REQUEST_QUEUED;
1009 * There is a post-proxy-type of fail. We run
1010 * the request through the pre/post proxy
1011 * handlers, just like it was a real proxied
1012 * request. However, we set the per-request
1013 * handler to NULL, as we don't want to do
1016 * Note that when we're not threaded, this will
1017 * process the request even if it's greater than
1018 * max_request_time. That's not fatal.
1020 request->priority = 0;
1021 rad_assert(request->proxy != NULL);
1022 thread_pool_addrequest(request, null_handler);
1026 * MAY free the request if we're over max_request_time,
1027 * AND we're not in threaded mode!
1029 * Note that we call this ONLY if we're threaded, as
1030 * if we're NOT threaded, request_post_handler() calls
1031 * wait_a_bit(), which means that "request" may not
1034 if (have_children) wait_a_bit(request);
1038 /* maybe check this against wait_for_proxy_id_to_expire? */
1039 static void no_response_to_proxied_request(void *ctx)
1041 REQUEST *request = ctx;
1045 rad_assert(request->magic == REQUEST_MAGIC);
1046 rad_assert(request->child_state == REQUEST_PROXIED);
1049 * If we've failed over to an internal home server,
1050 * replace the callback with the correct one. This
1051 * is due to locking issues with child threads...
1053 if (request->home_server->server) {
1054 wait_a_bit(request);
1058 check_for_zombie_home_server(request);
1060 home = request->home_server;
1063 * The default as of 2.1.7 is to allow requests to
1064 * fail-over to a backup home server when this one does
1065 * not respond. The old behavior can be configured as
1068 if (home->no_response_fail) {
1069 radlog(L_ERR, "Rejecting request %u (proxy Id %d) due to lack of any response from home server %s port %d",
1070 request->number, request->proxy->id,
1071 inet_ntop(request->proxy->dst_ipaddr.af,
1072 &request->proxy->dst_ipaddr.ipaddr,
1073 buffer, sizeof(buffer)),
1074 request->proxy->dst_port);
1076 post_proxy_fail_handler(request);
1078 rad_assert(request->ev == NULL);
1079 request->child_state = REQUEST_RUNNING;
1080 wait_a_bit(request);
1084 * Don't touch request due to race conditions
1086 if (home->state == HOME_STATE_IS_DEAD) {
1087 rad_assert(home->ev != NULL); /* or it will never wake up */
1092 * Enable the zombie period when we notice that the home
1093 * server hasn't responded. We do NOT back-date the start
1094 * of the zombie period.
1096 if (home->state == HOME_STATE_ALIVE) {
1097 home->state = HOME_STATE_ZOMBIE;
1098 home->zombie_period_start = now;
1099 fr_event_delete(el, &home->ev);
1100 home->currently_outstanding = 0;
1101 home->num_received_pings = 0;
1103 radlog(L_PROXY, "Marking home server %s port %d as zombie (it looks like it is dead).",
1104 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1105 buffer, sizeof(buffer)),
1109 * Start pinging the home server.
1111 ping_home_server(home);
1116 static void wait_a_bit(void *ctx)
1118 struct timeval when;
1119 REQUEST *request = ctx;
1120 fr_event_callback_t callback = NULL;
1122 rad_assert(request->magic == REQUEST_MAGIC);
1126 * The CoA request is a new (internally generated)
1127 * request, created in a child thread. We therefore need
1128 * some way to tie its events back into the main event
1131 if (request->coa && !request->coa->proxy_reply &&
1132 request->coa->next_callback) {
1133 request->coa->when = request->coa->next_when;
1134 INSERT_EVENT(request->coa->next_callback, request->coa);
1135 request->coa->next_callback = NULL;
1136 request->coa->parent = NULL;
1137 request->coa = NULL;
1141 switch (request->child_state) {
1142 case REQUEST_QUEUED:
1143 case REQUEST_RUNNING:
1145 * If we're not thread-capable, OR we're capable,
1146 * but have been told to run without threads,
1147 * complain when the requests is queued for a
1148 * thread, or running in a child thread.
1150 #ifdef HAVE_PTHREAD_H
1154 rad_assert("We do not have threads, but the request is marked as queued or running in a child thread" == NULL);
1158 #ifdef HAVE_PTHREAD_H
1160 * If we have threads, wait for the child thread
1163 when = request->received;
1164 when.tv_sec += request->root->max_request_time;
1167 * Normally called from the event loop with the
1168 * proper event loop time. Otherwise, called from
1169 * post proxy fail handler, which sets "now", and
1170 * this call won't re-set it, because we're not
1171 * in the event loop.
1173 fr_event_now(el, &now);
1176 * Request still has more time. Continue
1179 if (timercmp(&now, &when, <)) {
1180 if (request->delay < (USEC / 10)) {
1181 request->delay = USEC / 10;
1183 request->delay += request->delay >> 1;
1186 * Cap delays at something reasonable.
1188 if (request->delay > (request->root->max_request_time * USEC)) {
1189 request->delay = request->root->max_request_time * USEC;
1192 request->when = now;
1193 tv_add(&request->when, request->delay);
1194 callback = wait_a_bit;
1198 request->master_state = REQUEST_STOP_PROCESSING;
1201 * A child thread MAY still be running on the
1202 * request. Ask the thread to stop working on
1205 if (have_children &&
1206 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
1207 radlog(L_ERR, "WARNING: Unresponsive child for request %u, in module %s component %s",
1209 request->module ? request->module : "<server core>",
1210 request->component ? request->component : "<server core>");
1213 request->delay = USEC;
1214 tv_add(&request->when, request->delay);
1215 callback = wait_for_child_to_die;
1220 * Mark the request as no longer running,
1224 #ifdef HAVE_PTHREAD_H
1225 request->child_pid = NO_SUCH_CHILD_PID;
1230 * This is a CoA request. It's been divorced
1231 * from everything else, so we clean it up now.
1233 if (!request->in_request_hash &&
1235 (request->packet->code != request->proxy->code) &&
1236 ((request->proxy->code == PW_COA_REQUEST) ||
1237 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1239 * FIXME: Do CoA MIBs
1241 ev_request_free(&request);
1245 request_stats_final(request);
1246 cleanup_delay(request);
1249 case REQUEST_REJECT_DELAY:
1250 case REQUEST_CLEANUP_DELAY:
1251 #ifdef HAVE_PTHREAD_H
1252 request->child_pid = NO_SUCH_CHILD_PID;
1254 request_stats_final(request);
1256 case REQUEST_PROXIED:
1257 rad_assert(request->next_callback != NULL);
1258 rad_assert(request->next_callback != wait_a_bit);
1260 request->when = request->next_when;
1261 callback = request->next_callback;
1262 request->next_callback = NULL;
1266 rad_panic("Internal sanity check failure");
1271 * Something major went wrong. Discard the request, and
1274 * FIXME: No idea why this happens or how to fix it...
1275 * It seems to happen *only* when requests are proxied,
1276 * and where the home server doesn't respond. So it looks
1277 * like a race condition above, but it happens in debug
1278 * mode, with no threads...
1281 RDEBUG("WARNING: Internal sanity check failed in event handler for request %u: Discarding the request!", request->number);
1282 ev_request_free(&request);
1286 INSERT_EVENT(callback, request);
1290 static void no_response_to_coa_request(void *ctx)
1292 REQUEST *request = ctx;
1295 rad_assert(request->magic == REQUEST_MAGIC);
1296 rad_assert(request->child_state == REQUEST_PROXIED);
1297 rad_assert(request->home_server != NULL);
1298 rad_assert(!request->in_request_hash);
1300 radlog(L_ERR, "No response to CoA request sent to %s",
1301 inet_ntop(request->proxy->dst_ipaddr.af,
1302 &request->proxy->dst_ipaddr.ipaddr,
1303 buffer, sizeof(buffer)));
1308 request->packet->code |= (PW_COA_REQUEST << 8);
1309 post_proxy_fail_handler(request);
1313 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1317 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1324 packet->data = NULL;
1325 packet->data_len = 0;
1328 return 1; /* time stamp updated */
1333 * Called when we haven't received a response to a CoA request.
1335 static void retransmit_coa_request(void *ctx)
1339 REQUEST *request = ctx;
1341 rad_assert(request->magic == REQUEST_MAGIC);
1342 rad_assert(request->child_state == REQUEST_PROXIED);
1343 rad_assert(request->home_server != NULL);
1344 rad_assert(!request->in_request_hash);
1345 rad_assert(request->parent == NULL);
1347 fr_event_now(el, &now);
1350 * Cap count at MRC, if it is non-zero.
1352 if (request->home_server->coa_mrc &&
1353 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1354 no_response_to_coa_request(request);
1359 * RFC 5080 Section 2.2.1
1361 * RT = 2*RTprev + RAND*RTprev
1362 * = 1.9 * RTprev + rand(0,.2) * RTprev
1363 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1366 delay ^= (delay >> 16);
1368 frac = request->delay / 5;
1369 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1371 delay += (2 * request->delay) - (request->delay / 10);
1374 * Cap delay at MRT, if MRT is non-zero.
1376 if (request->home_server->coa_mrt &&
1377 (delay > (request->home_server->coa_mrt * USEC))) {
1378 int mrt_usec = request->home_server->coa_mrt * USEC;
1381 * delay = MRT + RAND * MRT
1382 * = 0.9 MRT + rand(0,.2) * MRT
1385 delay ^= (delay >> 15);
1387 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1388 delay += mrt_usec - (mrt_usec / 10);
1391 request->delay = delay;
1392 request->when = now;
1393 tv_add(&request->when, request->delay);
1394 mrd = request->proxy_when;
1395 mrd.tv_sec += request->home_server->coa_mrd;
1398 * Cap duration at MRD.
1400 if (timercmp(&mrd, &request->when, <)) {
1401 request->when = mrd;
1402 INSERT_EVENT(no_response_to_coa_request, request);
1405 INSERT_EVENT(retransmit_coa_request, request);
1408 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1409 if (!insert_into_proxy_hash(request, TRUE)) {
1410 DEBUG("ERROR: Failed to insert retransmission of CoA request into proxy list.");
1414 request->num_proxied_requests = 0;
1415 request->num_proxied_responses = 0;
1418 request->num_proxied_requests++;
1419 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1421 request->proxy_listener->send(request->proxy_listener,
1427 * The original request is either DONE, or in CLEANUP_DELAY.
1429 static int originated_coa_request(REQUEST *request)
1431 int delay, rcode, pre_proxy_type = 0;
1437 rad_assert(request->proxy == NULL);
1438 rad_assert(!request->in_proxy_hash);
1439 rad_assert(request->proxy_reply == NULL);
1442 * Check whether we want to originate one, or cancel one.
1444 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1445 if (!vp && request->coa) {
1446 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1450 if (vp->vp_integer == 0) {
1451 ev_request_free(&request->coa);
1452 return 1; /* success */
1456 if (!request->coa) request_alloc_coa(request);
1457 if (!request->coa) return 0;
1462 * src_ipaddr will be set up in proxy_encode.
1464 memset(&ipaddr, 0, sizeof(ipaddr));
1465 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1467 ipaddr.af = AF_INET;
1468 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1470 } else if ((vp = pairfind(coa->proxy->vps,
1471 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1472 ipaddr.af = AF_INET6;
1473 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1475 } else if ((vp = pairfind(coa->proxy->vps,
1476 PW_HOME_SERVER_POOL)) != NULL) {
1477 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1479 if (!coa->home_pool) {
1480 RDEBUG2("WARNING: No such home_server_pool %s",
1483 ev_request_free(&request->coa);
1490 } else if (request->client->coa_pool) {
1491 coa->home_pool = request->client->coa_pool;
1493 } else if (request->client->coa_server) {
1494 coa->home_server = request->client->coa_server;
1498 * If all else fails, send it to the client that
1499 * originated this request.
1501 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1505 * Use the pool, if it exists.
1507 if (coa->home_pool) {
1508 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1509 if (!coa->home_server) {
1510 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1514 } else if (!coa->home_server) {
1515 int port = PW_COA_UDP_PORT;
1517 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1518 if (vp) port = vp->vp_integer;
1520 coa->home_server = home_server_find(&ipaddr, port);
1521 if (!coa->home_server) {
1522 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1523 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1524 buffer, sizeof(buffer)), port);
1529 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1531 switch (vp->vp_integer) {
1532 case PW_COA_REQUEST:
1533 case PW_DISCONNECT_REQUEST:
1534 coa->proxy->code = vp->vp_integer;
1538 DEBUG("Cannot set CoA Packet-Type to code %d",
1544 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1547 * The rest of the server code assumes that
1548 * request->packet && request->reply exist. Copy them
1549 * from the original request.
1551 rad_assert(coa->packet != NULL);
1552 rad_assert(coa->packet->vps == NULL);
1553 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1554 coa->packet->vps = paircopy(request->packet->vps);
1555 coa->packet->data = NULL;
1556 rad_assert(coa->reply != NULL);
1557 rad_assert(coa->reply->vps == NULL);
1558 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1559 coa->reply->vps = paircopy(request->reply->vps);
1560 coa->reply->data = NULL;
1561 coa->config_items = paircopy(request->config_items);
1564 * Call the pre-proxy routines.
1566 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1568 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1569 pre_proxy_type = vp->vp_integer;
1572 if (coa->home_pool && coa->home_pool->virtual_server) {
1573 const char *old_server = coa->server;
1575 coa->server = coa->home_pool->virtual_server;
1576 RDEBUG2(" server %s {", coa->server);
1577 rcode = module_pre_proxy(pre_proxy_type, coa);
1579 coa->server = old_server;
1581 rcode = module_pre_proxy(pre_proxy_type, coa);
1588 * Only send the CoA packet if the pre-proxy code succeeded.
1590 case RLM_MODULE_NOOP:
1592 case RLM_MODULE_UPDATED:
1597 * Source IP / port is set when the proxy socket
1600 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1601 coa->proxy->dst_port = coa->home_server->port;
1603 if (!insert_into_proxy_hash(coa, FALSE)) {
1604 DEBUG("ERROR: Failed to insert CoA request into proxy list.");
1609 * We CANNOT divorce the CoA request from the parent
1610 * request. This function is running in a child thread,
1611 * and we need access to the main event loop in order to
1612 * to add the timers for the CoA packet. See
1617 * Forget about the original request completely at this
1622 gettimeofday(&request->proxy_when, NULL);
1623 request->received = request->next_when = request->proxy_when;
1624 rad_assert(request->proxy_reply == NULL);
1627 * Implement re-transmit algorithm as per RFC 5080
1630 * We want IRT + RAND*IRT
1631 * or 0.9 IRT + rand(0,.2) IRT
1633 * 2^20 ~ USEC, and we want 2.
1634 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1636 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1637 request->delay = delay * request->home_server->coa_irt;
1638 delay = request->home_server->coa_irt * USEC;
1639 delay -= delay / 10;
1640 delay += request->delay;
1642 request->delay = delay;
1643 tv_add(&request->next_when, delay);
1644 request->next_callback = retransmit_coa_request;
1647 * Note that we set proxied BEFORE sending the packet.
1649 * Once we send it, the request is tainted, as
1650 * another thread may have picked it up. Don't
1653 request->num_proxied_requests = 1;
1654 request->num_proxied_responses = 0;
1655 #ifdef HAVE_PTHREAD_H
1656 request->child_pid = NO_SUCH_CHILD_PID;
1659 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1661 request->child_state = REQUEST_PROXIED;
1663 DEBUG_PACKET(request, request->proxy, 1);
1665 request->proxy_listener->send(request->proxy_listener,
1669 #endif /* WITH_COA */
1672 static int process_proxy_reply(REQUEST *request)
1675 int post_proxy_type = 0;
1679 * Delete any reply we had accumulated until now.
1681 pairfree(&request->reply->vps);
1684 * Run the packet through the post-proxy stage,
1685 * BEFORE playing games with the attributes.
1687 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1689 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1690 post_proxy_type = vp->vp_integer;
1693 if (request->home_pool && request->home_pool->virtual_server) {
1694 const char *old_server = request->server;
1696 request->server = request->home_pool->virtual_server;
1697 RDEBUG2(" server %s {", request->server);
1698 rcode = module_post_proxy(post_proxy_type, request);
1700 request->server = old_server;
1702 rcode = module_post_proxy(post_proxy_type, request);
1706 if (request->packet->code == request->proxy->code)
1708 * Don't run the next bit if we originated a CoA
1709 * packet, after receiving an Access-Request or
1710 * Accounting-Request.
1715 * There may NOT be a proxy reply, as we may be
1716 * running Post-Proxy-Type = Fail.
1718 if (request->proxy_reply) {
1720 * Delete the Proxy-State Attributes from
1721 * the reply. These include Proxy-State
1722 * attributes from us and remote server.
1724 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1727 * Add the attributes left in the proxy
1728 * reply to the reply list.
1730 pairadd(&request->reply->vps, request->proxy_reply->vps);
1731 request->proxy_reply->vps = NULL;
1734 * Free proxy request pairs.
1736 pairfree(&request->proxy->vps);
1740 default: /* Don't do anything */
1742 case RLM_MODULE_FAIL:
1743 /* FIXME: debug print stuff */
1744 request->child_state = REQUEST_DONE;
1747 case RLM_MODULE_HANDLED:
1748 /* FIXME: debug print stuff */
1749 request->child_state = REQUEST_DONE;
1757 static int request_pre_handler(REQUEST *request)
1761 rad_assert(request->magic == REQUEST_MAGIC);
1762 rad_assert(request->packet != NULL);
1764 request->child_state = REQUEST_RUNNING;
1767 * Don't decode the packet if it's an internal "fake"
1768 * request. Instead, just return so that the caller can
1771 if (request->packet->dst_port == 0) {
1772 request->username = pairfind(request->packet->vps,
1774 request->password = pairfind(request->packet->vps,
1781 * Put the decoded packet into it's proper place.
1783 if (request->proxy_reply != NULL) {
1784 rcode = request->proxy_listener->decode(request->proxy_listener,
1786 DEBUG_PACKET(request, request->proxy_reply, 0);
1789 if (request->packet->vps == NULL) {
1790 rcode = request->listener->decode(request->listener, request);
1792 if (debug_condition) {
1794 const char *my_debug = debug_condition;
1797 * Ignore parse errors.
1799 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1803 request->options = 2;
1804 request->radlog = radlog_request;
1808 DEBUG_PACKET(request, request->packet, 0);
1814 RDEBUG("%s Dropping packet without response.", fr_strerror());
1815 request->reply->offset = -2; /* bad authenticator */
1816 request->child_state = REQUEST_DONE;
1820 if (!request->username) {
1821 request->username = pairfind(request->packet->vps,
1826 if (request->proxy) {
1827 return process_proxy_reply(request);
1837 * Do state handling when we proxy a request.
1839 static int proxy_request(REQUEST *request)
1841 struct timeval when;
1846 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
1847 ev_request_free(&request->coa);
1851 if (request->home_server->server) {
1852 RDEBUG("ERROR: Cannot proxy to a virtual server.");
1856 if (!insert_into_proxy_hash(request, FALSE)) {
1857 RDEBUG("ERROR: Failed to insert entry into proxy list.");
1861 request->proxy_listener->encode(request->proxy_listener, request);
1863 when = request->received;
1864 when.tv_sec += request->root->max_request_time;
1866 gettimeofday(&request->proxy_when, NULL);
1868 request->next_when = request->proxy_when;
1869 request->next_when.tv_sec += request->home_server->response_window;
1871 rad_assert(request->home_server->response_window > 0);
1873 if (timercmp(&when, &request->next_when, <)) {
1874 request->next_when = when;
1876 request->next_callback = no_response_to_proxied_request;
1878 RDEBUG2("Proxying request %u to home server %s port %d",
1880 inet_ntop(request->proxy->dst_ipaddr.af,
1881 &request->proxy->dst_ipaddr.ipaddr,
1882 buffer, sizeof(buffer)),
1883 request->proxy->dst_port);
1886 * Note that we set proxied BEFORE sending the packet.
1888 * Once we send it, the request is tainted, as
1889 * another thread may have picked it up. Don't
1892 request->num_proxied_requests = 1;
1893 request->num_proxied_responses = 0;
1894 #ifdef HAVE_PTHREAD_H
1895 request->child_pid = NO_SUCH_CHILD_PID;
1897 request->child_state = REQUEST_PROXIED;
1899 DEBUG_PACKET(request, request->proxy, 1);
1901 request->proxy_listener->send(request->proxy_listener,
1908 * "Proxy" the request by sending it to a new virtual server.
1910 static int proxy_to_virtual_server(REQUEST *request)
1913 RAD_REQUEST_FUNP fun;
1915 if (!request->home_server || !request->home_server->server) return 0;
1917 if (request->parent) {
1918 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1922 fake = request_alloc_fake(request);
1924 RDEBUG2("WARNING: Out of memory");
1928 fake->packet->vps = paircopy(request->proxy->vps);
1929 fake->server = request->home_server->server;
1931 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1932 fun = rad_authenticate;
1934 #ifdef WITH_ACCOUNTING
1935 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1936 fun = rad_accounting;
1940 RDEBUG2("Unknown packet type %d", request->proxy->code);
1941 ev_request_free(&fake);
1945 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1946 radius_handle_request(fake, fun);
1947 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1949 if (fake->reply->code != 0) {
1950 request->proxy_reply = fake->reply;
1954 * There was no response
1956 setup_post_proxy_fail(request);
1959 ev_request_free(&fake);
1961 process_proxy_reply(request);
1964 * Process it through the normal section again, but ONLY
1965 * if we received a proxy reply..
1967 if (request->proxy_reply) {
1968 if (request->server) RDEBUG("server %s {",
1969 request->server != NULL ?
1970 request->server : "");
1973 if (request->server) RDEBUG("} # server %s",
1974 request->server != NULL ?
1975 request->server : "");
1978 return 2; /* success, but NOT '1' !*/
1982 * Return 1 if we did proxy it, or the proxy attempt failed
1983 * completely. Either way, the caller doesn't touch the request
1984 * any more if we return 1.
1986 static int successfully_proxied_request(REQUEST *request)
1989 int pre_proxy_type = 0;
1990 VALUE_PAIR *realmpair;
1991 VALUE_PAIR *strippedname;
1993 char *realmname = NULL;
1995 REALM *realm = NULL;
1999 * If it was already proxied, do nothing.
2001 * FIXME: This should really be a serious error.
2003 if (request->in_proxy_hash ||
2004 (request->proxy_reply && (request->proxy_reply->code != 0))) {
2008 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
2009 if (!realmpair || (realmpair->length == 0)) {
2012 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
2015 switch (request->packet->code) {
2016 case PW_AUTHENTICATION_REQUEST:
2017 pool_type = HOME_TYPE_AUTH;
2020 #ifdef WITH_ACCOUNTING
2021 case PW_ACCOUNTING_REQUEST:
2022 pool_type = HOME_TYPE_ACCT;
2027 case PW_COA_REQUEST:
2028 case PW_DISCONNECT_REQUEST:
2029 pool_type = HOME_TYPE_COA;
2037 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2039 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2044 realmname = NULL; /* no realms */
2049 realmname = (char *) realmpair->vp_strvalue;
2051 realm = realm_find2(realmname);
2053 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2058 * Figure out which pool to use.
2060 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2061 pool = realm->auth_pool;
2063 #ifdef WITH_ACCOUNTING
2064 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2065 pool = realm->acct_pool;
2069 } else if ((request->packet->code == PW_COA_REQUEST) ||
2070 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2071 pool = realm->acct_pool;
2075 rad_panic("Internal sanity check failed");
2079 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2085 home = home_server_ldb(realmname, pool, request);
2087 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2091 request->home_pool = pool;
2095 * Once we've decided to proxy a request, we cannot send
2096 * a CoA packet. So we free up any CoA packet here.
2098 ev_request_free(&request->coa);
2101 * Remember that we sent the request to a Realm.
2103 if (realmname) pairadd(&request->packet->vps,
2104 pairmake("Realm", realmname, T_OP_EQ));
2107 * Strip the name, if told to.
2109 * Doing it here catches the case of proxied tunneled
2112 if (realm && (realm->striprealm == TRUE) &&
2113 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2115 * If there's a Stripped-User-Name attribute in
2116 * the request, then use THAT as the User-Name
2117 * for the proxied request, instead of the
2120 * This is done by making a copy of the
2121 * Stripped-User-Name attribute, turning it into
2122 * a User-Name attribute, deleting the
2123 * Stripped-User-Name and User-Name attributes
2124 * from the vps list, and making the new
2125 * User-Name the head of the vps list.
2127 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2129 vp = radius_paircreate(request, NULL,
2130 PW_USER_NAME, PW_TYPE_STRING);
2131 rad_assert(vp != NULL); /* handled by above function */
2132 /* Insert at the START of the list */
2133 vp->next = request->proxy->vps;
2134 request->proxy->vps = vp;
2136 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2137 sizeof(vp->vp_strvalue));
2138 vp->length = strippedname->length;
2141 * Do NOT delete Stripped-User-Name.
2146 * If there is no PW_CHAP_CHALLENGE attribute but
2147 * there is a PW_CHAP_PASSWORD we need to add it
2148 * since we can't use the request authenticator
2149 * anymore - we changed it.
2151 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2152 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2153 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2154 vp = radius_paircreate(request, &request->proxy->vps,
2155 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2156 vp->length = AUTH_VECTOR_LEN;
2157 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2161 * The RFC's say we have to do this, but FreeRADIUS
2164 vp = radius_paircreate(request, &request->proxy->vps,
2165 PW_PROXY_STATE, PW_TYPE_OCTETS);
2166 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2167 request->packet->id);
2168 vp->length = strlen(vp->vp_strvalue);
2171 * Should be done BEFORE inserting into proxy hash, as
2172 * pre-proxy may use this information, or change it.
2174 request->proxy->code = request->packet->code;
2177 * Call the pre-proxy routines.
2179 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2181 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2182 pre_proxy_type = vp->vp_integer;
2185 rad_assert(request->home_pool != NULL);
2187 if (request->home_pool->virtual_server) {
2188 const char *old_server = request->server;
2190 request->server = request->home_pool->virtual_server;
2191 RDEBUG2(" server %s {", request->server);
2192 rcode = module_pre_proxy(pre_proxy_type, request);
2194 request->server = old_server;
2196 rcode = module_pre_proxy(pre_proxy_type, request);
2199 case RLM_MODULE_FAIL:
2200 case RLM_MODULE_INVALID:
2201 case RLM_MODULE_NOTFOUND:
2202 case RLM_MODULE_USERLOCK:
2204 /* FIXME: debug print failed stuff */
2207 case RLM_MODULE_REJECT:
2208 case RLM_MODULE_HANDLED:
2212 * Only proxy the packet if the pre-proxy code succeeded.
2214 case RLM_MODULE_NOOP:
2216 case RLM_MODULE_UPDATED:
2221 * If it's a fake request, don't send the proxy
2222 * packet. The outer tunnel session will take
2223 * care of doing that.
2225 if (request->packet->dst_port == 0) {
2226 request->home_server = NULL;
2230 if (request->home_server->server) {
2231 return proxy_to_virtual_server(request);
2234 if (!proxy_request(request)) {
2235 RDEBUG("ERROR: Failed to proxy request %u", request->number);
2243 static void request_post_handler(REQUEST *request)
2245 int child_state = -1;
2246 struct timeval when;
2249 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2251 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2252 RDEBUG2("request %u was cancelled.", request->number);
2253 #ifdef HAVE_PTHREAD_H
2254 request->child_pid = NO_SUCH_CHILD_PID;
2256 child_state = REQUEST_DONE;
2260 if (request->child_state != REQUEST_RUNNING) {
2261 rad_panic("Internal sanity check failed");
2266 * If it's not in the request hash, it's a CoA request.
2269 if (!request->in_request_hash &&
2271 ((request->proxy->code == PW_COA_REQUEST) ||
2272 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2273 request->next_callback = NULL;
2274 child_state = REQUEST_DONE;
2280 * Catch Auth-Type := Reject BEFORE proxying the packet.
2282 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2283 (request->reply->code == 0) &&
2284 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2285 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2286 request->reply->code = PW_AUTHENTICATION_REJECT;
2290 if (request->root->proxy_requests &&
2291 !request->in_proxy_hash &&
2292 (request->reply->code == 0) &&
2293 (request->packet->dst_port != 0) &&
2294 (request->packet->code != PW_STATUS_SERVER)) {
2295 int rcode = successfully_proxied_request(request);
2297 if (rcode == 1) return; /* request is invalid */
2300 * Failed proxying it (dead home servers, etc.)
2301 * Run it through Post-Proxy-Type = Fail, and
2302 * respond to the request.
2304 * Note that we're in a child thread here, so we
2305 * do NOT re-schedule the request. Instead, we
2306 * do what we would have done, which is run the
2307 * pre-handler, a NULL request handler, and then
2310 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2311 request_pre_handler(request);
2315 * Else we weren't supposed to proxy it,
2316 * OR we proxied it internally to a virutal server.
2321 else if (request->proxy && request->coa) {
2322 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2323 ev_request_free(&request->coa);
2329 * Fake requests don't get encoded or signed. The caller
2330 * also requires the reply VP's, so we don't free them
2333 if (request->packet->dst_port == 0) {
2334 /* FIXME: RDEBUG going to the next request */
2335 #ifdef HAVE_PTHREAD_H
2336 request->child_pid = NO_SUCH_CHILD_PID;
2338 request->child_state = REQUEST_DONE;
2344 * Copy Proxy-State from the request to the reply.
2346 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2347 if (vp) pairadd(&request->reply->vps, vp);
2351 * Access-Requests get delayed or cached.
2353 switch (request->packet->code) {
2354 case PW_AUTHENTICATION_REQUEST:
2355 gettimeofday(&request->next_when, NULL);
2357 if (request->reply->code == 0) {
2359 * Check if the lack of response is intentional.
2361 vp = pairfind(request->config_items,
2362 PW_RESPONSE_PACKET_TYPE);
2364 RDEBUG2("There was no response configured: rejecting request %u",
2366 request->reply->code = PW_AUTHENTICATION_REJECT;
2368 } else if (vp->vp_integer == 256) {
2369 RDEBUG2("Not responding to request %u",
2373 * Force cleanup after a long
2374 * time, so that we don't
2375 * re-process the packet.
2377 request->next_when.tv_sec += request->root->max_request_time;
2378 request->next_callback = cleanup_delay;
2379 child_state = REQUEST_CLEANUP_DELAY;
2382 request->reply->code = vp->vp_integer;
2388 * Run rejected packets through
2390 * Post-Auth-Type = Reject
2392 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2393 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2394 vp = radius_pairmake(request, &request->config_items,
2395 "Post-Auth-Type", "Reject",
2397 if (vp) rad_postauth(request);
2400 * If configured, delay Access-Reject packets.
2402 * If request->root->reject_delay = 0, we discover
2403 * that we have to send the packet now.
2405 when = request->received;
2406 when.tv_sec += request->root->reject_delay;
2408 if (timercmp(&when, &request->next_when, >)) {
2409 RDEBUG2("Delaying reject of request %u for %d seconds",
2411 request->root->reject_delay);
2412 request->next_when = when;
2413 request->next_callback = reject_delay;
2414 #ifdef HAVE_PTHREAD_H
2415 request->child_pid = NO_SUCH_CHILD_PID;
2417 request->child_state = REQUEST_REJECT_DELAY;
2423 case PW_COA_REQUEST:
2424 case PW_DISCONNECT_REQUEST:
2426 request->next_when.tv_sec += request->root->cleanup_delay;
2427 request->next_callback = cleanup_delay;
2428 child_state = REQUEST_CLEANUP_DELAY;
2431 case PW_ACCOUNTING_REQUEST:
2432 request->next_callback = NULL; /* just to be safe */
2433 child_state = REQUEST_DONE;
2437 * FIXME: Status-Server should probably not be
2440 case PW_STATUS_SERVER:
2441 request->next_callback = NULL;
2442 child_state = REQUEST_DONE;
2449 request->next_callback = NULL;
2450 child_state = REQUEST_DONE;
2455 * Suppress "no reply" packets here, unless we're reading
2456 * from the "detail" file. In that case, we've got to
2457 * tell the detail file handler that the request is dead,
2458 * and it should re-send it.
2459 * If configured, encode, sign, and send.
2461 if ((request->reply->code != 0) ||
2462 (request->listener->type == RAD_LISTEN_DETAIL)) {
2463 DEBUG_PACKET(request, request->reply, 1);
2464 request->listener->send(request->listener, request);
2469 * Now that we've completely processed the request,
2470 * see if we need to originate a CoA request. But ONLY
2471 * if it wasn't proxied.
2473 if (!request->proxy &&
2474 (request->packet->code != PW_COA_REQUEST) &&
2475 (request->packet->code != PW_DISCONNECT_REQUEST) &&
2477 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL))) {
2478 if (!originated_coa_request(request)) {
2479 RDEBUG2("Do CoA Fail handler here");
2481 /* request->coa is stil set, so we can update events */
2487 * Clean up. These are no longer needed.
2489 pairfree(&request->config_items);
2491 pairfree(&request->packet->vps);
2492 request->username = NULL;
2493 request->password = NULL;
2495 pairfree(&request->reply->vps);
2498 if (request->proxy) {
2499 pairfree(&request->proxy->vps);
2501 if (request->proxy_reply) {
2502 pairfree(&request->proxy_reply->vps);
2507 * We're not tracking responses from the home
2508 * server, we can therefore free this memory in
2511 if (!request->in_proxy_hash) {
2512 rad_free(&request->proxy);
2513 rad_free(&request->proxy_reply);
2514 request->home_server = NULL;
2520 RDEBUG2("Finished request %u.", request->number);
2521 rad_assert(child_state >= 0);
2522 request->child_state = child_state;
2525 * Single threaded mode: update timers now.
2527 if (!have_children) wait_a_bit(request);
2531 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2537 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2538 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2540 switch (request->child_state) {
2541 case REQUEST_QUEUED:
2542 case REQUEST_RUNNING:
2546 radlog(L_ERR, "Discarding duplicate request from "
2547 "client %s port %d - ID: %d due to unfinished request %u",
2549 request->packet->src_port,request->packet->id,
2554 case REQUEST_PROXIED:
2556 * We're not supposed to have duplicate
2557 * accounting packets. The other states handle
2558 * duplicates fine (discard, or send duplicate
2559 * reply). But we do NOT want to retransmit an
2560 * accounting request here, because that would
2561 * involve updating the Acct-Delay-Time, and
2562 * therefore changing the packet Id, etc.
2564 * Instead, we just discard the packet. We may
2565 * eventually respond, or the client will send a
2566 * new accounting packet.
2568 * The same comments go for Status-Server, and
2569 * other packet types.
2571 * FIXME: coa: when we proxy CoA && Disconnect
2572 * packets, this logic has to be fixed.
2574 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2578 check_for_zombie_home_server(request);
2581 * If we've just discovered that the home server is
2582 * dead, send the packet to another one.
2584 if ((request->packet->dst_port != 0) &&
2585 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2588 remove_from_proxy_hash(request);
2590 home = home_server_ldb(NULL, request->home_pool, request);
2592 RDEBUG2("ERROR: Failed to find live home server for request %u", request->number);
2595 * Do post-request processing,
2596 * and any insertion of necessary
2599 post_proxy_fail_handler(request);
2603 request->proxy->code = request->packet->code;
2606 * Free the old packet, to force re-encoding
2608 free(request->proxy->data);
2609 request->proxy->data = NULL;
2610 request->proxy->data_len = 0;
2613 * This request failed over to a virtual
2614 * server. Push it back onto the queue
2617 if (request->home_server->server) {
2618 proxy_fallback_handler(request);
2623 * Try to proxy the request.
2625 if (!proxy_request(request)) {
2626 RDEBUG("ERROR: Failed to re-proxy request %u", request->number);
2627 goto no_home_servers;
2631 * This code executes in the main server
2632 * thread, so there's no need for locking.
2634 rad_assert(request->next_callback != NULL);
2635 INSERT_EVENT(request->next_callback, request);
2636 request->next_callback = NULL;
2638 } /* else the home server is still alive */
2640 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2641 inet_ntop(request->proxy->dst_ipaddr.af,
2642 &request->proxy->dst_ipaddr.ipaddr,
2643 buffer, sizeof(buffer)),
2644 request->proxy->dst_port,
2645 request->proxy->id);
2646 request->num_proxied_requests++;
2648 DEBUG_PACKET(request, request->proxy, 1);
2649 request->proxy_listener->send(request->proxy_listener,
2654 case REQUEST_REJECT_DELAY:
2655 RDEBUG2("Waiting to send Access-Reject "
2656 "to client %s port %d - ID: %d",
2658 request->packet->src_port, request->packet->id);
2661 case REQUEST_CLEANUP_DELAY:
2663 if (request->reply->code == 0) {
2664 RDEBUG2("Ignoring retransmit from client %s port %d "
2665 "- ID: %d, no reply was configured",
2667 request->packet->src_port, request->packet->id);
2672 * FIXME: This sends duplicate replies to
2673 * accounting requests, even if Acct-Delay-Time
2674 * or Event-Timestamp is in the packet. In those
2675 * cases, the Id should be changed, and the packet
2678 RDEBUG2("Sending duplicate reply "
2679 "to client %s port %d - ID: %d",
2681 request->packet->src_port, request->packet->id);
2682 DEBUG_PACKET(request, request->reply, 1);
2683 request->listener->send(request->listener, request);
2689 static void received_conflicting_request(REQUEST *request,
2690 const RADCLIENT *client)
2692 radlog(L_ERR, "Received conflicting packet from "
2693 "client %s port %d - ID: %d due to unfinished request %u. Giving up on old request.",
2695 request->packet->src_port, request->packet->id,
2699 * Nuke it from the request hash, so we can receive new
2702 remove_from_request_hash(request);
2704 switch (request->child_state) {
2705 #ifdef HAVE_PTHREAD_H
2707 * It's queued or running. Tell it to stop, and
2708 * wait for it to do so.
2710 case REQUEST_QUEUED:
2711 case REQUEST_RUNNING:
2712 request->master_state = REQUEST_STOP_PROCESSING;
2713 request->delay += request->delay >> 1;
2715 tv_add(&request->when, request->delay);
2717 INSERT_EVENT(wait_for_child_to_die, request);
2722 * Catch race conditions. It may have switched
2723 * from running to done while this code is being
2726 case REQUEST_REJECT_DELAY:
2727 case REQUEST_CLEANUP_DELAY:
2732 * It's in some other state, and therefore also
2733 * in the event queue. At some point, the
2734 * child will notice, and we can then delete it.
2736 case REQUEST_PROXIED:
2738 rad_assert(request->ev != NULL);
2744 static int can_handle_new_request(RADIUS_PACKET *packet,
2746 struct main_config_t *root)
2749 * Count the total number of requests, to see if
2750 * there are too many. If so, return with an
2753 if (root->max_requests) {
2754 int request_count = fr_packet_list_num_elements(pl);
2757 * This is a new request. Let's see if
2758 * it makes us go over our configured
2761 if (request_count > root->max_requests) {
2762 radlog(L_ERR, "Dropping request (%d is too many): "
2763 "from client %s port %d - ID: %d", request_count,
2765 packet->src_port, packet->id);
2766 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2767 "\tThe value for 'max_requests' is probably set too low.\n");
2769 } /* else there were a small number of requests */
2770 } /* else there was no configured limit for requests */
2773 * FIXME: Add per-client checks. If one client is sending
2774 * too many packets, start discarding them.
2776 * We increment the counters here, and decrement them
2777 * when the response is sent... somewhere in this file.
2781 * FUTURE: Add checks for system load. If the system is
2782 * busy, start dropping requests...
2784 * We can probably keep some statistics ourselves... if
2785 * there are more requests coming in than we can handle,
2786 * start dropping some.
2793 int received_request(rad_listen_t *listener,
2794 RADIUS_PACKET *packet, REQUEST **prequest,
2797 RADIUS_PACKET **packet_p;
2798 REQUEST *request = NULL;
2799 struct main_config_t *root = &mainconfig;
2801 packet_p = fr_packet_list_find(pl, packet);
2803 request = fr_packet2myptr(REQUEST, packet, packet_p);
2804 rad_assert(request->in_request_hash);
2806 if ((request->packet->data_len == packet->data_len) &&
2807 (memcmp(request->packet->vector, packet->vector,
2808 sizeof(packet->vector)) == 0)) {
2809 received_retransmit(request, client);
2814 * The new request is different from the old one,
2815 * but maybe the old is finished. If so, delete
2818 switch (request->child_state) {
2819 struct timeval when;
2823 * Special hacks for race conditions.
2824 * The reply is encoded, and therefore
2825 * likely sent. We received a *new*
2826 * packet from the client, likely before
2827 * the next line or two of code which
2828 * updated the child state. In this
2829 * case, just accept the new request.
2831 if ((request->reply->code != 0) &&
2832 request->reply->data) {
2833 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %u.",
2835 packet->src_port, packet->id,
2837 remove_from_request_hash(request);
2842 gettimeofday(&when, NULL);
2846 * If the cached request was received
2847 * within the last second, then we
2848 * discard the NEW request instead of the
2849 * old one. This will happen ONLY when
2850 * the client is severely broken, and is
2851 * sending conflicting packets very
2854 if (timercmp(&when, &request->received, <)) {
2855 radlog(L_ERR, "Discarding conflicting packet from "
2856 "client %s port %d - ID: %d due to recent request %u.",
2858 packet->src_port, packet->id,
2863 received_conflicting_request(request, client);
2867 case REQUEST_REJECT_DELAY:
2868 case REQUEST_CLEANUP_DELAY:
2869 request->child_state = REQUEST_DONE;
2871 cleanup_delay(request);
2878 * We may want to quench the new request.
2880 if ((listener->type != RAD_LISTEN_DETAIL) &&
2881 !can_handle_new_request(packet, client, root)) {
2886 * Create and initialize the new request.
2888 request = request_alloc(); /* never fails */
2890 if ((request->reply = rad_alloc(0)) == NULL) {
2891 radlog(L_ERR, "No memory");
2895 request->listener = listener;
2896 request->client = client;
2897 request->packet = packet;
2898 request->packet->timestamp = request->timestamp;
2899 request->number = request_num_counter++;
2900 request->priority = listener->type;
2901 #ifdef HAVE_PTHREAD_H
2902 request->child_pid = NO_SUCH_CHILD_PID;
2906 * Status-Server packets go to the head of the queue.
2908 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2911 * Set virtual server identity
2913 if (client->server) {
2914 request->server = client->server;
2915 } else if (listener->server) {
2916 request->server = listener->server;
2918 request->server = NULL;
2922 * Remember the request in the list.
2924 if (!fr_packet_list_insert(pl, &request->packet)) {
2925 radlog(L_ERR, "Failed to insert request %u in the list of live requests: discarding", request->number);
2926 ev_request_free(&request);
2930 request->in_request_hash = TRUE;
2931 request->root = root;
2935 * The request passes many of our sanity checks.
2936 * From here on in, if anything goes wrong, we
2937 * send a reject message, instead of dropping the
2942 * Build the reply template from the request.
2945 request->reply->sockfd = request->packet->sockfd;
2946 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2947 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2948 request->reply->dst_port = request->packet->src_port;
2949 request->reply->src_port = request->packet->dst_port;
2950 request->reply->id = request->packet->id;
2951 request->reply->code = 0; /* UNKNOWN code */
2952 memcpy(request->reply->vector, request->packet->vector,
2953 sizeof(request->reply->vector));
2954 request->reply->vps = NULL;
2955 request->reply->data = NULL;
2956 request->reply->data_len = 0;
2958 request->master_state = REQUEST_ACTIVE;
2959 request->child_state = REQUEST_QUEUED;
2960 request->next_callback = NULL;
2962 gettimeofday(&request->received, NULL);
2963 request->timestamp = request->received.tv_sec;
2964 request->when = request->received;
2966 request->delay = USEC;
2968 tv_add(&request->when, request->delay);
2970 INSERT_EVENT(wait_a_bit, request);
2972 *prequest = request;
2978 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2984 * Also removes from the proxy hash if responses == requests
2986 request = lookup_in_proxy_hash(packet);
2989 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2990 inet_ntop(packet->src_ipaddr.af,
2991 &packet->src_ipaddr.ipaddr,
2992 buffer, sizeof(buffer)),
2993 packet->src_port, packet->id);
2998 * We haven't replied to the NAS, but we have seen an
2999 * earlier reply from the home server. Ignore this packet,
3000 * as we're likely still processing the previous reply.
3002 if (request->proxy_reply) {
3003 if (memcmp(request->proxy_reply->vector,
3005 sizeof(request->proxy_reply->vector)) == 0) {
3006 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %u",
3007 inet_ntop(packet->src_ipaddr.af,
3008 &packet->src_ipaddr.ipaddr,
3009 buffer, sizeof(buffer)),
3010 packet->src_port, packet->id,
3014 * ? The home server gave us a new proxy
3015 * reply which doesn't match the old
3018 RDEBUG2("Ignoring conflicting proxy reply");
3021 /* assert that there's an event queued for request? */
3026 * Verify the packet before doing ANYTHING with it. This
3027 * means we're doing more MD5 checks in the server core.
3028 * However, we can fix that by moving to multiple threads
3029 * listening on sockets.
3031 * We do this AFTER looking the request up in the hash,
3032 * and AFTER vhecking if we saw a previous request. This
3033 * helps minimize the DoS effect of people attacking us
3034 * with spoofed packets.
3036 if (rad_verify(packet, request->proxy,
3037 request->home_server->secret) != 0) {
3038 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3042 gettimeofday(&now, NULL);
3045 * "ping" packets have a different algorithm for marking
3046 * a home server alive. They also skip all of the CoA,
3049 if (!request->packet) {
3050 request->proxy_reply = packet;
3051 received_response_to_ping(request);
3052 request->proxy_reply = NULL; /* caller will free it */
3053 ev_request_free(&request);
3058 * Maybe move this earlier in the decision process?
3059 * Having it here means that late or duplicate proxy
3060 * replies no longer get the home server marked as
3061 * "alive". This might be good for stability, though.
3063 * FIXME: Do we really want to do this whenever we
3064 * receive a packet? Setting this here means that we
3065 * mark it alive on *any* packet, even if it's lost all
3066 * of the *other* packets in the last 10s.
3068 request->home_server->state = HOME_STATE_ALIVE;
3072 * When originating CoA, the "proxy" reply is the reply
3073 * to the CoA request that we originated. At this point,
3074 * the original request is finished, and it has a reply.
3076 * However, if we haven't separated the two requests, do
3077 * so now. This is done so that cleaning up the original
3078 * request won't cause the CoA request to be free'd. See
3079 * util.c, request_free()
3081 if (request->parent && (request->parent->coa == request)) {
3082 request->parent->coa = NULL;
3083 request->parent = NULL;
3086 * The proxied packet was different from the
3087 * original packet, AND the proxied packet was
3090 } else if ((request->packet->code != request->proxy->code) &&
3091 ((request->proxy->code == PW_COA_REQUEST) ||
3092 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
3094 * It's already divorced: do nothing.
3099 * Skip the next set of checks, as the original
3100 * reply is cached. We want to be able to still
3101 * process the CoA reply, AND to reference the
3102 * original request/reply.
3104 * This is getting to be really quite a bit of a
3110 * If there's a reply to the NAS, ignore everything
3111 * related to proxy responses
3113 if (request->reply && request->reply->code != 0) {
3114 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3120 * The average includes our time to receive packets and
3121 * look them up in the hashes, which should be the same
3124 * We update the response time only for the FIRST packet
3127 if (request->home_server->ema.window > 0) {
3128 radius_stats_ema(&request->home_server->ema,
3129 &now, &request->proxy_when);
3133 switch (request->child_state) {
3134 case REQUEST_QUEUED:
3135 case REQUEST_RUNNING:
3136 radlog(L_ERR, "Internal sanity check failed for child state");
3139 case REQUEST_REJECT_DELAY:
3140 case REQUEST_CLEANUP_DELAY:
3142 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'",
3143 inet_ntop(packet->src_ipaddr.af,
3144 &packet->src_ipaddr.ipaddr,
3145 buffer, sizeof(buffer)),
3146 packet->src_port, packet->id,
3148 /* assert that there's an event queued for request? */
3151 case REQUEST_PROXIED:
3155 request->proxy_reply = packet;
3159 * Perform RTT calculations, as per RFC 2988 (for TCP).
3160 * Note that we only do so on the first response.
3162 if ((request->num_proxied_responses == 1)
3164 home_server *home = request->home_server;
3166 rtt = now.tv_sec - request->proxy_when.tv_sec;
3169 rtt -= request->proxy_when.tv_usec;
3171 if (!home->has_rtt) {
3172 home->has_rtt = TRUE;
3175 home->rttvar = rtt / 2;
3178 home->rttvar -= home->rttvar >> 2;
3179 home->rttvar += (home->srtt - rtt);
3180 home->srtt -= home->srtt >> 3;
3181 home->srtt += rtt >> 3;
3184 home->rto = home->srtt;
3185 if (home->rttvar > (USEC / 4)) {
3186 home->rto += home->rttvar * 4;
3193 request->child_state = REQUEST_QUEUED;
3194 request->when = now;
3195 request->delay = USEC;
3196 request->priority = RAD_LISTEN_PROXY;
3197 tv_add(&request->when, request->delay);
3200 * Wait a bit will take care of max_request_time
3202 INSERT_EVENT(wait_a_bit, request);
3208 void event_new_fd(rad_listen_t *this)
3212 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3214 this->print(this, buffer, sizeof(buffer));
3216 if (this->status == RAD_LISTEN_STATUS_INIT) {
3218 DEBUG("Listening on %s", buffer);
3220 radlog(L_INFO, " ... adding new socket %s", buffer);
3222 if (!fr_event_fd_insert(el, 0, this->fd,
3223 event_socket_handler, this)) {
3224 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3228 this->status = RAD_LISTEN_STATUS_KNOWN;
3232 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3233 radlog(L_INFO, " ... closing socket %s", buffer);
3235 fr_event_fd_delete(el, 0, this->fd);
3236 this->status = RAD_LISTEN_STATUS_FINISH;
3239 * Close the fd AFTER fixing up the requests and
3240 * listeners, so that they don't send/recv on the
3241 * wrong socket (if someone manages to open
3249 static void handle_signal_self(int flag)
3251 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3252 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3253 fr_event_loop_exit(el, 1);
3255 fr_event_loop_exit(el, 2);
3259 } /* else exit/term flags weren't set */
3262 * Tell the even loop to stop processing.
3264 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3266 static time_t last_hup = 0;
3269 if ((int) (when - last_hup) < 5) {
3270 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3274 radlog(L_INFO, "Received HUP signal.");
3278 fr_event_loop_exit(el, 0x80);
3282 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3286 * FIXME: O(N) loops suck.
3288 for (this = mainconfig.listen;
3290 this = this->next) {
3291 if (this->type != RAD_LISTEN_DETAIL) continue;
3294 * This one didn't send the signal, skip
3297 if (!this->decode(this, NULL)) continue;
3300 * Go service the interrupt.
3302 event_poll_detail(this);
3307 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3310 for (this = mainconfig.listen;
3312 this = this->next) {
3318 #ifndef WITH_SELF_PIPE
3319 void radius_signal_self(int flag)
3321 handle_signal_self(flag);
3325 * Inform ourselves that we received a signal.
3327 void radius_signal_self(int flag)
3333 * The read MUST be non-blocking for this to work.
3335 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3339 for (i = 0; i < rcode; i++) {
3340 buffer[0] |= buffer[i];
3348 write(self_pipe[1], buffer, 1);
3352 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3353 UNUSED int fd, UNUSED void *ctx)
3358 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3359 if (rcode <= 0) return;
3362 * Merge pending signals.
3364 for (i = 0; i < rcode; i++) {
3365 buffer[0] |= buffer[i];
3368 handle_signal_self(buffer[0]);
3373 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3376 rad_listen_t *listener = ctx;
3377 RAD_REQUEST_FUNP fun;
3380 rad_assert(xel == el);
3384 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3386 if (!listener->recv(listener, &fun, &request)) return;
3388 if (!thread_pool_addrequest(request, fun)) {
3389 request->child_state = REQUEST_DONE;
3395 * This function is called periodically to see if this detail
3396 * file is available for reading.
3398 static void event_poll_detail(void *ctx)
3401 RAD_REQUEST_FUNP fun;
3403 rad_listen_t *this = ctx;
3404 struct timeval when;
3405 listen_detail_t *detail = this->data;
3407 rad_assert(this->type == RAD_LISTEN_DETAIL);
3410 * Try to read something.
3412 * FIXME: This does poll AND receive.
3414 rcode = this->recv(this, &fun, &request);
3416 rad_assert(fun != NULL);
3417 rad_assert(request != NULL);
3419 if (!thread_pool_addrequest(request, fun)) {
3420 request->child_state = REQUEST_DONE;
3424 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3428 * Backdoor API to get the delay until the next poll
3431 delay = this->encode(this, NULL);
3432 tv_add(&when, delay);
3434 if (!fr_event_insert(el, event_poll_detail, this,
3435 &when, &detail->ev)) {
3436 radlog(L_ERR, "Failed creating handler");
3442 static void event_status(struct timeval *wake)
3444 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3448 if (debug_flag == 0) {
3450 radlog(L_INFO, "Ready to process requests.");
3451 just_started = FALSE;
3457 radlog(L_INFO, "Ready to process requests.");
3459 } else if ((wake->tv_sec != 0) ||
3460 (wake->tv_usec >= 100000)) {
3461 DEBUG("Waking up in %d.%01u seconds.",
3462 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3467 * FIXME: Put this somewhere else, where it isn't called
3468 * all of the time...
3471 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3473 * If there are no child threads, then there may
3474 * be child processes. In that case, wait for
3475 * their exit status, and throw that exit status
3476 * away. This helps get rid of zxombie children.
3478 while (waitpid(-1, &argval, WNOHANG) > 0) {
3486 * Externally-visibly functions.
3488 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3490 rad_listen_t *this, *head = NULL;
3494 time(&fr_start_time);
3496 el = fr_event_list_create(event_status);
3499 pl = fr_packet_list_create(0);
3500 if (!pl) return 0; /* leak el */
3502 request_num_counter = 0;
3505 if (mainconfig.proxy_requests) {
3507 * Create the tree for managing proxied requests and
3510 proxy_list = fr_packet_list_create(1);
3511 if (!proxy_list) return 0;
3513 #ifdef HAVE_PTHREAD_H
3514 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3515 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3523 #ifdef HAVE_PTHREAD_H
3525 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3527 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3530 * Initialize the threads ONLY if we're spawning, AND
3531 * we're running normally.
3533 if (spawn_flag && !check_config &&
3534 (thread_pool_init(cs, &spawn_flag) < 0)) {
3540 * Move all of the thread calls to this file?
3542 * It may be best for the mutexes to be in this file...
3544 have_children = spawn_flag;
3547 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3549 if (listen_init(cs, &head) < 0) {
3556 #ifdef WITH_SELF_PIPE
3558 * Child threads need a pipe to signal us, as do the
3561 if (pipe(self_pipe) < 0) {
3562 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3566 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3567 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3571 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3572 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3577 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3578 event_signal_handler, el)) {
3579 radlog(L_ERR, "Failed creating handler for signals");
3582 #endif /* WITH_SELF_PIPE */
3586 * Mark the proxy Fd's as unused.
3591 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3595 DEBUG("%s: #### Opening IP addresses and Ports ####",
3599 * The server temporarily switches to an unprivileged
3600 * user very early in the bootstrapping process.
3601 * However, some sockets MAY require privileged access
3602 * (bind to device, or to port < 1024, or to raw
3603 * sockets). Those sockets need to call suid up/down
3604 * themselves around the functions that need a privileged
3607 if (listen_init(cs, &head) < 0) {
3612 * At this point, no one has any business *ever* going
3615 fr_suid_down_permanent();
3618 * Add all of the sockets to the event loop.
3622 this = this->next) {
3625 this->print(this, buffer, sizeof(buffer));
3627 switch (this->type) {
3629 case RAD_LISTEN_DETAIL:
3630 DEBUG("Listening on %s", buffer);
3633 * Detail files are always known, and aren't
3634 * put into the socket event loop.
3636 this->status = RAD_LISTEN_STATUS_KNOWN;
3639 * Set up the first poll interval.
3641 event_poll_detail(this);
3646 case RAD_LISTEN_PROXY:
3647 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3648 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3650 proxy_fds[this->fd & 0x1f] = this->fd;
3651 proxy_listeners[this->fd & 0x1f] = this;
3652 if (!fr_packet_list_socket_add(proxy_list,
3666 mainconfig.listen = head;
3672 static int request_hash_cb(UNUSED void *ctx, void *data)
3674 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3677 rad_assert(request->in_proxy_hash == FALSE);
3680 ev_request_free(&request);
3687 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3689 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3691 ev_request_free(&request);
3697 void radius_event_free(void)
3700 * FIXME: Stop all threads, or at least check that
3701 * they're all waiting on the semaphore, and the queues
3707 * There are requests in the proxy hash that aren't
3708 * referenced from anywhere else. Remove them first.
3711 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3712 fr_packet_list_free(proxy_list);
3717 fr_packet_list_walk(pl, NULL, request_hash_cb);
3719 fr_packet_list_free(pl);
3722 fr_event_list_free(el);
3725 int radius_event_process(void)
3729 return fr_event_loop(el);
3732 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3734 request->options = RAD_REQUEST_OPTION_DEBUG2;
3736 if (request_pre_handler(request)) {
3737 rad_assert(fun != NULL);
3738 rad_assert(request != NULL);
3740 if (request->server) RDEBUG("server %s {",
3741 request->server != NULL ?
3742 request->server : "");
3745 if (request->server) RDEBUG("} # server %s",
3746 request->server != NULL ?
3747 request->server : "");
3749 request_post_handler(request);
3752 DEBUG2("Going to the next request");