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;
55 static int have_children;
56 static int just_started = TRUE;
60 #define WITH_SELF_PIPE (1)
65 static int self_pipe[2];
70 static pthread_mutex_t proxy_mutex;
73 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
74 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
76 #define NO_CHILD_THREAD (0)
79 * This is easier than ifdef's throughout the code.
81 #define PTHREAD_MUTEX_LOCK(_x)
82 #define PTHREAD_MUTEX_UNLOCK(_x)
83 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
85 radius_handle_request(request, fun);
90 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
93 static fr_packet_list_t *proxy_list = NULL;
96 * We keep the proxy FD's here. The RADIUS Id's are marked
97 * "allocated" per Id, via a bit per proxy FD.
99 static int proxy_all_used = FALSE;
100 static int proxy_fds[32];
101 static rad_listen_t *proxy_listeners[32];
102 static void check_for_zombie_home_server(REQUEST *request);
103 static void remove_from_proxy_hash(REQUEST *request);
105 #define remove_from_proxy_hash(foo)
108 static void request_post_handler(REQUEST *request);
109 static void wait_a_bit(void *ctx);
110 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
112 static void event_poll_detail(void *ctx);
115 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
118 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
122 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
125 static void tv_add(struct timeval *tv, int usec_delay)
127 if (usec_delay >= USEC) {
128 tv->tv_sec += usec_delay / USEC;
131 tv->tv_usec += usec_delay;
133 if (tv->tv_usec >= USEC) {
134 tv->tv_sec += tv->tv_usec / USEC;
139 static void remove_from_request_hash(REQUEST *request)
141 if (!request->in_request_hash) return;
143 fr_packet_list_yank(pl, request->packet);
144 request->in_request_hash = FALSE;
146 request_stats_final(request);
150 static void ev_request_free(REQUEST **prequest)
154 if (!prequest || !*prequest) return;
158 #ifdef HAVE_PTHREAD_H
160 * We can only free a request if there's no child thread
163 rad_assert(request->thread_id == NO_CHILD_THREAD);
169 * Divorce the child from the parent first,
170 * then clean up the child.
172 request->coa->parent = NULL;
173 ev_request_free(&request->coa);
177 * Divorce the parent from the child, and leave the
178 * parent still alive.
180 if (request->parent && (request->parent->coa == request)) {
181 request->parent->coa = NULL;
185 if (request->ev) fr_event_delete(el, &request->ev);
187 if (request->in_proxy_hash) remove_from_proxy_hash(request);
189 if (request->in_request_hash) remove_from_request_hash(request);
191 rad_assert(request->child_state != REQUEST_QUEUED);
193 request_free(prequest);
197 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
199 RADIUS_PACKET **proxy_p;
202 PTHREAD_MUTEX_LOCK(&proxy_mutex);
203 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
206 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
210 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
213 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
217 request->num_proxied_responses++;
220 * Catch the most common case of everything working
223 if (request->num_proxied_requests == request->num_proxied_responses) {
224 fr_packet_list_yank(proxy_list, request->proxy);
225 fr_packet_list_id_free(proxy_list, request->proxy);
226 request->in_proxy_hash = FALSE;
230 * On the FIRST reply, decrement the count of outstanding
231 * requests. Note that this is NOT the count of sent
232 * packets, but whether or not the home server has
235 if (!request->proxy_reply &&
236 request->home_server &&
237 request->home_server->currently_outstanding) {
238 request->home_server->currently_outstanding--;
241 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
247 static void remove_from_proxy_hash(REQUEST *request)
250 * Check this without grabbing the mutex because it's a
251 * lot faster that way.
253 if (!request->in_proxy_hash) return;
256 * The "not in hash" flag is definitive. However, if the
257 * flag says that it IS in the hash, there might still be
258 * a race condition where it isn't.
260 PTHREAD_MUTEX_LOCK(&proxy_mutex);
262 if (!request->in_proxy_hash) {
263 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
267 fr_packet_list_yank(proxy_list, request->proxy);
268 fr_packet_list_id_free(proxy_list, request->proxy);
271 * The home server hasn't replied, but we've given up on
272 * this request. Don't count this request against the
275 if (!request->proxy_reply &&
276 request->home_server &&
277 request->home_server->currently_outstanding) {
278 request->home_server->currently_outstanding--;
282 * Got from YES in hash, to NO, not in hash while we hold
283 * the mutex. This guarantees that when another thread
284 * grans the mutex, the "not in hash" flag is correct.
286 request->in_proxy_hash = FALSE;
288 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
291 static int proxy_add_fds(rad_listen_t *proxy_listener)
293 int i, proxy, found = -1;
295 proxy = proxy_listener->fd;
296 for (i = 0; i < 32; i++) {
298 * Found a free entry. Save the socket,
299 * and remember where we saved it.
301 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
302 found = (proxy + i) & 0x1f;
303 proxy_fds[found] = proxy;
304 proxy_listeners[found] = proxy_listener;
312 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
314 rad_listen_t *proxy_listener;
316 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
318 if (proxy_all_used) return 0;
321 * Allocate a new proxy fd. This function adds
322 * it to the tail of the list of listeners. With
323 * some care, this can be thread-safe.
325 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
326 if (!proxy_listener) {
327 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
334 if (proxy_add_fds(proxy_listener) < 0) {
335 proxy_all_used = TRUE;
336 listen_free(&proxy_listener);
337 radlog(L_ERR, "Failed creating new proxy socket: server is too busy and home servers appear to be down");
342 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
343 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
348 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
349 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
354 * Signal the main thread to add the new FD to the list
357 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
362 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
367 rad_assert(request->proxy != NULL);
368 rad_assert(proxy_list != NULL);
370 PTHREAD_MUTEX_LOCK(&proxy_mutex);
373 * Keep track of maximum outstanding requests to a
374 * particular home server. 'max_outstanding' is
375 * enforced in home_server_ldb(), in realms.c.
377 if (request->home_server) {
378 request->home_server->currently_outstanding++;
382 RADIUS_PACKET packet;
384 packet = *request->proxy;
386 if (!proxy_id_alloc(request, &packet)) {
387 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
392 * Yank the request, free the old Id, and
393 * remember the new Id.
395 fr_packet_list_yank(proxy_list, request->proxy);
396 fr_packet_list_id_free(proxy_list, request->proxy);
397 *request->proxy = packet;
399 } else if (!proxy_id_alloc(request, request->proxy)) {
400 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
404 rad_assert(request->proxy->sockfd >= 0);
407 * FIXME: Hack until we get rid of rad_listen_t, and put
408 * the information into the packet_list.
411 for (i = 0; i < 32; i++) {
412 if (proxy_fds[i] == request->proxy->sockfd) {
419 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
420 RDEBUG2("ERROR: All sockets are full.");
424 rad_assert(proxy_fds[proxy] != -1);
425 rad_assert(proxy_listeners[proxy] != NULL);
426 request->proxy_listener = proxy_listeners[proxy];
428 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
429 fr_packet_list_yank(proxy_list, request->proxy);
430 fr_packet_list_id_free(proxy_list, request->proxy);
431 request->proxy_listener = NULL;
432 request->in_proxy_hash = FALSE;
433 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
434 RDEBUG2("ERROR: Failed to insert entry into proxy list.");
438 request->in_proxy_hash = TRUE;
440 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
442 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
443 inet_ntop(request->proxy->dst_ipaddr.af,
444 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
445 request->proxy->dst_port,
453 * Called as BOTH an event, and in-line from other functions.
455 static void wait_for_proxy_id_to_expire(void *ctx)
457 REQUEST *request = ctx;
460 rad_assert(request->magic == REQUEST_MAGIC);
461 rad_assert(request->proxy != NULL);
463 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
464 request->when = request->proxy_when;
467 if (((request->proxy->code == PW_COA_REQUEST) ||
468 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
469 (request->packet->code != request->proxy->code)) {
470 request->when.tv_sec += request->home_server->coa_mrd;
473 request->when.tv_sec += request->home_server->response_window;
475 if ((request->num_proxied_requests == request->num_proxied_responses) ||
476 timercmp(&now, &request->when, >)) {
477 if (request->packet) {
478 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
479 request->number, request->packet->id,
480 (unsigned int) (request->timestamp - fr_start_time));
482 RDEBUG2("Cleaning up request %u with timestamp +%d",
484 (unsigned int) (request->timestamp - fr_start_time));
487 ev_request_free(&request);
491 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
495 #ifdef HAVE_PTHREAD_H
496 static void wait_for_child_to_die(void *ctx)
498 REQUEST *request = ctx;
500 rad_assert(request->magic == REQUEST_MAGIC);
502 if (request->in_request_hash) {
503 remove_from_request_hash(request);
507 * If it's still queued (waiting for a thread to pick it
508 * up) OR there's still a child thread handling it, THEN
511 if ((request->child_state == REQUEST_QUEUED) ||
512 (request->thread_id != NO_CHILD_THREAD)) {
514 * Cap delay at max_request_time
516 if (request->delay < (USEC * request->root->max_request_time)) {
517 request->delay += (request->delay >> 1);
518 radlog(L_INFO, "WARNING: Child is hung for request %u in component %s module %s.",
519 request->number, request->component, request->module);
521 request->delay = USEC * request->root->max_request_time;
522 RDEBUG2("WARNING: Child is hung after \"max_request_time\" for request %u",
525 tv_add(&request->when, request->delay);
527 INSERT_EVENT(wait_for_child_to_die, request);
531 rad_assert(request->thread_id == NO_CHILD_THREAD);
532 RDEBUG2("Child is finally responsive for request %u", request->number);
535 if (request->proxy) {
536 wait_for_proxy_id_to_expire(request);
541 request->child_state = REQUEST_DONE;
543 ev_request_free(&request);
547 static void cleanup_delay(void *ctx)
549 REQUEST *request = ctx;
551 rad_assert(request->magic == REQUEST_MAGIC);
552 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
553 (request->child_state == REQUEST_DONE));
555 remove_from_request_hash(request);
558 if (request->proxy && request->in_proxy_hash) {
559 wait_for_proxy_id_to_expire(request);
564 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
565 request->number, request->packet->id,
566 (unsigned int) (request->timestamp - fr_start_time));
568 ev_request_free(&request);
573 * In daemon mode, AND this request has debug flags set.
575 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
577 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
581 const char *received, *from;
582 const fr_ipaddr_t *ip;
587 rad_assert(request->radlog != NULL);
589 if (direction == 0) {
590 received = "Received";
591 from = "from"; /* what else? */
592 ip = &packet->src_ipaddr;
593 port = packet->src_port;
596 received = "Sending";
597 from = "to"; /* hah! */
598 ip = &packet->dst_ipaddr;
599 port = packet->dst_port;
603 * Client-specific debugging re-prints the input
604 * packet into the client log.
606 * This really belongs in a utility library
608 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
609 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
610 received, fr_packet_codes[packet->code], from,
611 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
612 port, packet->id, packet->data_len);
614 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
616 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
618 packet->code, packet->id, packet->data_len);
621 for (vp = packet->vps; vp != NULL; vp = vp->next) {
622 vp_prints(buffer, sizeof(buffer), vp);
623 request->radlog(L_DBG, 0, request, "\t%s", buffer);
627 static void reject_delay(void *ctx)
629 REQUEST *request = ctx;
631 rad_assert(request->magic == REQUEST_MAGIC);
632 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
634 RDEBUG2("Sending delayed reject for request %u", request->number);
636 DEBUG_PACKET(request, request->reply, 1);
638 request->listener->send(request->listener, request);
640 request->when.tv_sec += request->root->cleanup_delay;
641 request->child_state = REQUEST_CLEANUP_DELAY;
643 INSERT_EVENT(cleanup_delay, request);
648 void revive_home_server(void *ctx)
650 home_server *home = ctx;
654 home->state = HOME_STATE_ALIVE;
655 home->currently_outstanding = 0;
657 gettimeofday(&now, NULL);
658 home->revive_time = now;
661 * Delete any outstanding events.
663 if (home->ev) fr_event_delete(el, &home->ev);
665 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
666 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
667 buffer, sizeof(buffer)),
673 static void no_response_to_ping(void *ctx)
675 REQUEST *request = ctx;
679 rad_assert(request->home_server != NULL);
681 home = request->home_server;
682 home->num_received_pings = 0;
684 radlog(L_ERR, "No response to status check %d for home server %s port %d",
686 inet_ntop(request->proxy->dst_ipaddr.af,
687 &request->proxy->dst_ipaddr.ipaddr,
688 buffer, sizeof(buffer)),
689 request->proxy->dst_port);
691 check_for_zombie_home_server(request);
693 wait_for_proxy_id_to_expire(request);
697 static void received_response_to_ping(REQUEST *request)
703 rad_assert(request->home_server != NULL);
705 home = request->home_server;
706 home->num_received_pings++;
708 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
709 request->number, home->num_received_pings);
712 * Remove the request from any hashes
714 fr_event_delete(el, &request->ev);
715 remove_from_proxy_hash(request);
716 rad_assert(request->in_request_hash == FALSE);
719 * The control socket may have marked the home server as
720 * alive. OR, it may have suddenly started responding to
721 * requests again. If so, don't re-do the "make alive"
724 if (home->state == HOME_STATE_ALIVE) return;
727 * It's dead, and we haven't received enough ping
728 * responses to mark it "alive". Wait a bit.
730 * If it's zombie, we mark it alive immediately.
732 if ((home->state == HOME_STATE_IS_DEAD) &&
733 (home->num_received_pings < home->num_pings_to_alive)) {
737 home->state = HOME_STATE_ALIVE;
738 home->currently_outstanding = 0;
740 gettimeofday(&now, NULL);
741 home->revive_time = now;
743 if (!fr_event_delete(el, &home->ev)) {
744 RDEBUG2("Hmm... no event for home server. Oh well.");
747 radlog(L_PROXY, "Marking home server %s port %d alive",
748 inet_ntop(request->proxy->dst_ipaddr.af,
749 &request->proxy->dst_ipaddr.ipaddr,
750 buffer, sizeof(buffer)),
751 request->proxy->dst_port);
756 * Called from start of zombie period, OR after control socket
757 * marks the home server dead.
759 static void ping_home_server(void *ctx)
762 home_server *home = ctx;
766 if ((home->state == HOME_STATE_ALIVE) ||
767 (home->ping_check == HOME_PING_CHECK_NONE) ||
768 (home->ev != NULL)) {
772 request = request_alloc();
773 request->number = request_num_counter++;
775 request->proxy = rad_alloc(1);
776 rad_assert(request->proxy != NULL);
778 fr_event_now(el, &request->when);
779 home->when = request->when;
781 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
782 request->proxy->code = PW_STATUS_SERVER;
784 radius_pairmake(request, &request->proxy->vps,
785 "Message-Authenticator", "0x00", T_OP_SET);
787 } else if (home->type == HOME_TYPE_AUTH) {
788 request->proxy->code = PW_AUTHENTICATION_REQUEST;
790 radius_pairmake(request, &request->proxy->vps,
791 "User-Name", home->ping_user_name, T_OP_SET);
792 radius_pairmake(request, &request->proxy->vps,
793 "User-Password", home->ping_user_password, T_OP_SET);
794 radius_pairmake(request, &request->proxy->vps,
795 "Service-Type", "Authenticate-Only", T_OP_SET);
796 radius_pairmake(request, &request->proxy->vps,
797 "Message-Authenticator", "0x00", T_OP_SET);
800 #ifdef WITH_ACCOUNTING
801 request->proxy->code = PW_ACCOUNTING_REQUEST;
803 radius_pairmake(request, &request->proxy->vps,
804 "User-Name", home->ping_user_name, T_OP_SET);
805 radius_pairmake(request, &request->proxy->vps,
806 "Acct-Status-Type", "Stop", T_OP_SET);
807 radius_pairmake(request, &request->proxy->vps,
808 "Acct-Session-Id", "00000000", T_OP_SET);
809 vp = radius_pairmake(request, &request->proxy->vps,
810 "Event-Timestamp", "0", T_OP_SET);
811 vp->vp_date = request->when.tv_sec;
813 rad_assert("Internal sanity check failed");
817 radius_pairmake(request, &request->proxy->vps,
818 "NAS-Identifier", "Status Check. Are you alive?",
821 request->proxy->src_ipaddr = home->src_ipaddr;
822 request->proxy->dst_ipaddr = home->ipaddr;
823 request->proxy->dst_port = home->port;
824 request->home_server = home;
826 rad_assert(request->proxy_listener == NULL);
828 if (!insert_into_proxy_hash(request, FALSE)) {
829 RDEBUG2("ERROR: Failed to insert status check %d into proxy list. Discarding it.",
831 ev_request_free(&request);
834 rad_assert(request->proxy_listener != NULL);
835 request->proxy_listener->send(request->proxy_listener,
838 request->next_callback = NULL;
839 request->child_state = REQUEST_PROXIED;
840 gettimeofday(&request->when, NULL);
841 home->when = request->when;
842 request->when.tv_sec += home->ping_timeout;;
844 INSERT_EVENT(no_response_to_ping, request);
847 * Add +/- 2s of jitter, as suggested in RFC 3539
848 * and in the Issues and Fixes draft.
850 home->when.tv_sec += home->ping_interval - 2;
853 jitter ^= (jitter >> 10);
854 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
856 tv_add(&home->when, jitter);
858 INSERT_EVENT(ping_home_server, home);
862 void mark_home_server_dead(home_server *home, struct timeval *when)
864 int previous_state = home->state;
867 radlog(L_PROXY, "Marking home server %s port %d as dead.",
868 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
869 buffer, sizeof(buffer)),
872 home->state = HOME_STATE_IS_DEAD;
873 home->num_received_pings = 0;
875 if (home->ping_check != HOME_PING_CHECK_NONE) {
877 * If the control socket marks us dead, start
878 * pinging. Otherwise, we already started
879 * pinging when it was marked "zombie".
881 if (previous_state == HOME_STATE_ALIVE) {
882 ping_home_server(home);
887 * Revive it after a fixed period of time. This
888 * is very, very, bad.
891 home->when.tv_sec += home->revive_interval;
893 INSERT_EVENT(revive_home_server, home);
897 static void check_for_zombie_home_server(REQUEST *request)
900 struct timeval now, when;
902 home = request->home_server;
904 if (home->state != HOME_STATE_ZOMBIE) return;
906 when = home->zombie_period_start;
907 when.tv_sec += home->zombie_period;
909 fr_event_now(el, &now);
910 if (timercmp(&now, &when, <)) {
914 mark_home_server_dead(home, &when);
917 static int proxy_to_virtual_server(REQUEST *request);
919 static int virtual_server_handler(UNUSED REQUEST *request)
921 proxy_to_virtual_server(request);
925 static void proxy_fallback_handler(REQUEST *request)
930 * A proper time is required for wait_a_bit.
932 request->delay = USEC / 10;
933 gettimeofday(&now, NULL);
934 request->next_when = now;
935 tv_add(&request->next_when, request->delay);
936 request->next_callback = wait_a_bit;
939 * Re-queue the request.
941 request->child_state = REQUEST_QUEUED;
943 rad_assert(request->proxy != NULL);
944 if (!thread_pool_addrequest(request, virtual_server_handler)) {
945 request->child_state = REQUEST_DONE;
948 #ifdef HAVE_PTHREAD_H
950 * MAY free the request if we're over max_request_time,
951 * AND we're not in threaded mode!
953 * Note that we call this ONLY if we're threaded, as
954 * if we're NOT threaded, request_post_handler() calls
955 * wait_a_bit(), which means that "request" may not
958 if (have_children) wait_a_bit(request);
963 static int setup_post_proxy_fail(REQUEST *request)
965 DICT_VALUE *dval = NULL;
968 request->child_state = REQUEST_RUNNING;
970 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
971 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
973 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
974 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
978 * See no_response_to_coa_request
980 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
981 request->packet->code &= 0xff; /* restore it */
983 if (request->proxy->code == PW_COA_REQUEST) {
984 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
986 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
987 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
997 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
1000 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
1004 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1005 if (!vp) vp = radius_paircreate(request, &request->config_items,
1006 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
1007 vp->vp_integer = dval->value;
1009 rad_assert(request->proxy_reply == NULL);
1015 static int null_handler(UNUSED REQUEST *request)
1020 static void post_proxy_fail_handler(REQUEST *request)
1025 * A proper time is required for wait_a_bit.
1027 request->delay = USEC / 10;
1028 gettimeofday(&now, NULL);
1031 * Not set up to run Post-Proxy-Type = Fail.
1033 * Mark the request as still running, and figure out what
1036 if (!setup_post_proxy_fail(request)) {
1037 request_post_handler(request);
1041 * Re-queue the request.
1043 request->child_state = REQUEST_QUEUED;
1046 * There is a post-proxy-type of fail. We run
1047 * the request through the pre/post proxy
1048 * handlers, just like it was a real proxied
1049 * request. However, we set the per-request
1050 * handler to NULL, as we don't want to do
1053 * Note that when we're not threaded, this will
1054 * process the request even if it's greater than
1055 * max_request_time. That's not fatal.
1057 request->priority = 0;
1058 rad_assert(request->proxy != NULL);
1059 thread_pool_addrequest(request, null_handler);
1063 * MAY free the request if we're over max_request_time,
1064 * AND we're not in threaded mode!
1066 * Note that we call this ONLY if we're threaded, as
1067 * if we're NOT threaded, request_post_handler() calls
1068 * wait_a_bit(), which means that "request" may not
1071 if (have_children) wait_a_bit(request);
1075 /* maybe check this against wait_for_proxy_id_to_expire? */
1076 static void no_response_to_proxied_request(void *ctx)
1078 REQUEST *request = ctx;
1084 rad_assert(request->magic == REQUEST_MAGIC);
1085 rad_assert(request->child_state == REQUEST_PROXIED);
1088 * If we've failed over to an internal home server,
1089 * replace the callback with the correct one. This
1090 * is due to locking issues with child threads...
1092 if (request->home_server->server) {
1093 wait_a_bit(request);
1097 check_for_zombie_home_server(request);
1099 home = request->home_server;
1102 * The default as of 2.1.7 is to allow requests to
1103 * fail-over to a backup home server when this one does
1104 * not respond. The old behavior can be configured as
1107 if (home->no_response_fail) {
1108 radlog(L_ERR, "Rejecting request %u (proxy Id %d) due to lack of any response from home server %s port %d",
1109 request->number, request->proxy->id,
1110 inet_ntop(request->proxy->dst_ipaddr.af,
1111 &request->proxy->dst_ipaddr.ipaddr,
1112 buffer, sizeof(buffer)),
1113 request->proxy->dst_port);
1115 post_proxy_fail_handler(request);
1117 struct timeval when;
1120 * Do nothing, and let the request time out.
1122 rad_assert(request->ev == NULL);
1124 when = request->received;
1125 when.tv_sec += request->root->max_request_time;
1127 request->child_state = REQUEST_DONE;
1128 request->next_when = when;
1129 request->next_callback = cleanup_delay;
1131 if (request->in_proxy_hash) remove_from_proxy_hash(request);
1133 wait_a_bit(request);
1137 * Don't touch request due to race conditions
1141 * If it's not alive, don't try to make it a zombie.
1143 if (home->state != HOME_STATE_ALIVE) {
1145 * Don't check home->ev due to race conditions.
1151 * We've received a real packet recently. Don't mark the
1152 * server as zombie until we've received NO packets for a
1153 * while. The "1/4" of zombie period was chosen rather
1154 * arbitrarily. It's a balance between too short, which
1155 * gives quick fail-over and fail-back, or too long,
1156 * where the proxy still sends packets to an unresponsive
1159 fr_event_now(el, &now);
1160 start = now.tv_sec - ((home->zombie_period + 3) / 4);
1161 if (home->last_packet >= start) {
1166 * Set the home server to "zombie", as of the time
1169 home->state = HOME_STATE_ZOMBIE;
1171 home->zombie_period_start.tv_sec = start;
1172 home->zombie_period_start.tv_usec = USEC / 2;
1174 fr_event_delete(el, &home->ev);
1175 home->currently_outstanding = 0;
1176 home->num_received_pings = 0;
1178 radlog(L_PROXY, "Marking home server %s port %d as zombie (it looks like it is dead).",
1179 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1180 buffer, sizeof(buffer)),
1184 * Start pinging the home server.
1186 ping_home_server(home);
1190 static void wait_a_bit(void *ctx)
1192 struct timeval now, when;
1193 REQUEST *request = ctx;
1194 fr_event_callback_t callback = NULL;
1196 rad_assert(request->magic == REQUEST_MAGIC);
1200 * The CoA request is a new (internally generated)
1201 * request, created in a child thread. We therefore need
1202 * some way to tie its events back into the main event
1205 if (request->coa && !request->coa->proxy_reply &&
1206 request->coa->next_callback) {
1207 request->coa->when = request->coa->next_when;
1208 INSERT_EVENT(request->coa->next_callback, request->coa);
1209 request->coa->next_callback = NULL;
1210 request->coa->parent = NULL;
1211 request->coa = NULL;
1215 switch (request->child_state) {
1216 case REQUEST_QUEUED:
1217 case REQUEST_RUNNING:
1219 * If we're not thread-capable, OR we're capable,
1220 * but have been told to run without threads, and
1221 * the request is still running. This is usually
1222 * because the request was proxied, and the home
1223 * server didn't respond.
1225 #ifdef HAVE_PTHREAD_H
1229 request->child_state = REQUEST_DONE;
1233 #ifdef HAVE_PTHREAD_H
1235 * If we have threads, wait for the child thread
1238 when = request->received;
1239 when.tv_sec += request->root->max_request_time;
1242 * Normally called from the event loop with the
1243 * proper event loop time. Otherwise, called from
1244 * post proxy fail handler, which sets "now", and
1245 * this call won't re-set it, because we're not
1246 * in the event loop.
1248 fr_event_now(el, &now);
1251 * Request still has more time. Continue
1254 if (timercmp(&now, &when, <)) {
1255 if (request->delay < (USEC / 10)) {
1256 request->delay = USEC / 10;
1258 request->delay += request->delay >> 1;
1261 * Cap delays at something reasonable.
1263 if (request->delay > (request->root->max_request_time * USEC)) {
1264 request->delay = request->root->max_request_time * USEC;
1267 request->when = now;
1268 tv_add(&request->when, request->delay);
1269 callback = wait_a_bit;
1273 request->master_state = REQUEST_STOP_PROCESSING;
1276 * A child thread MAY still be running on the
1277 * request. Ask the thread to stop working on
1280 if (have_children &&
1281 (request->thread_id == NO_CHILD_THREAD)) {
1282 radlog(L_ERR, "WARNING: Unresponsive thread %d for request %u, in component %s module %s",
1283 request->number, request->thread_id,
1284 request->component ? request->component : "<server core>",
1285 request->module ? request->module : "<server core>");
1289 request->delay = USEC;
1290 tv_add(&request->when, request->delay);
1291 callback = wait_for_child_to_die;
1296 * Mark the request as no longer running,
1301 #ifdef HAVE_PTHREAD_H
1302 request->thread_id = NO_CHILD_THREAD;
1307 * This is a CoA request. It's been divorced
1308 * from everything else, so we clean it up now.
1310 if (!request->in_request_hash &&
1312 (request->packet->code != request->proxy->code) &&
1313 ((request->proxy->code == PW_COA_REQUEST) ||
1314 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1316 * FIXME: Do CoA MIBs
1318 ev_request_free(&request);
1322 request_stats_final(request);
1323 cleanup_delay(request);
1326 case REQUEST_REJECT_DELAY:
1327 case REQUEST_CLEANUP_DELAY:
1328 #ifdef HAVE_PTHREAD_H
1329 request->thread_id = NO_CHILD_THREAD;
1331 request_stats_final(request);
1334 case REQUEST_PROXIED:
1335 rad_assert(request->next_callback != NULL);
1336 rad_assert(request->next_callback != wait_a_bit);
1338 request->when = request->next_when;
1339 callback = request->next_callback;
1340 request->next_callback = NULL;
1344 rad_panic("Internal sanity check failure");
1349 * Something major went wrong. Discard the request, and
1352 * FIXME: No idea why this happens or how to fix it...
1353 * It seems to happen *only* when requests are proxied,
1354 * and where the home server doesn't respond. So it looks
1355 * like a race condition above, but it happens in debug
1356 * mode, with no threads...
1359 RDEBUG("WARNING: Internal sanity check failed in event handler for request %u: Discarding the request!", request->number);
1360 ev_request_free(&request);
1364 INSERT_EVENT(callback, request);
1368 static void no_response_to_coa_request(void *ctx)
1370 REQUEST *request = ctx;
1373 rad_assert(request->magic == REQUEST_MAGIC);
1374 rad_assert(request->child_state == REQUEST_PROXIED);
1375 rad_assert(request->home_server != NULL);
1376 rad_assert(!request->in_request_hash);
1378 radlog(L_ERR, "No response to CoA request sent to %s",
1379 inet_ntop(request->proxy->dst_ipaddr.af,
1380 &request->proxy->dst_ipaddr.ipaddr,
1381 buffer, sizeof(buffer)));
1386 request->packet->code |= (PW_COA_REQUEST << 8);
1387 post_proxy_fail_handler(request);
1391 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1395 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1402 packet->data = NULL;
1403 packet->data_len = 0;
1406 return 1; /* time stamp updated */
1411 * Called when we haven't received a response to a CoA request.
1413 static void retransmit_coa_request(void *ctx)
1416 struct timeval now, mrd;
1417 REQUEST *request = ctx;
1419 rad_assert(request->magic == REQUEST_MAGIC);
1420 rad_assert(request->child_state == REQUEST_PROXIED);
1421 rad_assert(request->home_server != NULL);
1422 rad_assert(!request->in_request_hash);
1423 rad_assert(request->parent == NULL);
1425 fr_event_now(el, &now);
1428 * Cap count at MRC, if it is non-zero.
1430 if (request->home_server->coa_mrc &&
1431 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1432 no_response_to_coa_request(request);
1437 * RFC 5080 Section 2.2.1
1439 * RT = 2*RTprev + RAND*RTprev
1440 * = 1.9 * RTprev + rand(0,.2) * RTprev
1441 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1444 delay ^= (delay >> 16);
1446 frac = request->delay / 5;
1447 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1449 delay += (2 * request->delay) - (request->delay / 10);
1452 * Cap delay at MRT, if MRT is non-zero.
1454 if (request->home_server->coa_mrt &&
1455 (delay > (request->home_server->coa_mrt * USEC))) {
1456 int mrt_usec = request->home_server->coa_mrt * USEC;
1459 * delay = MRT + RAND * MRT
1460 * = 0.9 MRT + rand(0,.2) * MRT
1463 delay ^= (delay >> 15);
1465 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1466 delay += mrt_usec - (mrt_usec / 10);
1469 request->delay = delay;
1470 request->when = now;
1471 tv_add(&request->when, request->delay);
1472 mrd = request->proxy_when;
1473 mrd.tv_sec += request->home_server->coa_mrd;
1476 * Cap duration at MRD.
1478 if (timercmp(&mrd, &request->when, <)) {
1479 request->when = mrd;
1480 INSERT_EVENT(no_response_to_coa_request, request);
1483 INSERT_EVENT(retransmit_coa_request, request);
1486 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1487 if (!insert_into_proxy_hash(request, TRUE)) {
1488 DEBUG("ERROR: Failed to insert retransmission of CoA request into proxy list.");
1492 request->num_proxied_requests = 0;
1493 request->num_proxied_responses = 0;
1496 request->num_proxied_requests++;
1497 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1499 request->proxy_listener->send(request->proxy_listener,
1505 * The original request is either DONE, or in CLEANUP_DELAY.
1507 static int originated_coa_request(REQUEST *request)
1509 int delay, rcode, pre_proxy_type = 0;
1515 rad_assert(request->proxy == NULL);
1516 rad_assert(!request->in_proxy_hash);
1517 rad_assert(request->proxy_reply == NULL);
1520 * Check whether we want to originate one, or cancel one.
1522 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1523 if (!vp && request->coa) {
1524 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1528 if (vp->vp_integer == 0) {
1529 ev_request_free(&request->coa);
1530 return 1; /* success */
1534 if (!request->coa) request_alloc_coa(request);
1535 if (!request->coa) return 0;
1540 * src_ipaddr will be set up in proxy_encode.
1542 memset(&ipaddr, 0, sizeof(ipaddr));
1543 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1545 ipaddr.af = AF_INET;
1546 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1548 } else if ((vp = pairfind(coa->proxy->vps,
1549 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1550 ipaddr.af = AF_INET6;
1551 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1553 } else if ((vp = pairfind(coa->proxy->vps,
1554 PW_HOME_SERVER_POOL)) != NULL) {
1555 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1557 if (!coa->home_pool) {
1558 RDEBUG2("WARNING: No such home_server_pool %s",
1561 ev_request_free(&request->coa);
1568 } else if (request->client->coa_pool) {
1569 coa->home_pool = request->client->coa_pool;
1571 } else if (request->client->coa_server) {
1572 coa->home_server = request->client->coa_server;
1576 * If all else fails, send it to the client that
1577 * originated this request.
1579 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1583 * Use the pool, if it exists.
1585 if (coa->home_pool) {
1586 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1587 if (!coa->home_server) {
1588 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1592 } else if (!coa->home_server) {
1593 int port = PW_COA_UDP_PORT;
1595 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1596 if (vp) port = vp->vp_integer;
1598 coa->home_server = home_server_find(&ipaddr, port);
1599 if (!coa->home_server) {
1600 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1601 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1602 buffer, sizeof(buffer)), port);
1607 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1609 switch (vp->vp_integer) {
1610 case PW_COA_REQUEST:
1611 case PW_DISCONNECT_REQUEST:
1612 coa->proxy->code = vp->vp_integer;
1616 DEBUG("Cannot set CoA Packet-Type to code %d",
1622 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1625 * The rest of the server code assumes that
1626 * request->packet && request->reply exist. Copy them
1627 * from the original request.
1629 rad_assert(coa->packet != NULL);
1630 rad_assert(coa->packet->vps == NULL);
1631 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1632 coa->packet->vps = paircopy(request->packet->vps);
1633 coa->packet->data = NULL;
1634 rad_assert(coa->reply != NULL);
1635 rad_assert(coa->reply->vps == NULL);
1636 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1637 coa->reply->vps = paircopy(request->reply->vps);
1638 coa->reply->data = NULL;
1639 coa->config_items = paircopy(request->config_items);
1642 * Call the pre-proxy routines.
1644 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1646 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1647 pre_proxy_type = vp->vp_integer;
1650 if (coa->home_pool && coa->home_pool->virtual_server) {
1651 const char *old_server = coa->server;
1653 coa->server = coa->home_pool->virtual_server;
1654 RDEBUG2(" server %s {", coa->server);
1655 rcode = module_pre_proxy(pre_proxy_type, coa);
1657 coa->server = old_server;
1659 rcode = module_pre_proxy(pre_proxy_type, coa);
1666 * Only send the CoA packet if the pre-proxy code succeeded.
1668 case RLM_MODULE_NOOP:
1670 case RLM_MODULE_UPDATED:
1675 * Source IP / port is set when the proxy socket
1678 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1679 coa->proxy->dst_port = coa->home_server->port;
1681 if (!insert_into_proxy_hash(coa, FALSE)) {
1682 DEBUG("ERROR: Failed to insert CoA request into proxy list.");
1687 * We CANNOT divorce the CoA request from the parent
1688 * request. This function is running in a child thread,
1689 * and we need access to the main event loop in order to
1690 * to add the timers for the CoA packet. See
1695 * Forget about the original request completely at this
1700 gettimeofday(&request->proxy_when, NULL);
1701 request->received = request->next_when = request->proxy_when;
1702 rad_assert(request->proxy_reply == NULL);
1705 * Implement re-transmit algorithm as per RFC 5080
1708 * We want IRT + RAND*IRT
1709 * or 0.9 IRT + rand(0,.2) IRT
1711 * 2^20 ~ USEC, and we want 2.
1712 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1714 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1715 request->delay = delay * request->home_server->coa_irt;
1716 delay = request->home_server->coa_irt * USEC;
1717 delay -= delay / 10;
1718 delay += request->delay;
1720 request->delay = delay;
1721 tv_add(&request->next_when, delay);
1722 request->next_callback = retransmit_coa_request;
1725 * Note that we set proxied BEFORE sending the packet.
1727 * Once we send it, the request is tainted, as
1728 * another thread may have picked it up. Don't
1731 request->num_proxied_requests = 1;
1732 request->num_proxied_responses = 0;
1734 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1736 request->child_state = REQUEST_PROXIED;
1738 DEBUG_PACKET(request, request->proxy, 1);
1740 #ifdef HAVE_PTHREAD_H
1741 request->thread_id = NO_CHILD_THREAD;
1744 request->proxy_listener->send(request->proxy_listener,
1748 #endif /* WITH_COA */
1751 static int process_proxy_reply(REQUEST *request)
1754 int post_proxy_type = 0;
1758 * Delete any reply we had accumulated until now.
1760 pairfree(&request->reply->vps);
1763 * Run the packet through the post-proxy stage,
1764 * BEFORE playing games with the attributes.
1766 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1769 * If we have a proxy_reply, and it was a reject, setup
1770 * post-proxy-type Reject
1772 if (!vp && request->proxy_reply &&
1773 request->proxy_reply->code == PW_AUTHENTICATION_REJECT) {
1776 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Reject");
1778 vp = radius_paircreate(request, &request->config_items,
1779 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
1780 vp->vp_integer = dval->value;
1785 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1786 post_proxy_type = vp->vp_integer;
1789 if (request->home_pool && request->home_pool->virtual_server) {
1790 const char *old_server = request->server;
1792 request->server = request->home_pool->virtual_server;
1793 RDEBUG2(" server %s {", request->server);
1794 rcode = module_post_proxy(post_proxy_type, request);
1796 request->server = old_server;
1798 rcode = module_post_proxy(post_proxy_type, request);
1802 if (request->packet->code == request->proxy->code)
1804 * Don't run the next bit if we originated a CoA
1805 * packet, after receiving an Access-Request or
1806 * Accounting-Request.
1811 * There may NOT be a proxy reply, as we may be
1812 * running Post-Proxy-Type = Fail.
1814 if (request->proxy_reply) {
1816 * Delete the Proxy-State Attributes from
1817 * the reply. These include Proxy-State
1818 * attributes from us and remote server.
1820 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1823 * Add the attributes left in the proxy
1824 * reply to the reply list.
1826 pairadd(&request->reply->vps, request->proxy_reply->vps);
1827 request->proxy_reply->vps = NULL;
1830 * Free proxy request pairs.
1832 pairfree(&request->proxy->vps);
1836 default: /* Don't do anything */
1838 case RLM_MODULE_FAIL:
1839 case RLM_MODULE_HANDLED:
1840 /* FIXME: debug print stuff */
1841 #ifdef HAVE_PTHREAD_H
1842 request->thread_id = NO_CHILD_THREAD;
1844 request->child_state = REQUEST_DONE;
1852 static int request_pre_handler(REQUEST *request)
1856 rad_assert(request->magic == REQUEST_MAGIC);
1857 rad_assert(request->packet != NULL);
1859 request->child_state = REQUEST_RUNNING;
1862 * Don't decode the packet if it's an internal "fake"
1863 * request. Instead, just return so that the caller can
1866 if (request->packet->dst_port == 0) {
1867 request->username = pairfind(request->packet->vps,
1869 request->password = pairfind(request->packet->vps,
1876 * Put the decoded packet into it's proper place.
1878 if (request->proxy_reply != NULL) {
1879 rcode = request->proxy_listener->decode(request->proxy_listener,
1881 DEBUG_PACKET(request, request->proxy_reply, 0);
1884 if (request->packet->vps == NULL) {
1885 rcode = request->listener->decode(request->listener, request);
1887 if (debug_condition) {
1889 const char *my_debug = debug_condition;
1892 * Ignore parse errors.
1894 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1898 request->options = 2;
1899 request->radlog = radlog_request;
1903 DEBUG_PACKET(request, request->packet, 0);
1909 RDEBUG("%s Dropping packet without response.", fr_strerror());
1910 request->reply->offset = -2; /* bad authenticator */
1911 #ifdef HAVE_PTHREAD_H
1912 request->thread_id = NO_CHILD_THREAD;
1914 request->child_state = REQUEST_DONE;
1918 if (!request->username) {
1919 request->username = pairfind(request->packet->vps,
1924 if (request->proxy) {
1925 return process_proxy_reply(request);
1935 * Do state handling when we proxy a request.
1937 static int proxy_request(REQUEST *request)
1939 struct timeval when;
1944 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
1945 ev_request_free(&request->coa);
1949 if (request->home_server->server) {
1950 RDEBUG("ERROR: Cannot proxy to a virtual server.");
1954 if (!insert_into_proxy_hash(request, FALSE)) {
1955 RDEBUG("ERROR: Failed to insert entry into proxy list.");
1959 request->proxy_listener->encode(request->proxy_listener, request);
1961 when = request->received;
1962 when.tv_sec += request->root->max_request_time;
1964 gettimeofday(&request->proxy_when, NULL);
1966 request->next_when = request->proxy_when;
1967 request->next_when.tv_sec += request->home_server->response_window;
1969 rad_assert(request->home_server->response_window > 0);
1971 if (timercmp(&when, &request->next_when, <)) {
1972 request->next_when = when;
1974 request->next_callback = no_response_to_proxied_request;
1976 RDEBUG2("Proxying request %u to home server %s port %d",
1978 inet_ntop(request->proxy->dst_ipaddr.af,
1979 &request->proxy->dst_ipaddr.ipaddr,
1980 buffer, sizeof(buffer)),
1981 request->proxy->dst_port);
1984 * Note that we set proxied BEFORE sending the packet.
1986 * Once we send it, the request is tainted, as
1987 * another thread may have picked it up. Don't
1990 request->num_proxied_requests = 1;
1991 request->num_proxied_responses = 0;
1992 #ifdef HAVE_PTHREAD_H
1993 request->thread_id = NO_CHILD_THREAD;
1995 request->child_state = REQUEST_PROXIED;
1997 DEBUG_PACKET(request, request->proxy, 1);
1999 request->proxy_listener->send(request->proxy_listener,
2006 * "Proxy" the request by sending it to a new virtual server.
2008 static int proxy_to_virtual_server(REQUEST *request)
2011 RAD_REQUEST_FUNP fun;
2013 if (!request->home_server || !request->home_server->server) return 0;
2015 if (request->parent) {
2016 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
2020 fake = request_alloc_fake(request);
2022 RDEBUG2("WARNING: Out of memory");
2026 fake->packet->vps = paircopy(request->proxy->vps);
2027 fake->server = request->home_server->server;
2029 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
2030 fun = rad_virtual_server;
2032 #ifdef WITH_ACCOUNTING
2033 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
2034 fun = rad_accounting;
2038 RDEBUG2("Unknown packet type %d", request->proxy->code);
2039 ev_request_free(&fake);
2043 RDEBUG2(">>> Sending proxied request internally to virtual server.");
2044 radius_handle_request(fake, fun);
2045 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
2047 if (fake->reply->code != 0) {
2048 request->proxy_reply = fake->reply;
2052 * There was no response
2054 setup_post_proxy_fail(request);
2057 ev_request_free(&fake);
2059 if (!process_proxy_reply(request)) {
2064 * Process it through the normal section again, but ONLY
2065 * if we received a proxy reply..
2067 if (request->proxy_reply) {
2068 if (request->server) RDEBUG("server %s {",
2069 request->server != NULL ?
2070 request->server : "");
2073 if (request->server) RDEBUG("} # server %s",
2074 request->server != NULL ?
2075 request->server : "");
2078 return 2; /* success, but NOT '1' !*/
2082 * Return 1 if we did proxy it, or the proxy attempt failed
2083 * completely. Either way, the caller doesn't touch the request
2084 * any more if we return 1.
2086 static int successfully_proxied_request(REQUEST *request)
2089 int pre_proxy_type = 0;
2090 VALUE_PAIR *realmpair;
2091 VALUE_PAIR *strippedname;
2093 char *realmname = NULL;
2095 REALM *realm = NULL;
2099 * If it was already proxied, do nothing.
2101 * FIXME: This should really be a serious error.
2103 if (request->in_proxy_hash ||
2104 (request->proxy_reply && (request->proxy_reply->code != 0))) {
2108 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
2109 if (!realmpair || (realmpair->length == 0)) {
2112 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
2115 switch (request->packet->code) {
2116 case PW_AUTHENTICATION_REQUEST:
2117 pool_type = HOME_TYPE_AUTH;
2120 #ifdef WITH_ACCOUNTING
2121 case PW_ACCOUNTING_REQUEST:
2122 pool_type = HOME_TYPE_ACCT;
2127 case PW_COA_REQUEST:
2128 case PW_DISCONNECT_REQUEST:
2129 pool_type = HOME_TYPE_COA;
2137 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2139 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2144 realmname = NULL; /* no realms */
2149 realmname = (char *) realmpair->vp_strvalue;
2151 realm = realm_find2(realmname);
2153 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2158 * Figure out which pool to use.
2160 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2161 pool = realm->auth_pool;
2163 #ifdef WITH_ACCOUNTING
2164 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2165 pool = realm->acct_pool;
2169 } else if ((request->packet->code == PW_COA_REQUEST) ||
2170 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2171 pool = realm->acct_pool;
2175 rad_panic("Internal sanity check failed");
2179 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2185 home = home_server_ldb(realmname, pool, request);
2187 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2191 request->home_pool = pool;
2195 * Once we've decided to proxy a request, we cannot send
2196 * a CoA packet. So we free up any CoA packet here.
2198 ev_request_free(&request->coa);
2201 * Remember that we sent the request to a Realm.
2203 if (realmname) pairadd(&request->packet->vps,
2204 pairmake("Realm", realmname, T_OP_EQ));
2207 * Strip the name, if told to.
2209 * Doing it here catches the case of proxied tunneled
2212 if (realm && (realm->striprealm == TRUE) &&
2213 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2215 * If there's a Stripped-User-Name attribute in
2216 * the request, then use THAT as the User-Name
2217 * for the proxied request, instead of the
2220 * This is done by making a copy of the
2221 * Stripped-User-Name attribute, turning it into
2222 * a User-Name attribute, deleting the
2223 * Stripped-User-Name and User-Name attributes
2224 * from the vps list, and making the new
2225 * User-Name the head of the vps list.
2227 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2229 vp = radius_paircreate(request, NULL,
2230 PW_USER_NAME, PW_TYPE_STRING);
2231 rad_assert(vp != NULL); /* handled by above function */
2232 /* Insert at the START of the list */
2233 vp->next = request->proxy->vps;
2234 request->proxy->vps = vp;
2236 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2237 sizeof(vp->vp_strvalue));
2238 vp->length = strippedname->length;
2241 * Do NOT delete Stripped-User-Name.
2246 * If there is no PW_CHAP_CHALLENGE attribute but
2247 * there is a PW_CHAP_PASSWORD we need to add it
2248 * since we can't use the request authenticator
2249 * anymore - we changed it.
2251 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2252 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2253 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2254 vp = radius_paircreate(request, &request->proxy->vps,
2255 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2256 vp->length = AUTH_VECTOR_LEN;
2257 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2261 * The RFC's say we have to do this, but FreeRADIUS
2264 vp = radius_paircreate(request, &request->proxy->vps,
2265 PW_PROXY_STATE, PW_TYPE_OCTETS);
2266 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2267 request->packet->id);
2268 vp->length = strlen(vp->vp_strvalue);
2271 * Should be done BEFORE inserting into proxy hash, as
2272 * pre-proxy may use this information, or change it.
2274 request->proxy->code = request->packet->code;
2277 * Call the pre-proxy routines.
2279 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2281 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2282 pre_proxy_type = vp->vp_integer;
2285 rad_assert(request->home_pool != NULL);
2287 if (request->home_pool->virtual_server) {
2288 const char *old_server = request->server;
2290 request->server = request->home_pool->virtual_server;
2291 RDEBUG2(" server %s {", request->server);
2292 rcode = module_pre_proxy(pre_proxy_type, request);
2294 request->server = old_server;
2296 rcode = module_pre_proxy(pre_proxy_type, request);
2299 case RLM_MODULE_FAIL:
2300 case RLM_MODULE_INVALID:
2301 case RLM_MODULE_NOTFOUND:
2302 case RLM_MODULE_USERLOCK:
2304 /* FIXME: debug print failed stuff */
2307 case RLM_MODULE_REJECT:
2308 case RLM_MODULE_HANDLED:
2312 * Only proxy the packet if the pre-proxy code succeeded.
2314 case RLM_MODULE_NOOP:
2316 case RLM_MODULE_UPDATED:
2321 * If it's a fake request, don't send the proxy
2322 * packet. The outer tunnel session will take
2323 * care of doing that.
2325 if (request->packet->dst_port == 0) {
2326 request->home_server = NULL;
2330 if (request->home_server->server) {
2331 return proxy_to_virtual_server(request);
2334 if (!proxy_request(request)) {
2335 RDEBUG("ERROR: Failed to proxy request %u", request->number);
2343 static void request_post_handler(REQUEST *request)
2345 int child_state = -1;
2346 struct timeval when;
2349 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2351 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2352 RDEBUG2("request %u was cancelled.", request->number);
2353 child_state = REQUEST_DONE;
2357 if (request->child_state != REQUEST_RUNNING) {
2358 radlog(L_ERR, "Request %d is unexpectedly in state %d. Stopping it.",
2359 request->number, request->child_state);
2365 * If it's not in the request hash, it's a CoA request.
2368 if (!request->in_request_hash &&
2370 ((request->proxy->code == PW_COA_REQUEST) ||
2371 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2372 request->next_callback = NULL;
2373 child_state = REQUEST_DONE;
2379 * Catch Auth-Type := Reject BEFORE proxying the packet.
2381 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2382 (request->reply->code == 0) &&
2383 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2384 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2385 request->reply->code = PW_AUTHENTICATION_REJECT;
2389 if (request->root->proxy_requests &&
2390 !request->in_proxy_hash &&
2391 (request->reply->code == 0) &&
2392 (request->packet->dst_port != 0) &&
2393 (request->packet->code != PW_STATUS_SERVER)) {
2394 int rcode = successfully_proxied_request(request);
2396 if (rcode == 1) return; /* "request" is now untouchable */
2399 * Failed proxying it (dead home servers, etc.)
2400 * Run it through Post-Proxy-Type = Fail, and
2401 * respond to the request.
2403 * Note that we're in a child thread here, so we
2404 * do NOT re-schedule the request. Instead, we
2405 * do what we would have done, which is run the
2406 * pre-handler, a NULL request handler, and then
2409 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2410 if (!request_pre_handler(request)) {
2416 * Else we weren't supposed to proxy it,
2417 * OR we proxied it internally to a virutal server.
2422 else if (request->proxy && request->coa) {
2423 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2424 ev_request_free(&request->coa);
2430 * Fake requests don't get encoded or signed. The caller
2431 * also requires the reply VP's, so we don't free them
2434 if (request->packet->dst_port == 0) {
2435 /* FIXME: RDEBUG going to the next request */
2436 #ifdef HAVE_PTHREAD_H
2437 request->thread_id = NO_CHILD_THREAD;
2439 request->child_state = REQUEST_DONE;
2445 * Copy Proxy-State from the request to the reply.
2447 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2448 if (vp) pairadd(&request->reply->vps, vp);
2452 * Access-Requests get delayed or cached.
2454 switch (request->packet->code) {
2455 case PW_AUTHENTICATION_REQUEST:
2456 gettimeofday(&request->next_when, NULL);
2459 * Override the response code if a
2460 * control:Response-Packet-Type attribute is present.
2462 vp = pairfind(request->config_items,
2463 PW_RESPONSE_PACKET_TYPE);
2465 if (vp->vp_integer == 256) {
2466 RDEBUG2("Not responding to request %u",
2470 * Force cleanup after a long
2471 * time, so that we don't
2472 * re-process the packet.
2474 request->reply->code = 0;
2475 request->next_when.tv_sec += request->root->max_request_time;
2476 request->next_callback = cleanup_delay;
2477 child_state = REQUEST_CLEANUP_DELAY;
2481 request->reply->code = vp->vp_integer;
2483 } else if (request->reply->code == 0) {
2484 RDEBUG2("There was no response configured: rejecting "
2485 "request %u", request->number);
2487 request->reply->code = PW_AUTHENTICATION_REJECT;
2491 * Do post-auth. If it returns reject, then
2492 * run Post-Auth-Type Reject.
2494 if (request->reply->code == PW_AUTHENTICATION_ACK) {
2495 if (rad_postauth(request) == RLM_MODULE_REJECT) {
2496 request->reply->code = PW_AUTHENTICATION_REJECT;
2501 * Run rejected packets through
2503 * Post-Auth-Type = Reject
2505 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2506 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2507 vp = radius_pairmake(request, &request->config_items,
2508 "Post-Auth-Type", "Reject",
2510 if (vp) rad_postauth(request);
2513 * If configured, delay Access-Reject packets.
2515 * If request->root->reject_delay = 0, we discover
2516 * that we have to send the packet now.
2518 when = request->received;
2519 when.tv_sec += request->root->reject_delay;
2521 if (timercmp(&when, &request->next_when, >)) {
2522 RDEBUG2("Delaying reject of request %u for %d seconds",
2524 request->root->reject_delay);
2525 request->next_when = when;
2526 request->next_callback = reject_delay;
2527 #ifdef HAVE_PTHREAD_H
2528 request->thread_id = NO_CHILD_THREAD;
2530 request->child_state = REQUEST_REJECT_DELAY;
2538 case PW_COA_REQUEST:
2539 case PW_DISCONNECT_REQUEST:
2541 request->next_when.tv_sec += request->root->cleanup_delay;
2542 request->next_callback = cleanup_delay;
2543 child_state = REQUEST_CLEANUP_DELAY;
2546 case PW_ACCOUNTING_REQUEST:
2547 request->next_callback = NULL; /* just to be safe */
2548 child_state = REQUEST_DONE;
2552 * FIXME: Status-Server should probably not be
2555 case PW_STATUS_SERVER:
2556 request->next_callback = NULL;
2557 child_state = REQUEST_DONE;
2564 request->next_callback = NULL;
2565 child_state = REQUEST_DONE;
2570 * Suppress "no reply" packets here, unless we're reading
2571 * from the "detail" file. In that case, we've got to
2572 * tell the detail file handler that the request is dead,
2573 * and it should re-send it.
2574 * If configured, encode, sign, and send.
2576 if ((request->reply->code != 0) ||
2577 (request->listener->type == RAD_LISTEN_DETAIL)) {
2578 DEBUG_PACKET(request, request->reply, 1);
2579 request->listener->send(request->listener, request);
2584 * Now that we've completely processed the request,
2585 * see if we need to originate a CoA request. But ONLY
2586 * if it wasn't proxied.
2588 if (!request->proxy &&
2589 (request->packet->code != PW_COA_REQUEST) &&
2590 (request->packet->code != PW_DISCONNECT_REQUEST) &&
2592 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL))) {
2593 if (!originated_coa_request(request)) {
2594 RDEBUG2("Do CoA Fail handler here");
2596 /* request->coa is stil set, so we can update events */
2602 * Clean up. These are no longer needed.
2604 pairfree(&request->config_items);
2606 pairfree(&request->packet->vps);
2607 request->username = NULL;
2608 request->password = NULL;
2610 pairfree(&request->reply->vps);
2613 if (request->proxy) {
2614 pairfree(&request->proxy->vps);
2616 if (request->proxy_reply) {
2617 pairfree(&request->proxy_reply->vps);
2622 * We're not tracking responses from the home
2623 * server, we can therefore free this memory in
2626 if (!request->in_proxy_hash) {
2627 rad_free(&request->proxy);
2628 rad_free(&request->proxy_reply);
2629 request->home_server = NULL;
2635 RDEBUG2("Finished request %u.", request->number);
2636 rad_assert(child_state >= 0);
2638 if (have_children) {
2639 #ifdef HAVE_PTHREAD_H
2640 request->thread_id = NO_CHILD_THREAD;
2642 request->child_state = child_state;
2644 request->child_state = child_state;
2647 * Single threaded mode: update timers now.
2649 wait_a_bit(request);
2654 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2660 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2661 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2663 switch (request->child_state) {
2664 case REQUEST_QUEUED:
2665 case REQUEST_RUNNING:
2666 radlog(L_ERR, "Discarding duplicate request from "
2667 "client %s port %d - ID: %u due to unfinished request %u in component %s module %s.",
2669 request->packet->src_port,request->packet->id,
2670 request->number, request->component, request->module);
2674 case REQUEST_PROXIED:
2676 * We're not supposed to have duplicate
2677 * accounting packets. The other states handle
2678 * duplicates fine (discard, or send duplicate
2679 * reply). But we do NOT want to retransmit an
2680 * accounting request here, because that would
2681 * involve updating the Acct-Delay-Time, and
2682 * therefore changing the packet Id, etc.
2684 * Instead, we just discard the packet. We may
2685 * eventually respond, or the client will send a
2686 * new accounting packet.
2688 * The same comments go for Status-Server, and
2689 * other packet types.
2691 * FIXME: coa: when we proxy CoA && Disconnect
2692 * packets, this logic has to be fixed.
2694 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2695 radlog(L_ERR, "Discarding duplicate request from "
2696 "client %s port %d - ID: %u due to unfinished proxied request %u",
2698 request->packet->src_port,request->packet->id,
2703 check_for_zombie_home_server(request);
2706 * If we've just discovered that the home server is
2707 * dead, send the packet to another one.
2709 if ((request->packet->dst_port != 0) &&
2710 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2713 remove_from_proxy_hash(request);
2715 home = home_server_ldb(NULL, request->home_pool, request);
2717 RDEBUG2("ERROR: Failed to find live home server for request %u", request->number);
2720 * Do post-request processing,
2721 * and any insertion of necessary
2724 post_proxy_fail_handler(request);
2728 request->proxy->code = request->packet->code;
2731 * Free the old packet, to force re-encoding
2733 free(request->proxy->data);
2734 request->proxy->data = NULL;
2735 request->proxy->data_len = 0;
2738 * This request failed over to a virtual
2739 * server. Push it back onto the queue
2742 if (request->home_server->server) {
2743 proxy_fallback_handler(request);
2748 * Try to proxy the request.
2750 if (!proxy_request(request)) {
2751 RDEBUG("ERROR: Failed to re-proxy request %u", request->number);
2752 goto no_home_servers;
2756 * This code executes in the main server
2757 * thread, so there's no need for locking.
2759 rad_assert(request->next_callback != NULL);
2760 INSERT_EVENT(request->next_callback, request);
2761 request->next_callback = NULL;
2763 } /* else the home server is still alive */
2765 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2766 inet_ntop(request->proxy->dst_ipaddr.af,
2767 &request->proxy->dst_ipaddr.ipaddr,
2768 buffer, sizeof(buffer)),
2769 request->proxy->dst_port,
2770 request->proxy->id);
2771 request->num_proxied_requests++;
2773 DEBUG_PACKET(request, request->proxy, 1);
2774 request->proxy_listener->send(request->proxy_listener,
2779 case REQUEST_REJECT_DELAY:
2780 RDEBUG2("Waiting to send Access-Reject "
2781 "to client %s port %d - ID: %d",
2783 request->packet->src_port, request->packet->id);
2786 case REQUEST_CLEANUP_DELAY:
2788 if (request->reply->code == 0) {
2789 RDEBUG2("Ignoring retransmit from client %s port %d "
2790 "- ID: %d, no reply was configured",
2792 request->packet->src_port, request->packet->id);
2797 * FIXME: This sends duplicate replies to
2798 * accounting requests, even if Acct-Delay-Time
2799 * or Event-Timestamp is in the packet. In those
2800 * cases, the Id should be changed, and the packet
2803 RDEBUG2("Sending duplicate reply "
2804 "to client %s port %d - ID: %d",
2806 request->packet->src_port, request->packet->id);
2807 DEBUG_PACKET(request, request->reply, 1);
2808 request->listener->send(request->listener, request);
2814 static void received_conflicting_request(REQUEST *request,
2815 const RADCLIENT *client)
2817 radlog(L_ERR, "Received conflicting packet from "
2818 "client %s port %d - ID: %d due to unfinished request %u. Giving up on old request.",
2820 request->packet->src_port, request->packet->id,
2824 * Nuke it from the request hash, so we can receive new
2827 remove_from_request_hash(request);
2829 switch (request->child_state) {
2830 #ifdef HAVE_PTHREAD_H
2832 * It's queued or running. Tell it to stop, and
2833 * wait for it to do so.
2835 case REQUEST_QUEUED:
2836 case REQUEST_RUNNING:
2837 request->master_state = REQUEST_STOP_PROCESSING;
2838 request->delay += request->delay >> 1;
2840 tv_add(&request->when, request->delay);
2842 INSERT_EVENT(wait_for_child_to_die, request);
2847 * Catch race conditions. It may have switched
2848 * from running to done while this code is being
2851 case REQUEST_REJECT_DELAY:
2852 case REQUEST_CLEANUP_DELAY:
2857 * It's in some other state, and therefore also
2858 * in the event queue. At some point, the
2859 * child will notice, and we can then delete it.
2861 case REQUEST_PROXIED:
2868 static int can_handle_new_request(RADIUS_PACKET *packet,
2870 struct main_config_t *root)
2873 * Count the total number of requests, to see if
2874 * there are too many. If so, return with an
2877 if (root->max_requests) {
2878 int request_count = fr_packet_list_num_elements(pl);
2881 * This is a new request. Let's see if
2882 * it makes us go over our configured
2885 if (request_count > root->max_requests) {
2886 radlog(L_ERR, "Dropping request (%d is too many): "
2887 "from client %s port %d - ID: %d", request_count,
2889 packet->src_port, packet->id);
2890 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2891 "\tThe value for 'max_requests' is probably set too low.\n");
2893 } /* else there were a small number of requests */
2894 } /* else there was no configured limit for requests */
2897 * FIXME: Add per-client checks. If one client is sending
2898 * too many packets, start discarding them.
2900 * We increment the counters here, and decrement them
2901 * when the response is sent... somewhere in this file.
2905 * FUTURE: Add checks for system load. If the system is
2906 * busy, start dropping requests...
2908 * We can probably keep some statistics ourselves... if
2909 * there are more requests coming in than we can handle,
2910 * start dropping some.
2917 int received_request(rad_listen_t *listener,
2918 RADIUS_PACKET *packet, REQUEST **prequest,
2921 RADIUS_PACKET **packet_p;
2922 REQUEST *request = NULL;
2923 struct main_config_t *root = &mainconfig;
2925 packet_p = fr_packet_list_find(pl, packet);
2927 request = fr_packet2myptr(REQUEST, packet, packet_p);
2928 rad_assert(request->in_request_hash);
2930 if ((request->packet->data_len == packet->data_len) &&
2931 (memcmp(request->packet->vector, packet->vector,
2932 sizeof(packet->vector)) == 0)) {
2933 received_retransmit(request, client);
2938 * The new request is different from the old one,
2939 * but maybe the old is finished. If so, delete
2942 switch (request->child_state) {
2943 struct timeval when;
2947 * Special hacks for race conditions.
2948 * The reply is encoded, and therefore
2949 * likely sent. We received a *new*
2950 * packet from the client, likely before
2951 * the next line or two of code which
2952 * updated the child state. In this
2953 * case, just accept the new request.
2955 if ((request->reply->code != 0) &&
2956 request->reply->data) {
2957 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %u.",
2959 packet->src_port, packet->id,
2961 remove_from_request_hash(request);
2966 gettimeofday(&when, NULL);
2970 * If the cached request was received
2971 * within the last second, then we
2972 * discard the NEW request instead of the
2973 * old one. This will happen ONLY when
2974 * the client is severely broken, and is
2975 * sending conflicting packets very
2978 if (timercmp(&when, &request->received, <)) {
2979 radlog(L_ERR, "Discarding conflicting packet from "
2980 "client %s port %d - ID: %d due to recent request %u.",
2982 packet->src_port, packet->id,
2987 received_conflicting_request(request, client);
2991 case REQUEST_REJECT_DELAY:
2992 case REQUEST_CLEANUP_DELAY:
2993 request->child_state = REQUEST_DONE;
2997 cleanup_delay(request);
3004 * We may want to quench the new request.
3006 if ((listener->type != RAD_LISTEN_DETAIL) &&
3007 !can_handle_new_request(packet, client, root)) {
3012 * Create and initialize the new request.
3014 request = request_alloc(); /* never fails */
3016 if ((request->reply = rad_alloc(0)) == NULL) {
3017 radlog(L_ERR, "No memory");
3021 request->listener = listener;
3022 request->client = client;
3023 request->packet = packet;
3024 request->packet->timestamp = request->timestamp;
3025 request->number = request_num_counter++;
3026 request->priority = listener->type;
3027 #ifdef HAVE_PTHREAD_H
3028 request->thread_id = NO_CHILD_THREAD;
3032 * Status-Server packets go to the head of the queue.
3034 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
3037 * Set virtual server identity
3039 if (client->server) {
3040 request->server = client->server;
3041 } else if (listener->server) {
3042 request->server = listener->server;
3044 request->server = NULL;
3048 * Remember the request in the list.
3050 if (!fr_packet_list_insert(pl, &request->packet)) {
3051 radlog(L_ERR, "Failed to insert request %u in the list of live requests: discarding", request->number);
3052 ev_request_free(&request);
3056 request->in_request_hash = TRUE;
3057 request->root = root;
3061 * The request passes many of our sanity checks.
3062 * From here on in, if anything goes wrong, we
3063 * send a reject message, instead of dropping the
3068 * Build the reply template from the request.
3071 request->reply->sockfd = request->packet->sockfd;
3072 request->reply->dst_ipaddr = request->packet->src_ipaddr;
3073 request->reply->src_ipaddr = request->packet->dst_ipaddr;
3074 request->reply->dst_port = request->packet->src_port;
3075 request->reply->src_port = request->packet->dst_port;
3076 request->reply->id = request->packet->id;
3077 request->reply->code = 0; /* UNKNOWN code */
3078 memcpy(request->reply->vector, request->packet->vector,
3079 sizeof(request->reply->vector));
3080 request->reply->vps = NULL;
3081 request->reply->data = NULL;
3082 request->reply->data_len = 0;
3084 request->master_state = REQUEST_ACTIVE;
3085 request->child_state = REQUEST_QUEUED;
3086 request->next_callback = NULL;
3088 gettimeofday(&request->received, NULL);
3089 request->timestamp = request->received.tv_sec;
3090 request->when = request->received;
3092 request->delay = USEC;
3094 tv_add(&request->when, request->delay);
3096 INSERT_EVENT(wait_a_bit, request);
3098 *prequest = request;
3104 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
3111 * Also removes from the proxy hash if responses == requests
3113 request = lookup_in_proxy_hash(packet);
3116 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
3117 inet_ntop(packet->src_ipaddr.af,
3118 &packet->src_ipaddr.ipaddr,
3119 buffer, sizeof(buffer)),
3120 packet->src_port, packet->id);
3125 * We haven't replied to the NAS, but we have seen an
3126 * earlier reply from the home server. Ignore this packet,
3127 * as we're likely still processing the previous reply.
3129 if (request->proxy_reply) {
3130 if (memcmp(request->proxy_reply->vector,
3132 sizeof(request->proxy_reply->vector)) == 0) {
3133 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %u",
3134 inet_ntop(packet->src_ipaddr.af,
3135 &packet->src_ipaddr.ipaddr,
3136 buffer, sizeof(buffer)),
3137 packet->src_port, packet->id,
3141 * ? The home server gave us a new proxy
3142 * reply which doesn't match the old
3145 RDEBUG2("Ignoring conflicting proxy reply");
3148 /* assert that there's an event queued for request? */
3153 * Verify the packet before doing ANYTHING with it. This
3154 * means we're doing more MD5 checks in the server core.
3155 * However, we can fix that by moving to multiple threads
3156 * listening on sockets.
3158 * We do this AFTER looking the request up in the hash,
3159 * and AFTER vhecking if we saw a previous request. This
3160 * helps minimize the DoS effect of people attacking us
3161 * with spoofed packets.
3163 if (rad_verify(packet, request->proxy,
3164 request->home_server->secret) != 0) {
3165 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3169 gettimeofday(&now, NULL);
3172 * "ping" packets have a different algorithm for marking
3173 * a home server alive. They also skip all of the CoA,
3176 if (!request->packet) {
3177 request->proxy_reply = packet;
3178 received_response_to_ping(request);
3179 request->proxy_reply = NULL; /* caller will free it */
3180 ev_request_free(&request);
3185 * Maybe move this earlier in the decision process?
3186 * Having it here means that late or duplicate proxy
3187 * replies no longer get the home server marked as
3188 * "alive". This might be good for stability, though.
3190 * FIXME: Do we really want to do this whenever we
3191 * receive a packet? Setting this here means that we
3192 * mark it alive on *any* packet, even if it's lost all
3193 * of the *other* packets in the last 10s.
3195 * This behavior could be configurable.
3197 request->home_server->state = HOME_STATE_ALIVE;
3198 request->home_server->last_packet = now.tv_sec;
3202 * When originating CoA, the "proxy" reply is the reply
3203 * to the CoA request that we originated. At this point,
3204 * the original request is finished, and it has a reply.
3206 * However, if we haven't separated the two requests, do
3207 * so now. This is done so that cleaning up the original
3208 * request won't cause the CoA request to be free'd. See
3209 * util.c, request_free()
3211 if (request->parent && (request->parent->coa == request)) {
3212 request->parent->coa = NULL;
3213 request->parent = NULL;
3216 * The proxied packet was different from the
3217 * original packet, AND the proxied packet was
3220 } else if ((request->packet->code != request->proxy->code) &&
3221 ((request->proxy->code == PW_COA_REQUEST) ||
3222 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
3224 * It's already divorced: do nothing.
3229 * Skip the next set of checks, as the original
3230 * reply is cached. We want to be able to still
3231 * process the CoA reply, AND to reference the
3232 * original request/reply.
3234 * This is getting to be really quite a bit of a
3240 * If there's a reply to the NAS, ignore everything
3241 * related to proxy responses
3243 if (request->reply && request->reply->code != 0) {
3244 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3250 * The average includes our time to receive packets and
3251 * look them up in the hashes, which should be the same
3254 * We update the response time only for the FIRST packet
3257 if (request->home_server->ema.window > 0) {
3258 radius_stats_ema(&request->home_server->ema,
3259 &now, &request->proxy_when);
3263 switch (request->child_state) {
3264 case REQUEST_QUEUED:
3265 case REQUEST_RUNNING:
3266 case REQUEST_REJECT_DELAY:
3267 case REQUEST_CLEANUP_DELAY:
3269 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'",
3270 inet_ntop(packet->src_ipaddr.af,
3271 &packet->src_ipaddr.ipaddr,
3272 buffer, sizeof(buffer)),
3273 packet->src_port, packet->id,
3275 /* assert that there's an event queued for request? */
3278 case REQUEST_PROXIED:
3282 request->proxy_reply = packet;
3286 * Perform RTT calculations, as per RFC 2988 (for TCP).
3287 * Note that we only do so on the first response.
3289 if ((request->num_proxied_responses == 1)
3291 home_server *home = request->home_server;
3293 rtt = now.tv_sec - request->proxy_when.tv_sec;
3296 rtt -= request->proxy_when.tv_usec;
3298 if (!home->has_rtt) {
3299 home->has_rtt = TRUE;
3302 home->rttvar = rtt / 2;
3305 home->rttvar -= home->rttvar >> 2;
3306 home->rttvar += (home->srtt - rtt);
3307 home->srtt -= home->srtt >> 3;
3308 home->srtt += rtt >> 3;
3311 home->rto = home->srtt;
3312 if (home->rttvar > (USEC / 4)) {
3313 home->rto += home->rttvar * 4;
3320 request->child_state = REQUEST_QUEUED;
3321 request->when = now;
3322 request->delay = USEC;
3323 request->priority = RAD_LISTEN_PROXY;
3324 tv_add(&request->when, request->delay);
3327 * Wait a bit will take care of max_request_time
3329 INSERT_EVENT(wait_a_bit, request);
3335 void event_new_fd(rad_listen_t *this)
3339 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3341 this->print(this, buffer, sizeof(buffer));
3343 if (this->status == RAD_LISTEN_STATUS_INIT) {
3345 DEBUG("Listening on %s", buffer);
3347 radlog(L_INFO, " ... adding new socket %s", buffer);
3349 if (!fr_event_fd_insert(el, 0, this->fd,
3350 event_socket_handler, this)) {
3351 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3355 this->status = RAD_LISTEN_STATUS_KNOWN;
3359 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3360 DEBUG(" ... closing socket %s", buffer);
3362 fr_event_fd_delete(el, 0, this->fd);
3363 this->status = RAD_LISTEN_STATUS_FINISH;
3366 * Close the fd AFTER fixing up the requests and
3367 * listeners, so that they don't send/recv on the
3368 * wrong socket (if someone manages to open
3376 static void handle_signal_self(int flag)
3378 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3379 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3380 radlog(L_INFO, "Signalled to exit");
3381 fr_event_loop_exit(el, 1);
3383 radlog(L_INFO, "Signalled to terminate");
3384 fr_event_loop_exit(el, 2);
3388 } /* else exit/term flags weren't set */
3391 * Tell the even loop to stop processing.
3393 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3395 static time_t last_hup = 0;
3398 if ((int) (when - last_hup) < 5) {
3399 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3403 radlog(L_INFO, "Received HUP signal.");
3407 fr_event_loop_exit(el, 0x80);
3411 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3415 * FIXME: O(N) loops suck.
3417 for (this = mainconfig.listen;
3419 this = this->next) {
3420 if (this->type != RAD_LISTEN_DETAIL) continue;
3423 * This one didn't send the signal, skip
3426 if (!this->decode(this, NULL)) continue;
3429 * Go service the interrupt.
3431 event_poll_detail(this);
3436 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3439 for (this = mainconfig.listen;
3441 this = this->next) {
3447 #ifndef WITH_SELF_PIPE
3448 void radius_signal_self(int flag)
3450 handle_signal_self(flag);
3454 * Inform ourselves that we received a signal.
3456 void radius_signal_self(int flag)
3462 * The read MUST be non-blocking for this to work.
3464 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3468 for (i = 0; i < rcode; i++) {
3469 buffer[0] |= buffer[i];
3477 write(self_pipe[1], buffer, 1);
3481 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3482 UNUSED int fd, UNUSED void *ctx)
3487 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3488 if (rcode <= 0) return;
3491 * Merge pending signals.
3493 for (i = 0; i < rcode; i++) {
3494 buffer[0] |= buffer[i];
3497 handle_signal_self(buffer[0]);
3502 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3505 rad_listen_t *listener = ctx;
3506 RAD_REQUEST_FUNP fun;
3509 rad_assert(xel == el);
3513 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3515 if (!listener->recv(listener, &fun, &request)) return;
3517 if (!thread_pool_addrequest(request, fun)) {
3518 request->child_state = REQUEST_DONE;
3524 * This function is called periodically to see if this detail
3525 * file is available for reading.
3527 static void event_poll_detail(void *ctx)
3530 RAD_REQUEST_FUNP fun;
3532 rad_listen_t *this = ctx;
3533 struct timeval now, when;
3534 listen_detail_t *detail = this->data;
3536 rad_assert(this->type == RAD_LISTEN_DETAIL);
3539 * Try to read something.
3541 * FIXME: This does poll AND receive.
3543 rcode = this->recv(this, &fun, &request);
3545 rad_assert(fun != NULL);
3546 rad_assert(request != NULL);
3548 if (!thread_pool_addrequest(request, fun)) {
3549 request->child_state = REQUEST_DONE;
3553 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3557 * Backdoor API to get the delay until the next poll
3560 delay = this->encode(this, NULL);
3561 tv_add(&when, delay);
3563 if (!fr_event_insert(el, event_poll_detail, this,
3564 &when, &detail->ev)) {
3565 radlog(L_ERR, "Failed creating handler");
3571 static void event_status(struct timeval *wake)
3573 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3577 if (debug_flag == 0) {
3579 radlog(L_INFO, "Ready to process requests.");
3580 just_started = FALSE;
3586 radlog(L_INFO, "Ready to process requests.");
3588 } else if ((wake->tv_sec != 0) ||
3589 (wake->tv_usec >= 100000)) {
3590 DEBUG("Waking up in %d.%01u seconds.",
3591 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3596 * FIXME: Put this somewhere else, where it isn't called
3597 * all of the time...
3600 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3602 * If there are no child threads, then there may
3603 * be child processes. In that case, wait for
3604 * their exit status, and throw that exit status
3605 * away. This helps get rid of zxombie children.
3607 while (waitpid(-1, &argval, WNOHANG) > 0) {
3615 * Externally-visibly functions.
3617 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3619 rad_listen_t *this, *head = NULL;
3623 time(&fr_start_time);
3625 el = fr_event_list_create(event_status);
3628 pl = fr_packet_list_create(0);
3629 if (!pl) return 0; /* leak el */
3631 request_num_counter = 0;
3634 if (mainconfig.proxy_requests) {
3636 * Create the tree for managing proxied requests and
3639 proxy_list = fr_packet_list_create(1);
3640 if (!proxy_list) return 0;
3642 #ifdef HAVE_PTHREAD_H
3643 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3644 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3652 #ifdef HAVE_PTHREAD_H
3654 * Initialize the threads ONLY if we're spawning, AND
3655 * we're running normally.
3657 if (spawn_flag && !check_config &&
3658 (thread_pool_init(cs, &spawn_flag) < 0)) {
3664 * Move all of the thread calls to this file?
3666 * It may be best for the mutexes to be in this file...
3668 have_children = spawn_flag;
3671 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3673 if (listen_init(cs, &head) < 0) {
3680 #ifdef WITH_SELF_PIPE
3682 * Child threads need a pipe to signal us, as do the
3685 if (pipe(self_pipe) < 0) {
3686 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3690 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
3691 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
3692 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3696 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
3697 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
3698 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3703 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3704 event_signal_handler, el)) {
3705 radlog(L_ERR, "Failed creating handler for signals");
3708 #endif /* WITH_SELF_PIPE */
3712 * Mark the proxy Fd's as unused.
3717 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3721 DEBUG("%s: #### Opening IP addresses and Ports ####",
3725 * The server temporarily switches to an unprivileged
3726 * user very early in the bootstrapping process.
3727 * However, some sockets MAY require privileged access
3728 * (bind to device, or to port < 1024, or to raw
3729 * sockets). Those sockets need to call suid up/down
3730 * themselves around the functions that need a privileged
3733 if (listen_init(cs, &head) < 0) {
3738 * At this point, no one has any business *ever* going
3741 fr_suid_down_permanent();
3744 * Add all of the sockets to the event loop.
3748 this = this->next) {
3751 this->print(this, buffer, sizeof(buffer));
3753 switch (this->type) {
3755 case RAD_LISTEN_DETAIL:
3756 DEBUG("Listening on %s", buffer);
3759 * Detail files are always known, and aren't
3760 * put into the socket event loop.
3762 this->status = RAD_LISTEN_STATUS_KNOWN;
3765 * Set up the first poll interval.
3767 event_poll_detail(this);
3772 case RAD_LISTEN_PROXY:
3773 if (proxy_add_fds(this) < 0) {
3774 radlog(L_ERR, "Failed creating new proxy socket");
3778 if (!fr_packet_list_socket_add(proxy_list,
3792 mainconfig.listen = head;
3798 static int request_hash_cb(UNUSED void *ctx, void *data)
3800 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3803 rad_assert(request->in_proxy_hash == FALSE);
3806 ev_request_free(&request);
3813 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3815 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3817 ev_request_free(&request);
3823 void radius_event_free(void)
3826 * Stop and join all threads.
3828 #ifdef HAVE_PTHREAD_H
3834 * There are requests in the proxy hash that aren't
3835 * referenced from anywhere else. Remove them first.
3838 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3839 fr_packet_list_free(proxy_list);
3844 fr_packet_list_walk(pl, NULL, request_hash_cb);
3846 fr_packet_list_free(pl);
3849 fr_event_list_free(el);
3852 int radius_event_process(void)
3856 return fr_event_loop(el);
3859 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3861 request->options = RAD_REQUEST_OPTION_DEBUG2;
3863 if (request_pre_handler(request)) {
3864 rad_assert(fun != NULL);
3865 rad_assert(request != NULL);
3867 if (request->server) RDEBUG("server %s {",
3868 request->server != NULL ?
3869 request->server : "");
3872 if (request->server) RDEBUG("} # server %s",
3873 request->server != NULL ?
3874 request->server : "");
3876 request_post_handler(request);
3879 DEBUG2("Going to the next request");