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 void force_log_reopen(void);
47 extern char *debug_condition;
50 * Ridiculous amounts of local state.
52 static fr_event_list_t *el = NULL;
53 static fr_packet_list_t *pl = NULL;
54 static int request_num_counter = 0;
55 static struct timeval now;
57 static int have_children;
58 static int just_started = TRUE;
62 #define WITH_SELF_PIPE (1)
67 static int self_pipe[2];
72 static pthread_mutex_t proxy_mutex;
75 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
76 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
78 static pthread_t NO_SUCH_CHILD_PID;
81 * This is easier than ifdef's throughout the code.
83 #define PTHREAD_MUTEX_LOCK(_x)
84 #define PTHREAD_MUTEX_UNLOCK(_x)
85 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
87 radius_handle_request(request, fun);
92 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
95 static fr_packet_list_t *proxy_list = NULL;
98 * We keep the proxy FD's here. The RADIUS Id's are marked
99 * "allocated" per Id, via a bit per proxy FD.
101 static int proxy_all_used = FALSE;
102 static int proxy_fds[32];
103 static rad_listen_t *proxy_listeners[32];
104 static void check_for_zombie_home_server(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);
152 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
154 RADIUS_PACKET **proxy_p;
157 PTHREAD_MUTEX_LOCK(&proxy_mutex);
158 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
161 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
165 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
168 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
172 request->num_proxied_responses++;
175 * Catch the most common case of everything working
178 if (request->num_proxied_requests == request->num_proxied_responses) {
179 fr_packet_list_yank(proxy_list, request->proxy);
180 fr_packet_list_id_free(proxy_list, request->proxy);
181 request->in_proxy_hash = FALSE;
185 * On the FIRST reply, decrement the count of outstanding
186 * requests. Note that this is NOT the count of sent
187 * packets, but whether or not the home server has
190 if (!request->proxy_reply &&
191 request->home_server &&
192 request->home_server->currently_outstanding) {
193 request->home_server->currently_outstanding--;
196 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
202 static void remove_from_proxy_hash(REQUEST *request)
205 * Check this without grabbing the mutex because it's a
206 * lot faster that way.
208 if (!request->in_proxy_hash) return;
211 * The "not in hash" flag is definitive. However, if the
212 * flag says that it IS in the hash, there might still be
213 * a race condition where it isn't.
215 PTHREAD_MUTEX_LOCK(&proxy_mutex);
217 if (!request->in_proxy_hash) {
218 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
222 fr_packet_list_yank(proxy_list, request->proxy);
223 fr_packet_list_id_free(proxy_list, request->proxy);
226 * The home server hasn't replied, but we've given up on
227 * this request. Don't count this request against the
230 if (!request->proxy_reply &&
231 request->home_server &&
232 request->home_server->currently_outstanding) {
233 request->home_server->currently_outstanding--;
237 * Got from YES in hash, to NO, not in hash while we hold
238 * the mutex. This guarantees that when another thread
239 * grans the mutex, the "not in hash" flag is correct.
241 request->in_proxy_hash = FALSE;
243 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
246 static void ev_request_free(REQUEST **prequest)
250 if (!prequest || !*prequest) return;
257 * Divorce the child from the parent first,
258 * then clean up the child.
260 request->coa->parent = NULL;
261 ev_request_free(&request->coa);
265 * Divorce the parent from the child, and leave the
266 * parent still alive.
268 if (request->parent && (request->parent->coa == request)) {
269 request->parent->coa = NULL;
273 if (request->ev) fr_event_delete(el, &request->ev);
274 if (request->in_proxy_hash) remove_from_proxy_hash(request);
275 if (request->in_request_hash) remove_from_request_hash(request);
277 request_free(prequest);
280 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
283 rad_listen_t *proxy_listener;
285 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
287 if (proxy_all_used) return 0;
290 * Allocate a new proxy fd. This function adds
291 * it to the tail of the list of listeners. With
292 * some care, this can be thread-safe.
294 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
295 if (!proxy_listener) {
296 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
304 proxy = proxy_listener->fd;
305 for (i = 0; i < 32; i++) {
307 * Found a free entry. Save the socket,
308 * and remember where we saved it.
310 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
311 found = (proxy + i) & 0x1f;
312 proxy_fds[found] = proxy;
313 proxy_listeners[found] = proxy_listener;
318 proxy_all_used = TRUE;
319 listen_free(&proxy_listener);
320 radlog(L_ERR, "Failed creating new proxy socket: server is too busy and home servers appear to be down");
325 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
326 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
331 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
332 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
337 * Signal the main thread to add the new FD to the list
340 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
345 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
350 rad_assert(request->proxy != NULL);
351 rad_assert(proxy_list != NULL);
353 PTHREAD_MUTEX_LOCK(&proxy_mutex);
356 * Keep track of maximum outstanding requests to a
357 * particular home server. 'max_outstanding' is
358 * enforced in home_server_ldb(), in realms.c.
360 if (request->home_server) {
361 request->home_server->currently_outstanding++;
365 RADIUS_PACKET packet;
367 packet = *request->proxy;
369 if (!proxy_id_alloc(request, &packet)) {
370 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
375 * Yank the request, free the old Id, and
376 * remember the new Id.
378 fr_packet_list_yank(proxy_list, request->proxy);
379 fr_packet_list_id_free(proxy_list, request->proxy);
380 *request->proxy = packet;
382 } else if (!proxy_id_alloc(request, request->proxy)) {
383 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
387 rad_assert(request->proxy->sockfd >= 0);
390 * FIXME: Hack until we get rid of rad_listen_t, and put
391 * the information into the packet_list.
394 for (i = 0; i < 32; i++) {
395 if (proxy_fds[i] == request->proxy->sockfd) {
402 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
403 RDEBUG2("ERROR: All sockets are full.");
407 rad_assert(proxy_fds[proxy] != -1);
408 rad_assert(proxy_listeners[proxy] != NULL);
409 request->proxy_listener = proxy_listeners[proxy];
411 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
412 fr_packet_list_id_free(proxy_list, request->proxy);
413 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
414 RDEBUG2("ERROR: Failed to insert entry into proxy list");
418 request->in_proxy_hash = TRUE;
420 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
422 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
423 inet_ntop(request->proxy->dst_ipaddr.af,
424 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
425 request->proxy->dst_port,
433 * Called as BOTH an event, and in-line from other functions.
435 static void wait_for_proxy_id_to_expire(void *ctx)
437 REQUEST *request = ctx;
439 rad_assert(request->magic == REQUEST_MAGIC);
440 rad_assert(request->proxy != NULL);
442 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
443 request->when = request->proxy_when;
446 if (((request->proxy->code == PW_COA_REQUEST) ||
447 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
448 (request->packet->code != request->proxy->code)) {
449 request->when.tv_sec += request->home_server->coa_mrd;
452 request->when.tv_sec += request->home_server->response_window;
454 if ((request->num_proxied_requests == request->num_proxied_responses) ||
455 timercmp(&now, &request->when, >)) {
456 if (request->packet) {
457 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
458 request->number, request->packet->id,
459 (unsigned int) (request->timestamp - fr_start_time));
461 RDEBUG2("Cleaning up request %d with timestamp +%d",
463 (unsigned int) (request->timestamp - fr_start_time));
466 ev_request_free(&request);
470 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
474 #ifdef HAVE_PTHREAD_H
475 static void wait_for_child_to_die(void *ctx)
477 REQUEST *request = ctx;
479 rad_assert(request->magic == REQUEST_MAGIC);
482 * If it's still queued (waiting for a thread to pick it
483 * up) OR, it's running AND there's still a child thread
484 * handling it, THEN delay some more.
486 if ((request->child_state == REQUEST_QUEUED) ||
487 ((request->child_state == REQUEST_RUNNING) &&
488 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0))) {
491 * Cap delay at five minutes.
493 if (request->delay < (USEC * 60 * 5)) {
494 request->delay += (request->delay >> 1);
495 radlog(L_INFO, "WARNING: Child is hung for request %d.",
498 RDEBUG2("Child is still stuck for request %d",
501 tv_add(&request->when, request->delay);
503 INSERT_EVENT(wait_for_child_to_die, request);
507 RDEBUG2("Child is finally responsive for request %d", request->number);
508 remove_from_request_hash(request);
511 if (request->proxy) {
512 wait_for_proxy_id_to_expire(request);
517 ev_request_free(&request);
521 static void cleanup_delay(void *ctx)
523 REQUEST *request = ctx;
525 rad_assert(request->magic == REQUEST_MAGIC);
526 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
527 (request->child_state == REQUEST_DONE));
529 remove_from_request_hash(request);
532 if (request->proxy && request->in_proxy_hash) {
533 wait_for_proxy_id_to_expire(request);
538 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
539 request->number, request->packet->id,
540 (unsigned int) (request->timestamp - fr_start_time));
542 ev_request_free(&request);
547 * In daemon mode, AND this request has debug flags set.
549 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
551 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
555 const char *received, *from;
556 const fr_ipaddr_t *ip;
561 rad_assert(request->radlog != NULL);
563 if (direction == 0) {
564 received = "Received";
565 from = "from"; /* what else? */
566 ip = &packet->src_ipaddr;
567 port = packet->src_port;
570 received = "Sending";
571 from = "to"; /* hah! */
572 ip = &packet->dst_ipaddr;
573 port = packet->dst_port;
577 * Client-specific debugging re-prints the input
578 * packet into the client log.
580 * This really belongs in a utility library
582 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
583 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
584 received, fr_packet_codes[packet->code], from,
585 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
586 port, packet->id, packet->data_len);
588 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
590 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
592 packet->code, packet->id, packet->data_len);
595 for (vp = packet->vps; vp != NULL; vp = vp->next) {
596 vp_prints(buffer, sizeof(buffer), vp);
597 request->radlog(L_DBG, 0, request, "\t%s", buffer);
601 static void reject_delay(void *ctx)
603 REQUEST *request = ctx;
605 rad_assert(request->magic == REQUEST_MAGIC);
606 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
608 RDEBUG2("Sending delayed reject for request %d", request->number);
610 DEBUG_PACKET(request, request->reply, 1);
612 request->listener->send(request->listener, request);
614 request->when.tv_sec += request->root->cleanup_delay;
615 request->child_state = REQUEST_CLEANUP_DELAY;
617 INSERT_EVENT(cleanup_delay, request);
622 void revive_home_server(void *ctx)
624 home_server *home = ctx;
627 home->state = HOME_STATE_ALIVE;
628 home->currently_outstanding = 0;
629 home->revive_time = now;
632 * Delete any outstanding events.
634 if (home->ev) fr_event_delete(el, &home->ev);
636 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
637 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
638 buffer, sizeof(buffer)),
644 static void no_response_to_ping(void *ctx)
646 REQUEST *request = ctx;
650 rad_assert(request->home_server != NULL);
652 home = request->home_server;
653 home->num_received_pings = 0;
655 radlog(L_ERR, "No response to status check %d for home server %s port %d",
657 inet_ntop(request->proxy->dst_ipaddr.af,
658 &request->proxy->dst_ipaddr.ipaddr,
659 buffer, sizeof(buffer)),
660 request->proxy->dst_port);
662 check_for_zombie_home_server(request);
664 wait_for_proxy_id_to_expire(request);
668 static void received_response_to_ping(REQUEST *request)
673 rad_assert(request->home_server != NULL);
675 home = request->home_server;
676 home->num_received_pings++;
678 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
679 request->number, home->num_received_pings);
682 * Remove the request from any hashes
684 fr_event_delete(el, &request->ev);
685 remove_from_proxy_hash(request);
686 rad_assert(request->in_request_hash == FALSE);
689 * The control socket may have marked the home server as
690 * alive. OR, it may have suddenly started responding to
691 * requests again. If so, don't re-do the "make alive"
694 if (home->state == HOME_STATE_ALIVE) return;
697 * We haven't received enough ping responses to mark it
698 * "alive". Wait a bit.
700 if (home->num_received_pings < home->num_pings_to_alive) {
704 home->state = HOME_STATE_ALIVE;
705 home->currently_outstanding = 0;
706 home->revive_time = now;
708 if (!fr_event_delete(el, &home->ev)) {
709 RDEBUG2("Hmm... no event for home server. Oh well.");
712 radlog(L_PROXY, "Marking home server %s port %d alive",
713 inet_ntop(request->proxy->dst_ipaddr.af,
714 &request->proxy->dst_ipaddr.ipaddr,
715 buffer, sizeof(buffer)),
716 request->proxy->dst_port);
721 * Called from start of zombie period, OR after control socket
722 * marks the home server dead.
724 static void ping_home_server(void *ctx)
727 home_server *home = ctx;
731 if ((home->state == HOME_STATE_ALIVE) ||
732 (home->ping_check == HOME_PING_CHECK_NONE) ||
733 (home->ev != NULL)) {
737 request = request_alloc();
738 request->number = request_num_counter++;
740 request->proxy = rad_alloc(1);
741 rad_assert(request->proxy != NULL);
743 fr_event_now(el, &request->when);
744 home->when = request->when;
746 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
747 request->proxy->code = PW_STATUS_SERVER;
749 radius_pairmake(request, &request->proxy->vps,
750 "Message-Authenticator", "0x00", T_OP_SET);
752 } else if (home->type == HOME_TYPE_AUTH) {
753 request->proxy->code = PW_AUTHENTICATION_REQUEST;
755 radius_pairmake(request, &request->proxy->vps,
756 "User-Name", home->ping_user_name, T_OP_SET);
757 radius_pairmake(request, &request->proxy->vps,
758 "User-Password", home->ping_user_password, T_OP_SET);
759 radius_pairmake(request, &request->proxy->vps,
760 "Service-Type", "Authenticate-Only", T_OP_SET);
761 radius_pairmake(request, &request->proxy->vps,
762 "Message-Authenticator", "0x00", T_OP_SET);
765 #ifdef WITH_ACCOUNTING
766 request->proxy->code = PW_ACCOUNTING_REQUEST;
768 radius_pairmake(request, &request->proxy->vps,
769 "User-Name", home->ping_user_name, T_OP_SET);
770 radius_pairmake(request, &request->proxy->vps,
771 "Acct-Status-Type", "Stop", T_OP_SET);
772 radius_pairmake(request, &request->proxy->vps,
773 "Acct-Session-Id", "00000000", T_OP_SET);
774 vp = radius_pairmake(request, &request->proxy->vps,
775 "Event-Timestamp", "0", T_OP_SET);
776 vp->vp_date = now.tv_sec;
778 rad_assert("Internal sanity check failed");
782 radius_pairmake(request, &request->proxy->vps,
783 "NAS-Identifier", "Status Check. Are you alive?",
786 request->proxy->dst_ipaddr = home->ipaddr;
787 request->proxy->dst_port = home->port;
788 request->home_server = home;
790 rad_assert(request->proxy_listener == NULL);
792 if (!insert_into_proxy_hash(request, FALSE)) {
793 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
795 ev_request_free(&request);
798 rad_assert(request->proxy_listener != NULL);
799 request->proxy_listener->send(request->proxy_listener,
802 request->next_callback = NULL;
803 request->child_state = REQUEST_PROXIED;
804 gettimeofday(&request->when, NULL);
805 home->when = request->when;
806 request->when.tv_sec += home->ping_timeout;;
808 INSERT_EVENT(no_response_to_ping, request);
811 * Add +/- 2s of jitter, as suggested in RFC 3539
812 * and in the Issues and Fixes draft.
814 home->when.tv_sec += home->ping_interval - 2;
817 jitter ^= (jitter >> 10);
818 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
820 tv_add(&home->when, jitter);
822 INSERT_EVENT(ping_home_server, home);
826 void mark_home_server_dead(home_server *home, struct timeval *when)
828 int previous_state = home->state;
831 radlog(L_PROXY, "Marking home server %s port %d as dead.",
832 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
833 buffer, sizeof(buffer)),
836 home->state = HOME_STATE_IS_DEAD;
837 home->num_received_pings = 0;
839 if (home->ping_check != HOME_PING_CHECK_NONE) {
841 * If the control socket marks us dead, start
842 * pinging. Otherwise, we already started
843 * pinging when it was marked "zombie".
845 if (previous_state == HOME_STATE_ALIVE) {
846 ping_home_server(home);
851 * Revive it after a fixed period of time. This
852 * is very, very, bad.
855 home->when.tv_sec += home->revive_interval;
857 INSERT_EVENT(revive_home_server, home);
861 static void check_for_zombie_home_server(REQUEST *request)
866 home = request->home_server;
868 if (home->state != HOME_STATE_ZOMBIE) return;
870 when = home->zombie_period_start;
871 when.tv_sec += home->zombie_period;
873 fr_event_now(el, &now);
874 if (timercmp(&now, &when, <)) {
878 mark_home_server_dead(home, &request->when);
881 static int proxy_to_virtual_server(REQUEST *request);
883 static int virtual_server_handler(UNUSED REQUEST *request)
885 proxy_to_virtual_server(request);
889 static void proxy_fallback_handler(REQUEST *request)
892 * A proper time is required for wait_a_bit.
894 request->delay = USEC / 10;
895 gettimeofday(&now, NULL);
896 request->next_when = now;
897 tv_add(&request->next_when, request->delay);
898 request->next_callback = wait_a_bit;
901 * Re-queue the request.
903 request->child_state = REQUEST_QUEUED;
905 rad_assert(request->proxy != NULL);
906 if (!thread_pool_addrequest(request, virtual_server_handler)) {
907 request->child_state = REQUEST_DONE;
910 #ifdef HAVE_PTHREAD_H
912 * MAY free the request if we're over max_request_time,
913 * AND we're not in threaded mode!
915 * Note that we call this ONLY if we're threaded, as
916 * if we're NOT threaded, request_post_handler() calls
917 * wait_a_bit(), which means that "request" may not
920 if (have_children) wait_a_bit(request);
925 static int setup_post_proxy_fail(REQUEST *request)
927 DICT_VALUE *dval = NULL;
930 request->child_state = REQUEST_RUNNING;
932 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
933 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
935 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
936 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
940 * See no_response_to_coa_request
942 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
943 request->packet->code &= 0xff; /* restore it */
945 if (request->proxy->code == PW_COA_REQUEST) {
946 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
948 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
949 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
959 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
962 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
966 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
967 if (!vp) vp = radius_paircreate(request, &request->config_items,
968 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
969 vp->vp_integer = dval->value;
971 rad_assert(request->proxy_reply == NULL);
977 static int null_handler(UNUSED REQUEST *request)
982 static void post_proxy_fail_handler(REQUEST *request)
985 * A proper time is required for wait_a_bit.
987 request->delay = USEC / 10;
988 gettimeofday(&now, NULL);
991 * Not set up to run Post-Proxy-Type = Fail.
993 * Mark the request as still running, and figure out what
996 if (!setup_post_proxy_fail(request)) {
997 request_post_handler(request);
1001 * Re-queue the request.
1003 request->child_state = REQUEST_QUEUED;
1006 * There is a post-proxy-type of fail. We run
1007 * the request through the pre/post proxy
1008 * handlers, just like it was a real proxied
1009 * request. However, we set the per-request
1010 * handler to NULL, as we don't want to do
1013 * Note that when we're not threaded, this will
1014 * process the request even if it's greater than
1015 * max_request_time. That's not fatal.
1017 request->priority = 0;
1018 rad_assert(request->proxy != NULL);
1019 thread_pool_addrequest(request, null_handler);
1023 * MAY free the request if we're over max_request_time,
1024 * AND we're not in threaded mode!
1026 * Note that we call this ONLY if we're threaded, as
1027 * if we're NOT threaded, request_post_handler() calls
1028 * wait_a_bit(), which means that "request" may not
1031 if (have_children) wait_a_bit(request);
1035 /* maybe check this against wait_for_proxy_id_to_expire? */
1036 static void no_response_to_proxied_request(void *ctx)
1038 REQUEST *request = ctx;
1042 rad_assert(request->magic == REQUEST_MAGIC);
1043 rad_assert(request->child_state == REQUEST_PROXIED);
1046 * If we've failed over to an internal home server,
1047 * replace the callback with the correct one. This
1048 * is due to locking issues with child threads...
1050 if (request->home_server->server) {
1051 wait_a_bit(request);
1055 check_for_zombie_home_server(request);
1057 home = request->home_server;
1060 * The default as of 2.1.7 is to allow requests to
1061 * fail-over to a backup home server when this one does
1062 * not respond. The old behavior can be configured as
1065 if (home->no_response_fail) {
1066 radlog(L_ERR, "Rejecting request %d (proxy Id %d) due to lack of any response from home server %s port %d",
1067 request->number, request->proxy->id,
1068 inet_ntop(request->proxy->dst_ipaddr.af,
1069 &request->proxy->dst_ipaddr.ipaddr,
1070 buffer, sizeof(buffer)),
1071 request->proxy->dst_port);
1073 post_proxy_fail_handler(request);
1075 rad_assert(request->ev == NULL);
1076 request->child_state = REQUEST_RUNNING;
1077 wait_a_bit(request);
1081 * Don't touch request due to race conditions
1083 if (home->state == HOME_STATE_IS_DEAD) {
1084 rad_assert(home->ev != NULL); /* or it will never wake up */
1089 * Enable the zombie period when we notice that the home
1090 * server hasn't responded. We do NOT back-date the start
1091 * of the zombie period.
1093 if (home->state == HOME_STATE_ALIVE) {
1094 home->state = HOME_STATE_ZOMBIE;
1095 home->zombie_period_start = now;
1097 radlog(L_PROXY, "Marking home server %s port %d as zombie (it looks like it is dead).",
1098 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1099 buffer, sizeof(buffer)),
1103 * Start pinging the home server.
1105 ping_home_server(home);
1110 static void wait_a_bit(void *ctx)
1112 struct timeval when;
1113 REQUEST *request = ctx;
1114 fr_event_callback_t callback = NULL;
1116 rad_assert(request->magic == REQUEST_MAGIC);
1120 * The CoA request is a new (internally generated)
1121 * request, created in a child thread. We therefore need
1122 * some way to tie its events back into the main event
1125 if (request->coa && !request->coa->proxy_reply &&
1126 request->coa->next_callback) {
1127 request->coa->when = request->coa->next_when;
1128 INSERT_EVENT(request->coa->next_callback, request->coa);
1129 request->coa->next_callback = NULL;
1130 request->coa->parent = NULL;
1131 request->coa = NULL;
1135 switch (request->child_state) {
1136 case REQUEST_QUEUED:
1137 case REQUEST_RUNNING:
1138 when = request->received;
1139 when.tv_sec += request->root->max_request_time;
1142 * Normally called from the event loop with the
1143 * proper event loop time. Otherwise, called from
1144 * post proxy fail handler, which sets "now", and
1145 * this call won't re-set it, because we're not
1146 * in the event loop.
1148 fr_event_now(el, &now);
1151 * Request still has more time. Continue
1154 if (timercmp(&now, &when, <) ||
1155 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1156 (request->child_state == REQUEST_QUEUED))) {
1157 if (request->delay < (USEC / 10)) {
1158 request->delay = USEC / 10;
1160 request->delay += request->delay >> 1;
1164 * Cap wait at some sane value for detail
1167 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1168 (request->delay > (request->root->max_request_time * USEC))) {
1169 request->delay = request->root->max_request_time * USEC;
1173 request->when = now;
1174 tv_add(&request->when, request->delay);
1175 callback = wait_a_bit;
1180 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1182 * A child thread MAY still be running on the
1183 * request. Ask the thread to stop working on
1186 if (have_children &&
1187 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
1188 request->master_state = REQUEST_STOP_PROCESSING;
1190 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1192 request->module ? request->module : "<server core>",
1193 request->component ? request->component : "<server core>");
1195 request->delay = USEC / 4;
1196 tv_add(&request->when, request->delay);
1197 callback = wait_for_child_to_die;
1203 * Else no child thread is processing the
1204 * request. We probably should have just marked
1205 * the request as 'done' elsewhere, like in the
1206 * post-proxy-fail handler. But doing that would
1207 * involve checking for max_request_time in
1208 * multiple places, so this may be simplest.
1210 request->child_state = REQUEST_DONE;
1214 * Mark the request as no longer running,
1218 #ifdef HAVE_PTHREAD_H
1219 request->child_pid = NO_SUCH_CHILD_PID;
1224 * This is a CoA request. It's been divorced
1225 * from everything else, so we clean it up now.
1227 if (!request->in_request_hash &&
1229 (request->packet->code != request->proxy->code) &&
1230 ((request->proxy->code == PW_COA_REQUEST) ||
1231 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1233 * FIXME: Do CoA MIBs
1235 ev_request_free(&request);
1239 request_stats_final(request);
1240 cleanup_delay(request);
1243 case REQUEST_REJECT_DELAY:
1244 case REQUEST_CLEANUP_DELAY:
1245 #ifdef HAVE_PTHREAD_H
1246 request->child_pid = NO_SUCH_CHILD_PID;
1248 request_stats_final(request);
1250 case REQUEST_PROXIED:
1251 rad_assert(request->next_callback != NULL);
1252 rad_assert(request->next_callback != wait_a_bit);
1254 request->when = request->next_when;
1255 callback = request->next_callback;
1256 request->next_callback = NULL;
1260 rad_panic("Internal sanity check failure");
1265 * Something major went wrong. Discard the request, and
1268 * FIXME: No idea why this happens or how to fix it...
1269 * It seems to happen *only* when requests are proxied,
1270 * and where the home server doesn't respond. So it looks
1271 * like a race condition above, but it happens in debug
1272 * mode, with no threads...
1275 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1276 ev_request_free(&request);
1280 INSERT_EVENT(callback, request);
1284 static void no_response_to_coa_request(void *ctx)
1286 REQUEST *request = ctx;
1289 rad_assert(request->magic == REQUEST_MAGIC);
1290 rad_assert(request->child_state == REQUEST_PROXIED);
1291 rad_assert(request->home_server != NULL);
1292 rad_assert(!request->in_request_hash);
1294 radlog(L_ERR, "No response to CoA request sent to %s",
1295 inet_ntop(request->proxy->dst_ipaddr.af,
1296 &request->proxy->dst_ipaddr.ipaddr,
1297 buffer, sizeof(buffer)));
1302 request->packet->code |= (PW_COA_REQUEST << 8);
1303 post_proxy_fail_handler(request);
1307 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1311 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1318 packet->data = NULL;
1319 packet->data_len = 0;
1322 return 1; /* time stamp updated */
1327 * Called when we haven't received a response to a CoA request.
1329 static void retransmit_coa_request(void *ctx)
1333 REQUEST *request = ctx;
1335 rad_assert(request->magic == REQUEST_MAGIC);
1336 rad_assert(request->child_state == REQUEST_PROXIED);
1337 rad_assert(request->home_server != NULL);
1338 rad_assert(!request->in_request_hash);
1339 rad_assert(request->parent == NULL);
1341 fr_event_now(el, &now);
1344 * Cap count at MRC, if it is non-zero.
1346 if (request->home_server->coa_mrc &&
1347 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1348 no_response_to_coa_request(request);
1353 * RFC 5080 Section 2.2.1
1355 * RT = 2*RTprev + RAND*RTprev
1356 * = 1.9 * RTprev + rand(0,.2) * RTprev
1357 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1360 delay ^= (delay >> 16);
1362 frac = request->delay / 5;
1363 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1365 delay += (2 * request->delay) - (request->delay / 10);
1368 * Cap delay at MRT, if MRT is non-zero.
1370 if (request->home_server->coa_mrt &&
1371 (delay > (request->home_server->coa_mrt * USEC))) {
1372 int mrt_usec = request->home_server->coa_mrt * USEC;
1375 * delay = MRT + RAND * MRT
1376 * = 0.9 MRT + rand(0,.2) * MRT
1379 delay ^= (delay >> 15);
1381 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1382 delay += mrt_usec - (mrt_usec / 10);
1385 request->delay = delay;
1386 request->when = now;
1387 tv_add(&request->when, request->delay);
1388 mrd = request->proxy_when;
1389 mrd.tv_sec += request->home_server->coa_mrd;
1392 * Cap duration at MRD.
1394 if (timercmp(&mrd, &request->when, <)) {
1395 request->when = mrd;
1396 INSERT_EVENT(no_response_to_coa_request, request);
1399 INSERT_EVENT(retransmit_coa_request, request);
1402 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1403 if (!insert_into_proxy_hash(request, TRUE)) {
1404 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1408 request->num_proxied_requests = 0;
1409 request->num_proxied_responses = 0;
1412 request->num_proxied_requests++;
1413 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1415 request->proxy_listener->send(request->proxy_listener,
1421 * The original request is either DONE, or in CLEANUP_DELAY.
1423 static int originated_coa_request(REQUEST *request)
1425 int delay, rcode, pre_proxy_type = 0;
1431 rad_assert(request->proxy == NULL);
1432 rad_assert(!request->in_proxy_hash);
1433 rad_assert(request->proxy_reply == NULL);
1435 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1436 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1438 if (vp->vp_integer == 0) {
1439 ev_request_free(&request->coa);
1440 return 1; /* success */
1443 if (!request->coa) request_alloc_coa(request);
1444 if (!request->coa) return 0;
1450 * src_ipaddr will be set up in proxy_encode.
1452 memset(&ipaddr, 0, sizeof(ipaddr));
1453 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1455 ipaddr.af = AF_INET;
1456 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1458 } else if ((vp = pairfind(coa->proxy->vps,
1459 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1460 ipaddr.af = AF_INET6;
1461 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1463 } else if ((vp = pairfind(coa->proxy->vps,
1464 PW_HOME_SERVER_POOL)) != NULL) {
1465 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1467 if (!coa->home_pool) {
1468 RDEBUG2("WARNING: No such home_server_pool %s",
1471 ev_request_free(&request->coa);
1478 } else if (request->client->coa_pool) {
1479 coa->home_pool = request->client->coa_pool;
1481 } else if (request->client->coa_server) {
1482 coa->home_server = request->client->coa_server;
1486 * If all else fails, send it to the client that
1487 * originated this request.
1489 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1493 * Use the pool, if it exists.
1495 if (coa->home_pool) {
1496 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1497 if (!coa->home_server) {
1498 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1502 } else if (!coa->home_server) {
1503 int port = PW_COA_UDP_PORT;
1505 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1506 if (vp) port = vp->vp_integer;
1508 coa->home_server = home_server_find(&ipaddr, port);
1509 if (!coa->home_server) {
1510 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1511 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1512 buffer, sizeof(buffer)), port);
1517 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1519 switch (vp->vp_integer) {
1520 case PW_COA_REQUEST:
1521 case PW_DISCONNECT_REQUEST:
1522 coa->proxy->code = vp->vp_integer;
1526 DEBUG("Cannot set CoA Packet-Type to code %d",
1532 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1535 * The rest of the server code assumes that
1536 * request->packet && request->reply exist. Copy them
1537 * from the original request.
1539 rad_assert(coa->packet != NULL);
1540 rad_assert(coa->packet->vps == NULL);
1541 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1542 coa->packet->vps = paircopy(request->packet->vps);
1543 coa->packet->data = NULL;
1544 rad_assert(coa->reply != NULL);
1545 rad_assert(coa->reply->vps == NULL);
1546 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1547 coa->reply->vps = paircopy(request->reply->vps);
1548 coa->reply->data = NULL;
1549 coa->config_items = paircopy(request->config_items);
1552 * Call the pre-proxy routines.
1554 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1556 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1557 pre_proxy_type = vp->vp_integer;
1560 if (coa->home_pool && coa->home_pool->virtual_server) {
1561 const char *old_server = coa->server;
1563 coa->server = coa->home_pool->virtual_server;
1564 RDEBUG2(" server %s {", coa->server);
1565 rcode = module_pre_proxy(pre_proxy_type, coa);
1567 coa->server = old_server;
1569 rcode = module_pre_proxy(pre_proxy_type, coa);
1576 * Only send the CoA packet if the pre-proxy code succeeded.
1578 case RLM_MODULE_NOOP:
1580 case RLM_MODULE_UPDATED:
1585 * Source IP / port is set when the proxy socket
1588 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1589 coa->proxy->dst_port = coa->home_server->port;
1591 if (!insert_into_proxy_hash(coa, FALSE)) {
1592 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1597 * We CANNOT divorce the CoA request from the parent
1598 * request. This function is running in a child thread,
1599 * and we need access to the main event loop in order to
1600 * to add the timers for the CoA packet. See
1605 * Forget about the original request completely at this
1610 gettimeofday(&request->proxy_when, NULL);
1611 request->received = request->next_when = request->proxy_when;
1612 rad_assert(request->proxy_reply == NULL);
1615 * Implement re-transmit algorithm as per RFC 5080
1618 * We want IRT + RAND*IRT
1619 * or 0.9 IRT + rand(0,.2) IRT
1621 * 2^20 ~ USEC, and we want 2.
1622 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1624 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1625 request->delay = delay * request->home_server->coa_irt;
1626 delay = request->home_server->coa_irt * USEC;
1627 delay -= delay / 10;
1628 delay += request->delay;
1630 request->delay = delay;
1631 tv_add(&request->next_when, delay);
1632 request->next_callback = retransmit_coa_request;
1635 * Note that we set proxied BEFORE sending the packet.
1637 * Once we send it, the request is tainted, as
1638 * another thread may have picked it up. Don't
1641 request->num_proxied_requests = 1;
1642 request->num_proxied_responses = 0;
1643 request->child_pid = NO_SUCH_CHILD_PID;
1645 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1647 request->child_state = REQUEST_PROXIED;
1649 DEBUG_PACKET(request, request->proxy, 1);
1651 request->proxy_listener->send(request->proxy_listener,
1655 #endif /* WITH_COA */
1658 static int process_proxy_reply(REQUEST *request)
1661 int post_proxy_type = 0;
1665 * Delete any reply we had accumulated until now.
1667 pairfree(&request->reply->vps);
1670 * Run the packet through the post-proxy stage,
1671 * BEFORE playing games with the attributes.
1673 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1675 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1676 post_proxy_type = vp->vp_integer;
1679 if (request->home_pool && request->home_pool->virtual_server) {
1680 const char *old_server = request->server;
1682 request->server = request->home_pool->virtual_server;
1683 RDEBUG2(" server %s {", request->server);
1684 rcode = module_post_proxy(post_proxy_type, request);
1686 request->server = old_server;
1688 rcode = module_post_proxy(post_proxy_type, request);
1692 if (request->packet->code == request->proxy->code)
1694 * Don't run the next bit if we originated a CoA
1695 * packet, after receiving an Access-Request or
1696 * Accounting-Request.
1701 * There may NOT be a proxy reply, as we may be
1702 * running Post-Proxy-Type = Fail.
1704 if (request->proxy_reply) {
1706 * Delete the Proxy-State Attributes from
1707 * the reply. These include Proxy-State
1708 * attributes from us and remote server.
1710 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1713 * Add the attributes left in the proxy
1714 * reply to the reply list.
1716 pairadd(&request->reply->vps, request->proxy_reply->vps);
1717 request->proxy_reply->vps = NULL;
1720 * Free proxy request pairs.
1722 pairfree(&request->proxy->vps);
1726 default: /* Don't do anything */
1728 case RLM_MODULE_FAIL:
1729 /* FIXME: debug print stuff */
1730 request->child_state = REQUEST_DONE;
1733 case RLM_MODULE_HANDLED:
1734 /* FIXME: debug print stuff */
1735 request->child_state = REQUEST_DONE;
1743 static int request_pre_handler(REQUEST *request)
1747 rad_assert(request->magic == REQUEST_MAGIC);
1748 rad_assert(request->packet != NULL);
1750 request->child_state = REQUEST_RUNNING;
1753 * Don't decode the packet if it's an internal "fake"
1754 * request. Instead, just return so that the caller can
1757 if (request->packet->dst_port == 0) {
1758 request->username = pairfind(request->packet->vps,
1760 request->password = pairfind(request->packet->vps,
1767 * Put the decoded packet into it's proper place.
1769 if (request->proxy_reply != NULL) {
1770 rcode = request->proxy_listener->decode(request->proxy_listener,
1772 DEBUG_PACKET(request, request->proxy_reply, 0);
1775 if (request->packet->vps == NULL) {
1776 rcode = request->listener->decode(request->listener, request);
1778 if (debug_condition) {
1780 const char *my_debug = debug_condition;
1783 * Ignore parse errors.
1785 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1789 request->options = 2;
1790 request->radlog = radlog_request;
1794 DEBUG_PACKET(request, request->packet, 0);
1800 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1801 request->child_state = REQUEST_DONE;
1805 if (!request->username) {
1806 request->username = pairfind(request->packet->vps,
1811 if (request->proxy) {
1812 return process_proxy_reply(request);
1822 * Do state handling when we proxy a request.
1824 static int proxy_request(REQUEST *request)
1826 struct timeval when;
1829 if (request->home_server->server) {
1830 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1834 if (!insert_into_proxy_hash(request, FALSE)) {
1835 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1839 request->proxy_listener->encode(request->proxy_listener, request);
1841 when = request->received;
1842 when.tv_sec += request->root->max_request_time;
1844 gettimeofday(&request->proxy_when, NULL);
1846 request->next_when = request->proxy_when;
1847 request->next_when.tv_sec += request->home_server->response_window;
1849 rad_assert(request->home_server->response_window > 0);
1851 if (timercmp(&when, &request->next_when, <)) {
1852 request->next_when = when;
1854 request->next_callback = no_response_to_proxied_request;
1856 RDEBUG2("Proxying request %d to home server %s port %d",
1858 inet_ntop(request->proxy->dst_ipaddr.af,
1859 &request->proxy->dst_ipaddr.ipaddr,
1860 buffer, sizeof(buffer)),
1861 request->proxy->dst_port);
1864 * Note that we set proxied BEFORE sending the packet.
1866 * Once we send it, the request is tainted, as
1867 * another thread may have picked it up. Don't
1870 request->num_proxied_requests = 1;
1871 request->num_proxied_responses = 0;
1872 #ifdef HAVE_PTHREAD_H
1873 request->child_pid = NO_SUCH_CHILD_PID;
1875 request->child_state = REQUEST_PROXIED;
1877 DEBUG_PACKET(request, request->proxy, 1);
1879 request->proxy_listener->send(request->proxy_listener,
1886 * "Proxy" the request by sending it to a new virtual server.
1888 static int proxy_to_virtual_server(REQUEST *request)
1891 RAD_REQUEST_FUNP fun;
1893 if (!request->home_server || !request->home_server->server) return 0;
1895 if (request->parent) {
1896 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1900 fake = request_alloc_fake(request);
1902 RDEBUG2("WARNING: Out of memory");
1906 fake->packet->vps = paircopy(request->proxy->vps);
1907 fake->server = request->home_server->server;
1909 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1910 fun = rad_authenticate;
1912 #ifdef WITH_ACCOUNTING
1913 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1914 fun = rad_accounting;
1918 RDEBUG2("Unknown packet type %d", request->proxy->code);
1919 ev_request_free(&fake);
1923 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1924 radius_handle_request(fake, fun);
1925 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1927 if (fake->reply->code != 0) {
1928 request->proxy_reply = fake->reply;
1932 * There was no response
1934 setup_post_proxy_fail(request);
1937 ev_request_free(&fake);
1939 process_proxy_reply(request);
1942 * Process it through the normal section again, but ONLY
1943 * if we received a proxy reply..
1945 if (request->proxy_reply) {
1946 if (request->server) RDEBUG("server %s {",
1947 request->server != NULL ?
1948 request->server : "");
1951 if (request->server) RDEBUG("} # server %s",
1952 request->server != NULL ?
1953 request->server : "");
1956 return 2; /* success, but NOT '1' !*/
1960 * Return 1 if we did proxy it, or the proxy attempt failed
1961 * completely. Either way, the caller doesn't touch the request
1962 * any more if we return 1.
1964 static int successfully_proxied_request(REQUEST *request)
1967 int pre_proxy_type = 0;
1968 VALUE_PAIR *realmpair;
1969 VALUE_PAIR *strippedname;
1971 char *realmname = NULL;
1973 REALM *realm = NULL;
1977 * If it was already proxied, do nothing.
1979 * FIXME: This should really be a serious error.
1981 if (request->in_proxy_hash ||
1982 (request->proxy_reply && (request->proxy_reply->code != 0))) {
1986 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1987 if (!realmpair || (realmpair->length == 0)) {
1990 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
1993 switch (request->packet->code) {
1994 case PW_AUTHENTICATION_REQUEST:
1995 pool_type = HOME_TYPE_AUTH;
1998 #ifdef WITH_ACCOUNTING
1999 case PW_ACCOUNTING_REQUEST:
2000 pool_type = HOME_TYPE_ACCT;
2005 case PW_COA_REQUEST:
2006 case PW_DISCONNECT_REQUEST:
2007 pool_type = HOME_TYPE_COA;
2015 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2017 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2022 realmname = NULL; /* no realms */
2027 realmname = (char *) realmpair->vp_strvalue;
2029 realm = realm_find2(realmname);
2031 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2036 * Figure out which pool to use.
2038 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2039 pool = realm->auth_pool;
2041 #ifdef WITH_ACCOUNTING
2042 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2043 pool = realm->acct_pool;
2047 } else if ((request->packet->code == PW_COA_REQUEST) ||
2048 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2049 pool = realm->acct_pool;
2053 rad_panic("Internal sanity check failed");
2057 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2063 home = home_server_ldb(realmname, pool, request);
2065 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2069 request->home_pool = pool;
2073 * Once we've decided to proxy a request, we cannot send
2074 * a CoA packet. So we free up any CoA packet here.
2076 ev_request_free(&request->coa);
2079 * Remember that we sent the request to a Realm.
2081 if (realmname) pairadd(&request->packet->vps,
2082 pairmake("Realm", realmname, T_OP_EQ));
2085 * Strip the name, if told to.
2087 * Doing it here catches the case of proxied tunneled
2090 if (realm && (realm->striprealm == TRUE) &&
2091 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2093 * If there's a Stripped-User-Name attribute in
2094 * the request, then use THAT as the User-Name
2095 * for the proxied request, instead of the
2098 * This is done by making a copy of the
2099 * Stripped-User-Name attribute, turning it into
2100 * a User-Name attribute, deleting the
2101 * Stripped-User-Name and User-Name attributes
2102 * from the vps list, and making the new
2103 * User-Name the head of the vps list.
2105 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2107 vp = radius_paircreate(request, NULL,
2108 PW_USER_NAME, PW_TYPE_STRING);
2109 rad_assert(vp != NULL); /* handled by above function */
2110 /* Insert at the START of the list */
2111 vp->next = request->proxy->vps;
2112 request->proxy->vps = vp;
2114 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2115 sizeof(vp->vp_strvalue));
2116 vp->length = strippedname->length;
2119 * Do NOT delete Stripped-User-Name.
2124 * If there is no PW_CHAP_CHALLENGE attribute but
2125 * there is a PW_CHAP_PASSWORD we need to add it
2126 * since we can't use the request authenticator
2127 * anymore - we changed it.
2129 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2130 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2131 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2132 vp = radius_paircreate(request, &request->proxy->vps,
2133 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2134 vp->length = AUTH_VECTOR_LEN;
2135 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2139 * The RFC's say we have to do this, but FreeRADIUS
2142 vp = radius_paircreate(request, &request->proxy->vps,
2143 PW_PROXY_STATE, PW_TYPE_OCTETS);
2144 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2145 request->packet->id);
2146 vp->length = strlen(vp->vp_strvalue);
2149 * Should be done BEFORE inserting into proxy hash, as
2150 * pre-proxy may use this information, or change it.
2152 request->proxy->code = request->packet->code;
2155 * Call the pre-proxy routines.
2157 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2159 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2160 pre_proxy_type = vp->vp_integer;
2163 rad_assert(request->home_pool != NULL);
2165 if (request->home_pool->virtual_server) {
2166 const char *old_server = request->server;
2168 request->server = request->home_pool->virtual_server;
2169 RDEBUG2(" server %s {", request->server);
2170 rcode = module_pre_proxy(pre_proxy_type, request);
2172 request->server = old_server;
2174 rcode = module_pre_proxy(pre_proxy_type, request);
2177 case RLM_MODULE_FAIL:
2178 case RLM_MODULE_INVALID:
2179 case RLM_MODULE_NOTFOUND:
2180 case RLM_MODULE_USERLOCK:
2182 /* FIXME: debug print failed stuff */
2185 case RLM_MODULE_REJECT:
2186 case RLM_MODULE_HANDLED:
2190 * Only proxy the packet if the pre-proxy code succeeded.
2192 case RLM_MODULE_NOOP:
2194 case RLM_MODULE_UPDATED:
2199 * If it's a fake request, don't send the proxy
2200 * packet. The outer tunnel session will take
2201 * care of doing that.
2203 if (request->packet->dst_port == 0) {
2204 request->home_server = NULL;
2208 if (request->home_server->server) {
2209 return proxy_to_virtual_server(request);
2212 if (!proxy_request(request)) {
2213 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2221 static void request_post_handler(REQUEST *request)
2223 int child_state = -1;
2224 struct timeval when;
2227 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2229 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2230 RDEBUG2("Request %d was cancelled.", request->number);
2231 #ifdef HAVE_PTHREAD_H
2232 request->child_pid = NO_SUCH_CHILD_PID;
2234 child_state = REQUEST_DONE;
2238 if (request->child_state != REQUEST_RUNNING) {
2239 rad_panic("Internal sanity check failed");
2244 * If it's not in the request hash, it's a CoA request.
2247 if (!request->in_request_hash &&
2249 ((request->proxy->code == PW_COA_REQUEST) ||
2250 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2251 request->next_callback = NULL;
2252 child_state = REQUEST_DONE;
2258 * Catch Auth-Type := Reject BEFORE proxying the packet.
2260 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2261 (request->reply->code == 0) &&
2262 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2263 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2264 request->reply->code = PW_AUTHENTICATION_REJECT;
2268 if (request->root->proxy_requests &&
2269 !request->in_proxy_hash &&
2270 (request->reply->code == 0) &&
2271 (request->packet->dst_port != 0) &&
2272 (request->packet->code != PW_STATUS_SERVER)) {
2273 int rcode = successfully_proxied_request(request);
2275 if (rcode == 1) return; /* request is invalid */
2278 * Failed proxying it (dead home servers, etc.)
2279 * Run it through Post-Proxy-Type = Fail, and
2280 * respond to the request.
2282 * Note that we're in a child thread here, so we
2283 * do NOT re-schedule the request. Instead, we
2284 * do what we would have done, which is run the
2285 * pre-handler, a NULL request handler, and then
2288 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2289 request_pre_handler(request);
2293 * Else we weren't supposed to proxy it,
2294 * OR we proxied it internally to a virutal server.
2300 * Fake requests don't get encoded or signed. The caller
2301 * also requires the reply VP's, so we don't free them
2304 if (request->packet->dst_port == 0) {
2305 /* FIXME: RDEBUG going to the next request */
2306 #ifdef HAVE_PTHREAD_H
2307 request->child_pid = NO_SUCH_CHILD_PID;
2309 request->child_state = REQUEST_DONE;
2315 * Copy Proxy-State from the request to the reply.
2317 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2318 if (vp) pairadd(&request->reply->vps, vp);
2322 * Access-Requests get delayed or cached.
2324 switch (request->packet->code) {
2325 case PW_AUTHENTICATION_REQUEST:
2326 gettimeofday(&request->next_when, NULL);
2328 if (request->reply->code == 0) {
2330 * Check if the lack of response is intentional.
2332 vp = pairfind(request->config_items,
2333 PW_RESPONSE_PACKET_TYPE);
2335 RDEBUG2("There was no response configured: rejecting request %d",
2337 request->reply->code = PW_AUTHENTICATION_REJECT;
2339 } else if (vp->vp_integer == 256) {
2340 RDEBUG2("Not responding to request %d",
2344 * Force cleanup after a long
2345 * time, so that we don't
2346 * re-process the packet.
2348 request->next_when.tv_sec += request->root->max_request_time;
2349 request->next_callback = cleanup_delay;
2350 child_state = REQUEST_CLEANUP_DELAY;
2353 request->reply->code = vp->vp_integer;
2359 * Run rejected packets through
2361 * Post-Auth-Type = Reject
2363 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2364 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2365 vp = radius_pairmake(request, &request->config_items,
2366 "Post-Auth-Type", "Reject",
2368 if (vp) rad_postauth(request);
2371 * If configured, delay Access-Reject packets.
2373 * If request->root->reject_delay = 0, we discover
2374 * that we have to send the packet now.
2376 when = request->received;
2377 when.tv_sec += request->root->reject_delay;
2379 if (timercmp(&when, &request->next_when, >)) {
2380 RDEBUG2("Delaying reject of request %d for %d seconds",
2382 request->root->reject_delay);
2383 request->next_when = when;
2384 request->next_callback = reject_delay;
2385 #ifdef HAVE_PTHREAD_H
2386 request->child_pid = NO_SUCH_CHILD_PID;
2388 request->child_state = REQUEST_REJECT_DELAY;
2394 case PW_COA_REQUEST:
2395 case PW_DISCONNECT_REQUEST:
2397 request->next_when.tv_sec += request->root->cleanup_delay;
2398 request->next_callback = cleanup_delay;
2399 child_state = REQUEST_CLEANUP_DELAY;
2402 case PW_ACCOUNTING_REQUEST:
2403 request->next_callback = NULL; /* just to be safe */
2404 child_state = REQUEST_DONE;
2408 * FIXME: Status-Server should probably not be
2411 case PW_STATUS_SERVER:
2412 request->next_callback = NULL;
2413 child_state = REQUEST_DONE;
2420 request->next_callback = NULL;
2421 child_state = REQUEST_DONE;
2426 * Suppress "no reply" packets here, unless we're reading
2427 * from the "detail" file. In that case, we've got to
2428 * tell the detail file handler that the request is dead,
2429 * and it should re-send it.
2430 * If configured, encode, sign, and send.
2432 if ((request->reply->code != 0) ||
2433 (request->listener->type == RAD_LISTEN_DETAIL)) {
2434 DEBUG_PACKET(request, request->reply, 1);
2435 request->listener->send(request->listener, request);
2440 * Now that we've completely processed the request,
2441 * see if we need to originate a CoA request.
2444 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2445 if (!originated_coa_request(request)) {
2446 RDEBUG2("Do CoA Fail handler here");
2448 /* request->coa is stil set, so we can update events */
2454 * Clean up. These are no longer needed.
2456 pairfree(&request->config_items);
2458 pairfree(&request->packet->vps);
2459 request->username = NULL;
2460 request->password = NULL;
2462 pairfree(&request->reply->vps);
2465 if (request->proxy) {
2466 pairfree(&request->proxy->vps);
2468 if (request->proxy_reply) {
2469 pairfree(&request->proxy_reply->vps);
2474 * We're not tracking responses from the home
2475 * server, we can therefore free this memory in
2478 if (!request->in_proxy_hash) {
2479 rad_free(&request->proxy);
2480 rad_free(&request->proxy_reply);
2481 request->home_server = NULL;
2487 RDEBUG2("Finished request %d.", request->number);
2488 rad_assert(child_state >= 0);
2489 request->child_state = child_state;
2492 * Single threaded mode: update timers now.
2494 if (!have_children) wait_a_bit(request);
2498 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2504 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2505 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2507 switch (request->child_state) {
2508 case REQUEST_QUEUED:
2509 case REQUEST_RUNNING:
2513 radlog(L_ERR, "Discarding duplicate request from "
2514 "client %s port %d - ID: %d due to unfinished request %d",
2516 request->packet->src_port,request->packet->id,
2521 case REQUEST_PROXIED:
2523 * We're not supposed to have duplicate
2524 * accounting packets. The other states handle
2525 * duplicates fine (discard, or send duplicate
2526 * reply). But we do NOT want to retransmit an
2527 * accounting request here, because that would
2528 * involve updating the Acct-Delay-Time, and
2529 * therefore changing the packet Id, etc.
2531 * Instead, we just discard the packet. We may
2532 * eventually respond, or the client will send a
2533 * new accounting packet.
2535 * The same comments go for Status-Server, and
2536 * other packet types.
2538 * FIXME: coa: when we proxy CoA && Disconnect
2539 * packets, this logic has to be fixed.
2541 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2545 check_for_zombie_home_server(request);
2548 * If we've just discovered that the home server is
2549 * dead, send the packet to another one.
2551 if ((request->packet->dst_port != 0) &&
2552 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2555 remove_from_proxy_hash(request);
2557 home = home_server_ldb(NULL, request->home_pool, request);
2559 RDEBUG2("Failed to find live home server for request %d", request->number);
2562 * Do post-request processing,
2563 * and any insertion of necessary
2566 post_proxy_fail_handler(request);
2570 request->proxy->code = request->packet->code;
2573 * Free the old packet, to force re-encoding
2575 free(request->proxy->data);
2576 request->proxy->data = NULL;
2577 request->proxy->data_len = 0;
2580 * This request failed over to a virtual
2581 * server. Push it back onto the queue
2584 if (request->home_server->server) {
2585 proxy_fallback_handler(request);
2590 * Try to proxy the request.
2592 if (!proxy_request(request)) {
2593 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2594 goto no_home_servers;
2598 * This code executes in the main server
2599 * thread, so there's no need for locking.
2601 rad_assert(request->next_callback != NULL);
2602 INSERT_EVENT(request->next_callback, request);
2603 request->next_callback = NULL;
2605 } /* else the home server is still alive */
2607 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2608 inet_ntop(request->proxy->dst_ipaddr.af,
2609 &request->proxy->dst_ipaddr.ipaddr,
2610 buffer, sizeof(buffer)),
2611 request->proxy->dst_port,
2612 request->proxy->id);
2613 request->num_proxied_requests++;
2615 DEBUG_PACKET(request, request->proxy, 1);
2616 request->proxy_listener->send(request->proxy_listener,
2621 case REQUEST_REJECT_DELAY:
2622 RDEBUG2("Waiting to send Access-Reject "
2623 "to client %s port %d - ID: %d",
2625 request->packet->src_port, request->packet->id);
2628 case REQUEST_CLEANUP_DELAY:
2630 if (request->reply->code == 0) {
2631 RDEBUG2("Ignoring retransmit from client %s port %d "
2632 "- ID: %d, no reply was configured",
2634 request->packet->src_port, request->packet->id);
2639 * FIXME: This sends duplicate replies to
2640 * accounting requests, even if Acct-Delay-Time
2641 * or Event-Timestamp is in the packet. In those
2642 * cases, the Id should be changed, and the packet
2645 RDEBUG2("Sending duplicate reply "
2646 "to client %s port %d - ID: %d",
2648 request->packet->src_port, request->packet->id);
2649 DEBUG_PACKET(request, request->reply, 1);
2650 request->listener->send(request->listener, request);
2656 static void received_conflicting_request(REQUEST *request,
2657 const RADCLIENT *client)
2659 radlog(L_ERR, "Received conflicting packet from "
2660 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2662 request->packet->src_port, request->packet->id,
2666 * Nuke it from the request hash, so we can receive new
2669 remove_from_request_hash(request);
2671 switch (request->child_state) {
2672 #ifdef HAVE_PTHREAD_H
2674 * It's queued or running. Tell it to stop, and
2675 * wait for it to do so.
2677 case REQUEST_QUEUED:
2678 case REQUEST_RUNNING:
2679 request->master_state = REQUEST_STOP_PROCESSING;
2680 request->delay += request->delay >> 1;
2682 tv_add(&request->when, request->delay);
2684 INSERT_EVENT(wait_for_child_to_die, request);
2689 * Catch race conditions. It may have switched
2690 * from running to done while this code is being
2693 case REQUEST_REJECT_DELAY:
2694 case REQUEST_CLEANUP_DELAY:
2699 * It's in some other state, and therefore also
2700 * in the event queue. At some point, the
2701 * child will notice, and we can then delete it.
2703 case REQUEST_PROXIED:
2705 rad_assert(request->ev != NULL);
2711 static int can_handle_new_request(RADIUS_PACKET *packet,
2713 struct main_config_t *root)
2716 * Count the total number of requests, to see if
2717 * there are too many. If so, return with an
2720 if (root->max_requests) {
2721 int request_count = fr_packet_list_num_elements(pl);
2724 * This is a new request. Let's see if
2725 * it makes us go over our configured
2728 if (request_count > root->max_requests) {
2729 radlog(L_ERR, "Dropping request (%d is too many): "
2730 "from client %s port %d - ID: %d", request_count,
2732 packet->src_port, packet->id);
2733 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2734 "\tThe value for 'max_requests' is probably set too low.\n");
2736 } /* else there were a small number of requests */
2737 } /* else there was no configured limit for requests */
2740 * FIXME: Add per-client checks. If one client is sending
2741 * too many packets, start discarding them.
2743 * We increment the counters here, and decrement them
2744 * when the response is sent... somewhere in this file.
2748 * FUTURE: Add checks for system load. If the system is
2749 * busy, start dropping requests...
2751 * We can probably keep some statistics ourselves... if
2752 * there are more requests coming in than we can handle,
2753 * start dropping some.
2760 int received_request(rad_listen_t *listener,
2761 RADIUS_PACKET *packet, REQUEST **prequest,
2764 RADIUS_PACKET **packet_p;
2765 REQUEST *request = NULL;
2766 struct main_config_t *root = &mainconfig;
2768 packet_p = fr_packet_list_find(pl, packet);
2770 request = fr_packet2myptr(REQUEST, packet, packet_p);
2771 rad_assert(request->in_request_hash);
2773 if ((request->packet->data_len == packet->data_len) &&
2774 (memcmp(request->packet->vector, packet->vector,
2775 sizeof(packet->vector)) == 0)) {
2776 received_retransmit(request, client);
2781 * The new request is different from the old one,
2782 * but maybe the old is finished. If so, delete
2785 switch (request->child_state) {
2786 struct timeval when;
2790 * Special hacks for race conditions.
2791 * The reply is encoded, and therefore
2792 * likely sent. We received a *new*
2793 * packet from the client, likely before
2794 * the next line or two of code which
2795 * updated the child state. In this
2796 * case, just accept the new request.
2798 if ((request->reply->code != 0) &&
2799 request->reply->data) {
2800 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2802 packet->src_port, packet->id,
2804 remove_from_request_hash(request);
2809 gettimeofday(&when, NULL);
2813 * If the cached request was received
2814 * within the last second, then we
2815 * discard the NEW request instead of the
2816 * old one. This will happen ONLY when
2817 * the client is severely broken, and is
2818 * sending conflicting packets very
2821 if (timercmp(&when, &request->received, <)) {
2822 radlog(L_ERR, "Discarding conflicting packet from "
2823 "client %s port %d - ID: %d due to recent request %d.",
2825 packet->src_port, packet->id,
2830 received_conflicting_request(request, client);
2834 case REQUEST_REJECT_DELAY:
2835 case REQUEST_CLEANUP_DELAY:
2836 request->child_state = REQUEST_DONE;
2838 cleanup_delay(request);
2845 * We may want to quench the new request.
2847 if ((listener->type != RAD_LISTEN_DETAIL) &&
2848 !can_handle_new_request(packet, client, root)) {
2853 * Create and initialize the new request.
2855 request = request_alloc(); /* never fails */
2857 if ((request->reply = rad_alloc(0)) == NULL) {
2858 radlog(L_ERR, "No memory");
2862 request->listener = listener;
2863 request->client = client;
2864 request->packet = packet;
2865 request->packet->timestamp = request->timestamp;
2866 request->number = request_num_counter++;
2867 request->priority = listener->type;
2868 #ifdef HAVE_PTHREAD_H
2869 request->child_pid = NO_SUCH_CHILD_PID;
2873 * Status-Server packets go to the head of the queue.
2875 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2878 * Set virtual server identity
2880 if (client->server) {
2881 request->server = client->server;
2882 } else if (listener->server) {
2883 request->server = listener->server;
2885 request->server = NULL;
2889 * Remember the request in the list.
2891 if (!fr_packet_list_insert(pl, &request->packet)) {
2892 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2893 ev_request_free(&request);
2897 request->in_request_hash = TRUE;
2898 request->root = root;
2902 * The request passes many of our sanity checks.
2903 * From here on in, if anything goes wrong, we
2904 * send a reject message, instead of dropping the
2909 * Build the reply template from the request.
2912 request->reply->sockfd = request->packet->sockfd;
2913 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2914 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2915 request->reply->dst_port = request->packet->src_port;
2916 request->reply->src_port = request->packet->dst_port;
2917 request->reply->id = request->packet->id;
2918 request->reply->code = 0; /* UNKNOWN code */
2919 memcpy(request->reply->vector, request->packet->vector,
2920 sizeof(request->reply->vector));
2921 request->reply->vps = NULL;
2922 request->reply->data = NULL;
2923 request->reply->data_len = 0;
2925 request->master_state = REQUEST_ACTIVE;
2926 request->child_state = REQUEST_QUEUED;
2927 request->next_callback = NULL;
2929 gettimeofday(&request->received, NULL);
2930 request->timestamp = request->received.tv_sec;
2931 request->when = request->received;
2933 request->delay = USEC;
2935 tv_add(&request->when, request->delay);
2937 INSERT_EVENT(wait_a_bit, request);
2939 *prequest = request;
2945 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2951 * Also removes from the proxy hash if responses == requests
2953 request = lookup_in_proxy_hash(packet);
2956 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2957 inet_ntop(packet->src_ipaddr.af,
2958 &packet->src_ipaddr.ipaddr,
2959 buffer, sizeof(buffer)),
2960 packet->src_port, packet->id);
2965 * We haven't replied to the NAS, but we have seen an
2966 * earlier reply from the home server. Ignore this packet,
2967 * as we're likely still processing the previous reply.
2969 if (request->proxy_reply) {
2970 if (memcmp(request->proxy_reply->vector,
2972 sizeof(request->proxy_reply->vector)) == 0) {
2973 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2974 inet_ntop(packet->src_ipaddr.af,
2975 &packet->src_ipaddr.ipaddr,
2976 buffer, sizeof(buffer)),
2977 packet->src_port, packet->id,
2981 * ? The home server gave us a new proxy
2982 * reply which doesn't match the old
2985 RDEBUG2("Ignoring conflicting proxy reply");
2988 /* assert that there's an event queued for request? */
2993 * Verify the packet before doing ANYTHING with it. This
2994 * means we're doing more MD5 checks in the server core.
2995 * However, we can fix that by moving to multiple threads
2996 * listening on sockets.
2998 * We do this AFTER looking the request up in the hash,
2999 * and AFTER vhecking if we saw a previous request. This
3000 * helps minimize the DoS effect of people attacking us
3001 * with spoofed packets.
3003 if (rad_verify(packet, request->proxy,
3004 request->home_server->secret) != 0) {
3005 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3009 gettimeofday(&now, NULL);
3012 * Maybe move this earlier in the decision process?
3013 * Having it here means that late or duplicate proxy
3014 * replies no longer get the home server marked as
3015 * "alive". This might be good for stability, though.
3017 * FIXME: Do we really want to do this whenever we
3018 * receive a packet? Setting this here means that we
3019 * mark it alive on *any* packet, even if it's lost all
3020 * of the *other* packets in the last 10s.
3022 if (request->proxy->code != PW_STATUS_SERVER) {
3023 request->home_server->state = HOME_STATE_ALIVE;
3028 * When originating CoA, the "proxy" reply is the reply
3029 * to the CoA request that we originated. At this point,
3030 * the original request is finished, and it has a reply.
3032 * However, if we haven't separated the two requests, do
3033 * so now. This is done so that cleaning up the original
3034 * request won't cause the CoA request to be free'd. See
3035 * util.c, request_free()
3037 if (request->parent && (request->parent->coa == request)) {
3038 request->parent->coa = NULL;
3039 request->parent = NULL;
3043 * Skip the next set of checks, as the original
3044 * reply is cached. We want to be able to still
3045 * process the CoA reply, AND to reference the
3046 * original request/reply.
3048 * This is getting to be really quite a bit of a
3054 * If there's a reply to the NAS, ignore everything
3055 * related to proxy responses
3057 if (request->reply && request->reply->code != 0) {
3058 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3064 * The average includes our time to receive packets and
3065 * look them up in the hashes, which should be the same
3068 * We update the response time only for the FIRST packet
3071 if (request->home_server->ema.window > 0) {
3072 radius_stats_ema(&request->home_server->ema,
3073 &now, &request->proxy_when);
3077 switch (request->child_state) {
3078 case REQUEST_QUEUED:
3079 case REQUEST_RUNNING:
3080 radlog(L_ERR, "Internal sanity check failed for child state");
3083 case REQUEST_REJECT_DELAY:
3084 case REQUEST_CLEANUP_DELAY:
3086 radlog(L_ERR, "Reply from home server %s port %d - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
3087 inet_ntop(packet->src_ipaddr.af,
3088 &packet->src_ipaddr.ipaddr,
3089 buffer, sizeof(buffer)),
3090 packet->src_port, packet->id,
3092 /* assert that there's an event queued for request? */
3095 case REQUEST_PROXIED:
3099 request->proxy_reply = packet;
3103 * Perform RTT calculations, as per RFC 2988 (for TCP).
3104 * Note that we only do so on the first response.
3106 if ((request->num_proxied_responses == 1)
3108 home_server *home = request->home_server;
3110 rtt = now.tv_sec - request->proxy_when.tv_sec;
3113 rtt -= request->proxy_when.tv_usec;
3115 if (!home->has_rtt) {
3116 home->has_rtt = TRUE;
3119 home->rttvar = rtt / 2;
3122 home->rttvar -= home->rttvar >> 2;
3123 home->rttvar += (home->srtt - rtt);
3124 home->srtt -= home->srtt >> 3;
3125 home->srtt += rtt >> 3;
3128 home->rto = home->srtt;
3129 if (home->rttvar > (USEC / 4)) {
3130 home->rto += home->rttvar * 4;
3138 * There's no incoming request, so it's a proxied packet
3141 if (!request->packet) {
3142 received_response_to_ping(request);
3143 request->proxy_reply = NULL; /* caller will free it */
3144 ev_request_free(&request);
3148 request->child_state = REQUEST_QUEUED;
3149 request->when = now;
3150 request->delay = USEC;
3151 request->priority = RAD_LISTEN_PROXY;
3152 tv_add(&request->when, request->delay);
3155 * Wait a bit will take care of max_request_time
3157 INSERT_EVENT(wait_a_bit, request);
3163 void event_new_fd(rad_listen_t *this)
3167 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3169 this->print(this, buffer, sizeof(buffer));
3171 if (this->status == RAD_LISTEN_STATUS_INIT) {
3173 DEBUG("Listening on %s", buffer);
3175 radlog(L_INFO, " ... adding new socket %s", buffer);
3177 if (!fr_event_fd_insert(el, 0, this->fd,
3178 event_socket_handler, this)) {
3179 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3183 this->status = RAD_LISTEN_STATUS_KNOWN;
3187 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3188 radlog(L_INFO, " ... closing socket %s", buffer);
3190 fr_event_fd_delete(el, 0, this->fd);
3191 this->status = RAD_LISTEN_STATUS_FINISH;
3194 * Close the fd AFTER fixing up the requests and
3195 * listeners, so that they don't send/recv on the
3196 * wrong socket (if someone manages to open
3204 static void handle_signal_self(int flag)
3206 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3207 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3208 fr_event_loop_exit(el, 1);
3210 fr_event_loop_exit(el, 2);
3214 } /* else exit/term flags weren't set */
3217 * Tell the even loop to stop processing.
3219 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3221 static time_t last_hup = 0;
3223 radlog(L_INFO, "Received HUP signal.");
3226 if ((int) (when - last_hup) < 5) {
3227 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3232 fr_event_loop_exit(el, 0x80);
3236 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3240 * FIXME: O(N) loops suck.
3242 for (this = mainconfig.listen;
3244 this = this->next) {
3245 if (this->type != RAD_LISTEN_DETAIL) continue;
3248 * This one didn't send the signal, skip
3251 if (!this->decode(this, NULL)) continue;
3254 * Go service the interrupt.
3256 event_poll_detail(this);
3261 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3264 for (this = mainconfig.listen;
3266 this = this->next) {
3272 #ifndef WITH_SELF_PIPE
3273 void radius_signal_self(int flag)
3275 handle_signal_self(flag);
3279 * Inform ourselves that we received a signal.
3281 void radius_signal_self(int flag)
3287 * The read MUST be non-blocking for this to work.
3289 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3293 for (i = 0; i < rcode; i++) {
3294 buffer[0] |= buffer[i];
3302 write(self_pipe[1], buffer, 1);
3306 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3307 UNUSED int fd, UNUSED void *ctx)
3312 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3313 if (rcode <= 0) return;
3316 * Merge pending signals.
3318 for (i = 0; i < rcode; i++) {
3319 buffer[0] |= buffer[i];
3322 handle_signal_self(buffer[0]);
3327 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3330 rad_listen_t *listener = ctx;
3331 RAD_REQUEST_FUNP fun;
3334 rad_assert(xel == el);
3338 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3340 if (!listener->recv(listener, &fun, &request)) return;
3342 if (!thread_pool_addrequest(request, fun)) {
3343 request->child_state = REQUEST_DONE;
3349 * This function is called periodically to see if this detail
3350 * file is available for reading.
3352 static void event_poll_detail(void *ctx)
3355 RAD_REQUEST_FUNP fun;
3357 rad_listen_t *this = ctx;
3358 struct timeval when;
3359 listen_detail_t *detail = this->data;
3361 rad_assert(this->type == RAD_LISTEN_DETAIL);
3364 * Try to read something.
3366 * FIXME: This does poll AND receive.
3368 rcode = this->recv(this, &fun, &request);
3370 rad_assert(fun != NULL);
3371 rad_assert(request != NULL);
3373 if (!thread_pool_addrequest(request, fun)) {
3374 request->child_state = REQUEST_DONE;
3378 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3382 * Backdoor API to get the delay until the next poll
3385 delay = this->encode(this, NULL);
3386 tv_add(&when, delay);
3388 if (!fr_event_insert(el, event_poll_detail, this,
3389 &when, &detail->ev)) {
3390 radlog(L_ERR, "Failed creating handler");
3396 static void event_status(struct timeval *wake)
3398 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3402 if (debug_flag == 0) {
3404 radlog(L_INFO, "Ready to process requests.");
3405 just_started = FALSE;
3411 radlog(L_INFO, "Ready to process requests.");
3413 } else if ((wake->tv_sec != 0) ||
3414 (wake->tv_usec >= 100000)) {
3415 DEBUG("Waking up in %d.%01u seconds.",
3416 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3421 * FIXME: Put this somewhere else, where it isn't called
3422 * all of the time...
3425 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3427 * If there are no child threads, then there may
3428 * be child processes. In that case, wait for
3429 * their exit status, and throw that exit status
3430 * away. This helps get rid of zxombie children.
3432 while (waitpid(-1, &argval, WNOHANG) > 0) {
3440 * Externally-visibly functions.
3442 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3444 rad_listen_t *this, *head = NULL;
3448 time(&fr_start_time);
3450 el = fr_event_list_create(event_status);
3453 pl = fr_packet_list_create(0);
3454 if (!pl) return 0; /* leak el */
3456 request_num_counter = 0;
3459 if (mainconfig.proxy_requests) {
3461 * Create the tree for managing proxied requests and
3464 proxy_list = fr_packet_list_create(1);
3465 if (!proxy_list) return 0;
3467 #ifdef HAVE_PTHREAD_H
3468 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3469 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3478 * Just before we spawn the child threads, force the log
3479 * subsystem to re-open the log file for every write.
3481 if (spawn_flag) force_log_reopen();
3483 #ifdef HAVE_PTHREAD_H
3485 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3487 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3490 * Initialize the threads ONLY if we're spawning, AND
3491 * we're running normally.
3493 if (spawn_flag && !check_config &&
3494 (thread_pool_init(cs, &spawn_flag) < 0)) {
3500 * Move all of the thread calls to this file?
3502 * It may be best for the mutexes to be in this file...
3504 have_children = spawn_flag;
3507 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3512 #ifdef WITH_SELF_PIPE
3514 * Child threads need a pipe to signal us, as do the
3517 if (pipe(self_pipe) < 0) {
3518 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3522 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3523 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3527 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3528 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3533 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3534 event_signal_handler, el)) {
3535 radlog(L_ERR, "Failed creating handler for signals");
3538 #endif /* WITH_SELF_PIPE */
3542 * Mark the proxy Fd's as unused.
3547 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3551 DEBUG("%s: #### Opening IP addresses and Ports ####",
3555 * The server temporarily switches to an unprivileged
3556 * user very early in the bootstrapping process.
3557 * However, some sockets MAY require privileged access
3558 * (bind to device, or to port < 1024, or to raw
3559 * sockets). Those sockets need to call suid up/down
3560 * themselves around the functions that need a privileged
3563 if (listen_init(cs, &head) < 0) {
3568 * At this point, no one has any business *ever* going
3571 fr_suid_down_permanent();
3574 * Add all of the sockets to the event loop.
3578 this = this->next) {
3581 this->print(this, buffer, sizeof(buffer));
3583 switch (this->type) {
3585 case RAD_LISTEN_DETAIL:
3586 DEBUG("Listening on %s", buffer);
3589 * Detail files are always known, and aren't
3590 * put into the socket event loop.
3592 this->status = RAD_LISTEN_STATUS_KNOWN;
3595 * Set up the first poll interval.
3597 event_poll_detail(this);
3602 case RAD_LISTEN_PROXY:
3603 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3604 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3606 proxy_fds[this->fd & 0x1f] = this->fd;
3607 proxy_listeners[this->fd & 0x1f] = this;
3608 if (!fr_packet_list_socket_add(proxy_list,
3622 mainconfig.listen = head;
3628 static int request_hash_cb(UNUSED void *ctx, void *data)
3630 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3633 rad_assert(request->in_proxy_hash == FALSE);
3636 ev_request_free(&request);
3643 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3645 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3647 ev_request_free(&request);
3653 void radius_event_free(void)
3656 * FIXME: Stop all threads, or at least check that
3657 * they're all waiting on the semaphore, and the queues
3663 * There are requests in the proxy hash that aren't
3664 * referenced from anywhere else. Remove them first.
3667 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3668 fr_packet_list_free(proxy_list);
3673 fr_packet_list_walk(pl, NULL, request_hash_cb);
3675 fr_packet_list_free(pl);
3678 fr_event_list_free(el);
3681 int radius_event_process(void)
3685 return fr_event_loop(el);
3688 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3690 request->options = RAD_REQUEST_OPTION_DEBUG2;
3692 if (request_pre_handler(request)) {
3693 rad_assert(fun != NULL);
3694 rad_assert(request != NULL);
3696 if (request->server) RDEBUG("server %s {",
3697 request->server != NULL ?
3698 request->server : "");
3701 if (request->server) RDEBUG("} # server %s",
3702 request->server != NULL ?
3703 request->server : "");
3705 request_post_handler(request);
3708 DEBUG2("Going to the next request");