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_fds[32];
102 static rad_listen_t *proxy_listeners[32];
104 #define remove_from_proxy_hash(foo)
107 static void request_post_handler(REQUEST *request);
108 static void wait_a_bit(void *ctx);
109 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
111 static void event_poll_detail(void *ctx);
114 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
117 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
121 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
124 static void tv_add(struct timeval *tv, int usec_delay)
126 if (usec_delay > USEC) {
127 tv->tv_sec += usec_delay / USEC;
130 tv->tv_usec += usec_delay;
132 if (tv->tv_usec > USEC) {
138 static void remove_from_request_hash(REQUEST *request)
140 if (!request->in_request_hash) return;
142 fr_packet_list_yank(pl, request->packet);
143 request->in_request_hash = FALSE;
145 request_stats_final(request);
150 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
152 RADIUS_PACKET **proxy_p;
155 PTHREAD_MUTEX_LOCK(&proxy_mutex);
156 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
159 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
163 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
166 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
170 request->num_proxied_responses++;
173 * Catch the most common case of everything working
176 if (request->num_proxied_requests == request->num_proxied_responses) {
177 fr_packet_list_yank(proxy_list, request->proxy);
178 fr_packet_list_id_free(proxy_list, request->proxy);
179 request->in_proxy_hash = FALSE;
183 * On the FIRST reply, decrement the count of outstanding
184 * requests. Note that this is NOT the count of sent
185 * packets, but whether or not the home server has
188 if (!request->proxy_reply &&
189 request->home_server &&
190 request->home_server->currently_outstanding) {
191 request->home_server->currently_outstanding--;
194 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
200 static void remove_from_proxy_hash(REQUEST *request)
203 * Check this without grabbing the mutex because it's a
204 * lot faster that way.
206 if (!request->in_proxy_hash) return;
209 * The "not in hash" flag is definitive. However, if the
210 * flag says that it IS in the hash, there might still be
211 * a race condition where it isn't.
213 PTHREAD_MUTEX_LOCK(&proxy_mutex);
215 if (!request->in_proxy_hash) {
216 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
220 fr_packet_list_yank(proxy_list, request->proxy);
221 fr_packet_list_id_free(proxy_list, request->proxy);
224 * The home server hasn't replied, but we've given up on
225 * this request. Don't count this request against the
228 if (!request->proxy_reply &&
229 request->home_server &&
230 request->home_server->currently_outstanding) {
231 request->home_server->currently_outstanding--;
235 * Got from YES in hash, to NO, not in hash while we hold
236 * the mutex. This guarantees that when another thread
237 * grans the mutex, the "not in hash" flag is correct.
239 request->in_proxy_hash = FALSE;
241 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
244 static void ev_request_free(REQUEST **prequest)
248 if (!prequest || !*prequest) return;
255 * Divorce the child from the parent first,
256 * then clean up the child.
258 request->coa->parent = NULL;
259 ev_request_free(&request->coa);
263 * Divorce the parent from the child, and leave the
264 * parent still alive.
266 if (request->parent && (request->parent->coa == request)) {
267 request->parent->coa = NULL;
271 if (request->ev) fr_event_delete(el, &request->ev);
272 if (request->in_proxy_hash) remove_from_proxy_hash(request);
273 if (request->in_request_hash) remove_from_request_hash(request);
275 request_free(prequest);
278 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
281 rad_listen_t *proxy_listener;
283 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
286 * Allocate a new proxy fd. This function adds
287 * it to the tail of the list of listeners. With
288 * some care, this can be thread-safe.
290 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
291 if (!proxy_listener) {
292 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
300 proxy = proxy_listener->fd;
301 for (i = 0; i < 32; i++) {
303 * Found a free entry. Save the socket,
304 * and remember where we saved it.
306 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
307 found = (proxy + i) & 0x1f;
308 proxy_fds[found] = proxy;
309 proxy_listeners[found] = proxy_listener;
313 rad_assert(found >= 0);
315 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
316 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
321 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
322 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
327 * Signal the main thread to add the new FD to the list
330 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
335 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
340 rad_assert(request->proxy != NULL);
341 rad_assert(proxy_list != NULL);
343 PTHREAD_MUTEX_LOCK(&proxy_mutex);
346 * Keep track of maximum outstanding requests to a
347 * particular home server. 'max_outstanding' is
348 * enforced in home_server_ldb(), in realms.c.
350 if (request->home_server) {
351 request->home_server->currently_outstanding++;
355 RADIUS_PACKET packet;
357 packet = *request->proxy;
359 if (!proxy_id_alloc(request, &packet)) {
360 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
365 * Yank the request, free the old Id, and
366 * remember the new Id.
368 fr_packet_list_yank(proxy_list, request->proxy);
369 fr_packet_list_id_free(proxy_list, request->proxy);
370 *request->proxy = packet;
372 } else if (!proxy_id_alloc(request, request->proxy)) {
373 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
377 rad_assert(request->proxy->sockfd >= 0);
380 * FIXME: Hack until we get rid of rad_listen_t, and put
381 * the information into the packet_list.
384 for (i = 0; i < 32; i++) {
385 if (proxy_fds[i] == request->proxy->sockfd) {
392 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
393 RDEBUG2("ERROR: All sockets are full.");
397 rad_assert(proxy_fds[proxy] != -1);
398 rad_assert(proxy_listeners[proxy] != NULL);
399 request->proxy_listener = proxy_listeners[proxy];
401 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
402 fr_packet_list_id_free(proxy_list, request->proxy);
403 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
404 RDEBUG2("ERROR: Failed to insert entry into proxy list");
408 request->in_proxy_hash = TRUE;
410 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
412 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
413 inet_ntop(request->proxy->dst_ipaddr.af,
414 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
415 request->proxy->dst_port,
423 * Called as BOTH an event, and in-line from other functions.
425 static void wait_for_proxy_id_to_expire(void *ctx)
427 REQUEST *request = ctx;
429 rad_assert(request->magic == REQUEST_MAGIC);
430 rad_assert(request->proxy != NULL);
432 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
433 request->when = request->proxy_when;
436 if (((request->proxy->code == PW_COA_REQUEST) ||
437 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
438 (request->packet->code != request->proxy->code)) {
439 request->when.tv_sec += request->home_server->coa_mrd;
442 request->when.tv_sec += request->home_server->response_window;
444 if ((request->num_proxied_requests == request->num_proxied_responses) ||
445 timercmp(&now, &request->when, >)) {
446 if (request->packet) {
447 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
448 request->number, request->packet->id,
449 (unsigned int) (request->timestamp - fr_start_time));
451 RDEBUG2("Cleaning up request %d with timestamp +%d",
453 (unsigned int) (request->timestamp - fr_start_time));
456 ev_request_free(&request);
460 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
464 #ifdef HAVE_PTHREAD_H
465 static void wait_for_child_to_die(void *ctx)
467 REQUEST *request = ctx;
469 rad_assert(request->magic == REQUEST_MAGIC);
471 if ((request->child_state == REQUEST_QUEUED) |
472 (request->child_state == REQUEST_RUNNING)) {
473 request->delay += (request->delay >> 1);
474 tv_add(&request->when, request->delay);
476 RDEBUG2("Child is still stuck for request %d", request->number);
478 INSERT_EVENT(wait_for_child_to_die, request);
482 RDEBUG2("Child is finally responsive for request %d", request->number);
483 remove_from_request_hash(request);
486 if (request->proxy) {
487 wait_for_proxy_id_to_expire(request);
492 ev_request_free(&request);
496 static void cleanup_delay(void *ctx)
498 REQUEST *request = ctx;
500 rad_assert(request->magic == REQUEST_MAGIC);
501 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
502 (request->child_state == REQUEST_DONE));
504 remove_from_request_hash(request);
507 if (request->proxy && request->in_proxy_hash) {
508 wait_for_proxy_id_to_expire(request);
513 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
514 request->number, request->packet->id,
515 (unsigned int) (request->timestamp - fr_start_time));
517 ev_request_free(&request);
522 * In daemon mode, AND this request has debug flags set.
524 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
526 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
530 const char *received, *from;
531 const fr_ipaddr_t *ip;
536 rad_assert(request->radlog != NULL);
538 if (direction == 0) {
539 received = "Received";
540 from = "from"; /* what else? */
541 ip = &packet->src_ipaddr;
542 port = packet->src_port;
545 received = "Sending";
546 from = "to"; /* hah! */
547 ip = &packet->dst_ipaddr;
548 port = packet->dst_port;
552 * Client-specific debugging re-prints the input
553 * packet into the client log.
555 * This really belongs in a utility library
557 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
558 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
559 received, fr_packet_codes[packet->code], from,
560 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
561 port, packet->id, packet->data_len);
563 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
565 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
567 packet->code, packet->id, packet->data_len);
570 for (vp = packet->vps; vp != NULL; vp = vp->next) {
571 vp_prints(buffer, sizeof(buffer), vp);
572 request->radlog(L_DBG, 0, request, "\t%s", buffer);
576 static void reject_delay(void *ctx)
578 REQUEST *request = ctx;
580 rad_assert(request->magic == REQUEST_MAGIC);
581 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
583 RDEBUG2("Sending delayed reject for request %d", request->number);
585 DEBUG_PACKET(request, request->reply, 1);
587 request->listener->send(request->listener, request);
589 request->when.tv_sec += request->root->cleanup_delay;
590 request->child_state = REQUEST_CLEANUP_DELAY;
592 INSERT_EVENT(cleanup_delay, request);
597 void revive_home_server(void *ctx)
599 home_server *home = ctx;
602 home->state = HOME_STATE_ALIVE;
603 home->currently_outstanding = 0;
604 home->revive_time = now;
607 * Delete any outstanding events.
609 if (home->ev) fr_event_delete(el, &home->ev);
611 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
612 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
613 buffer, sizeof(buffer)),
619 static void no_response_to_ping(void *ctx)
621 REQUEST *request = ctx;
625 rad_assert(request->home_server != NULL);
627 home = request->home_server;
628 home->num_received_pings = 0;
630 RDEBUG2("No response to status check %d from home server %s port %d",
632 inet_ntop(request->proxy->dst_ipaddr.af,
633 &request->proxy->dst_ipaddr.ipaddr,
634 buffer, sizeof(buffer)),
635 request->proxy->dst_port);
637 wait_for_proxy_id_to_expire(request);
641 static void received_response_to_ping(REQUEST *request)
646 rad_assert(request->home_server != NULL);
648 home = request->home_server;
649 home->num_received_pings++;
651 RDEBUG2("Received response to status check %d (%d in current sequence)",
652 request->number, home->num_received_pings);
655 * Remove the request from any hashes
657 fr_event_delete(el, &request->ev);
658 remove_from_proxy_hash(request);
659 rad_assert(request->in_request_hash == FALSE);
662 * The control socket may have marked the home server as
663 * alive. OR, it may have suddenly started responding to
664 * requests again. If so, don't re-do the "make alive"
667 if (home->state == HOME_STATE_ALIVE) return;
670 * We haven't received enough ping responses to mark it
671 * "alive". Wait a bit.
673 if (home->num_received_pings < home->num_pings_to_alive) {
677 home->state = HOME_STATE_ALIVE;
678 home->currently_outstanding = 0;
679 home->revive_time = now;
681 if (!fr_event_delete(el, &home->ev)) {
682 RDEBUG2("Hmm... no event for home server. Oh well.");
685 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
686 inet_ntop(request->proxy->dst_ipaddr.af,
687 &request->proxy->dst_ipaddr.ipaddr,
688 buffer, sizeof(buffer)),
689 request->proxy->dst_port);
694 * Called from start of zombie period, OR after control socket
695 * marks the home server dead.
697 static void ping_home_server(void *ctx)
700 home_server *home = ctx;
704 if ((home->state == HOME_STATE_ALIVE) ||
705 (home->ping_check == HOME_PING_CHECK_NONE) ||
706 (home->ev != NULL)) {
710 request = request_alloc();
711 request->number = request_num_counter++;
713 request->proxy = rad_alloc(1);
714 rad_assert(request->proxy != NULL);
716 fr_event_now(el, &request->when);
717 home->when = request->when;
719 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
720 request->proxy->code = PW_STATUS_SERVER;
722 radius_pairmake(request, &request->proxy->vps,
723 "Message-Authenticator", "0x00", T_OP_SET);
725 } else if (home->type == HOME_TYPE_AUTH) {
726 request->proxy->code = PW_AUTHENTICATION_REQUEST;
728 radius_pairmake(request, &request->proxy->vps,
729 "User-Name", home->ping_user_name, T_OP_SET);
730 radius_pairmake(request, &request->proxy->vps,
731 "User-Password", home->ping_user_password, T_OP_SET);
732 radius_pairmake(request, &request->proxy->vps,
733 "Service-Type", "Authenticate-Only", T_OP_SET);
734 radius_pairmake(request, &request->proxy->vps,
735 "Message-Authenticator", "0x00", T_OP_SET);
738 #ifdef WITH_ACCOUNTING
739 request->proxy->code = PW_ACCOUNTING_REQUEST;
741 radius_pairmake(request, &request->proxy->vps,
742 "User-Name", home->ping_user_name, T_OP_SET);
743 radius_pairmake(request, &request->proxy->vps,
744 "Acct-Status-Type", "Stop", T_OP_SET);
745 radius_pairmake(request, &request->proxy->vps,
746 "Acct-Session-Id", "00000000", T_OP_SET);
747 vp = radius_pairmake(request, &request->proxy->vps,
748 "Event-Timestamp", "0", T_OP_SET);
749 vp->vp_date = now.tv_sec;
751 rad_assert("Internal sanity check failed");
755 radius_pairmake(request, &request->proxy->vps,
756 "NAS-Identifier", "Status Check. Are you alive?",
759 request->proxy->dst_ipaddr = home->ipaddr;
760 request->proxy->dst_port = home->port;
761 request->home_server = home;
763 rad_assert(request->proxy_listener == NULL);
765 if (!insert_into_proxy_hash(request, FALSE)) {
766 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
768 ev_request_free(&request);
771 rad_assert(request->proxy_listener != NULL);
772 request->proxy_listener->send(request->proxy_listener,
775 request->next_callback = NULL;
776 request->child_state = REQUEST_PROXIED;
777 request->when.tv_sec += home->ping_timeout;;
779 INSERT_EVENT(no_response_to_ping, request);
782 * Add +/- 2s of jitter, as suggested in RFC 3539
783 * and in the Issues and Fixes draft.
785 home->when.tv_sec += home->ping_interval - 2;
788 jitter ^= (jitter >> 10);
789 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
791 tv_add(&home->when, jitter);
793 INSERT_EVENT(ping_home_server, home);
797 void mark_home_server_dead(home_server *home, struct timeval *when)
799 int previous_state = home->state;
802 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
803 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
804 buffer, sizeof(buffer)),
807 home->state = HOME_STATE_IS_DEAD;
808 home->num_received_pings = 0;
810 if (home->ping_check != HOME_PING_CHECK_NONE) {
812 * If the control socket marks us dead, start
813 * pinging. Otherwise, we already started
814 * pinging when it was marked "zombie".
816 if (previous_state == HOME_STATE_ALIVE) {
817 ping_home_server(home);
822 * Revive it after a fixed period of time. This
823 * is very, very, bad.
826 home->when.tv_sec += home->revive_interval;
828 INSERT_EVENT(revive_home_server, home);
832 static void check_for_zombie_home_server(REQUEST *request)
837 home = request->home_server;
839 if (home->state != HOME_STATE_ZOMBIE) return;
841 when = home->zombie_period_start;
842 when.tv_sec += home->zombie_period;
844 fr_event_now(el, &now);
845 if (timercmp(&now, &when, <)) {
849 mark_home_server_dead(home, &request->when);
852 static int proxy_to_virtual_server(REQUEST *request);
854 static int virtual_server_handler(UNUSED REQUEST *request)
856 proxy_to_virtual_server(request);
860 static void proxy_fallback_handler(REQUEST *request)
863 * A proper time is required for wait_a_bit.
865 request->delay = USEC / 10;
866 gettimeofday(&now, NULL);
867 request->next_when = now;
868 tv_add(&request->next_when, request->delay);
869 request->next_callback = wait_a_bit;
872 * Re-queue the request.
874 request->child_state = REQUEST_QUEUED;
876 rad_assert(request->proxy != NULL);
877 if (!thread_pool_addrequest(request, virtual_server_handler)) {
878 request->child_state = REQUEST_DONE;
881 #ifdef HAVE_PTHREAD_H
883 * MAY free the request if we're over max_request_time,
884 * AND we're not in threaded mode!
886 * Note that we call this ONLY if we're threaded, as
887 * if we're NOT threaded, request_post_handler() calls
888 * wait_a_bit(), which means that "request" may not
891 if (have_children) wait_a_bit(request);
896 static int setup_post_proxy_fail(REQUEST *request)
898 DICT_VALUE *dval = NULL;
901 request->child_state = REQUEST_RUNNING;
903 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
904 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
906 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
907 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
911 * See no_response_to_coa_request
913 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
914 request->packet->code &= 0xff; /* restore it */
916 if (request->proxy->code == PW_COA_REQUEST) {
917 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
919 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
920 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
930 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
933 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
937 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
938 if (!vp) vp = radius_paircreate(request, &request->config_items,
939 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
940 vp->vp_integer = dval->value;
942 rad_assert(request->proxy_reply == NULL);
948 static int null_handler(UNUSED REQUEST *request)
953 static void post_proxy_fail_handler(REQUEST *request)
956 * A proper time is required for wait_a_bit.
958 request->delay = USEC / 10;
959 gettimeofday(&now, NULL);
962 * Not set up to run Post-Proxy-Type = Fail.
964 * Mark the request as still running, and figure out what
967 if (!setup_post_proxy_fail(request)) {
968 request_post_handler(request);
972 * Re-queue the request.
974 request->child_state = REQUEST_QUEUED;
977 * There is a post-proxy-type of fail. We run
978 * the request through the pre/post proxy
979 * handlers, just like it was a real proxied
980 * request. However, we set the per-request
981 * handler to NULL, as we don't want to do
984 * Note that when we're not threaded, this will
985 * process the request even if it's greater than
986 * max_request_time. That's not fatal.
988 request->priority = 0;
989 rad_assert(request->proxy != NULL);
990 thread_pool_addrequest(request, null_handler);
994 * MAY free the request if we're over max_request_time,
995 * AND we're not in threaded mode!
997 * Note that we call this ONLY if we're threaded, as
998 * if we're NOT threaded, request_post_handler() calls
999 * wait_a_bit(), which means that "request" may not
1002 if (have_children) wait_a_bit(request);
1006 /* maybe check this against wait_for_proxy_id_to_expire? */
1007 static void no_response_to_proxied_request(void *ctx)
1009 REQUEST *request = ctx;
1013 rad_assert(request->magic == REQUEST_MAGIC);
1014 rad_assert(request->child_state == REQUEST_PROXIED);
1017 * If we've failed over to an internal home server,
1018 * replace the callback with the correct one. This
1019 * is due to locking issues with child threads...
1021 if (request->home_server->server) {
1022 wait_a_bit(request);
1026 check_for_zombie_home_server(request);
1028 home = request->home_server;
1031 * The default as of 2.1.7 is to allow requests to
1032 * fail-over to a backup home server when this one does
1033 * not respond. The old behavior can be configured as
1036 if (home->no_response_fail) {
1037 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
1039 inet_ntop(request->proxy->dst_ipaddr.af,
1040 &request->proxy->dst_ipaddr.ipaddr,
1041 buffer, sizeof(buffer)),
1042 request->proxy->dst_port);
1044 post_proxy_fail_handler(request);
1048 * Don't touch request due to race conditions
1050 if (home->state == HOME_STATE_IS_DEAD) {
1051 rad_assert(home->ev != NULL); /* or it will never wake up */
1056 * Enable the zombie period when we notice that the home
1057 * server hasn't responded. We do NOT back-date the start
1058 * of the zombie period.
1060 if (home->state == HOME_STATE_ALIVE) {
1061 home->state = HOME_STATE_ZOMBIE;
1062 home->zombie_period_start = now;
1064 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1065 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1066 buffer, sizeof(buffer)),
1070 * Start pinging the home server.
1072 ping_home_server(home);
1077 static void wait_a_bit(void *ctx)
1079 struct timeval when;
1080 REQUEST *request = ctx;
1081 fr_event_callback_t callback = NULL;
1083 rad_assert(request->magic == REQUEST_MAGIC);
1087 * The CoA request is a new (internally generated)
1088 * request, created in a child thread. We therefore need
1089 * some way to tie its events back into the main event
1092 if (request->coa && !request->coa->proxy_reply &&
1093 request->coa->next_callback) {
1094 request->coa->when = request->coa->next_when;
1095 INSERT_EVENT(request->coa->next_callback, request->coa);
1096 request->coa->next_callback = NULL;
1097 request->coa->parent = NULL;
1098 request->coa = NULL;
1102 switch (request->child_state) {
1103 case REQUEST_QUEUED:
1104 case REQUEST_RUNNING:
1105 when = request->received;
1106 when.tv_sec += request->root->max_request_time;
1109 * Normally called from the event loop with the
1110 * proper event loop time. Otherwise, called from
1111 * post proxy fail handler, which sets "now", and
1112 * this call won't re-set it, because we're not
1113 * in the event loop.
1115 fr_event_now(el, &now);
1118 * Request still has more time. Continue
1121 if (timercmp(&now, &when, <) ||
1122 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1123 (request->child_state == REQUEST_QUEUED))) {
1124 if (request->delay < (USEC / 10)) {
1125 request->delay = USEC / 10;
1127 request->delay += request->delay >> 1;
1131 * Cap wait at some sane value for detail
1134 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1135 (request->delay > (request->root->max_request_time * USEC))) {
1136 request->delay = request->root->max_request_time * USEC;
1140 request->when = now;
1141 tv_add(&request->when, request->delay);
1142 callback = wait_a_bit;
1146 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1148 * A child thread MAY still be running on the
1149 * request. Ask the thread to stop working on
1152 if (have_children) {
1153 /* FIXME: kill unresponsive children? */
1156 * Print this error message ONLY if
1157 * there's a child currently processing
1158 * the request. As we don't have thread
1159 * locks here, there may be race
1160 * conditions on this check. But it's
1161 * just an error message, so that's OK.
1163 if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1164 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1166 request->module ? request->module : "<server core>",
1167 request->component ? request->component : "<server core>");
1170 request->master_state = REQUEST_STOP_PROCESSING;
1172 request->delay = USEC / 4;
1173 tv_add(&request->when, request->delay);
1174 callback = wait_for_child_to_die;
1180 * Else there are no child threads. We probably
1181 * should have just marked the request as 'done'
1182 * elsewhere, like in the post-proxy-fail
1183 * handler. But doing that would involve
1184 * checking for max_request_time in multiple
1185 * places, so this may be simplest.
1187 request->child_state = REQUEST_DONE;
1191 * Mark the request as no longer running,
1195 #ifdef HAVE_PTHREAD_H
1196 request->child_pid = NO_SUCH_CHILD_PID;
1201 * This is a CoA request. It's been divorced
1202 * from everything else, so we clean it up now.
1204 if (!request->in_request_hash &&
1206 (request->packet->code != request->proxy->code) &&
1207 ((request->proxy->code == PW_COA_REQUEST) ||
1208 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1210 * FIXME: Do CoA MIBs
1212 ev_request_free(&request);
1216 request_stats_final(request);
1217 cleanup_delay(request);
1220 case REQUEST_REJECT_DELAY:
1221 case REQUEST_CLEANUP_DELAY:
1222 #ifdef HAVE_PTHREAD_H
1223 request->child_pid = NO_SUCH_CHILD_PID;
1225 request_stats_final(request);
1227 case REQUEST_PROXIED:
1228 rad_assert(request->next_callback != NULL);
1229 rad_assert(request->next_callback != wait_a_bit);
1231 request->when = request->next_when;
1232 callback = request->next_callback;
1233 request->next_callback = NULL;
1237 rad_panic("Internal sanity check failure");
1242 * Something major went wrong. Discard the request, and
1245 * FIXME: No idea why this happens or how to fix it...
1246 * It seems to happen *only* when requests are proxied,
1247 * and where the home server doesn't respond. So it looks
1248 * like a race condition above, but it happens in debug
1249 * mode, with no threads...
1252 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1253 ev_request_free(&request);
1257 INSERT_EVENT(callback, request);
1261 static void no_response_to_coa_request(void *ctx)
1263 REQUEST *request = ctx;
1266 rad_assert(request->magic == REQUEST_MAGIC);
1267 rad_assert(request->child_state == REQUEST_PROXIED);
1268 rad_assert(request->home_server != NULL);
1269 rad_assert(!request->in_request_hash);
1271 radlog(L_ERR, "No response to CoA request sent to %s",
1272 inet_ntop(request->proxy->dst_ipaddr.af,
1273 &request->proxy->dst_ipaddr.ipaddr,
1274 buffer, sizeof(buffer)));
1279 request->packet->code |= (PW_COA_REQUEST << 8);
1280 post_proxy_fail_handler(request);
1284 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1288 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1295 packet->data = NULL;
1296 packet->data_len = 0;
1299 return 1; /* time stamp updated */
1304 * Called when we haven't received a response to a CoA request.
1306 static void retransmit_coa_request(void *ctx)
1310 REQUEST *request = ctx;
1312 rad_assert(request->magic == REQUEST_MAGIC);
1313 rad_assert(request->child_state == REQUEST_PROXIED);
1314 rad_assert(request->home_server != NULL);
1315 rad_assert(!request->in_request_hash);
1316 rad_assert(request->parent == NULL);
1318 fr_event_now(el, &now);
1321 * Cap count at MRC, if it is non-zero.
1323 if (request->home_server->coa_mrc &&
1324 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1325 no_response_to_coa_request(request);
1330 * RFC 5080 Section 2.2.1
1332 * RT = 2*RTprev + RAND*RTprev
1333 * = 1.9 * RTprev + rand(0,.2) * RTprev
1334 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1337 delay ^= (delay >> 16);
1339 frac = request->delay / 5;
1340 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1342 delay += (2 * request->delay) - (request->delay / 10);
1345 * Cap delay at MRT, if MRT is non-zero.
1347 if (request->home_server->coa_mrt &&
1348 (delay > (request->home_server->coa_mrt * USEC))) {
1349 int mrt_usec = request->home_server->coa_mrt * USEC;
1352 * delay = MRT + RAND * MRT
1353 * = 0.9 MRT + rand(0,.2) * MRT
1356 delay ^= (delay >> 15);
1358 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1359 delay += mrt_usec - (mrt_usec / 10);
1362 request->delay = delay;
1363 request->when = now;
1364 tv_add(&request->when, request->delay);
1365 mrd = request->proxy_when;
1366 mrd.tv_sec += request->home_server->coa_mrd;
1369 * Cap duration at MRD.
1371 if (timercmp(&mrd, &request->when, <)) {
1372 request->when = mrd;
1373 INSERT_EVENT(no_response_to_coa_request, request);
1376 INSERT_EVENT(retransmit_coa_request, request);
1379 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1380 if (!insert_into_proxy_hash(request, TRUE)) {
1381 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1385 request->num_proxied_requests = 0;
1386 request->num_proxied_responses = 0;
1389 request->num_proxied_requests++;
1390 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1392 request->proxy_listener->send(request->proxy_listener,
1398 * The original request is either DONE, or in CLEANUP_DELAY.
1400 static int originated_coa_request(REQUEST *request)
1402 int delay, rcode, pre_proxy_type = 0;
1408 rad_assert(request->proxy == NULL);
1409 rad_assert(!request->in_proxy_hash);
1410 rad_assert(request->proxy_reply == NULL);
1412 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1413 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1415 if (vp->vp_integer == 0) {
1416 ev_request_free(&request->coa);
1417 return 1; /* success */
1420 if (!request->coa) request_alloc_coa(request);
1421 if (!request->coa) return 0;
1427 * src_ipaddr will be set up in proxy_encode.
1429 memset(&ipaddr, 0, sizeof(ipaddr));
1430 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1432 ipaddr.af = AF_INET;
1433 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1435 } else if ((vp = pairfind(coa->proxy->vps,
1436 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1437 ipaddr.af = AF_INET6;
1438 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1440 } else if ((vp = pairfind(coa->proxy->vps,
1441 PW_HOME_SERVER_POOL)) != NULL) {
1442 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1444 if (!coa->home_pool) {
1445 RDEBUG2("WARNING: No such home_server_pool %s",
1448 ev_request_free(&request->coa);
1455 } else if (request->client->coa_pool) {
1456 coa->home_pool = request->client->coa_pool;
1458 } else if (request->client->coa_server) {
1459 coa->home_server = request->client->coa_server;
1463 * If all else fails, send it to the client that
1464 * originated this request.
1466 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1470 * Use the pool, if it exists.
1472 if (coa->home_pool) {
1473 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1474 if (!coa->home_server) {
1475 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1479 } else if (!coa->home_server) {
1480 int port = PW_COA_UDP_PORT;
1482 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1483 if (vp) port = vp->vp_integer;
1485 coa->home_server = home_server_find(&ipaddr, port);
1486 if (!coa->home_server) {
1487 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1488 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1489 buffer, sizeof(buffer)), port);
1494 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1496 switch (vp->vp_integer) {
1497 case PW_COA_REQUEST:
1498 case PW_DISCONNECT_REQUEST:
1499 coa->proxy->code = vp->vp_integer;
1503 DEBUG("Cannot set CoA Packet-Type to code %d",
1509 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1512 * The rest of the server code assumes that
1513 * request->packet && request->reply exist. Copy them
1514 * from the original request.
1516 rad_assert(coa->packet != NULL);
1517 rad_assert(coa->packet->vps == NULL);
1518 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1519 coa->packet->vps = paircopy(request->packet->vps);
1520 coa->packet->data = NULL;
1521 rad_assert(coa->reply != NULL);
1522 rad_assert(coa->reply->vps == NULL);
1523 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1524 coa->reply->vps = paircopy(request->reply->vps);
1525 coa->reply->data = NULL;
1526 coa->config_items = paircopy(request->config_items);
1529 * Call the pre-proxy routines.
1531 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1533 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1534 pre_proxy_type = vp->vp_integer;
1537 if (coa->home_pool && coa->home_pool->virtual_server) {
1538 const char *old_server = coa->server;
1540 coa->server = coa->home_pool->virtual_server;
1541 RDEBUG2(" server %s {", coa->server);
1542 rcode = module_pre_proxy(pre_proxy_type, coa);
1544 coa->server = old_server;
1546 rcode = module_pre_proxy(pre_proxy_type, coa);
1553 * Only send the CoA packet if the pre-proxy code succeeded.
1555 case RLM_MODULE_NOOP:
1557 case RLM_MODULE_UPDATED:
1562 * Source IP / port is set when the proxy socket
1565 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1566 coa->proxy->dst_port = coa->home_server->port;
1568 if (!insert_into_proxy_hash(coa, FALSE)) {
1569 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1574 * We CANNOT divorce the CoA request from the parent
1575 * request. This function is running in a child thread,
1576 * and we need access to the main event loop in order to
1577 * to add the timers for the CoA packet. See
1582 * Forget about the original request completely at this
1587 gettimeofday(&request->proxy_when, NULL);
1588 request->received = request->next_when = request->proxy_when;
1589 rad_assert(request->proxy_reply == NULL);
1592 * Implement re-transmit algorithm as per RFC 5080
1595 * We want IRT + RAND*IRT
1596 * or 0.9 IRT + rand(0,.2) IRT
1598 * 2^20 ~ USEC, and we want 2.
1599 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1601 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1602 request->delay = delay * request->home_server->coa_irt;
1603 delay = request->home_server->coa_irt * USEC;
1604 delay -= delay / 10;
1605 delay += request->delay;
1607 request->delay = delay;
1608 tv_add(&request->next_when, delay);
1609 request->next_callback = retransmit_coa_request;
1612 * Note that we set proxied BEFORE sending the packet.
1614 * Once we send it, the request is tainted, as
1615 * another thread may have picked it up. Don't
1618 request->num_proxied_requests = 1;
1619 request->num_proxied_responses = 0;
1620 request->child_pid = NO_SUCH_CHILD_PID;
1622 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1624 request->child_state = REQUEST_PROXIED;
1626 DEBUG_PACKET(request, request->proxy, 1);
1628 request->proxy_listener->send(request->proxy_listener,
1632 #endif /* WITH_COA */
1635 static int process_proxy_reply(REQUEST *request)
1638 int post_proxy_type = 0;
1642 * Delete any reply we had accumulated until now.
1644 pairfree(&request->reply->vps);
1647 * Run the packet through the post-proxy stage,
1648 * BEFORE playing games with the attributes.
1650 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1652 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1653 post_proxy_type = vp->vp_integer;
1656 if (request->home_pool && request->home_pool->virtual_server) {
1657 const char *old_server = request->server;
1659 request->server = request->home_pool->virtual_server;
1660 RDEBUG2(" server %s {", request->server);
1661 rcode = module_post_proxy(post_proxy_type, request);
1663 request->server = old_server;
1665 rcode = module_post_proxy(post_proxy_type, request);
1669 if (request->packet->code == request->proxy->code)
1671 * Don't run the next bit if we originated a CoA
1672 * packet, after receiving an Access-Request or
1673 * Accounting-Request.
1678 * There may NOT be a proxy reply, as we may be
1679 * running Post-Proxy-Type = Fail.
1681 if (request->proxy_reply) {
1683 * Delete the Proxy-State Attributes from
1684 * the reply. These include Proxy-State
1685 * attributes from us and remote server.
1687 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1690 * Add the attributes left in the proxy
1691 * reply to the reply list.
1693 pairadd(&request->reply->vps, request->proxy_reply->vps);
1694 request->proxy_reply->vps = NULL;
1697 * Free proxy request pairs.
1699 pairfree(&request->proxy->vps);
1703 default: /* Don't do anything */
1705 case RLM_MODULE_FAIL:
1706 /* FIXME: debug print stuff */
1707 request->child_state = REQUEST_DONE;
1710 case RLM_MODULE_HANDLED:
1711 /* FIXME: debug print stuff */
1712 request->child_state = REQUEST_DONE;
1720 static int request_pre_handler(REQUEST *request)
1724 rad_assert(request->magic == REQUEST_MAGIC);
1725 rad_assert(request->packet != NULL);
1727 request->child_state = REQUEST_RUNNING;
1730 * Don't decode the packet if it's an internal "fake"
1731 * request. Instead, just return so that the caller can
1734 if (request->packet->dst_port == 0) {
1735 request->username = pairfind(request->packet->vps,
1737 request->password = pairfind(request->packet->vps,
1744 * Put the decoded packet into it's proper place.
1746 if (request->proxy_reply != NULL) {
1747 rcode = request->proxy_listener->decode(request->proxy_listener,
1749 DEBUG_PACKET(request, request->proxy_reply, 0);
1752 if (request->packet->vps == NULL) {
1753 rcode = request->listener->decode(request->listener, request);
1755 if (debug_condition) {
1757 const char *my_debug = debug_condition;
1760 * Ignore parse errors.
1762 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1766 request->options = 2;
1767 request->radlog = radlog_request;
1771 DEBUG_PACKET(request, request->packet, 0);
1777 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1778 request->child_state = REQUEST_DONE;
1782 if (!request->username) {
1783 request->username = pairfind(request->packet->vps,
1788 if (request->proxy) {
1789 return process_proxy_reply(request);
1799 * Do state handling when we proxy a request.
1801 static int proxy_request(REQUEST *request)
1803 struct timeval when;
1806 if (request->home_server->server) {
1807 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1811 if (!insert_into_proxy_hash(request, FALSE)) {
1812 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1816 request->proxy_listener->encode(request->proxy_listener, request);
1818 when = request->received;
1819 when.tv_sec += request->root->max_request_time;
1821 gettimeofday(&request->proxy_when, NULL);
1823 request->next_when = request->proxy_when;
1824 request->next_when.tv_sec += request->home_server->response_window;
1826 rad_assert(request->home_server->response_window > 0);
1828 if (timercmp(&when, &request->next_when, <)) {
1829 request->next_when = when;
1831 request->next_callback = no_response_to_proxied_request;
1833 RDEBUG2("Proxying request %d to home server %s port %d",
1835 inet_ntop(request->proxy->dst_ipaddr.af,
1836 &request->proxy->dst_ipaddr.ipaddr,
1837 buffer, sizeof(buffer)),
1838 request->proxy->dst_port);
1841 * Note that we set proxied BEFORE sending the packet.
1843 * Once we send it, the request is tainted, as
1844 * another thread may have picked it up. Don't
1847 request->num_proxied_requests = 1;
1848 request->num_proxied_responses = 0;
1849 #ifdef HAVE_PTHREAD_H
1850 request->child_pid = NO_SUCH_CHILD_PID;
1852 request->child_state = REQUEST_PROXIED;
1854 DEBUG_PACKET(request, request->proxy, 1);
1856 request->proxy_listener->send(request->proxy_listener,
1863 * "Proxy" the request by sending it to a new virtual server.
1865 static int proxy_to_virtual_server(REQUEST *request)
1868 RAD_REQUEST_FUNP fun;
1870 if (!request->home_server || !request->home_server->server) return 0;
1872 if (request->parent) {
1873 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1877 fake = request_alloc_fake(request);
1879 RDEBUG2("WARNING: Out of memory");
1883 fake->packet->vps = paircopy(request->proxy->vps);
1884 fake->server = request->home_server->server;
1886 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1887 fun = rad_authenticate;
1889 #ifdef WITH_ACCOUNTING
1890 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1891 fun = rad_accounting;
1895 RDEBUG2("Unknown packet type %d", request->proxy->code);
1896 ev_request_free(&fake);
1900 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1901 radius_handle_request(fake, fun);
1902 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1904 if (fake->reply->code != 0) {
1905 request->proxy_reply = fake->reply;
1909 * There was no response
1911 setup_post_proxy_fail(request);
1914 ev_request_free(&fake);
1916 process_proxy_reply(request);
1919 * Process it through the normal section again, but ONLY
1920 * if we received a proxy reply..
1922 if (request->proxy_reply) {
1923 if (request->server) RDEBUG("server %s {",
1924 request->server != NULL ?
1925 request->server : "");
1928 if (request->server) RDEBUG("} # server %s",
1929 request->server != NULL ?
1930 request->server : "");
1933 return 2; /* success, but NOT '1' !*/
1937 * Return 1 if we did proxy it, or the proxy attempt failed
1938 * completely. Either way, the caller doesn't touch the request
1939 * any more if we return 1.
1941 static int successfully_proxied_request(REQUEST *request)
1944 int pre_proxy_type = 0;
1945 VALUE_PAIR *realmpair;
1946 VALUE_PAIR *strippedname;
1948 char *realmname = NULL;
1950 REALM *realm = NULL;
1954 * If it was already proxied, do nothing.
1956 * FIXME: This should really be a serious error.
1958 if (request->in_proxy_hash ||
1959 (request->proxy_reply && (request->proxy_reply->code != 0))) {
1963 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1964 if (!realmpair || (realmpair->length == 0)) {
1967 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
1970 switch (request->packet->code) {
1971 case PW_AUTHENTICATION_REQUEST:
1972 pool_type = HOME_TYPE_AUTH;
1975 #ifdef WITH_ACCOUNTING
1976 case PW_ACCOUNTING_REQUEST:
1977 pool_type = HOME_TYPE_ACCT;
1982 case PW_COA_REQUEST:
1983 case PW_DISCONNECT_REQUEST:
1984 pool_type = HOME_TYPE_COA;
1992 pool = home_pool_byname(vp->vp_strvalue, pool_type);
1994 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
1999 realmname = NULL; /* no realms */
2004 realmname = (char *) realmpair->vp_strvalue;
2006 realm = realm_find2(realmname);
2008 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2013 * Figure out which pool to use.
2015 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2016 pool = realm->auth_pool;
2018 #ifdef WITH_ACCOUNTING
2019 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2020 pool = realm->acct_pool;
2024 } else if ((request->packet->code == PW_COA_REQUEST) ||
2025 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2026 pool = realm->acct_pool;
2030 rad_panic("Internal sanity check failed");
2034 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2040 home = home_server_ldb(realmname, pool, request);
2042 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2046 request->home_pool = pool;
2050 * Once we've decided to proxy a request, we cannot send
2051 * a CoA packet. So we free up any CoA packet here.
2053 ev_request_free(&request->coa);
2056 * Remember that we sent the request to a Realm.
2058 if (realmname) pairadd(&request->packet->vps,
2059 pairmake("Realm", realmname, T_OP_EQ));
2062 * Strip the name, if told to.
2064 * Doing it here catches the case of proxied tunneled
2067 if (realm && (realm->striprealm == TRUE) &&
2068 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2070 * If there's a Stripped-User-Name attribute in
2071 * the request, then use THAT as the User-Name
2072 * for the proxied request, instead of the
2075 * This is done by making a copy of the
2076 * Stripped-User-Name attribute, turning it into
2077 * a User-Name attribute, deleting the
2078 * Stripped-User-Name and User-Name attributes
2079 * from the vps list, and making the new
2080 * User-Name the head of the vps list.
2082 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2084 vp = radius_paircreate(request, NULL,
2085 PW_USER_NAME, PW_TYPE_STRING);
2086 rad_assert(vp != NULL); /* handled by above function */
2087 /* Insert at the START of the list */
2088 vp->next = request->proxy->vps;
2089 request->proxy->vps = vp;
2091 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2092 sizeof(vp->vp_strvalue));
2093 vp->length = strippedname->length;
2096 * Do NOT delete Stripped-User-Name.
2101 * If there is no PW_CHAP_CHALLENGE attribute but
2102 * there is a PW_CHAP_PASSWORD we need to add it
2103 * since we can't use the request authenticator
2104 * anymore - we changed it.
2106 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2107 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2108 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2109 vp = radius_paircreate(request, &request->proxy->vps,
2110 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2111 vp->length = AUTH_VECTOR_LEN;
2112 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2116 * The RFC's say we have to do this, but FreeRADIUS
2119 vp = radius_paircreate(request, &request->proxy->vps,
2120 PW_PROXY_STATE, PW_TYPE_OCTETS);
2121 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2122 request->packet->id);
2123 vp->length = strlen(vp->vp_strvalue);
2126 * Should be done BEFORE inserting into proxy hash, as
2127 * pre-proxy may use this information, or change it.
2129 request->proxy->code = request->packet->code;
2132 * Call the pre-proxy routines.
2134 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2136 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2137 pre_proxy_type = vp->vp_integer;
2140 rad_assert(request->home_pool != NULL);
2142 if (request->home_pool->virtual_server) {
2143 const char *old_server = request->server;
2145 request->server = request->home_pool->virtual_server;
2146 RDEBUG2(" server %s {", request->server);
2147 rcode = module_pre_proxy(pre_proxy_type, request);
2149 request->server = old_server;
2151 rcode = module_pre_proxy(pre_proxy_type, request);
2154 case RLM_MODULE_FAIL:
2155 case RLM_MODULE_INVALID:
2156 case RLM_MODULE_NOTFOUND:
2157 case RLM_MODULE_USERLOCK:
2159 /* FIXME: debug print failed stuff */
2162 case RLM_MODULE_REJECT:
2163 case RLM_MODULE_HANDLED:
2167 * Only proxy the packet if the pre-proxy code succeeded.
2169 case RLM_MODULE_NOOP:
2171 case RLM_MODULE_UPDATED:
2176 * If it's a fake request, don't send the proxy
2177 * packet. The outer tunnel session will take
2178 * care of doing that.
2180 if (request->packet->dst_port == 0) {
2181 request->home_server = NULL;
2185 if (request->home_server->server) {
2186 return proxy_to_virtual_server(request);
2189 if (!proxy_request(request)) {
2190 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2198 static void request_post_handler(REQUEST *request)
2200 int child_state = -1;
2201 struct timeval when;
2204 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2206 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2207 RDEBUG2("Request %d was cancelled.", request->number);
2208 #ifdef HAVE_PTHREAD_H
2209 request->child_pid = NO_SUCH_CHILD_PID;
2211 child_state = REQUEST_DONE;
2215 if (request->child_state != REQUEST_RUNNING) {
2216 rad_panic("Internal sanity check failed");
2221 * If it's not in the request hash, it's a CoA request.
2224 if (!request->in_request_hash &&
2226 ((request->proxy->code == PW_COA_REQUEST) ||
2227 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2228 request->next_callback = NULL;
2229 child_state = REQUEST_DONE;
2235 * Catch Auth-Type := Reject BEFORE proxying the packet.
2237 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2238 (request->reply->code == 0) &&
2239 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2240 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2241 request->reply->code = PW_AUTHENTICATION_REJECT;
2245 if (request->root->proxy_requests &&
2246 !request->in_proxy_hash &&
2247 (request->reply->code == 0) &&
2248 (request->packet->dst_port != 0) &&
2249 (request->packet->code != PW_STATUS_SERVER)) {
2250 int rcode = successfully_proxied_request(request);
2252 if (rcode == 1) return; /* request is invalid */
2255 * Failed proxying it (dead home servers, etc.)
2256 * Run it through Post-Proxy-Type = Fail, and
2257 * respond to the request.
2259 * Note that we're in a child thread here, so we
2260 * do NOT re-schedule the request. Instead, we
2261 * do what we would have done, which is run the
2262 * pre-handler, a NULL request handler, and then
2265 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2266 request_pre_handler(request);
2270 * Else we weren't supposed to proxy it,
2271 * OR we proxied it internally to a virutal server.
2277 * Fake requests don't get encoded or signed. The caller
2278 * also requires the reply VP's, so we don't free them
2281 if (request->packet->dst_port == 0) {
2282 /* FIXME: RDEBUG going to the next request */
2283 #ifdef HAVE_PTHREAD_H
2284 request->child_pid = NO_SUCH_CHILD_PID;
2286 request->child_state = REQUEST_DONE;
2292 * Copy Proxy-State from the request to the reply.
2294 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2295 if (vp) pairadd(&request->reply->vps, vp);
2299 * Access-Requests get delayed or cached.
2301 switch (request->packet->code) {
2302 case PW_AUTHENTICATION_REQUEST:
2303 gettimeofday(&request->next_when, NULL);
2305 if (request->reply->code == 0) {
2307 * Check if the lack of response is intentional.
2309 vp = pairfind(request->config_items,
2310 PW_RESPONSE_PACKET_TYPE);
2312 RDEBUG2("There was no response configured: rejecting request %d",
2314 request->reply->code = PW_AUTHENTICATION_REJECT;
2316 } else if (vp->vp_integer == 256) {
2317 RDEBUG2("Not responding to request %d",
2321 * Force cleanup after a long
2322 * time, so that we don't
2323 * re-process the packet.
2325 request->next_when.tv_sec += request->root->max_request_time;
2326 request->next_callback = cleanup_delay;
2327 child_state = REQUEST_CLEANUP_DELAY;
2330 request->reply->code = vp->vp_integer;
2336 * Run rejected packets through
2338 * Post-Auth-Type = Reject
2340 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2341 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2342 vp = radius_pairmake(request, &request->config_items,
2343 "Post-Auth-Type", "Reject",
2345 if (vp) rad_postauth(request);
2348 * If configured, delay Access-Reject packets.
2350 * If request->root->reject_delay = 0, we discover
2351 * that we have to send the packet now.
2353 when = request->received;
2354 when.tv_sec += request->root->reject_delay;
2356 if (timercmp(&when, &request->next_when, >)) {
2357 RDEBUG2("Delaying reject of request %d for %d seconds",
2359 request->root->reject_delay);
2360 request->next_when = when;
2361 request->next_callback = reject_delay;
2362 #ifdef HAVE_PTHREAD_H
2363 request->child_pid = NO_SUCH_CHILD_PID;
2365 request->child_state = REQUEST_REJECT_DELAY;
2371 case PW_COA_REQUEST:
2372 case PW_DISCONNECT_REQUEST:
2374 request->next_when.tv_sec += request->root->cleanup_delay;
2375 request->next_callback = cleanup_delay;
2376 child_state = REQUEST_CLEANUP_DELAY;
2379 case PW_ACCOUNTING_REQUEST:
2380 request->next_callback = NULL; /* just to be safe */
2381 child_state = REQUEST_DONE;
2385 * FIXME: Status-Server should probably not be
2388 case PW_STATUS_SERVER:
2389 request->next_callback = NULL;
2390 child_state = REQUEST_DONE;
2397 request->next_callback = NULL;
2398 child_state = REQUEST_DONE;
2403 * Suppress "no reply" packets here, unless we're reading
2404 * from the "detail" file. In that case, we've got to
2405 * tell the detail file handler that the request is dead,
2406 * and it should re-send it.
2407 * If configured, encode, sign, and send.
2409 if ((request->reply->code != 0) ||
2410 (request->listener->type == RAD_LISTEN_DETAIL)) {
2411 DEBUG_PACKET(request, request->reply, 1);
2412 request->listener->send(request->listener, request);
2417 * Now that we've completely processed the request,
2418 * see if we need to originate a CoA request.
2421 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2422 if (!originated_coa_request(request)) {
2423 RDEBUG2("Do CoA Fail handler here");
2425 /* request->coa is stil set, so we can update events */
2431 * Clean up. These are no longer needed.
2433 pairfree(&request->config_items);
2435 pairfree(&request->packet->vps);
2436 request->username = NULL;
2437 request->password = NULL;
2439 pairfree(&request->reply->vps);
2442 if (request->proxy) {
2443 pairfree(&request->proxy->vps);
2445 if (request->proxy_reply) {
2446 pairfree(&request->proxy_reply->vps);
2451 * We're not tracking responses from the home
2452 * server, we can therefore free this memory in
2455 if (!request->in_proxy_hash) {
2456 rad_free(&request->proxy);
2457 rad_free(&request->proxy_reply);
2458 request->home_server = NULL;
2464 RDEBUG2("Finished request %d.", request->number);
2465 rad_assert(child_state >= 0);
2466 request->child_state = child_state;
2469 * Single threaded mode: update timers now.
2471 if (!have_children) wait_a_bit(request);
2475 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2481 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2482 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2484 switch (request->child_state) {
2485 case REQUEST_QUEUED:
2486 case REQUEST_RUNNING:
2490 radlog(L_ERR, "Discarding duplicate request from "
2491 "client %s port %d - ID: %d due to unfinished request %d",
2493 request->packet->src_port,request->packet->id,
2498 case REQUEST_PROXIED:
2500 * We're not supposed to have duplicate
2501 * accounting packets. The other states handle
2502 * duplicates fine (discard, or send duplicate
2503 * reply). But we do NOT want to retransmit an
2504 * accounting request here, because that would
2505 * involve updating the Acct-Delay-Time, and
2506 * therefore changing the packet Id, etc.
2508 * Instead, we just discard the packet. We may
2509 * eventually respond, or the client will send a
2510 * new accounting packet.
2512 * The same comments go for Status-Server, and
2513 * other packet types.
2515 * FIXME: coa: when we proxy CoA && Disconnect
2516 * packets, this logic has to be fixed.
2518 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2522 check_for_zombie_home_server(request);
2525 * If we've just discovered that the home server is
2526 * dead, send the packet to another one.
2528 if ((request->packet->dst_port != 0) &&
2529 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2532 remove_from_proxy_hash(request);
2534 home = home_server_ldb(NULL, request->home_pool, request);
2536 RDEBUG2("Failed to find live home server for request %d", request->number);
2539 * Do post-request processing,
2540 * and any insertion of necessary
2543 post_proxy_fail_handler(request);
2547 request->proxy->code = request->packet->code;
2550 * Free the old packet, to force re-encoding
2552 free(request->proxy->data);
2553 request->proxy->data = NULL;
2554 request->proxy->data_len = 0;
2557 * This request failed over to a virtual
2558 * server. Push it back onto the queue
2561 if (request->home_server->server) {
2562 proxy_fallback_handler(request);
2567 * Try to proxy the request.
2569 if (!proxy_request(request)) {
2570 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2571 goto no_home_servers;
2575 * This code executes in the main server
2576 * thread, so there's no need for locking.
2578 rad_assert(request->next_callback != NULL);
2579 INSERT_EVENT(request->next_callback, request);
2580 request->next_callback = NULL;
2582 } /* else the home server is still alive */
2584 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2585 inet_ntop(request->proxy->dst_ipaddr.af,
2586 &request->proxy->dst_ipaddr.ipaddr,
2587 buffer, sizeof(buffer)),
2588 request->proxy->dst_port,
2589 request->proxy->id);
2590 request->num_proxied_requests++;
2592 DEBUG_PACKET(request, request->proxy, 1);
2593 request->proxy_listener->send(request->proxy_listener,
2598 case REQUEST_REJECT_DELAY:
2599 RDEBUG2("Waiting to send Access-Reject "
2600 "to client %s port %d - ID: %d",
2602 request->packet->src_port, request->packet->id);
2605 case REQUEST_CLEANUP_DELAY:
2607 if (request->reply->code == 0) {
2608 RDEBUG2("Ignoring retransmit from client %s port %d "
2609 "- ID: %d, no reply was configured",
2611 request->packet->src_port, request->packet->id);
2616 * FIXME: This sends duplicate replies to
2617 * accounting requests, even if Acct-Delay-Time
2618 * or Event-Timestamp is in the packet. In those
2619 * cases, the Id should be changed, and the packet
2622 RDEBUG2("Sending duplicate reply "
2623 "to client %s port %d - ID: %d",
2625 request->packet->src_port, request->packet->id);
2626 DEBUG_PACKET(request, request->reply, 1);
2627 request->listener->send(request->listener, request);
2633 static void received_conflicting_request(REQUEST *request,
2634 const RADCLIENT *client)
2636 radlog(L_ERR, "Received conflicting packet from "
2637 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2639 request->packet->src_port, request->packet->id,
2643 * Nuke it from the request hash, so we can receive new
2646 remove_from_request_hash(request);
2648 switch (request->child_state) {
2649 #ifdef HAVE_PTHREAD_H
2651 * It's queued or running. Tell it to stop, and
2652 * wait for it to do so.
2654 case REQUEST_QUEUED:
2655 case REQUEST_RUNNING:
2656 request->master_state = REQUEST_STOP_PROCESSING;
2657 request->delay += request->delay >> 1;
2659 tv_add(&request->when, request->delay);
2661 INSERT_EVENT(wait_for_child_to_die, request);
2666 * Catch race conditions. It may have switched
2667 * from running to done while this code is being
2670 case REQUEST_REJECT_DELAY:
2671 case REQUEST_CLEANUP_DELAY:
2676 * It's in some other state, and therefore also
2677 * in the event queue. At some point, the
2678 * child will notice, and we can then delete it.
2680 case REQUEST_PROXIED:
2682 rad_assert(request->ev != NULL);
2688 static int can_handle_new_request(RADIUS_PACKET *packet,
2690 struct main_config_t *root)
2693 * Count the total number of requests, to see if
2694 * there are too many. If so, return with an
2697 if (root->max_requests) {
2698 int request_count = fr_packet_list_num_elements(pl);
2701 * This is a new request. Let's see if
2702 * it makes us go over our configured
2705 if (request_count > root->max_requests) {
2706 radlog(L_ERR, "Dropping request (%d is too many): "
2707 "from client %s port %d - ID: %d", request_count,
2709 packet->src_port, packet->id);
2710 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2711 "\tThe value for 'max_requests' is probably set too low.\n");
2713 } /* else there were a small number of requests */
2714 } /* else there was no configured limit for requests */
2717 * FIXME: Add per-client checks. If one client is sending
2718 * too many packets, start discarding them.
2720 * We increment the counters here, and decrement them
2721 * when the response is sent... somewhere in this file.
2725 * FUTURE: Add checks for system load. If the system is
2726 * busy, start dropping requests...
2728 * We can probably keep some statistics ourselves... if
2729 * there are more requests coming in than we can handle,
2730 * start dropping some.
2737 int received_request(rad_listen_t *listener,
2738 RADIUS_PACKET *packet, REQUEST **prequest,
2741 RADIUS_PACKET **packet_p;
2742 REQUEST *request = NULL;
2743 struct main_config_t *root = &mainconfig;
2745 packet_p = fr_packet_list_find(pl, packet);
2747 request = fr_packet2myptr(REQUEST, packet, packet_p);
2748 rad_assert(request->in_request_hash);
2750 if ((request->packet->data_len == packet->data_len) &&
2751 (memcmp(request->packet->vector, packet->vector,
2752 sizeof(packet->vector)) == 0)) {
2753 received_retransmit(request, client);
2758 * The new request is different from the old one,
2759 * but maybe the old is finished. If so, delete
2762 switch (request->child_state) {
2763 struct timeval when;
2767 * Special hacks for race conditions.
2768 * The reply is encoded, and therefore
2769 * likely sent. We received a *new*
2770 * packet from the client, likely before
2771 * the next line or two of code which
2772 * updated the child state. In this
2773 * case, just accept the new request.
2775 if ((request->reply->code != 0) &&
2776 request->reply->data) {
2777 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2779 packet->src_port, packet->id,
2781 remove_from_request_hash(request);
2786 gettimeofday(&when, NULL);
2790 * If the cached request was received
2791 * within the last second, then we
2792 * discard the NEW request instead of the
2793 * old one. This will happen ONLY when
2794 * the client is severely broken, and is
2795 * sending conflicting packets very
2798 if (timercmp(&when, &request->received, <)) {
2799 radlog(L_ERR, "Discarding conflicting packet from "
2800 "client %s port %d - ID: %d due to recent request %d.",
2802 packet->src_port, packet->id,
2807 received_conflicting_request(request, client);
2811 case REQUEST_REJECT_DELAY:
2812 case REQUEST_CLEANUP_DELAY:
2813 request->child_state = REQUEST_DONE;
2815 cleanup_delay(request);
2822 * We may want to quench the new request.
2824 if ((listener->type != RAD_LISTEN_DETAIL) &&
2825 !can_handle_new_request(packet, client, root)) {
2830 * Create and initialize the new request.
2832 request = request_alloc(); /* never fails */
2834 if ((request->reply = rad_alloc(0)) == NULL) {
2835 radlog(L_ERR, "No memory");
2839 request->listener = listener;
2840 request->client = client;
2841 request->packet = packet;
2842 request->packet->timestamp = request->timestamp;
2843 request->number = request_num_counter++;
2844 request->priority = listener->type;
2845 #ifdef HAVE_PTHREAD_H
2846 request->child_pid = NO_SUCH_CHILD_PID;
2850 * Status-Server packets go to the head of the queue.
2852 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2855 * Set virtual server identity
2857 if (client->server) {
2858 request->server = client->server;
2859 } else if (listener->server) {
2860 request->server = listener->server;
2862 request->server = NULL;
2866 * Remember the request in the list.
2868 if (!fr_packet_list_insert(pl, &request->packet)) {
2869 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2870 ev_request_free(&request);
2874 request->in_request_hash = TRUE;
2875 request->root = root;
2879 * The request passes many of our sanity checks.
2880 * From here on in, if anything goes wrong, we
2881 * send a reject message, instead of dropping the
2886 * Build the reply template from the request.
2889 request->reply->sockfd = request->packet->sockfd;
2890 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2891 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2892 request->reply->dst_port = request->packet->src_port;
2893 request->reply->src_port = request->packet->dst_port;
2894 request->reply->id = request->packet->id;
2895 request->reply->code = 0; /* UNKNOWN code */
2896 memcpy(request->reply->vector, request->packet->vector,
2897 sizeof(request->reply->vector));
2898 request->reply->vps = NULL;
2899 request->reply->data = NULL;
2900 request->reply->data_len = 0;
2902 request->master_state = REQUEST_ACTIVE;
2903 request->child_state = REQUEST_QUEUED;
2904 request->next_callback = NULL;
2906 gettimeofday(&request->received, NULL);
2907 request->timestamp = request->received.tv_sec;
2908 request->when = request->received;
2910 request->delay = USEC;
2912 tv_add(&request->when, request->delay);
2914 INSERT_EVENT(wait_a_bit, request);
2916 *prequest = request;
2922 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2928 * Also removes from the proxy hash if responses == requests
2930 request = lookup_in_proxy_hash(packet);
2933 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2934 inet_ntop(packet->src_ipaddr.af,
2935 &packet->src_ipaddr.ipaddr,
2936 buffer, sizeof(buffer)),
2937 packet->src_port, packet->id);
2942 * We haven't replied to the NAS, but we have seen an
2943 * earlier reply from the home server. Ignore this packet,
2944 * as we're likely still processing the previous reply.
2946 if (request->proxy_reply) {
2947 if (memcmp(request->proxy_reply->vector,
2949 sizeof(request->proxy_reply->vector)) == 0) {
2950 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2951 inet_ntop(packet->src_ipaddr.af,
2952 &packet->src_ipaddr.ipaddr,
2953 buffer, sizeof(buffer)),
2954 packet->src_port, packet->id,
2958 * ? The home server gave us a new proxy
2959 * reply which doesn't match the old
2962 RDEBUG2("Ignoring conflicting proxy reply");
2965 /* assert that there's an event queued for request? */
2970 * Verify the packet before doing ANYTHING with it. This
2971 * means we're doing more MD5 checks in the server core.
2972 * However, we can fix that by moving to multiple threads
2973 * listening on sockets.
2975 * We do this AFTER looking the request up in the hash,
2976 * and AFTER vhecking if we saw a previous request. This
2977 * helps minimize the DoS effect of people attacking us
2978 * with spoofed packets.
2980 if (rad_verify(packet, request->proxy,
2981 request->home_server->secret) != 0) {
2982 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2986 gettimeofday(&now, NULL);
2989 * Maybe move this earlier in the decision process?
2990 * Having it here means that late or duplicate proxy
2991 * replies no longer get the home server marked as
2992 * "alive". This might be good for stability, though.
2994 * FIXME: Do we really want to do this whenever we
2995 * receive a packet? Setting this here means that we
2996 * mark it alive on *any* packet, even if it's lost all
2997 * of the *other* packets in the last 10s.
2999 request->home_server->state = HOME_STATE_ALIVE;
3003 * When originating CoA, the "proxy" reply is the reply
3004 * to the CoA request that we originated. At this point,
3005 * the original request is finished, and it has a reply.
3007 * However, if we haven't separated the two requests, do
3008 * so now. This is done so that cleaning up the original
3009 * request won't cause the CoA request to be free'd. See
3010 * util.c, request_free()
3012 if (request->parent && (request->parent->coa == request)) {
3013 request->parent->coa = NULL;
3014 request->parent = NULL;
3018 * Skip the next set of checks, as the original
3019 * reply is cached. We want to be able to still
3020 * process the CoA reply, AND to reference the
3021 * original request/reply.
3023 * This is getting to be really quite a bit of a
3029 * If there's a reply to the NAS, ignore everything
3030 * related to proxy responses
3032 if (request->reply && request->reply->code != 0) {
3033 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3039 * The average includes our time to receive packets and
3040 * look them up in the hashes, which should be the same
3043 * We update the response time only for the FIRST packet
3046 if (request->home_server->ema.window > 0) {
3047 radius_stats_ema(&request->home_server->ema,
3048 &now, &request->proxy_when);
3052 switch (request->child_state) {
3053 case REQUEST_QUEUED:
3054 case REQUEST_RUNNING:
3055 radlog(L_ERR, "Internal sanity check failed for child state");
3058 case REQUEST_REJECT_DELAY:
3059 case REQUEST_CLEANUP_DELAY:
3061 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'",
3062 inet_ntop(packet->src_ipaddr.af,
3063 &packet->src_ipaddr.ipaddr,
3064 buffer, sizeof(buffer)),
3065 packet->src_port, packet->id,
3067 /* assert that there's an event queued for request? */
3070 case REQUEST_PROXIED:
3074 request->proxy_reply = packet;
3078 * Perform RTT calculations, as per RFC 2988 (for TCP).
3079 * Note that we only do so on the first response.
3081 if ((request->num_proxied_responses == 1)
3083 home_server *home = request->home_server;
3085 rtt = now.tv_sec - request->proxy_when.tv_sec;
3088 rtt -= request->proxy_when.tv_usec;
3090 if (!home->has_rtt) {
3091 home->has_rtt = TRUE;
3094 home->rttvar = rtt / 2;
3097 home->rttvar -= home->rttvar >> 2;
3098 home->rttvar += (home->srtt - rtt);
3099 home->srtt -= home->srtt >> 3;
3100 home->srtt += rtt >> 3;
3103 home->rto = home->srtt;
3104 if (home->rttvar > (USEC / 4)) {
3105 home->rto += home->rttvar * 4;
3113 * There's no incoming request, so it's a proxied packet
3116 if (!request->packet) {
3117 received_response_to_ping(request);
3118 request->proxy_reply = NULL; /* caller will free it */
3119 ev_request_free(&request);
3123 request->child_state = REQUEST_QUEUED;
3124 request->when = now;
3125 request->delay = USEC;
3126 request->priority = RAD_LISTEN_PROXY;
3127 tv_add(&request->when, request->delay);
3130 * Wait a bit will take care of max_request_time
3132 INSERT_EVENT(wait_a_bit, request);
3138 void event_new_fd(rad_listen_t *this)
3142 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3144 this->print(this, buffer, sizeof(buffer));
3146 if (this->status == RAD_LISTEN_STATUS_INIT) {
3148 DEBUG("Listening on %s", buffer);
3150 DEBUG2(" ... adding new socket %s", buffer);
3152 if (!fr_event_fd_insert(el, 0, this->fd,
3153 event_socket_handler, this)) {
3154 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3158 this->status = RAD_LISTEN_STATUS_KNOWN;
3162 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3163 DEBUG2(" ... closing socket %s", buffer);
3165 fr_event_fd_delete(el, 0, this->fd);
3166 this->status = RAD_LISTEN_STATUS_FINISH;
3169 * Close the fd AFTER fixing up the requests and
3170 * listeners, so that they don't send/recv on the
3171 * wrong socket (if someone manages to open
3179 static void handle_signal_self(int flag)
3181 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3182 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3183 fr_event_loop_exit(el, 1);
3185 fr_event_loop_exit(el, 2);
3189 } /* else exit/term flags weren't set */
3192 * Tell the even loop to stop processing.
3194 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3196 static time_t last_hup = 0;
3198 DEBUG("Received HUP signal.");
3201 if ((int) (when - last_hup) < 5) {
3202 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3207 fr_event_loop_exit(el, 0x80);
3211 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3215 * FIXME: O(N) loops suck.
3217 for (this = mainconfig.listen;
3219 this = this->next) {
3220 if (this->type != RAD_LISTEN_DETAIL) continue;
3223 * This one didn't send the signal, skip
3226 if (!this->decode(this, NULL)) continue;
3229 * Go service the interrupt.
3231 event_poll_detail(this);
3236 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3239 for (this = mainconfig.listen;
3241 this = this->next) {
3247 #ifndef WITH_SELF_PIPE
3248 void radius_signal_self(int flag)
3250 handle_signal_self(flag);
3254 * Inform ourselves that we received a signal.
3256 void radius_signal_self(int flag)
3262 * The read MUST be non-blocking for this to work.
3264 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3268 for (i = 0; i < rcode; i++) {
3269 buffer[0] |= buffer[i];
3277 write(self_pipe[1], buffer, 1);
3281 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3282 UNUSED int fd, UNUSED void *ctx)
3287 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3288 if (rcode <= 0) return;
3291 * Merge pending signals.
3293 for (i = 0; i < rcode; i++) {
3294 buffer[0] |= buffer[i];
3297 handle_signal_self(buffer[0]);
3302 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3305 rad_listen_t *listener = ctx;
3306 RAD_REQUEST_FUNP fun;
3309 rad_assert(xel == el);
3313 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3315 if (!listener->recv(listener, &fun, &request)) return;
3317 if (!thread_pool_addrequest(request, fun)) {
3318 request->child_state = REQUEST_DONE;
3322 typedef struct listen_detail_t {
3327 * This function is called periodically to see if this detail
3328 * file is available for reading.
3330 static void event_poll_detail(void *ctx)
3333 RAD_REQUEST_FUNP fun;
3335 rad_listen_t *this = ctx;
3336 struct timeval when;
3337 listen_detail_t *detail = this->data;
3339 rad_assert(this->type == RAD_LISTEN_DETAIL);
3342 * Try to read something.
3344 * FIXME: This does poll AND receive.
3346 rcode = this->recv(this, &fun, &request);
3348 rad_assert(fun != NULL);
3349 rad_assert(request != NULL);
3351 if (!thread_pool_addrequest(request, fun)) {
3352 request->child_state = REQUEST_DONE;
3356 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3360 * Backdoor API to get the delay until the next poll
3363 delay = this->encode(this, NULL);
3364 tv_add(&when, delay);
3366 if (!fr_event_insert(el, event_poll_detail, this,
3367 &when, &detail->ev)) {
3368 radlog(L_ERR, "Failed creating handler");
3374 static void event_status(struct timeval *wake)
3376 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3380 if (debug_flag == 0) {
3382 radlog(L_INFO, "Ready to process requests.");
3383 just_started = FALSE;
3389 DEBUG("Ready to process requests.");
3391 } else if ((wake->tv_sec != 0) ||
3392 (wake->tv_usec >= 100000)) {
3393 DEBUG("Waking up in %d.%01u seconds.",
3394 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3399 * FIXME: Put this somewhere else, where it isn't called
3400 * all of the time...
3403 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3405 * If there are no child threads, then there may
3406 * be child processes. In that case, wait for
3407 * their exit status, and throw that exit status
3408 * away. This helps get rid of zxombie children.
3410 while (waitpid(-1, &argval, WNOHANG) > 0) {
3418 * Externally-visibly functions.
3420 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3422 rad_listen_t *this, *head = NULL;
3426 time(&fr_start_time);
3428 el = fr_event_list_create(event_status);
3431 pl = fr_packet_list_create(0);
3432 if (!pl) return 0; /* leak el */
3434 request_num_counter = 0;
3437 if (mainconfig.proxy_requests) {
3438 pthread_mutexattr_t attr;
3441 * Create the tree for managing proxied requests and
3444 proxy_list = fr_packet_list_create(1);
3445 if (!proxy_list) return 0;
3447 #ifdef HAVE_PTHREAD_H
3448 pthread_mutexattr_init(&attr);
3450 #ifdef PTHREAD_MUTEX_RECURSIVE
3451 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) < 0) {
3452 radlog(L_ERR, "FATAL: Failed to set type for proxy mutex: %s",
3458 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3459 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3464 pthread_mutexattr_destroy(&attr);
3470 * Just before we spawn the child threads, force the log
3471 * subsystem to re-open the log file for every write.
3473 if (spawn_flag) force_log_reopen();
3475 #ifdef HAVE_PTHREAD_H
3477 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3479 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3482 * Initialize the threads ONLY if we're spawning, AND
3483 * we're running normally.
3485 if (spawn_flag && !check_config &&
3486 (thread_pool_init(cs, &spawn_flag) < 0)) {
3492 * Move all of the thread calls to this file?
3494 * It may be best for the mutexes to be in this file...
3496 have_children = spawn_flag;
3499 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3504 #ifdef WITH_SELF_PIPE
3506 * Child threads need a pipe to signal us, as do the
3509 if (pipe(self_pipe) < 0) {
3510 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3514 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3515 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3519 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3520 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3525 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3526 event_signal_handler, el)) {
3527 radlog(L_ERR, "Failed creating handler for signals");
3530 #endif /* WITH_SELF_PIPE */
3534 * Mark the proxy Fd's as unused.
3539 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3543 DEBUG("%s: #### Opening IP addresses and Ports ####",
3547 * The server temporarily switches to an unprivileged
3548 * user very early in the bootstrapping process.
3549 * However, some sockets MAY require privileged access
3550 * (bind to device, or to port < 1024, or to raw
3551 * sockets). Those sockets need to call suid up/down
3552 * themselves around the functions that need a privileged
3555 if (listen_init(cs, &head) < 0) {
3560 * At this point, no one has any business *ever* going
3563 fr_suid_down_permanent();
3566 * Add all of the sockets to the event loop.
3570 this = this->next) {
3573 this->print(this, buffer, sizeof(buffer));
3575 switch (this->type) {
3577 case RAD_LISTEN_DETAIL:
3578 DEBUG("Listening on %s", buffer);
3581 * Detail files are always known, and aren't
3582 * put into the socket event loop.
3584 this->status = RAD_LISTEN_STATUS_KNOWN;
3587 * Set up the first poll interval.
3589 event_poll_detail(this);
3594 case RAD_LISTEN_PROXY:
3595 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3596 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3598 proxy_fds[this->fd & 0x1f] = this->fd;
3599 proxy_listeners[this->fd & 0x1f] = this;
3600 if (!fr_packet_list_socket_add(proxy_list,
3614 mainconfig.listen = head;
3620 static int request_hash_cb(UNUSED void *ctx, void *data)
3622 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3625 rad_assert(request->in_proxy_hash == FALSE);
3628 ev_request_free(&request);
3635 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3637 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3639 ev_request_free(&request);
3645 void radius_event_free(void)
3648 * FIXME: Stop all threads, or at least check that
3649 * they're all waiting on the semaphore, and the queues
3655 * There are requests in the proxy hash that aren't
3656 * referenced from anywhere else. Remove them first.
3659 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3660 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3661 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3662 fr_packet_list_free(proxy_list);
3667 fr_packet_list_walk(pl, NULL, request_hash_cb);
3669 fr_packet_list_free(pl);
3672 fr_event_list_free(el);
3675 int radius_event_process(void)
3679 return fr_event_loop(el);
3682 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3684 request->options = RAD_REQUEST_OPTION_DEBUG2;
3686 if (request_pre_handler(request)) {
3687 rad_assert(fun != NULL);
3688 rad_assert(request != NULL);
3690 if (request->server) RDEBUG("server %s {",
3691 request->server != NULL ?
3692 request->server : "");
3695 if (request->server) RDEBUG("} # server %s",
3696 request->server != NULL ?
3697 request->server : "");
3699 request_post_handler(request);
3702 DEBUG2("Going to the next request");