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)
202 if (!request->in_proxy_hash) return;
204 PTHREAD_MUTEX_LOCK(&proxy_mutex);
205 fr_packet_list_yank(proxy_list, request->proxy);
206 fr_packet_list_id_free(proxy_list, request->proxy);
209 * The home server hasn't replied, but we've given up on
210 * this request. Don't count this request against the
213 if (!request->proxy_reply &&
214 request->home_server &&
215 request->home_server->currently_outstanding) {
216 request->home_server->currently_outstanding--;
219 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
221 request->in_proxy_hash = FALSE;
224 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
227 rad_listen_t *proxy_listener;
229 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
232 * Allocate a new proxy fd. This function adds
233 * it to the tail of the list of listeners. With
234 * some care, this can be thread-safe.
236 proxy_listener = proxy_new_listener();
237 if (!proxy_listener) {
238 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
246 proxy = proxy_listener->fd;
247 for (i = 0; i < 32; i++) {
249 * Found a free entry. Save the socket,
250 * and remember where we saved it.
252 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
253 found = (proxy + i) & 0x1f;
254 proxy_fds[found] = proxy;
255 proxy_listeners[found] = proxy_listener;
259 rad_assert(found >= 0);
261 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
262 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
267 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
268 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
273 * Signal the main thread to add the new FD to the list
276 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
281 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
286 rad_assert(request->proxy != NULL);
287 rad_assert(proxy_list != NULL);
289 PTHREAD_MUTEX_LOCK(&proxy_mutex);
292 * Keep track of maximum outstanding requests to a
293 * particular home server. 'max_outstanding' is
294 * enforced in home_server_ldb(), in realms.c.
296 if (request->home_server) {
297 request->home_server->currently_outstanding++;
298 request->home_server->stats.total_requests++;
302 RADIUS_PACKET packet;
304 packet = *request->proxy;
306 if (!proxy_id_alloc(request, &packet)) {
307 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
312 * Yank the request, free the old Id, and
313 * remember the new Id.
315 fr_packet_list_yank(proxy_list, request->proxy);
316 fr_packet_list_id_free(proxy_list, request->proxy);
317 *request->proxy = packet;
319 } else if (!proxy_id_alloc(request, request->proxy)) {
320 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
324 rad_assert(request->proxy->sockfd >= 0);
327 * FIXME: Hack until we get rid of rad_listen_t, and put
328 * the information into the packet_list.
331 for (i = 0; i < 32; i++) {
332 if (proxy_fds[i] == request->proxy->sockfd) {
339 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
340 RDEBUG2("ERROR: All sockets are full.");
344 rad_assert(proxy_fds[proxy] != -1);
345 rad_assert(proxy_listeners[proxy] != NULL);
346 request->proxy_listener = proxy_listeners[proxy];
348 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
349 fr_packet_list_id_free(proxy_list, request->proxy);
350 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
351 RDEBUG2("ERROR: Failed to insert entry into proxy list");
355 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
357 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
358 inet_ntop(request->proxy->dst_ipaddr.af,
359 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
360 request->proxy->dst_port,
363 request->in_proxy_hash = TRUE;
370 * Called as BOTH an event, and in-line from other functions.
372 static void wait_for_proxy_id_to_expire(void *ctx)
374 REQUEST *request = ctx;
376 rad_assert(request->magic == REQUEST_MAGIC);
377 rad_assert(request->proxy != NULL);
379 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
380 request->when = request->proxy_when;
383 if ((request->proxy->code == PW_COA_REQUEST) ||
384 (request->proxy->code == PW_DISCONNECT_REQUEST)) {
385 request->when.tv_sec += request->home_server->coa_mrd;
388 request->when.tv_sec += request->home_server->response_window;
390 if ((request->num_proxied_requests == request->num_proxied_responses) ||
391 timercmp(&now, &request->when, >)) {
392 if (request->packet) {
393 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
394 request->number, request->packet->id,
395 (unsigned int) (request->timestamp - fr_start_time));
397 RDEBUG2("Cleaning up request %d with timestamp +%d",
399 (unsigned int) (request->timestamp - fr_start_time));
402 fr_event_delete(el, &request->ev);
403 remove_from_proxy_hash(request);
404 remove_from_request_hash(request);
405 request_free(&request);
409 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
413 #ifdef HAVE_PTHREAD_H
414 static void wait_for_child_to_die(void *ctx)
416 REQUEST *request = ctx;
418 rad_assert(request->magic == REQUEST_MAGIC);
420 if ((request->child_state == REQUEST_QUEUED) |
421 (request->child_state == REQUEST_RUNNING)) {
422 request->delay += (request->delay >> 1);
423 tv_add(&request->when, request->delay);
425 RDEBUG2("Child is still stuck for request %d", request->number);
427 INSERT_EVENT(wait_for_child_to_die, request);
431 RDEBUG2("Child is finally responsive for request %d", request->number);
432 remove_from_request_hash(request);
435 if (request->proxy) {
436 wait_for_proxy_id_to_expire(request);
441 request_free(&request);
445 static void cleanup_delay(void *ctx)
447 REQUEST *request = ctx;
449 rad_assert(request->magic == REQUEST_MAGIC);
450 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
451 (request->child_state == REQUEST_DONE));
453 remove_from_request_hash(request);
456 if (request->proxy && request->in_proxy_hash) {
457 wait_for_proxy_id_to_expire(request);
462 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
463 request->number, request->packet->id,
464 (unsigned int) (request->timestamp - fr_start_time));
466 fr_event_delete(el, &request->ev);
467 request_free(&request);
472 * FIXME: Put into a libradius function.
474 #define MAX_PACKET_CODE (52)
475 static const char *packet_codes[] = {
480 "Accounting-Request",
481 "Accounting-Response",
486 "Accounting-Message",
497 "Resource-Free-Request",
498 "Resource-Free-Response",
499 "Resource-Query-Request",
500 "Resource-Query-Response",
501 "Alternate-Resource-Reclaim-Request",
502 "NAS-Reboot-Request",
503 "NAS-Reboot-Response",
516 "Disconnect-Request",
526 "IP-Address-Allocate",
532 * In daemon mode, AND this request has debug flags set.
534 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
536 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
540 const char *received, *from;
541 const fr_ipaddr_t *ip;
546 if (direction == 0) {
547 received = "Received";
548 from = "from"; /* what else? */
549 ip = &packet->src_ipaddr;
550 port = packet->src_port;
553 received = "Sending";
554 from = "to"; /* hah! */
555 ip = &packet->dst_ipaddr;
556 port = packet->dst_port;
560 * Client-specific debugging re-prints the input
561 * packet into the client log.
563 * This really belongs in a utility library
565 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
566 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
567 received, packet_codes[packet->code], from,
568 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
569 port, packet->id, packet->data_len);
571 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
573 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
575 packet->code, packet->id, packet->data_len);
578 for (vp = packet->vps; vp != NULL; vp = vp->next) {
579 vp_prints(buffer, sizeof(buffer), vp);
580 request->radlog(L_DBG, 0, request, "\t%s", buffer);
584 static void reject_delay(void *ctx)
586 REQUEST *request = ctx;
588 rad_assert(request->magic == REQUEST_MAGIC);
589 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
591 RDEBUG2("Sending delayed reject for request %d", request->number);
593 DEBUG_PACKET(request, request->reply, 1);
595 request->listener->send(request->listener, request);
597 request->when.tv_sec += request->root->cleanup_delay;
598 request->child_state = REQUEST_CLEANUP_DELAY;
600 INSERT_EVENT(cleanup_delay, request);
605 void revive_home_server(void *ctx)
607 home_server *home = ctx;
610 home->state = HOME_STATE_ALIVE;
611 home->currently_outstanding = 0;
612 home->revive_time = now;
615 * Delete any outstanding events.
617 if (home->ev) fr_event_delete(el, &home->ev);
619 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
620 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
621 buffer, sizeof(buffer)),
627 static void no_response_to_ping(void *ctx)
629 REQUEST *request = ctx;
633 rad_assert(request->home_server != NULL);
635 home = request->home_server;
636 home->num_received_pings = 0;
638 RDEBUG2("No response to status check %d from home server %s port %d",
640 inet_ntop(request->proxy->dst_ipaddr.af,
641 &request->proxy->dst_ipaddr.ipaddr,
642 buffer, sizeof(buffer)),
643 request->proxy->dst_port);
645 wait_for_proxy_id_to_expire(request);
649 static void received_response_to_ping(REQUEST *request)
654 rad_assert(request->home_server != NULL);
656 home = request->home_server;
657 home->num_received_pings++;
659 RDEBUG2("Received response to status check %d (%d in current sequence)",
660 request->number, home->num_received_pings);
663 * Remove the request from any hashes
665 fr_event_delete(el, &request->ev);
666 remove_from_proxy_hash(request);
667 rad_assert(request->in_request_hash == FALSE);
668 request_free(&request);
671 * The control socket may have marked the home server as
672 * alive. OR, it may have suddenly started responding to
673 * requests again. If so, don't re-do the "make alive"
676 if (home->state == HOME_STATE_ALIVE) return;
679 * We haven't received enough ping responses to mark it
680 * "alive". Wait a bit.
682 if (home->num_received_pings < home->num_pings_to_alive) {
686 home->state = HOME_STATE_ALIVE;
687 home->currently_outstanding = 0;
688 home->revive_time = now;
690 if (!fr_event_delete(el, &home->ev)) {
691 RDEBUG2("Hmm... no event for home server. Oh well.");
694 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
695 inet_ntop(request->proxy->dst_ipaddr.af,
696 &request->proxy->dst_ipaddr.ipaddr,
697 buffer, sizeof(buffer)),
698 request->proxy->dst_port);
703 * Called from start of zombie period, OR after control socket
704 * marks the home server dead.
706 static void ping_home_server(void *ctx)
709 home_server *home = ctx;
713 if (home->state == HOME_STATE_ALIVE) {
714 radlog(L_INFO, "Suspicious proxy state... continuing");
718 request = request_alloc();
719 request->number = request_num_counter++;
721 request->proxy = rad_alloc(1);
722 rad_assert(request->proxy != NULL);
724 fr_event_now(el, &request->when);
725 home->when = request->when;
727 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
728 request->proxy->code = PW_STATUS_SERVER;
730 radius_pairmake(request, &request->proxy->vps,
731 "Message-Authenticator", "0x00", T_OP_SET);
733 } else if (home->type == HOME_TYPE_AUTH) {
734 request->proxy->code = PW_AUTHENTICATION_REQUEST;
736 radius_pairmake(request, &request->proxy->vps,
737 "User-Name", home->ping_user_name, T_OP_SET);
738 radius_pairmake(request, &request->proxy->vps,
739 "User-Password", home->ping_user_password, T_OP_SET);
740 radius_pairmake(request, &request->proxy->vps,
741 "Service-Type", "Authenticate-Only", T_OP_SET);
742 radius_pairmake(request, &request->proxy->vps,
743 "Message-Authenticator", "0x00", T_OP_SET);
746 #ifdef WITH_ACCOUNTING
747 request->proxy->code = PW_ACCOUNTING_REQUEST;
749 radius_pairmake(request, &request->proxy->vps,
750 "User-Name", home->ping_user_name, T_OP_SET);
751 radius_pairmake(request, &request->proxy->vps,
752 "Acct-Status-Type", "Stop", T_OP_SET);
753 radius_pairmake(request, &request->proxy->vps,
754 "Acct-Session-Id", "00000000", T_OP_SET);
755 vp = radius_pairmake(request, &request->proxy->vps,
756 "Event-Timestamp", "0", T_OP_SET);
757 vp->vp_date = now.tv_sec;
759 rad_assert("Internal sanity check failed");
763 radius_pairmake(request, &request->proxy->vps,
764 "NAS-Identifier", "Status Check. Are you alive?",
767 request->proxy->dst_ipaddr = home->ipaddr;
768 request->proxy->dst_port = home->port;
769 request->home_server = home;
771 rad_assert(request->proxy_listener == NULL);
773 if (!insert_into_proxy_hash(request, FALSE)) {
774 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
776 request_free(&request);
779 rad_assert(request->proxy_listener != NULL);
780 request->proxy_listener->send(request->proxy_listener,
783 request->next_callback = NULL;
784 request->child_state = REQUEST_PROXIED;
785 request->when.tv_sec += home->ping_timeout;;
787 INSERT_EVENT(no_response_to_ping, request);
790 * Add +/- 2s of jitter, as suggested in RFC 3539
791 * and in the Issues and Fixes draft.
793 home->when.tv_sec += home->ping_interval - 2;
796 jitter ^= (jitter >> 10);
797 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
799 tv_add(&home->when, jitter);
801 INSERT_EVENT(ping_home_server, home);
805 void mark_home_server_dead(home_server *home, struct timeval *when)
807 int previous_state = home->state;
810 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
811 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
812 buffer, sizeof(buffer)),
815 home->state = HOME_STATE_IS_DEAD;
816 home->num_received_pings = 0;
818 if (home->ping_check != HOME_PING_CHECK_NONE) {
820 * If the control socket marks us dead, start
821 * pinging. Otherwise, we already started
822 * pinging when it was marked "zombie".
824 if (previous_state == HOME_STATE_ALIVE) {
825 ping_home_server(home);
830 * Revive it after a fixed period of time. This
831 * is very, very, bad.
834 home->when.tv_sec += home->revive_interval;
836 INSERT_EVENT(revive_home_server, home);
840 static void check_for_zombie_home_server(REQUEST *request)
845 home = request->home_server;
847 if (home->state != HOME_STATE_ZOMBIE) return;
849 when = home->zombie_period_start;
850 when.tv_sec += home->zombie_period;
852 fr_event_now(el, &now);
853 if (timercmp(&now, &when, <)) {
857 mark_home_server_dead(home, &request->when);
860 static int proxy_to_virtual_server(REQUEST *request);
862 static int virtual_server_handler(UNUSED REQUEST *request)
864 proxy_to_virtual_server(request);
868 static void proxy_fallback_handler(REQUEST *request)
871 * A proper time is required for wait_a_bit.
873 request->delay = USEC / 10;
874 gettimeofday(&now, NULL);
875 request->next_when = now;
876 tv_add(&request->next_when, request->delay);
877 request->next_callback = wait_a_bit;
880 * Re-queue the request.
882 request->child_state = REQUEST_QUEUED;
884 rad_assert(request->proxy != NULL);
885 if (!thread_pool_addrequest(request, virtual_server_handler)) {
886 request->child_state = REQUEST_DONE;
889 #ifdef HAVE_PTHREAD_H
891 * MAY free the request if we're over max_request_time,
892 * AND we're not in threaded mode!
894 * Note that we call this ONLY if we're threaded, as
895 * if we're NOT threaded, request_post_handler() calls
896 * wait_a_bit(), which means that "request" may not
899 if (have_children) wait_a_bit(request);
904 static int setup_post_proxy_fail(REQUEST *request)
906 DICT_VALUE *dval = NULL;
909 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
910 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
912 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
913 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
917 * See no_response_to_coa_request
919 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
920 request->packet->code &= 0xff; /* restore it */
922 if (request->proxy->code == PW_COA_REQUEST) {
923 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
925 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
926 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
936 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
939 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
943 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
944 if (!vp) vp = radius_paircreate(request, &request->config_items,
945 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
946 vp->vp_integer = dval->value;
948 rad_assert(request->proxy_reply == NULL);
954 static int null_handler(UNUSED REQUEST *request)
959 static void post_proxy_fail_handler(REQUEST *request)
962 * A proper time is required for wait_a_bit.
964 request->delay = USEC / 10;
965 gettimeofday(&now, NULL);
968 * Not set up to run Post-Proxy-Type = Fail.
970 * Mark the request as still running, and figure out what
973 if (!setup_post_proxy_fail(request)) {
974 request->child_state = REQUEST_RUNNING;
975 request_post_handler(request);
979 * Re-queue the request.
981 request->child_state = REQUEST_QUEUED;
984 * There is a post-proxy-type of fail. We run
985 * the request through the pre/post proxy
986 * handlers, just like it was a real proxied
987 * request. However, we set the per-request
988 * handler to NULL, as we don't want to do
991 * Note that when we're not threaded, this will
992 * process the request even if it's greater than
993 * max_request_time. That's not fatal.
995 request->priority = 0;
996 rad_assert(request->proxy != NULL);
997 thread_pool_addrequest(request, null_handler);
1001 * MAY free the request if we're over max_request_time,
1002 * AND we're not in threaded mode!
1004 * Note that we call this ONLY if we're threaded, as
1005 * if we're NOT threaded, request_post_handler() calls
1006 * wait_a_bit(), which means that "request" may not
1009 if (have_children) wait_a_bit(request);
1013 /* maybe check this against wait_for_proxy_id_to_expire? */
1014 static void no_response_to_proxied_request(void *ctx)
1016 REQUEST *request = ctx;
1020 rad_assert(request->magic == REQUEST_MAGIC);
1021 rad_assert(request->child_state == REQUEST_PROXIED);
1024 * If we've failed over to an internal home server,
1025 * replace the callback with the correct one. This
1026 * is due to locking issues with child threads...
1028 if (request->home_server->server) {
1029 wait_a_bit(request);
1033 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
1035 inet_ntop(request->proxy->dst_ipaddr.af,
1036 &request->proxy->dst_ipaddr.ipaddr,
1037 buffer, sizeof(buffer)),
1038 request->proxy->dst_port);
1040 check_for_zombie_home_server(request);
1042 home = request->home_server;
1044 post_proxy_fail_handler(request);
1047 * Don't touch request due to race conditions
1049 if (home->state == HOME_STATE_IS_DEAD) {
1050 rad_assert(home->ev != NULL); /* or it will never wake up */
1055 * Enable the zombie period when we notice that the home
1056 * server hasn't responded. We do NOT back-date the start
1057 * of the zombie period.
1059 if (home->state == HOME_STATE_ALIVE) {
1060 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1061 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1062 buffer, sizeof(buffer)),
1064 home->state = HOME_STATE_ZOMBIE;
1065 home->zombie_period_start = now;
1068 * Start pinging the home server.
1070 ping_home_server(home);
1075 static void wait_a_bit(void *ctx)
1077 struct timeval when;
1078 REQUEST *request = ctx;
1079 fr_event_callback_t callback = NULL;
1081 rad_assert(request->magic == REQUEST_MAGIC);
1085 * The CoA request is a new (internally generated)
1086 * request, created in a child thread. We therefore need
1087 * some way to tie its events back into the main event
1090 if (request->coa && !request->coa->proxy_reply &&
1091 request->coa->next_callback) {
1092 request->coa->when = request->coa->next_when;
1093 INSERT_EVENT(request->coa->next_callback, request->coa);
1094 request->coa->next_callback = NULL;
1095 request->coa->parent = NULL;
1096 request->coa = NULL;
1100 switch (request->child_state) {
1101 case REQUEST_QUEUED:
1102 case REQUEST_RUNNING:
1103 when = request->received;
1104 when.tv_sec += request->root->max_request_time;
1107 * Normally called from the event loop with the
1108 * proper event loop time. Otherwise, called from
1109 * post proxy fail handler, which sets "now", and
1110 * this call won't re-set it, because we're not
1111 * in the event loop.
1113 fr_event_now(el, &now);
1116 * Request still has more time. Continue
1119 if (timercmp(&now, &when, <) ||
1120 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1121 (request->child_state == REQUEST_QUEUED))) {
1122 if (request->delay < (USEC / 10)) {
1123 request->delay = USEC / 10;
1125 request->delay += request->delay >> 1;
1129 * Cap wait at some sane value for detail
1132 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1133 (request->delay > (request->root->max_request_time * USEC))) {
1134 request->delay = request->root->max_request_time * USEC;
1138 request->when = now;
1139 tv_add(&request->when, request->delay);
1140 callback = wait_a_bit;
1144 #if defined(HAVE_PTHREAD_H)
1146 * A child thread MAY still be running on the
1147 * request. Ask the thread to stop working on
1150 if (have_children) {
1151 /* FIXME: kill unresponsive children? */
1154 * Print this error message ONLY if
1155 * there's a child currently processing
1156 * the request. As we don't have thread
1157 * locks here, there may be race
1158 * conditions on this check. But it's
1159 * just an error message, so that's OK.
1161 if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1162 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1164 request->module ? request->module : "<server core>",
1165 request->component ? request->component : "<server core>");
1168 request->master_state = REQUEST_STOP_PROCESSING;
1170 request->delay = USEC / 4;
1171 tv_add(&request->when, request->delay);
1172 callback = wait_for_child_to_die;
1178 * Else there are no child threads. We probably
1179 * should have just marked the request as 'done'
1180 * elsewhere, like in the post-proxy-fail
1181 * handler. But doing that would involve
1182 * checking for max_request_time in multiple
1183 * places, so this may be simplest.
1185 request->child_state = REQUEST_DONE;
1189 * Mark the request as no longer running,
1193 #ifdef HAVE_PTHREAD_H
1194 request->child_pid = NO_SUCH_CHILD_PID;
1199 * This is a CoA request. It's been divorced
1200 * from everything else, so we clean it up now.
1202 if (!request->in_request_hash &&
1204 (request->packet->code != request->proxy->code) &&
1205 ((request->proxy->code == PW_COA_REQUEST) ||
1206 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1208 * FIXME: Do CoA MIBs
1210 fr_event_delete(el, &request->ev);
1211 remove_from_proxy_hash(request);
1212 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 fr_event_delete(el, &request->ev);
1254 remove_from_proxy_hash(request);
1255 remove_from_request_hash(request);
1256 request_free(&request);
1260 INSERT_EVENT(callback, request);
1264 static void no_response_to_coa_request(void *ctx)
1266 REQUEST *request = ctx;
1269 rad_assert(request->magic == REQUEST_MAGIC);
1270 rad_assert(request->child_state == REQUEST_PROXIED);
1271 rad_assert(request->home_server != NULL);
1272 rad_assert(!request->in_request_hash);
1274 radlog(L_ERR, "No response to CoA request sent to %s",
1275 inet_ntop(request->proxy->dst_ipaddr.af,
1276 &request->proxy->dst_ipaddr.ipaddr,
1277 buffer, sizeof(buffer)));
1282 request->packet->code |= (PW_COA_REQUEST << 8);
1283 post_proxy_fail_handler(request);
1287 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1291 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1298 packet->data = NULL;
1299 packet->data_len = 0;
1302 return 1; /* time stamp updated */
1307 * Called when we haven't received a response to a CoA request.
1309 static void retransmit_coa_request(void *ctx)
1313 REQUEST *request = ctx;
1315 rad_assert(request->magic == REQUEST_MAGIC);
1316 rad_assert(request->child_state == REQUEST_PROXIED);
1317 rad_assert(request->home_server != NULL);
1318 rad_assert(!request->in_request_hash);
1319 rad_assert(request->parent == NULL);
1321 fr_event_now(el, &now);
1324 * Cap count at MRC, if it is non-zero.
1326 if (request->home_server->coa_mrc &&
1327 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1328 no_response_to_coa_request(request);
1333 * RFC 5080 Section 2.2.1
1335 * RT = 2*RTprev + RAND*RTprev
1336 * = 1.9 * RTprev + rand(0,.2) * RTprev
1337 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1340 delay ^= (delay >> 16);
1342 frac = request->delay / 5;
1343 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1345 delay += (2 * request->delay) - (request->delay / 10);
1348 * Cap delay at MRT, if MRT is non-zero.
1350 if (request->home_server->coa_mrt &&
1351 (delay > (request->home_server->coa_mrt * USEC))) {
1352 int mrt_usec = request->home_server->coa_mrt * USEC;
1355 * delay = MRT + RAND * MRT
1356 * = 0.9 MRT + rand(0,.2) * MRT
1359 delay ^= (delay >> 15);
1361 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1362 delay += mrt_usec - (mrt_usec / 10);
1365 request->delay = delay;
1366 request->when = now;
1367 tv_add(&request->when, request->delay);
1368 mrd = request->proxy_when;
1369 mrd.tv_sec += request->home_server->coa_mrd;
1372 * Cap duration at MRD.
1374 if (timercmp(&mrd, &request->when, <)) {
1375 request->when = mrd;
1376 INSERT_EVENT(no_response_to_coa_request, request);
1379 INSERT_EVENT(retransmit_coa_request, request);
1382 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1383 if (!insert_into_proxy_hash(request, TRUE)) {
1384 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1388 request->num_proxied_requests = 0;
1389 request->num_proxied_responses = 0;
1392 request->num_proxied_requests++;
1393 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1395 request->proxy_listener->send(request->proxy_listener,
1401 * The original request is either DONE, or in CLEANUP_DELAY.
1403 static int originated_coa_request(REQUEST *request)
1405 int delay, rcode, pre_proxy_type = 0;
1411 rad_assert(request->proxy == NULL);
1412 rad_assert(!request->in_proxy_hash);
1413 rad_assert(request->proxy_reply == NULL);
1415 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1416 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1418 if (vp->vp_integer == 0) {
1419 request_free(&request->coa);
1420 return 1; /* success */
1423 if (!request->coa) request_alloc_coa(request);
1424 if (!request->coa) return 0;
1430 * src_ipaddr will be set up in proxy_encode.
1432 memset(&ipaddr, 0, sizeof(ipaddr));
1433 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1435 ipaddr.af = AF_INET;
1436 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1438 } else if ((vp = pairfind(coa->proxy->vps,
1439 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1440 ipaddr.af = AF_INET6;
1441 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1443 } else if ((vp = pairfind(coa->proxy->vps,
1444 PW_HOME_SERVER_POOL)) != NULL) {
1445 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1447 if (!coa->home_pool) {
1448 RDEBUG2("WARNING: No such home_server_pool %s",
1451 request_free(&request->coa);
1458 } else if (request->client->coa_pool) {
1459 coa->home_pool = request->client->coa_pool;
1461 } else if (request->client->coa_server) {
1462 coa->home_server = request->client->coa_server;
1466 * If all else fails, send it to the client that
1467 * originated this request.
1469 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1473 * Use the pool, if it exists.
1475 if (coa->home_pool) {
1476 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1477 if (!coa->home_server) {
1478 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1482 } else if (!coa->home_server) {
1483 int port = PW_COA_UDP_PORT;
1485 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1486 if (vp) port = vp->vp_integer;
1488 coa->home_server = home_server_find(&ipaddr, port);
1489 if (!coa->home_server) {
1490 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1491 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1492 buffer, sizeof(buffer)), port);
1497 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1499 switch (vp->vp_integer) {
1500 case PW_COA_REQUEST:
1501 case PW_DISCONNECT_REQUEST:
1502 coa->proxy->code = vp->vp_integer;
1506 DEBUG("Cannot set CoA Packet-Type to code %d",
1512 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1515 * The rest of the server code assumes that
1516 * request->packet && request->reply exist. Copy them
1517 * from the original request.
1519 rad_assert(coa->packet != NULL);
1520 rad_assert(coa->packet->vps == NULL);
1521 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1522 coa->packet->vps = paircopy(request->packet->vps);
1523 coa->packet->data = NULL;
1524 rad_assert(coa->reply != NULL);
1525 rad_assert(coa->reply->vps == NULL);
1526 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1527 coa->reply->vps = paircopy(request->reply->vps);
1528 coa->reply->data = NULL;
1529 coa->config_items = paircopy(request->config_items);
1532 * Call the pre-proxy routines.
1534 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1536 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1537 pre_proxy_type = vp->vp_integer;
1540 if (coa->home_pool && coa->home_pool->virtual_server) {
1541 const char *old_server = coa->server;
1543 coa->server = coa->home_pool->virtual_server;
1544 RDEBUG2(" server %s {", coa->server);
1545 rcode = module_pre_proxy(pre_proxy_type, coa);
1547 coa->server = old_server;
1549 rcode = module_pre_proxy(pre_proxy_type, coa);
1556 * Only send the CoA packet if the pre-proxy code succeeded.
1558 case RLM_MODULE_NOOP:
1560 case RLM_MODULE_UPDATED:
1565 * Source IP / port is set when the proxy socket
1568 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1569 coa->proxy->dst_port = coa->home_server->port;
1571 if (!insert_into_proxy_hash(coa, FALSE)) {
1572 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1577 * Forget about the original request completely at this
1582 gettimeofday(&request->proxy_when, NULL);
1583 request->received = request->next_when = request->proxy_when;
1584 rad_assert(request->proxy_reply == NULL);
1587 * Implement re-transmit algorithm as per RFC 5080
1590 * We want IRT + RAND*IRT
1591 * or 0.9 IRT + rand(0,.2) IRT
1593 * 2^20 ~ USEC, and we want 2.
1594 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1596 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1597 request->delay = delay * request->home_server->coa_irt;
1598 delay = request->home_server->coa_irt * USEC;
1599 delay -= delay / 10;
1600 delay += request->delay;
1602 request->delay = delay;
1603 tv_add(&request->next_when, delay);
1604 request->next_callback = retransmit_coa_request;
1607 * Note that we set proxied BEFORE sending the packet.
1609 * Once we send it, the request is tainted, as
1610 * another thread may have picked it up. Don't
1613 request->num_proxied_requests = 1;
1614 request->num_proxied_responses = 0;
1615 request->child_pid = NO_SUCH_CHILD_PID;
1617 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1619 request->child_state = REQUEST_PROXIED;
1621 DEBUG_PACKET(request, request->proxy, 1);
1623 request->proxy_listener->send(request->proxy_listener,
1627 #endif /* WITH_COA */
1630 static int process_proxy_reply(REQUEST *request)
1633 int post_proxy_type = 0;
1637 * Delete any reply we had accumulated until now.
1639 pairfree(&request->reply->vps);
1642 * Run the packet through the post-proxy stage,
1643 * BEFORE playing games with the attributes.
1645 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1647 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1648 post_proxy_type = vp->vp_integer;
1651 if (request->home_pool && request->home_pool->virtual_server) {
1652 const char *old_server = request->server;
1654 request->server = request->home_pool->virtual_server;
1655 RDEBUG2(" server %s {", request->server);
1656 rcode = module_post_proxy(post_proxy_type, request);
1658 request->server = old_server;
1660 rcode = module_post_proxy(post_proxy_type, request);
1664 if (request->packet->code == request->proxy->code)
1666 * Don't run the next bit if we originated a CoA
1667 * packet, after receiving an Access-Request or
1668 * Accounting-Request.
1673 * There may NOT be a proxy reply, as we may be
1674 * running Post-Proxy-Type = Fail.
1676 if (request->proxy_reply) {
1678 * Delete the Proxy-State Attributes from
1679 * the reply. These include Proxy-State
1680 * attributes from us and remote server.
1682 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1685 * Add the attributes left in the proxy
1686 * reply to the reply list.
1688 pairadd(&request->reply->vps, request->proxy_reply->vps);
1689 request->proxy_reply->vps = NULL;
1692 * Free proxy request pairs.
1694 pairfree(&request->proxy->vps);
1698 default: /* Don't do anything */
1700 case RLM_MODULE_FAIL:
1701 /* FIXME: debug print stuff */
1702 request->child_state = REQUEST_DONE;
1705 case RLM_MODULE_HANDLED:
1706 /* FIXME: debug print stuff */
1707 request->child_state = REQUEST_DONE;
1715 static int request_pre_handler(REQUEST *request)
1719 rad_assert(request->magic == REQUEST_MAGIC);
1720 rad_assert(request->packet != NULL);
1722 request->child_state = REQUEST_RUNNING;
1725 * Don't decode the packet if it's an internal "fake"
1726 * request. Instead, just return so that the caller can
1729 if (request->packet->dst_port == 0) {
1730 request->username = pairfind(request->packet->vps,
1732 request->password = pairfind(request->packet->vps,
1739 * Put the decoded packet into it's proper place.
1741 if (request->proxy_reply != NULL) {
1742 rcode = request->proxy_listener->decode(request->proxy_listener,
1744 DEBUG_PACKET(request, request->proxy_reply, 0);
1747 if (request->packet->vps == NULL) {
1748 rcode = request->listener->decode(request->listener, request);
1750 if (debug_condition) {
1752 const char *my_debug = debug_condition;
1755 * Ignore parse errors.
1757 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1761 request->options = 2;
1762 request->radlog = radlog_request;
1766 DEBUG_PACKET(request, request->packet, 0);
1772 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1773 request->child_state = REQUEST_DONE;
1777 if (!request->username) {
1778 request->username = pairfind(request->packet->vps,
1783 if (request->proxy) {
1784 return process_proxy_reply(request);
1794 * Do state handling when we proxy a request.
1796 static int proxy_request(REQUEST *request)
1798 struct timeval when;
1801 if (request->home_server->server) {
1802 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1806 if (!insert_into_proxy_hash(request, FALSE)) {
1807 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1811 request->proxy_listener->encode(request->proxy_listener, request);
1813 when = request->received;
1814 when.tv_sec += request->root->max_request_time;
1816 gettimeofday(&request->proxy_when, NULL);
1818 request->next_when = request->proxy_when;
1819 request->next_when.tv_sec += request->home_server->response_window;
1821 rad_assert(request->home_server->response_window > 0);
1823 if (timercmp(&when, &request->next_when, <)) {
1824 request->next_when = when;
1826 request->next_callback = no_response_to_proxied_request;
1828 RDEBUG2("Proxying request %d to home server %s port %d",
1830 inet_ntop(request->proxy->dst_ipaddr.af,
1831 &request->proxy->dst_ipaddr.ipaddr,
1832 buffer, sizeof(buffer)),
1833 request->proxy->dst_port);
1836 * Note that we set proxied BEFORE sending the packet.
1838 * Once we send it, the request is tainted, as
1839 * another thread may have picked it up. Don't
1842 request->num_proxied_requests = 1;
1843 request->num_proxied_responses = 0;
1844 #ifdef HAVE_PTHREAD_H
1845 request->child_pid = NO_SUCH_CHILD_PID;
1847 request->child_state = REQUEST_PROXIED;
1849 DEBUG_PACKET(request, request->proxy, 1);
1851 request->proxy_listener->send(request->proxy_listener,
1858 * "Proxy" the request by sending it to a new virtual server.
1860 static int proxy_to_virtual_server(REQUEST *request)
1863 RAD_REQUEST_FUNP fun;
1865 if (!request->home_server || !request->home_server->server) return 0;
1867 if (request->parent) {
1868 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1872 fake = request_alloc_fake(request);
1874 RDEBUG2("WARNING: Out of memory");
1878 fake->packet->vps = paircopy(request->proxy->vps);
1879 fake->server = request->home_server->server;
1881 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1882 fun = rad_authenticate;
1884 #ifdef WITH_ACCOUNTING
1885 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1886 fun = rad_accounting;
1890 RDEBUG2("Unknown packet type %d", request->proxy->code);
1891 request_free(&fake);
1895 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1896 radius_handle_request(fake, fun);
1897 RDEBUG2("<<< Received proxied response from internal virtual server.");
1899 request->proxy_reply = fake->reply;
1902 request_free(&fake);
1904 process_proxy_reply(request);
1907 return 2; /* success, but NOT '1' !*/
1911 * Return 1 if we did proxy it, or the proxy attempt failed
1912 * completely. Either way, the caller doesn't touch the request
1913 * any more if we return 1.
1915 static int successfully_proxied_request(REQUEST *request)
1918 int pre_proxy_type = 0;
1919 VALUE_PAIR *realmpair;
1920 VALUE_PAIR *strippedname;
1922 char *realmname = NULL;
1924 REALM *realm = NULL;
1928 * If it was already proxied, do nothing.
1930 * FIXME: This should really be a serious error.
1932 if (request->in_proxy_hash) {
1936 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1937 if (!realmpair || (realmpair->length == 0)) {
1941 realmname = (char *) realmpair->vp_strvalue;
1943 realm = realm_find2(realmname);
1945 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1950 * Figure out which pool to use.
1952 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1953 pool = realm->auth_pool;
1955 #ifdef WITH_ACCOUNTING
1956 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1957 pool = realm->acct_pool;
1961 rad_panic("Internal sanity check failed");
1965 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1970 home = home_server_ldb(realmname, pool, request);
1972 RDEBUG2("ERROR: Failed to find live home server for realm %s",
1976 request->home_pool = pool;
1979 * Remember that we sent the request to a Realm.
1981 pairadd(&request->packet->vps,
1982 pairmake("Realm", realmname, T_OP_EQ));
1985 * Strip the name, if told to.
1987 * Doing it here catches the case of proxied tunneled
1990 if (realm->striprealm == TRUE &&
1991 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1993 * If there's a Stripped-User-Name attribute in
1994 * the request, then use THAT as the User-Name
1995 * for the proxied request, instead of the
1998 * This is done by making a copy of the
1999 * Stripped-User-Name attribute, turning it into
2000 * a User-Name attribute, deleting the
2001 * Stripped-User-Name and User-Name attributes
2002 * from the vps list, and making the new
2003 * User-Name the head of the vps list.
2005 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2007 vp = radius_paircreate(request, NULL,
2008 PW_USER_NAME, PW_TYPE_STRING);
2009 rad_assert(vp != NULL); /* handled by above function */
2010 /* Insert at the START of the list */
2011 vp->next = request->proxy->vps;
2012 request->proxy->vps = vp;
2014 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2015 sizeof(vp->vp_strvalue));
2016 vp->length = strippedname->length;
2019 * Do NOT delete Stripped-User-Name.
2024 * If there is no PW_CHAP_CHALLENGE attribute but
2025 * there is a PW_CHAP_PASSWORD we need to add it
2026 * since we can't use the request authenticator
2027 * anymore - we changed it.
2029 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2030 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2031 vp = radius_paircreate(request, &request->proxy->vps,
2032 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2033 vp->length = AUTH_VECTOR_LEN;
2034 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2038 * The RFC's say we have to do this, but FreeRADIUS
2041 vp = radius_paircreate(request, &request->proxy->vps,
2042 PW_PROXY_STATE, PW_TYPE_OCTETS);
2043 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2044 request->packet->id);
2045 vp->length = strlen(vp->vp_strvalue);
2048 * Should be done BEFORE inserting into proxy hash, as
2049 * pre-proxy may use this information, or change it.
2051 request->proxy->code = request->packet->code;
2054 * Call the pre-proxy routines.
2056 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2058 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2059 pre_proxy_type = vp->vp_integer;
2062 rad_assert(request->home_pool != NULL);
2064 if (request->home_pool->virtual_server) {
2065 const char *old_server = request->server;
2067 request->server = request->home_pool->virtual_server;
2068 RDEBUG2(" server %s {", request->server);
2069 rcode = module_pre_proxy(pre_proxy_type, request);
2071 request->server = old_server;
2073 rcode = module_pre_proxy(pre_proxy_type, request);
2076 case RLM_MODULE_FAIL:
2077 case RLM_MODULE_INVALID:
2078 case RLM_MODULE_NOTFOUND:
2079 case RLM_MODULE_USERLOCK:
2081 /* FIXME: debug print failed stuff */
2084 case RLM_MODULE_REJECT:
2085 case RLM_MODULE_HANDLED:
2089 * Only proxy the packet if the pre-proxy code succeeded.
2091 case RLM_MODULE_NOOP:
2093 case RLM_MODULE_UPDATED:
2098 * If it's a fake request, don't send the proxy
2099 * packet. The outer tunnel session will take
2100 * care of doing that.
2102 if (request->packet->dst_port == 0) {
2103 request->home_server = NULL;
2107 if (request->home_server->server) {
2108 return proxy_to_virtual_server(request);
2111 if (!proxy_request(request)) {
2112 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2120 static void request_post_handler(REQUEST *request)
2122 int child_state = -1;
2123 struct timeval when;
2126 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2128 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2129 RDEBUG2("Request %d was cancelled.", request->number);
2130 #ifdef HAVE_PTHREAD_H
2131 request->child_pid = NO_SUCH_CHILD_PID;
2133 child_state = REQUEST_DONE;
2137 if (request->child_state != REQUEST_RUNNING) {
2138 rad_panic("Internal sanity check failed");
2143 * If it's not in the request hash, it's a CoA request.
2146 if (!request->in_request_hash &&
2148 ((request->proxy->code == PW_COA_REQUEST) ||
2149 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2150 request->next_callback = NULL;
2151 child_state = REQUEST_DONE;
2156 if ((request->reply->code == 0) &&
2157 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2158 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2159 request->reply->code = PW_AUTHENTICATION_REJECT;
2163 if (request->root->proxy_requests &&
2164 !request->in_proxy_hash &&
2165 (request->reply->code == 0) &&
2166 (request->packet->dst_port != 0) &&
2167 (request->packet->code != PW_STATUS_SERVER)) {
2168 int rcode = successfully_proxied_request(request);
2172 * If we proxy it, we CANNOT originate a CoA
2173 * request at the same time.
2175 if (rcode != 0) request_free(&request->coa);
2178 if (rcode == 1) return;
2181 * Failed proxying it (dead home servers, etc.)
2182 * Run it through Post-Proxy-Type = Fail, and
2183 * respond to the request.
2185 * Note that we're in a child thread here, so we
2186 * do NOT re-schedule the request. Instead, we
2187 * do what we would have done, which is run the
2188 * pre-handler, a NULL request handler, and then
2191 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2192 request_pre_handler(request);
2196 * Else we weren't supposed to proxy it,
2197 * OR we proxied it internally to a virutal server.
2203 * Fake requests don't get encoded or signed. The caller
2204 * also requires the reply VP's, so we don't free them
2207 if (request->packet->dst_port == 0) {
2208 /* FIXME: RDEBUG going to the next request */
2209 #ifdef HAVE_PTHREAD_H
2210 request->child_pid = NO_SUCH_CHILD_PID;
2212 request->child_state = REQUEST_DONE;
2218 * Copy Proxy-State from the request to the reply.
2220 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2221 if (vp) pairadd(&request->reply->vps, vp);
2225 * Access-Requests get delayed or cached.
2227 switch (request->packet->code) {
2228 case PW_AUTHENTICATION_REQUEST:
2229 gettimeofday(&request->next_when, NULL);
2231 if (request->reply->code == 0) {
2233 * Check if the lack of response is intentional.
2235 vp = pairfind(request->config_items,
2236 PW_RESPONSE_PACKET_TYPE);
2238 RDEBUG2("There was no response configured: rejecting request %d",
2240 request->reply->code = PW_AUTHENTICATION_REJECT;
2241 } else if (vp->vp_integer == 256) {
2242 RDEBUG2("Not responding to request %d",
2246 request->reply->code = vp->vp_integer;
2252 * Run rejected packets through
2254 * Post-Auth-Type = Reject
2256 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2257 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2258 vp = radius_pairmake(request, &request->config_items,
2259 "Post-Auth-Type", "Reject",
2261 if (vp) rad_postauth(request);
2264 * If configured, delay Access-Reject packets.
2266 * If request->root->reject_delay = 0, we discover
2267 * that we have to send the packet now.
2269 when = request->received;
2270 when.tv_sec += request->root->reject_delay;
2272 if (timercmp(&when, &request->next_when, >)) {
2273 RDEBUG2("Delaying reject of request %d for %d seconds",
2275 request->root->reject_delay);
2276 request->next_when = when;
2277 request->next_callback = reject_delay;
2278 #ifdef HAVE_PTHREAD_H
2279 request->child_pid = NO_SUCH_CHILD_PID;
2281 request->child_state = REQUEST_REJECT_DELAY;
2286 request->next_when.tv_sec += request->root->cleanup_delay;
2287 request->next_callback = cleanup_delay;
2288 child_state = REQUEST_CLEANUP_DELAY;
2291 case PW_ACCOUNTING_REQUEST:
2292 request->next_callback = NULL; /* just to be safe */
2293 child_state = REQUEST_DONE;
2297 * FIXME: Status-Server should probably not be
2300 case PW_STATUS_SERVER:
2301 request->next_callback = NULL;
2302 child_state = REQUEST_DONE;
2306 if ((request->packet->code > 1024) &&
2307 (request->packet->code < (1024 + 254 + 1))) {
2308 request->next_callback = NULL;
2309 child_state = REQUEST_DONE;
2313 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
2314 request->next_callback = NULL;
2315 child_state = REQUEST_DONE;
2320 * Suppress "no reply" packets here, unless we're reading
2321 * from the "detail" file. In that case, we've got to
2322 * tell the detail file handler that the request is dead,
2323 * and it should re-send it.
2324 * If configured, encode, sign, and send.
2326 if ((request->reply->code != 0) ||
2327 (request->listener->type == RAD_LISTEN_DETAIL)) {
2328 DEBUG_PACKET(request, request->reply, 1);
2329 request->listener->send(request->listener, request);
2334 * Now that we've completely processed the request,
2335 * see if we need to originate a CoA request.
2338 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2339 if (!originated_coa_request(request)) {
2340 RDEBUG2("Do CoA Fail handler here");
2342 /* request->coa is stil set, so we can update events */
2348 * Clean up. These are no longer needed.
2350 pairfree(&request->config_items);
2352 pairfree(&request->packet->vps);
2353 request->username = NULL;
2354 request->password = NULL;
2356 pairfree(&request->reply->vps);
2359 if (request->proxy) {
2360 pairfree(&request->proxy->vps);
2362 if (request->proxy_reply) {
2363 pairfree(&request->proxy_reply->vps);
2368 * We're not tracking responses from the home
2369 * server, we can therefore free this memory in
2372 if (!request->in_proxy_hash) {
2373 rad_free(&request->proxy);
2374 rad_free(&request->proxy_reply);
2375 request->home_server = NULL;
2381 RDEBUG2("Finished request %d.", request->number);
2382 rad_assert(child_state >= 0);
2383 request->child_state = child_state;
2386 * Single threaded mode: update timers now.
2388 if (!have_children) wait_a_bit(request);
2392 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2398 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2399 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2401 switch (request->child_state) {
2402 case REQUEST_QUEUED:
2403 case REQUEST_RUNNING:
2407 radlog(L_ERR, "Discarding duplicate request from "
2408 "client %s port %d - ID: %d due to unfinished request %d",
2410 request->packet->src_port,request->packet->id,
2415 case REQUEST_PROXIED:
2417 * We're not supposed to have duplicate
2418 * accounting packets. The other states handle
2419 * duplicates fine (discard, or send duplicate
2420 * reply). But we do NOT want to retransmit an
2421 * accounting request here, because that would
2422 * involve updating the Acct-Delay-Time, and
2423 * therefore changing the packet Id, etc.
2425 * Instead, we just discard the packet. We may
2426 * eventually respond, or the client will send a
2427 * new accounting packet.
2429 * The same comments go for Status-Server, and
2430 * other packet types.
2432 * FIXME: coa: when we proxy CoA && Disconnect
2433 * packets, this logic has to be fixed.
2435 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2439 check_for_zombie_home_server(request);
2442 * If we've just discovered that the home server is
2443 * dead, send the packet to another one.
2445 if ((request->packet->dst_port != 0) &&
2446 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2449 remove_from_proxy_hash(request);
2451 home = home_server_ldb(NULL, request->home_pool, request);
2453 RDEBUG2("Failed to find live home server for request %d", request->number);
2456 * Do post-request processing,
2457 * and any insertion of necessary
2460 post_proxy_fail_handler(request);
2464 request->proxy->code = request->packet->code;
2467 * Free the old packet, to force re-encoding
2469 free(request->proxy->data);
2470 request->proxy->data = NULL;
2471 request->proxy->data_len = 0;
2474 * This request failed over to a virtual
2475 * server. Push it back onto the queue
2478 if (request->home_server->server) {
2479 proxy_fallback_handler(request);
2484 * Try to proxy the request.
2486 if (!proxy_request(request)) {
2487 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2488 goto no_home_servers;
2492 * This code executes in the main server
2493 * thread, so there's no need for locking.
2495 rad_assert(request->next_callback != NULL);
2496 INSERT_EVENT(request->next_callback, request);
2497 request->next_callback = NULL;
2499 } /* else the home server is still alive */
2501 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2502 inet_ntop(request->proxy->dst_ipaddr.af,
2503 &request->proxy->dst_ipaddr.ipaddr,
2504 buffer, sizeof(buffer)),
2505 request->proxy->dst_port,
2506 request->proxy->id);
2507 request->num_proxied_requests++;
2509 DEBUG_PACKET(request, request->proxy, 1);
2510 request->proxy_listener->send(request->proxy_listener,
2515 case REQUEST_REJECT_DELAY:
2516 RDEBUG2("Waiting to send Access-Reject "
2517 "to client %s port %d - ID: %d",
2519 request->packet->src_port, request->packet->id);
2522 case REQUEST_CLEANUP_DELAY:
2525 * FIXME: This sends duplicate replies to
2526 * accounting requests, even if Acct-Delay-Time
2527 * or Event-Timestamp is in the packet. In those
2528 * cases, the Id should be changed, and the packet
2531 RDEBUG2("Sending duplicate reply "
2532 "to client %s port %d - ID: %d",
2534 request->packet->src_port, request->packet->id);
2535 DEBUG_PACKET(request, request->reply, 1);
2536 request->listener->send(request->listener, request);
2542 static void received_conflicting_request(REQUEST *request,
2543 const RADCLIENT *client)
2545 radlog(L_ERR, "Received conflicting packet from "
2546 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2548 request->packet->src_port, request->packet->id,
2552 * Nuke it from the request hash, so we can receive new
2555 remove_from_request_hash(request);
2557 switch (request->child_state) {
2558 #ifdef HAVE_PTHREAD_H
2560 * It's queued or running. Tell it to stop, and
2561 * wait for it to do so.
2563 case REQUEST_QUEUED:
2564 case REQUEST_RUNNING:
2565 request->master_state = REQUEST_STOP_PROCESSING;
2566 request->delay += request->delay >> 1;
2568 tv_add(&request->when, request->delay);
2570 INSERT_EVENT(wait_for_child_to_die, request);
2575 * It's in some other state, and therefore also
2576 * in the event queue. At some point, the
2577 * child will notice, and we can then delete it.
2580 rad_assert(request->ev != NULL);
2586 static int can_handle_new_request(RADIUS_PACKET *packet,
2588 struct main_config_t *root)
2591 * Count the total number of requests, to see if
2592 * there are too many. If so, return with an
2595 if (root->max_requests) {
2596 int request_count = fr_packet_list_num_elements(pl);
2599 * This is a new request. Let's see if
2600 * it makes us go over our configured
2603 if (request_count > root->max_requests) {
2604 radlog(L_ERR, "Dropping request (%d is too many): "
2605 "from client %s port %d - ID: %d", request_count,
2607 packet->src_port, packet->id);
2608 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2609 "\tThe value for 'max_requests' is probably set too low.\n");
2611 } /* else there were a small number of requests */
2612 } /* else there was no configured limit for requests */
2615 * FIXME: Add per-client checks. If one client is sending
2616 * too many packets, start discarding them.
2618 * We increment the counters here, and decrement them
2619 * when the response is sent... somewhere in this file.
2623 * FUTURE: Add checks for system load. If the system is
2624 * busy, start dropping requests...
2626 * We can probably keep some statistics ourselves... if
2627 * there are more requests coming in than we can handle,
2628 * start dropping some.
2635 int received_request(rad_listen_t *listener,
2636 RADIUS_PACKET *packet, REQUEST **prequest,
2639 RADIUS_PACKET **packet_p;
2640 REQUEST *request = NULL;
2641 struct main_config_t *root = &mainconfig;
2643 packet_p = fr_packet_list_find(pl, packet);
2645 request = fr_packet2myptr(REQUEST, packet, packet_p);
2646 rad_assert(request->in_request_hash);
2648 if ((request->packet->data_len == packet->data_len) &&
2649 (memcmp(request->packet->vector, packet->vector,
2650 sizeof(packet->vector)) == 0)) {
2651 received_retransmit(request, client);
2656 * The new request is different from the old one,
2657 * but maybe the old is finished. If so, delete
2660 switch (request->child_state) {
2661 struct timeval when;
2664 gettimeofday(&when, NULL);
2668 * If the cached request was received
2669 * within the last second, then we
2670 * discard the NEW request instead of the
2671 * old one. This will happen ONLY when
2672 * the client is severely broken, and is
2673 * sending conflicting packets very
2676 if (timercmp(&when, &request->received, <)) {
2677 radlog(L_ERR, "Discarding conflicting packet from "
2678 "client %s port %d - ID: %d due to recent request %d.",
2680 packet->src_port, packet->id,
2685 received_conflicting_request(request, client);
2689 case REQUEST_REJECT_DELAY:
2690 case REQUEST_CLEANUP_DELAY:
2691 request->child_state = REQUEST_DONE;
2693 cleanup_delay(request);
2700 * We may want to quench the new request.
2702 if ((listener->type != RAD_LISTEN_DETAIL) &&
2703 !can_handle_new_request(packet, client, root)) {
2708 * Create and initialize the new request.
2710 request = request_alloc(); /* never fails */
2712 if ((request->reply = rad_alloc(0)) == NULL) {
2713 radlog(L_ERR, "No memory");
2717 request->listener = listener;
2718 request->client = client;
2719 request->packet = packet;
2720 request->packet->timestamp = request->timestamp;
2721 request->number = request_num_counter++;
2722 request->priority = listener->type;
2723 #ifdef HAVE_PTHREAD_H
2724 request->child_pid = NO_SUCH_CHILD_PID;
2728 * Status-Server packets go to the head of the queue.
2730 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2733 * Set virtual server identity
2735 if (client->server) {
2736 request->server = client->server;
2737 } else if (listener->server) {
2738 request->server = listener->server;
2740 request->server = NULL;
2744 * Remember the request in the list.
2746 if (!fr_packet_list_insert(pl, &request->packet)) {
2747 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2748 request_free(&request);
2752 request->in_request_hash = TRUE;
2753 request->root = root;
2757 * The request passes many of our sanity checks.
2758 * From here on in, if anything goes wrong, we
2759 * send a reject message, instead of dropping the
2764 * Build the reply template from the request.
2767 request->reply->sockfd = request->packet->sockfd;
2768 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2769 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2770 request->reply->dst_port = request->packet->src_port;
2771 request->reply->src_port = request->packet->dst_port;
2772 request->reply->id = request->packet->id;
2773 request->reply->code = 0; /* UNKNOWN code */
2774 memcpy(request->reply->vector, request->packet->vector,
2775 sizeof(request->reply->vector));
2776 request->reply->vps = NULL;
2777 request->reply->data = NULL;
2778 request->reply->data_len = 0;
2780 request->master_state = REQUEST_ACTIVE;
2781 request->child_state = REQUEST_QUEUED;
2782 request->next_callback = NULL;
2784 gettimeofday(&request->received, NULL);
2785 request->timestamp = request->received.tv_sec;
2786 request->when = request->received;
2788 request->delay = USEC;
2790 tv_add(&request->when, request->delay);
2792 INSERT_EVENT(wait_a_bit, request);
2794 *prequest = request;
2800 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2806 * Also removes from the proxy hash if responses == requests
2808 request = lookup_in_proxy_hash(packet);
2811 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2812 inet_ntop(packet->src_ipaddr.af,
2813 &packet->src_ipaddr.ipaddr,
2814 buffer, sizeof(buffer)),
2815 packet->src_port, packet->id);
2819 gettimeofday(&now, NULL);
2821 request->home_server->state = HOME_STATE_ALIVE;
2825 * This is a response to a CoA packet that we originated.
2826 * It's handled differently from normal proxied packets.
2828 if (request->packet->code != request->proxy->code) {
2830 * The parent request is done, but we haven't
2831 * figured that out yet. Separate the two
2832 * requests here, the FIRST time we process the
2833 * packet. If there is a proxy reply already, it
2834 * gets ignored below.
2836 if (!request->proxy_reply && request->parent &&
2837 (request->parent->coa == request)) {
2838 request->parent->coa = NULL;
2839 request->parent = NULL;
2843 * request->reply exists, and we don't care about
2844 * it here. So we skip the next step.
2846 rad_assert(request->packet != NULL);
2847 rad_assert(request->reply != NULL);
2851 if (request->reply && request->reply->code != 0) {
2852 RDEBUG2("We already replied to this request. Discarding response.");
2857 * We had previously received a reply, so we
2858 * don't need to do anything here.
2860 if (request->proxy_reply) {
2861 if (memcmp(request->proxy_reply->vector,
2863 sizeof(request->proxy_reply->vector)) == 0) {
2864 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2865 inet_ntop(packet->src_ipaddr.af,
2866 &packet->src_ipaddr.ipaddr,
2867 buffer, sizeof(buffer)),
2868 packet->src_port, packet->id,
2872 * ? The home server gave us a new proxy
2873 * reply, which doesn't match the old
2876 RDEBUG2("Ignoring conflicting proxy reply");
2879 /* assert that there's an event queued for request? */
2884 * The average includes our time to receive packets and
2885 * look them up in the hashes, which should be the same
2888 * We update the response time only for the FIRST packet
2891 else if (request->home_server->ema.window > 0) {
2892 radius_stats_ema(&request->home_server->ema,
2893 &now, &request->proxy_when);
2897 switch (request->child_state) {
2898 case REQUEST_QUEUED:
2899 case REQUEST_RUNNING:
2900 radlog(L_ERR, "Internal sanity check failed for child state");
2903 case REQUEST_REJECT_DELAY:
2904 case REQUEST_CLEANUP_DELAY:
2906 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'",
2907 inet_ntop(packet->src_ipaddr.af,
2908 &packet->src_ipaddr.ipaddr,
2909 buffer, sizeof(buffer)),
2910 packet->src_port, packet->id,
2912 /* assert that there's an event queued for request? */
2915 case REQUEST_PROXIED:
2919 request->proxy_reply = packet;
2923 * Perform RTT calculations, as per RFC 2988 (for TCP).
2924 * Note that we only do so on the first response.
2926 if ((request->num_proxied_responses == 1)
2928 home_server *home = request->home_server;
2930 rtt = now.tv_sec - request->proxy_when.tv_sec;
2933 rtt -= request->proxy_when.tv_usec;
2935 if (!home->has_rtt) {
2936 home->has_rtt = TRUE;
2939 home->rttvar = rtt / 2;
2942 home->rttvar -= home->rttvar >> 2;
2943 home->rttvar += (home->srtt - rtt);
2944 home->srtt -= home->srtt >> 3;
2945 home->srtt += rtt >> 3;
2948 home->rto = home->srtt;
2949 if (home->rttvar > (USEC / 4)) {
2950 home->rto += home->rttvar * 4;
2958 * There's no incoming request, so it's a proxied packet
2961 if (!request->packet) {
2962 received_response_to_ping(request);
2966 request->child_state = REQUEST_QUEUED;
2967 request->when = now;
2968 request->delay = USEC;
2969 request->priority = RAD_LISTEN_PROXY;
2970 tv_add(&request->when, request->delay);
2973 * Wait a bit will take care of max_request_time
2975 INSERT_EVENT(wait_a_bit, request);
2981 void event_new_fd(rad_listen_t *this)
2985 this->print(this, buffer, sizeof(buffer));
2987 if (this->status == RAD_LISTEN_STATUS_INIT) {
2989 DEBUG("Listening on %s", buffer);
2991 DEBUG2(" ... adding new socket %s", buffer);
2993 if (!fr_event_fd_insert(el, 0, this->fd,
2994 event_socket_handler, this)) {
2995 radlog(L_ERR, "Failed remembering handle for proxy socket!");
2999 this->status = RAD_LISTEN_STATUS_KNOWN;
3003 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3004 DEBUG2(" ... closing socket %s", buffer);
3006 fr_event_fd_delete(el, 0, this->fd);
3007 this->status = RAD_LISTEN_STATUS_FINISH;
3010 * Close the fd AFTER fixing up the requests and
3011 * listeners, so that they don't send/recv on the
3012 * wrong socket (if someone manages to open
3020 static void handle_signal_self(int flag)
3022 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3023 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3024 fr_event_loop_exit(el, 1);
3026 fr_event_loop_exit(el, 2);
3030 } /* else exit/term flags weren't set */
3033 * Tell the even loop to stop processing.
3035 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3037 static time_t last_hup = 0;
3039 DEBUG("Received HUP signal.");
3042 if ((int) (when - last_hup) < 5) {
3043 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3048 fr_event_loop_exit(el, 0x80);
3052 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3056 * FIXME: O(N) loops suck.
3058 for (this = mainconfig.listen;
3060 this = this->next) {
3062 struct timeval when;
3064 if (this->type != RAD_LISTEN_DETAIL) continue;
3066 delay = detail_delay(this);
3067 if (!delay) continue;
3069 fr_event_now(el, &now);
3071 tv_add(&when, delay);
3073 if (delay > (USEC / 10)) {
3074 DEBUG("Delaying next detail event for %d.%01u seconds.",
3075 delay / USEC, (delay % USEC) / 100000);
3079 * Reset the detail timer.
3081 if (!fr_event_insert(el, event_poll_detail, this,
3083 radlog(L_ERR, "Failed remembering detail timer");
3090 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3093 for (this = mainconfig.listen;
3095 this = this->next) {
3096 if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
3103 #ifndef WITH_SELF_PIPE
3104 void radius_signal_self(int flag)
3106 handle_signal_self(flag);
3110 * Inform ourselves that we received a signal.
3112 void radius_signal_self(int flag)
3118 * The read MUST be non-blocking for this to work.
3120 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3124 for (i = 0; i < rcode; i++) {
3125 buffer[0] |= buffer[i];
3133 write(self_pipe[1], buffer, 1);
3137 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3138 UNUSED int fd, UNUSED void *ctx)
3143 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3144 if (rcode <= 0) return;
3147 * Merge pending signals.
3149 for (i = 0; i < rcode; i++) {
3150 buffer[0] |= buffer[i];
3153 handle_signal_self(buffer[0]);
3158 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3161 rad_listen_t *listener = ctx;
3162 RAD_REQUEST_FUNP fun;
3165 rad_assert(xel == el);
3169 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3171 if (!listener->recv(listener, &fun, &request)) return;
3173 if (!thread_pool_addrequest(request, fun)) {
3174 request->child_state = REQUEST_DONE;
3180 * This function is called periodically to see if this detail
3181 * file is available for reading.
3183 static void event_poll_detail(void *ctx)
3186 RAD_REQUEST_FUNP fun;
3188 rad_listen_t *this = ctx;
3189 struct timeval when;
3191 fr_event_now(el, &now);
3195 * Set the next poll time to be 1.0 to 1.1s, to help
3196 * spread the load a bit over time.
3199 when.tv_usec += fr_rand() % (USEC / 10);
3201 rad_assert(this->type == RAD_LISTEN_DETAIL);
3204 * Try to read something.
3206 * FIXME: This does poll AND receive.
3208 rcode = this->recv(this, &fun, &request);
3210 rad_assert(fun != NULL);
3211 rad_assert(request != NULL);
3213 if (!thread_pool_addrequest(request, fun)) {
3214 request->child_state = REQUEST_DONE;
3219 * Reset the poll to fire one second from now. If the
3220 * detail reader DOES read a packet, it will send us a
3221 * signal when it's done, and the signal handler will
3222 * reset the timer to a more appropriate (i.e. shorter)
3225 if (!fr_event_insert(el, event_poll_detail, this,
3227 radlog(L_ERR, "Failed creating handler");
3233 static void event_status(struct timeval *wake)
3235 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3239 if (debug_flag == 0) {
3241 radlog(L_INFO, "Ready to process requests.");
3242 just_started = FALSE;
3248 DEBUG("Ready to process requests.");
3250 } else if ((wake->tv_sec != 0) ||
3251 (wake->tv_usec >= 100000)) {
3252 DEBUG("Waking up in %d.%01u seconds.",
3253 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3258 * FIXME: Put this somewhere else, where it isn't called
3259 * all of the time...
3262 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3264 * If there are no child threads, then there may
3265 * be child processes. In that case, wait for
3266 * their exit status, and throw that exit status
3267 * away. This helps get rid of zxombie children.
3269 while (waitpid(-1, &argval, WNOHANG) > 0) {
3277 * Externally-visibly functions.
3279 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3281 rad_listen_t *this, *head = NULL;
3285 time(&fr_start_time);
3287 el = fr_event_list_create(event_status);
3290 pl = fr_packet_list_create(0);
3291 if (!pl) return 0; /* leak el */
3293 request_num_counter = 0;
3296 * Move all of the thread calls to this file?
3298 * It may be best for the mutexes to be in this file...
3300 have_children = spawn_flag;
3303 if (mainconfig.proxy_requests) {
3305 * Create the tree for managing proxied requests and
3308 proxy_list = fr_packet_list_create(1);
3309 if (!proxy_list) return 0;
3311 #ifdef HAVE_PTHREAD_H
3312 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3313 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3322 * Just before we spawn the child threads, force the log
3323 * subsystem to re-open the log file for every write.
3325 if (spawn_flag) force_log_reopen();
3327 #ifdef HAVE_PTHREAD_H
3329 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3331 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3333 if (thread_pool_init(cs, spawn_flag) < 0) {
3339 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3344 #ifdef WITH_SELF_PIPE
3346 * Child threads need a pipe to signal us, as do the
3349 if (pipe(self_pipe) < 0) {
3350 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3354 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3355 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3359 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3360 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3365 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3366 event_signal_handler, el)) {
3367 radlog(L_ERR, "Failed creating handler for signals");
3370 #endif /* WITH_SELF_PIPE */
3374 * Mark the proxy Fd's as unused.
3379 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3383 DEBUG("%s: #### Opening IP addresses and Ports ####",
3387 * The server temporarily switches to an unprivileged
3388 * user very early in the bootstrapping process.
3389 * However, some sockets MAY require privileged access
3390 * (bind to device, or to port < 1024, or to raw
3391 * sockets). Those sockets need to call suid up/down
3392 * themselves around the functions that need a privileged
3395 if (listen_init(cs, &head) < 0) {
3400 * At this point, no one has any business *ever* going
3403 fr_suid_down_permanent();
3406 * Add all of the sockets to the event loop.
3410 this = this->next) {
3413 this->print(this, buffer, sizeof(buffer));
3415 switch (this->type) {
3417 struct timeval when;
3419 case RAD_LISTEN_DETAIL:
3420 DEBUG("Listening on %s", buffer);
3423 * Add some initial jitter to help spread
3426 when.tv_sec = fr_start_time + 1;
3427 when.tv_usec = fr_rand() % USEC;
3429 if (!fr_event_insert(el, event_poll_detail, this,
3431 radlog(L_ERR, "Failed creating detail poll timer");
3438 case RAD_LISTEN_PROXY:
3439 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3440 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3442 proxy_fds[this->fd & 0x1f] = this->fd;
3443 proxy_listeners[this->fd & 0x1f] = this;
3444 if (!fr_packet_list_socket_add(proxy_list,
3456 * The file descriptor isn't ready. Poll for
3457 * when it will become ready. This is for the
3467 mainconfig.listen = head;
3473 static int request_hash_cb(UNUSED void *ctx, void *data)
3475 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3478 rad_assert(request->in_proxy_hash == FALSE);
3481 fr_event_delete(el, &request->ev);
3482 remove_from_request_hash(request);
3483 request_free(&request);
3490 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3492 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3494 fr_packet_list_yank(proxy_list, request->proxy);
3495 request->in_proxy_hash = FALSE;
3497 if (!request->in_request_hash) {
3498 fr_event_delete(el, &request->ev);
3499 request_free(&request);
3506 void radius_event_free(void)
3509 * FIXME: Stop all threads, or at least check that
3510 * they're all waiting on the semaphore, and the queues
3516 * There are requests in the proxy hash that aren't
3517 * referenced from anywhere else. Remove them first.
3520 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3521 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3522 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3523 fr_packet_list_free(proxy_list);
3528 fr_packet_list_walk(pl, NULL, request_hash_cb);
3530 fr_packet_list_free(pl);
3533 fr_event_list_free(el);
3536 int radius_event_process(void)
3540 return fr_event_loop(el);
3543 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3545 request->options = RAD_REQUEST_OPTION_DEBUG2;
3547 if (request_pre_handler(request)) {
3548 rad_assert(fun != NULL);
3549 rad_assert(request != NULL);
3551 if (request->server) RDEBUG("server %s {",
3555 if (request->server) RDEBUG("} # server %s",
3558 request_post_handler(request);
3561 DEBUG2("Going to the next request");