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 has_detail_listener = FALSE;
59 static int just_started = TRUE;
62 static int self_pipe[2];
67 static pthread_mutex_t proxy_mutex;
70 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
71 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
74 * This is easier than ifdef's throughout the code.
76 #define PTHREAD_MUTEX_LOCK(_x)
77 #define PTHREAD_MUTEX_UNLOCK(_x)
78 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
80 radius_handle_request(request, fun);
85 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
88 static fr_packet_list_t *proxy_list = NULL;
91 * We keep the proxy FD's here. The RADIUS Id's are marked
92 * "allocated" per Id, via a bit per proxy FD.
94 static int proxy_fds[32];
95 static rad_listen_t *proxy_listeners[32];
97 #define remove_from_proxy_hash(foo)
100 static void request_post_handler(REQUEST *request);
101 static void wait_a_bit(void *ctx);
102 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
104 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
107 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
114 static void tv_add(struct timeval *tv, int usec_delay)
116 if (usec_delay > USEC) {
117 tv->tv_sec += usec_delay / USEC;
120 tv->tv_usec += usec_delay;
122 if (tv->tv_usec > USEC) {
128 static void remove_from_request_hash(REQUEST *request)
130 if (!request->in_request_hash) return;
132 fr_packet_list_yank(pl, request->packet);
133 request->in_request_hash = FALSE;
135 request_stats_final(request);
140 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
142 RADIUS_PACKET **proxy_p;
145 PTHREAD_MUTEX_LOCK(&proxy_mutex);
146 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
149 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
153 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
156 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
160 request->num_proxied_responses++;
163 * Catch the most common case of everything working
166 if (request->num_proxied_requests == request->num_proxied_responses) {
167 fr_packet_list_yank(proxy_list, request->proxy);
168 fr_packet_list_id_free(proxy_list, request->proxy);
169 request->in_proxy_hash = FALSE;
173 * On the FIRST reply, decrement the count of outstanding
174 * requests. Note that this is NOT the count of sent
175 * packets, but whether or not the home server has
178 if (!request->proxy_reply &&
179 request->home_server->currently_outstanding) {
180 request->home_server->currently_outstanding--;
183 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
189 static void remove_from_proxy_hash(REQUEST *request)
191 if (!request->in_proxy_hash) return;
193 PTHREAD_MUTEX_LOCK(&proxy_mutex);
194 fr_packet_list_yank(proxy_list, request->proxy);
195 fr_packet_list_id_free(proxy_list, request->proxy);
198 * The home server hasn't replied, but we've given up on
199 * this request. Don't count this request against the
202 if (!request->proxy_reply &&
203 request->home_server->currently_outstanding) {
204 request->home_server->currently_outstanding--;
207 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
209 request->in_proxy_hash = FALSE;
213 static int insert_into_proxy_hash(REQUEST *request)
218 rad_assert(request->proxy != NULL);
219 rad_assert(proxy_list != NULL);
221 request->proxy->sockfd = -1;
223 PTHREAD_MUTEX_LOCK(&proxy_mutex);
225 request->home_server->currently_outstanding++;
227 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
229 rad_listen_t *proxy_listener;
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 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
239 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
247 proxy = proxy_listener->fd;
248 for (i = 0; i < 32; i++) {
250 * Found a free entry. Save the socket,
251 * and remember where we saved it.
253 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
254 found = (proxy + i) & 0x1f;
255 proxy_fds[found] = proxy;
256 proxy_listeners[found] = proxy_listener;
260 rad_assert(found >= 0);
262 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
263 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
264 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
269 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
270 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
271 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
276 * Signal the main thread to add the new FD to the list
279 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
281 rad_assert(request->proxy->sockfd >= 0);
284 * FIXME: Hack until we get rid of rad_listen_t, and put
285 * the information into the packet_list.
288 for (i = 0; i < 32; i++) {
289 if (proxy_fds[i] == request->proxy->sockfd) {
296 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
297 RDEBUG2("ERROR: All sockets are full.");
301 rad_assert(proxy_fds[proxy] != -1);
302 rad_assert(proxy_listeners[proxy] != NULL);
303 request->proxy_listener = proxy_listeners[proxy];
305 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
306 fr_packet_list_id_free(proxy_list, request->proxy);
307 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
308 RDEBUG2("ERROR: Failed to insert entry into proxy list");
312 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
314 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
315 inet_ntop(request->proxy->dst_ipaddr.af,
316 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
317 request->proxy->dst_port,
320 request->in_proxy_hash = TRUE;
327 * Called as BOTH an event, and in-line from other functions.
329 static void wait_for_proxy_id_to_expire(void *ctx)
331 REQUEST *request = ctx;
332 home_server *home = request->home_server;
334 rad_assert(request->magic == REQUEST_MAGIC);
335 rad_assert(request->proxy != NULL);
337 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
338 request->when = request->proxy_when;
339 request->when.tv_sec += home->response_window;
341 if ((request->num_proxied_requests == request->num_proxied_responses) ||
342 timercmp(&now, &request->when, >)) {
343 if (request->packet) {
344 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
345 request->number, request->packet->id,
346 (unsigned int) (request->timestamp - fr_start_time));
348 RDEBUG2("Cleaning up request %d with timestamp +%d",
350 (unsigned int) (request->timestamp - fr_start_time));
352 fr_event_delete(el, &request->ev);
353 remove_from_proxy_hash(request);
354 remove_from_request_hash(request);
355 request_free(&request);
359 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
363 #ifdef HAVE_PTHREAD_H
364 static void wait_for_child_to_die(void *ctx)
366 REQUEST *request = ctx;
368 rad_assert(request->magic == REQUEST_MAGIC);
370 if ((request->child_state == REQUEST_QUEUED) |
371 (request->child_state == REQUEST_RUNNING)) {
372 request->delay += (request->delay >> 1);
373 tv_add(&request->when, request->delay);
375 RDEBUG2("Child is still stuck for request %d", request->number);
377 INSERT_EVENT(wait_for_child_to_die, request);
381 RDEBUG2("Child is finally responsive for request %d", request->number);
382 remove_from_request_hash(request);
385 if (request->proxy) {
386 wait_for_proxy_id_to_expire(request);
391 request_free(&request);
395 static void cleanup_delay(void *ctx)
397 REQUEST *request = ctx;
399 rad_assert(request->magic == REQUEST_MAGIC);
400 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
401 (request->child_state == REQUEST_DONE));
403 remove_from_request_hash(request);
406 if (request->proxy && request->in_proxy_hash) {
407 wait_for_proxy_id_to_expire(request);
412 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
413 request->number, request->packet->id,
414 (unsigned int) (request->timestamp - fr_start_time));
416 fr_event_delete(el, &request->ev);
417 request_free(&request);
422 * FIXME: Put into a libradius function.
424 #define MAX_PACKET_CODE (52)
425 static const char *packet_codes[] = {
430 "Accounting-Request",
431 "Accounting-Response",
436 "Accounting-Message",
447 "Resource-Free-Request",
448 "Resource-Free-Response",
449 "Resource-Query-Request",
450 "Resource-Query-Response",
451 "Alternate-Resource-Reclaim-Request",
452 "NAS-Reboot-Request",
453 "NAS-Reboot-Response",
466 "Disconnect-Request",
476 "IP-Address-Allocate",
482 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
486 const char *received, *from;
487 const fr_ipaddr_t *ip;
492 if (direction == 0) {
493 received = "Received";
494 from = "from"; /* what else? */
495 ip = &packet->src_ipaddr;
496 port = packet->src_port;
499 received = "Sending";
500 from = "to"; /* hah! */
501 ip = &packet->dst_ipaddr;
502 port = packet->dst_port;
506 * Client-specific debugging re-prints the input
507 * packet into the client log.
509 * This really belongs in a utility library
511 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
512 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
513 received, packet_codes[packet->code], from,
514 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
515 port, packet->id, packet->data_len);
517 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
519 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
521 packet->code, packet->id, packet->data_len);
524 for (vp = packet->vps; vp != NULL; vp = vp->next) {
525 vp_prints(buffer, sizeof(buffer), vp);
526 request->radlog(L_DBG, 0, request, "\t%s", buffer);
530 static void reject_delay(void *ctx)
532 REQUEST *request = ctx;
534 rad_assert(request->magic == REQUEST_MAGIC);
535 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
537 RDEBUG2("Sending delayed reject for request %d", request->number);
539 if (!debug_flag && request->options) {
540 debug_packet(request, request->reply, 1);
542 request->listener->send(request->listener, request);
544 request->when.tv_sec += request->root->cleanup_delay;
545 request->child_state = REQUEST_CLEANUP_DELAY;
547 INSERT_EVENT(cleanup_delay, request);
552 static void revive_home_server(void *ctx)
554 home_server *home = ctx;
557 home->state = HOME_STATE_ALIVE;
558 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
559 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
560 buffer, sizeof(buffer)),
562 home->currently_outstanding = 0;
563 home->revive_time = now;
567 static void no_response_to_ping(void *ctx)
569 REQUEST *request = ctx;
570 home_server *home = request->home_server;
573 home->num_received_pings = 0;
575 RDEBUG2("No response to status check %d from home server %s port %d",
577 inet_ntop(request->proxy->dst_ipaddr.af,
578 &request->proxy->dst_ipaddr.ipaddr,
579 buffer, sizeof(buffer)),
580 request->proxy->dst_port);
582 wait_for_proxy_id_to_expire(request);
586 static void received_response_to_ping(REQUEST *request)
588 home_server *home = request->home_server;
591 home->num_received_pings++;
593 RDEBUG2("Received response to status check %d (%d in current sequence)",
594 request->number, home->num_received_pings);
596 if (home->num_received_pings < home->num_pings_to_alive) {
597 wait_for_proxy_id_to_expire(request);
601 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
602 inet_ntop(request->proxy->dst_ipaddr.af,
603 &request->proxy->dst_ipaddr.ipaddr,
604 buffer, sizeof(buffer)),
605 request->proxy->dst_port);
607 if (!fr_event_delete(el, &home->ev)) {
608 RDEBUG2("Hmm... no event for home server, WTF?");
611 if (!fr_event_delete(el, &request->ev)) {
612 RDEBUG2("Hmm... no event for request, WTF?");
615 wait_for_proxy_id_to_expire(request);
617 home->state = HOME_STATE_ALIVE;
618 home->currently_outstanding = 0;
619 home->revive_time = now;
623 static void ping_home_server(void *ctx)
626 home_server *home = ctx;
630 if (home->state == HOME_STATE_ALIVE) {
631 radlog(L_INFO, "Suspicious proxy state... continuing");
635 request = request_alloc();
636 request->number = request_num_counter++;
638 request->proxy = rad_alloc(1);
639 rad_assert(request->proxy != NULL);
641 fr_event_now(el, &request->when);
642 home->when = request->when;
644 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
645 request->proxy->code = PW_STATUS_SERVER;
647 radius_pairmake(request, &request->proxy->vps,
648 "Message-Authenticator", "0x00", T_OP_SET);
650 } else if (home->type == HOME_TYPE_AUTH) {
651 request->proxy->code = PW_AUTHENTICATION_REQUEST;
653 radius_pairmake(request, &request->proxy->vps,
654 "User-Name", home->ping_user_name, T_OP_SET);
655 radius_pairmake(request, &request->proxy->vps,
656 "User-Password", home->ping_user_password, T_OP_SET);
657 radius_pairmake(request, &request->proxy->vps,
658 "Service-Type", "Authenticate-Only", T_OP_SET);
659 radius_pairmake(request, &request->proxy->vps,
660 "Message-Authenticator", "0x00", T_OP_SET);
663 #ifdef WITH_ACCOUNTING
664 request->proxy->code = PW_ACCOUNTING_REQUEST;
666 radius_pairmake(request, &request->proxy->vps,
667 "User-Name", home->ping_user_name, T_OP_SET);
668 radius_pairmake(request, &request->proxy->vps,
669 "Acct-Status-Type", "Stop", T_OP_SET);
670 radius_pairmake(request, &request->proxy->vps,
671 "Acct-Session-Id", "00000000", T_OP_SET);
672 vp = radius_pairmake(request, &request->proxy->vps,
673 "Event-Timestamp", "0", T_OP_SET);
674 vp->vp_date = now.tv_sec;
676 rad_assert("Internal sanity check failed");
680 radius_pairmake(request, &request->proxy->vps,
681 "NAS-Identifier", "Status Check. Are you alive?",
684 request->proxy->dst_ipaddr = home->ipaddr;
685 request->proxy->dst_port = home->port;
686 request->home_server = home;
688 rad_assert(request->proxy_listener == NULL);
690 if (!insert_into_proxy_hash(request)) {
691 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
693 request_free(&request);
696 rad_assert(request->proxy_listener != NULL);
697 request->proxy_listener->send(request->proxy_listener,
700 request->next_callback = NULL;
701 request->child_state = REQUEST_PROXIED;
702 request->when.tv_sec += home->ping_timeout;;
704 INSERT_EVENT(no_response_to_ping, request);
707 * Add +/- 2s of jitter, as suggested in RFC 3539
708 * and in the Issues and Fixes draft.
710 home->when.tv_sec += home->ping_interval - 2;
713 jitter ^= (jitter >> 10);
714 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
716 tv_add(&home->when, jitter);
719 INSERT_EVENT(ping_home_server, home);
723 static void check_for_zombie_home_server(REQUEST *request)
729 home = request->home_server;
731 if (home->state != HOME_STATE_ZOMBIE) return;
733 when = home->zombie_period_start;
734 when.tv_sec += home->zombie_period;
736 fr_event_now(el, &now);
737 if (timercmp(&now, &when, <)) {
742 * It's been a zombie for too long, mark it as
745 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
746 inet_ntop(request->proxy->dst_ipaddr.af,
747 &request->proxy->dst_ipaddr.ipaddr,
748 buffer, sizeof(buffer)),
749 request->proxy->dst_port);
750 home->state = HOME_STATE_IS_DEAD;
751 home->num_received_pings = 0;
752 home->when = request->when;
754 if (home->ping_check != HOME_PING_CHECK_NONE) {
755 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
756 (home->ping_user_name != NULL));
757 home->when.tv_sec += home->ping_interval;
759 INSERT_EVENT(ping_home_server, home);
761 home->when.tv_sec += home->revive_interval;
763 INSERT_EVENT(revive_home_server, home);
767 static int proxy_to_virtual_server(REQUEST *request);
769 static int virtual_server_handler(UNUSED REQUEST *request)
771 proxy_to_virtual_server(request);
775 static void proxy_fallback_handler(REQUEST *request)
778 * A proper time is required for wait_a_bit.
780 request->delay = USEC / 10;
781 gettimeofday(&now, NULL);
782 request->next_when = now;
783 tv_add(&request->next_when, request->delay);
784 request->next_callback = wait_a_bit;
787 * Re-queue the request.
789 request->child_state = REQUEST_QUEUED;
791 rad_assert(request->proxy != NULL);
792 if (!thread_pool_addrequest(request, virtual_server_handler)) {
793 request->child_state = REQUEST_DONE;
796 #ifdef HAVE_PTHREAD_H
798 * MAY free the request if we're over max_request_time,
799 * AND we're not in threaded mode!
801 * Note that we call this ONLY if we're threaded, as
802 * if we're NOT threaded, request_post_handler() calls
803 * wait_a_bit(), which means that "request" may not
806 if (have_children) wait_a_bit(request);
811 static int setup_post_proxy_fail(REQUEST *request)
813 DICT_VALUE *dval = NULL;
816 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
817 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
819 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
820 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
826 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
829 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
833 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
834 if (!vp) vp = radius_paircreate(request, &request->config_items,
835 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
836 vp->vp_integer = dval->value;
838 rad_assert(request->proxy_reply == NULL);
844 static int null_handler(UNUSED REQUEST *request)
849 static void post_proxy_fail_handler(REQUEST *request)
852 * A proper time is required for wait_a_bit.
854 request->delay = USEC / 10;
855 gettimeofday(&now, NULL);
858 * Not set up to run Post-Proxy-Type = Fail.
860 * Mark the request as still running, and figure out what
863 if (!setup_post_proxy_fail(request)) {
864 request->child_state = REQUEST_RUNNING;
865 request_post_handler(request);
869 * Re-queue the request.
871 request->child_state = REQUEST_QUEUED;
874 * There is a post-proxy-type of fail. We run
875 * the request through the pre/post proxy
876 * handlers, just like it was a real proxied
877 * request. However, we set the per-request
878 * handler to NULL, as we don't want to do
881 * Note that when we're not threaded, this will
882 * process the request even if it's greater than
883 * max_request_time. That's not fatal.
885 request->priority = 0;
886 rad_assert(request->proxy != NULL);
887 thread_pool_addrequest(request, null_handler);
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);
903 /* maybe check this against wait_for_proxy_id_to_expire? */
904 static void no_response_to_proxied_request(void *ctx)
906 REQUEST *request = ctx;
910 rad_assert(request->magic == REQUEST_MAGIC);
911 rad_assert(request->child_state == REQUEST_PROXIED);
914 * If we've failed over to an internal home server,
915 * replace the callback with the correct one. This
916 * is due to locking issues with child threads...
918 if (request->home_server->server) {
923 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
925 inet_ntop(request->proxy->dst_ipaddr.af,
926 &request->proxy->dst_ipaddr.ipaddr,
927 buffer, sizeof(buffer)),
928 request->proxy->dst_port);
930 check_for_zombie_home_server(request);
932 home = request->home_server;
934 post_proxy_fail_handler(request);
937 * Don't touch request due to race conditions
939 if (home->state == HOME_STATE_IS_DEAD) {
940 rad_assert(home->ev != NULL); /* or it will never wake up */
945 * Enable the zombie period when we notice that the home
946 * server hasn't responded. We also back-date the start
947 * of the zombie period to when the proxied request was
950 if (home->state == HOME_STATE_ALIVE) {
951 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
952 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
953 buffer, sizeof(buffer)),
955 home->state = HOME_STATE_ZOMBIE;
956 home->zombie_period_start = now;
957 home->zombie_period_start.tv_sec -= home->response_window;
963 static void wait_a_bit(void *ctx)
966 REQUEST *request = ctx;
967 fr_event_callback_t callback = NULL;
969 rad_assert(request->magic == REQUEST_MAGIC);
971 switch (request->child_state) {
973 case REQUEST_RUNNING:
974 when = request->received;
975 when.tv_sec += request->root->max_request_time;
978 * Normally called from the event loop with the
979 * proper event loop time. Otherwise, called from
980 * post proxy fail handler, which sets "now", and
981 * this call won't re-set it, because we're not
984 fr_event_now(el, &now);
987 * Request still has more time. Continue
990 if (timercmp(&now, &when, <) ||
991 ((request->listener->type == RAD_LISTEN_DETAIL) &&
992 (request->child_state == REQUEST_QUEUED))) {
993 if (request->delay < (USEC / 10)) {
994 request->delay = USEC / 10;
996 request->delay += request->delay >> 1;
1000 * Cap wait at some sane value for detail
1003 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1004 (request->delay > (request->root->max_request_time * USEC))) {
1005 request->delay = request->root->max_request_time * USEC;
1009 request->when = now;
1010 tv_add(&request->when, request->delay);
1011 callback = wait_a_bit;
1015 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1017 * A child thread MAY still be running on the
1018 * request. Ask the thread to stop working on
1021 if (have_children) {
1022 /* FIXME: kill unresponsive children? */
1025 * Print this error message ONLY if
1026 * there's a child currently processing
1027 * the request. As we don't have thread
1028 * locks here, there may be race
1029 * conditions on this check. But it's
1030 * just an error message, so that's OK.
1032 if (request->child_pid != NO_SUCH_CHILD_PID) {
1033 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
1034 (unsigned long)request->child_pid, request->number,
1035 request->module ? request->module : "<server core>",
1036 request->component ? request->component : "<server core>");
1039 request->master_state = REQUEST_STOP_PROCESSING;
1041 request->delay = USEC / 4;
1042 tv_add(&request->when, request->delay);
1043 callback = wait_for_child_to_die;
1049 * Else there are no child threads. We probably
1050 * should have just marked the request as 'done'
1051 * elsewhere, like in the post-proxy-fail
1052 * handler. But doing that would involve
1053 * checking for max_request_time in multiple
1054 * places, so this may be simplest.
1056 request->child_state = REQUEST_DONE;
1060 * Mark the request as no longer running,
1064 #ifdef HAVE_PTHREAD_H
1065 request->child_pid = NO_SUCH_CHILD_PID;
1067 request_stats_final(request);
1068 cleanup_delay(request);
1071 case REQUEST_REJECT_DELAY:
1072 case REQUEST_CLEANUP_DELAY:
1073 #ifdef HAVE_PTHREAD_H
1074 request->child_pid = NO_SUCH_CHILD_PID;
1076 request_stats_final(request);
1078 case REQUEST_PROXIED:
1079 rad_assert(request->next_callback != NULL);
1080 rad_assert(request->next_callback != wait_a_bit);
1082 request->when = request->next_when;
1083 callback = request->next_callback;
1084 request->next_callback = NULL;
1088 rad_panic("Internal sanity check failure");
1093 * Something major went wrong. Discard the request, and
1096 * FIXME: No idea why this happens or how to fix it...
1097 * It seems to happen *only* when requests are proxied,
1098 * and where the home server doesn't respond. So it looks
1099 * like a race condition above, but it happens in debug
1100 * mode, with no threads...
1103 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1104 fr_event_delete(el, &request->ev);
1105 remove_from_proxy_hash(request);
1106 remove_from_request_hash(request);
1107 request_free(&request);
1111 INSERT_EVENT(callback, request);
1116 static int process_proxy_reply(REQUEST *request)
1119 int post_proxy_type = 0;
1123 * Delete any reply we had accumulated until now.
1125 pairfree(&request->reply->vps);
1128 * Run the packet through the post-proxy stage,
1129 * BEFORE playing games with the attributes.
1131 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1133 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1134 post_proxy_type = vp->vp_integer;
1137 rad_assert(request->home_pool != NULL);
1139 if (request->home_pool->virtual_server) {
1140 const char *old_server = request->server;
1142 request->server = request->home_pool->virtual_server;
1143 RDEBUG2(" server %s {", request->server);
1144 rcode = module_post_proxy(post_proxy_type, request);
1146 request->server = old_server;
1148 rcode = module_post_proxy(post_proxy_type, request);
1152 * There may NOT be a proxy reply, as we may be
1153 * running Post-Proxy-Type = Fail.
1155 if (request->proxy_reply) {
1157 * Delete the Proxy-State Attributes from
1158 * the reply. These include Proxy-State
1159 * attributes from us and remote server.
1161 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1164 * Add the attributes left in the proxy
1165 * reply to the reply list.
1167 pairadd(&request->reply->vps, request->proxy_reply->vps);
1168 request->proxy_reply->vps = NULL;
1171 * Free proxy request pairs.
1173 pairfree(&request->proxy->vps);
1177 default: /* Don't do anything */
1179 case RLM_MODULE_FAIL:
1180 /* FIXME: debug print stuff */
1181 request->child_state = REQUEST_DONE;
1184 case RLM_MODULE_HANDLED:
1185 /* FIXME: debug print stuff */
1186 request->child_state = REQUEST_DONE;
1194 static int request_pre_handler(REQUEST *request)
1198 rad_assert(request->magic == REQUEST_MAGIC);
1199 rad_assert(request->packet != NULL);
1201 request->child_state = REQUEST_RUNNING;
1204 * Don't decode the packet if it's an internal "fake"
1205 * request. Instead, just return so that the caller can
1208 if (request->packet->dst_port == 0) {
1209 request->username = pairfind(request->packet->vps,
1211 request->password = pairfind(request->packet->vps,
1218 * Put the decoded packet into it's proper place.
1220 if (request->proxy_reply != NULL) {
1221 rcode = request->proxy_listener->decode(request->proxy_listener,
1223 if (!debug_flag && request->options) {
1224 debug_packet(request, request->proxy_reply, 0);
1228 if (request->packet->vps == NULL) {
1229 rcode = request->listener->decode(request->listener, request);
1231 if (debug_condition) {
1235 * Ignore parse errors.
1237 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1238 &debug_condition, 1,
1241 request->priority = 2;
1242 request->radlog = radlog_request;
1246 if (!debug_flag && request->options) {
1247 debug_packet(request, request->packet, 0);
1254 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1255 request->child_state = REQUEST_DONE;
1260 if (!request->proxy)
1263 request->username = pairfind(request->packet->vps,
1268 return process_proxy_reply(request);
1278 * Do state handling when we proxy a request.
1280 static int proxy_request(REQUEST *request)
1282 struct timeval when;
1285 if (request->home_server->server) {
1286 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1290 if (!insert_into_proxy_hash(request)) {
1291 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1295 request->proxy_listener->encode(request->proxy_listener, request);
1297 when = request->received;
1298 when.tv_sec += request->root->max_request_time;
1300 gettimeofday(&request->proxy_when, NULL);
1302 request->next_when = request->proxy_when;
1303 request->next_when.tv_sec += request->home_server->response_window;
1305 rad_assert(request->home_server->response_window > 0);
1307 if (timercmp(&when, &request->next_when, <)) {
1308 request->next_when = when;
1310 request->next_callback = no_response_to_proxied_request;
1312 RDEBUG2("Proxying request %d to home server %s port %d",
1314 inet_ntop(request->proxy->dst_ipaddr.af,
1315 &request->proxy->dst_ipaddr.ipaddr,
1316 buffer, sizeof(buffer)),
1317 request->proxy->dst_port);
1320 * Note that we set proxied BEFORE sending the packet.
1322 * Once we send it, the request is tainted, as
1323 * another thread may have picked it up. Don't
1326 request->num_proxied_requests = 1;
1327 request->num_proxied_responses = 0;
1328 #ifdef HAVE_PTHREAD_H
1329 request->child_pid = NO_SUCH_CHILD_PID;
1331 request->child_state = REQUEST_PROXIED;
1333 if (!debug_flag && request->options) {
1334 debug_packet(request, request->proxy, 1);
1337 request->proxy_listener->send(request->proxy_listener,
1344 * "Proxy" the request by sending it to a new virtual server.
1346 static int proxy_to_virtual_server(REQUEST *request)
1349 RAD_REQUEST_FUNP fun;
1351 if (!request->home_server || !request->home_server->server) return 0;
1353 if (request->parent) {
1354 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1358 fake = request_alloc_fake(request);
1360 RDEBUG2("WARNING: Out of memory");
1364 fake->packet->vps = paircopy(request->proxy->vps);
1365 fake->server = request->home_server->server;
1367 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1368 fun = rad_authenticate;
1370 #ifdef WITH_ACCOUNTING
1371 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1372 fun = rad_accounting;
1376 RDEBUG2("Unknown packet type %d", request->proxy->code);
1380 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1381 radius_handle_request(fake, fun);
1382 RDEBUG2("<<< Received proxied response from internal virtual server.");
1384 request->proxy_reply = fake->reply;
1387 request_free(&fake);
1389 process_proxy_reply(request);
1392 return 2; /* success, but NOT '1' !*/
1397 * Return 1 if we did proxy it, or the proxy attempt failed
1398 * completely. Either way, the caller doesn't touch the request
1399 * any more if we return 1.
1401 static int successfully_proxied_request(REQUEST *request)
1404 int pre_proxy_type = 0;
1405 VALUE_PAIR *realmpair;
1406 VALUE_PAIR *strippedname;
1410 REALM *realm = NULL;
1414 * If it was already proxied, do nothing.
1416 * FIXME: This should really be a serious error.
1418 if (request->in_proxy_hash) {
1422 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1423 if (!realmpair || (realmpair->length == 0)) {
1427 realmname = (char *) realmpair->vp_strvalue;
1429 realm = realm_find2(realmname);
1431 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1436 * Figure out which pool to use.
1438 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1439 pool = realm->auth_pool;
1441 #ifdef WITH_ACCOUNTING
1442 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1443 pool = realm->acct_pool;
1447 rad_panic("Internal sanity check failed");
1451 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1456 home = home_server_ldb(realmname, pool, request);
1458 RDEBUG2("ERROR: Failed to find live home server for realm %s",
1462 request->home_pool = pool;
1465 * Remember that we sent the request to a Realm.
1467 pairadd(&request->packet->vps,
1468 pairmake("Realm", realmname, T_OP_EQ));
1472 * We read the packet from a detail file, AND it came from
1473 * the server we're about to send it to. Don't do that.
1475 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1476 (request->listener->type == RAD_LISTEN_DETAIL) &&
1477 (home->ipaddr.af == AF_INET) &&
1478 (request->packet->src_ipaddr.af == AF_INET) &&
1479 (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1480 RDEBUG2(" rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1486 * Allocate the proxy packet, only if it wasn't already
1487 * allocated by a module. This check is mainly to support
1488 * the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1490 * In those cases, the EAP module creates a "fake"
1491 * request, and recursively passes it through the
1492 * authentication stage of the server. The module then
1493 * checks if the request was supposed to be proxied, and
1494 * if so, creates a proxy packet from the TUNNELED request,
1495 * and not from the EAP request outside of the tunnel.
1497 * The proxy then works like normal, except that the response
1498 * packet is "eaten" by the EAP module, and encapsulated into
1501 if (!request->proxy) {
1502 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1503 radlog(L_ERR|L_CONS, "no memory");
1508 * Copy the request, then look up name and
1509 * plain-text password in the copy.
1511 * Note that the User-Name attribute is the
1512 * *original* as sent over by the client. The
1513 * Stripped-User-Name attribute is the one hacked
1514 * through the 'hints' file.
1516 request->proxy->vps = paircopy(request->packet->vps);
1520 * Strip the name, if told to.
1522 * Doing it here catches the case of proxied tunneled
1525 if (realm->striprealm == TRUE &&
1526 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1528 * If there's a Stripped-User-Name attribute in
1529 * the request, then use THAT as the User-Name
1530 * for the proxied request, instead of the
1533 * This is done by making a copy of the
1534 * Stripped-User-Name attribute, turning it into
1535 * a User-Name attribute, deleting the
1536 * Stripped-User-Name and User-Name attributes
1537 * from the vps list, and making the new
1538 * User-Name the head of the vps list.
1540 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1542 vp = radius_paircreate(request, NULL,
1543 PW_USER_NAME, PW_TYPE_STRING);
1544 rad_assert(vp != NULL); /* handled by above function */
1545 /* Insert at the START of the list */
1546 vp->next = request->proxy->vps;
1547 request->proxy->vps = vp;
1549 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1550 sizeof(vp->vp_strvalue));
1551 vp->length = strippedname->length;
1554 * Do NOT delete Stripped-User-Name.
1559 * If there is no PW_CHAP_CHALLENGE attribute but
1560 * there is a PW_CHAP_PASSWORD we need to add it
1561 * since we can't use the request authenticator
1562 * anymore - we changed it.
1564 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1565 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1566 vp = radius_paircreate(request, &request->proxy->vps,
1567 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1568 vp->length = AUTH_VECTOR_LEN;
1569 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1573 * The RFC's say we have to do this, but FreeRADIUS
1576 vp = radius_paircreate(request, &request->proxy->vps,
1577 PW_PROXY_STATE, PW_TYPE_OCTETS);
1578 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
1579 request->packet->id);
1580 vp->length = strlen(vp->vp_strvalue);
1583 * Should be done BEFORE inserting into proxy hash, as
1584 * pre-proxy may use this information, or change it.
1586 request->proxy->code = request->packet->code;
1587 request->proxy->dst_ipaddr = home->ipaddr;
1588 request->proxy->dst_port = home->port;
1589 request->home_server = home;
1592 * Call the pre-proxy routines.
1594 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1596 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1597 pre_proxy_type = vp->vp_integer;
1600 rad_assert(request->home_pool != NULL);
1602 if (request->home_pool->virtual_server) {
1603 const char *old_server = request->server;
1605 request->server = request->home_pool->virtual_server;
1606 RDEBUG2(" server %s {", request->server);
1607 rcode = module_pre_proxy(pre_proxy_type, request);
1609 request->server = old_server;
1611 rcode = module_pre_proxy(pre_proxy_type, request);
1614 case RLM_MODULE_FAIL:
1615 case RLM_MODULE_INVALID:
1616 case RLM_MODULE_NOTFOUND:
1617 case RLM_MODULE_USERLOCK:
1619 /* FIXME: debug print failed stuff */
1622 case RLM_MODULE_REJECT:
1623 case RLM_MODULE_HANDLED:
1627 * Only proxy the packet if the pre-proxy code succeeded.
1629 case RLM_MODULE_NOOP:
1631 case RLM_MODULE_UPDATED:
1636 * If it's a fake request, don't send the proxy
1637 * packet. The outer tunnel session will take
1638 * care of doing that.
1640 if (request->packet->dst_port == 0) {
1641 request->home_server = NULL;
1645 if (request->home_server->server) {
1646 return proxy_to_virtual_server(request);
1649 if (!proxy_request(request)) {
1650 RDEBUG("ERROR: Failed to proxy request %d", request->number);
1659 static void request_post_handler(REQUEST *request)
1661 int child_state = -1;
1662 struct timeval when;
1665 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1667 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1668 RDEBUG2("Request %d was cancelled.", request->number);
1669 #ifdef HAVE_PTHREAD_H
1670 request->child_pid = NO_SUCH_CHILD_PID;
1672 request->child_state = REQUEST_DONE;
1676 if (request->child_state != REQUEST_RUNNING) {
1677 rad_panic("Internal sanity check failed");
1680 if ((request->reply->code == 0) &&
1681 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1682 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1683 request->reply->code = PW_AUTHENTICATION_REJECT;
1687 if (request->root->proxy_requests &&
1688 !request->in_proxy_hash &&
1689 (request->reply->code == 0) &&
1690 (request->packet->dst_port != 0) &&
1691 (request->packet->code != PW_STATUS_SERVER)) {
1692 int rcode = successfully_proxied_request(request);
1694 if (rcode == 1) return;
1697 * Failed proxying it (dead home servers, etc.)
1698 * Run it through Post-Proxy-Type = Fail, and
1699 * respond to the request.
1701 * Note that we're in a child thread here, so we
1702 * do NOT re-schedule the request. Instead, we
1703 * do what we would have done, which is run the
1704 * pre-handler, a NULL request handler, and then
1707 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1708 request_pre_handler(request);
1712 * Else we weren't supposed to proxy it,
1713 * OR we proxied it internally to a virutal server.
1719 * Fake requests don't get encoded or signed. The caller
1720 * also requires the reply VP's, so we don't free them
1723 if (request->packet->dst_port == 0) {
1724 /* FIXME: RDEBUG going to the next request */
1725 #ifdef HAVE_PTHREAD_H
1726 request->child_pid = NO_SUCH_CHILD_PID;
1728 request->child_state = REQUEST_DONE;
1734 * Copy Proxy-State from the request to the reply.
1736 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1737 if (vp) pairadd(&request->reply->vps, vp);
1741 * Access-Requests get delayed or cached.
1743 switch (request->packet->code) {
1744 case PW_AUTHENTICATION_REQUEST:
1745 gettimeofday(&request->next_when, NULL);
1747 if (request->reply->code == 0) {
1749 * Check if the lack of response is intentional.
1751 vp = pairfind(request->config_items,
1752 PW_RESPONSE_PACKET_TYPE);
1754 RDEBUG2("There was no response configured: rejecting request %d",
1756 request->reply->code = PW_AUTHENTICATION_REJECT;
1757 } else if (vp->vp_integer == 256) {
1758 RDEBUG2("Not responding to request %d",
1762 request->reply->code = vp->vp_integer;
1768 * Run rejected packets through
1770 * Post-Auth-Type = Reject
1772 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1773 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1774 vp = radius_pairmake(request, &request->config_items,
1775 "Post-Auth-Type", "Reject",
1777 if (vp) rad_postauth(request);
1780 * If configured, delay Access-Reject packets.
1782 * If request->root->reject_delay = 0, we discover
1783 * that we have to send the packet now.
1785 when = request->received;
1786 when.tv_sec += request->root->reject_delay;
1788 if (timercmp(&when, &request->next_when, >)) {
1789 RDEBUG2("Delaying reject of request %d for %d seconds",
1791 request->root->reject_delay);
1792 request->next_when = when;
1793 request->next_callback = reject_delay;
1794 #ifdef HAVE_PTHREAD_H
1795 request->child_pid = NO_SUCH_CHILD_PID;
1797 request->child_state = REQUEST_REJECT_DELAY;
1802 request->next_when.tv_sec += request->root->cleanup_delay;
1803 request->next_callback = cleanup_delay;
1804 child_state = REQUEST_CLEANUP_DELAY;
1807 case PW_ACCOUNTING_REQUEST:
1808 request->next_callback = NULL; /* just to be safe */
1809 child_state = REQUEST_DONE;
1813 * FIXME: Status-Server should probably not be
1816 case PW_STATUS_SERVER:
1817 request->next_callback = NULL;
1818 child_state = REQUEST_DONE;
1822 if ((request->packet->code > 1024) &&
1823 (request->packet->code < (1024 + 254 + 1))) {
1824 request->next_callback = NULL;
1825 child_state = REQUEST_DONE;
1829 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
1830 rad_panic("Unknown packet type");
1835 * Suppress "no reply" packets here, unless we're reading
1836 * from the "detail" file. In that case, we've got to
1837 * tell the detail file handler that the request is dead,
1838 * and it should re-send it.
1839 * If configured, encode, sign, and send.
1841 if ((request->reply->code != 0) ||
1842 (request->listener->type == RAD_LISTEN_DETAIL)) {
1843 if (!debug_flag && request->options) {
1844 debug_packet(request, request->reply, 1);
1846 request->listener->send(request->listener, request);
1850 * Clean up. These are no longer needed.
1852 pairfree(&request->config_items);
1854 pairfree(&request->packet->vps);
1855 request->username = NULL;
1856 request->password = NULL;
1858 pairfree(&request->reply->vps);
1861 if (request->proxy) {
1862 pairfree(&request->proxy->vps);
1864 if (request->proxy_reply) {
1865 pairfree(&request->proxy_reply->vps);
1870 * We're not tracking responses from the home
1871 * server, we can therefore free this memory in
1874 if (!request->in_proxy_hash) {
1875 rad_free(&request->proxy);
1876 rad_free(&request->proxy_reply);
1877 request->home_server = NULL;
1883 RDEBUG2("Finished request %d.", request->number);
1885 request->child_state = child_state;
1888 * Single threaded mode: update timers now.
1890 if (!have_children) wait_a_bit(request);
1894 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1900 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
1901 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
1903 switch (request->child_state) {
1904 case REQUEST_QUEUED:
1905 case REQUEST_RUNNING:
1909 radlog(L_ERR, "Discarding duplicate request from "
1910 "client %s port %d - ID: %d due to unfinished request %d",
1912 request->packet->src_port,request->packet->id,
1917 case REQUEST_PROXIED:
1919 * We're not supposed to have duplicate
1920 * accounting packets. The other states handle
1921 * duplicates fine (discard, or send duplicate
1922 * reply). But we do NOT want to retransmit an
1923 * accounting request here, because that would
1924 * involve updating the Acct-Delay-Time, and
1925 * therefore changing the packet Id, etc.
1927 * Instead, we just discard the packet. We may
1928 * eventually respond, or the client will send a
1929 * new accounting packet.
1931 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1935 check_for_zombie_home_server(request);
1938 * If we've just discovered that the home server is
1939 * dead, send the packet to another one.
1941 if ((request->packet->dst_port != 0) &&
1942 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1945 remove_from_proxy_hash(request);
1947 home = home_server_ldb(NULL, request->home_pool, request);
1949 RDEBUG2("Failed to find live home server for request %d", request->number);
1952 * Do post-request processing,
1953 * and any insertion of necessary
1956 post_proxy_fail_handler(request);
1960 request->proxy->code = request->packet->code;
1961 request->proxy->dst_ipaddr = home->ipaddr;
1962 request->proxy->dst_port = home->port;
1963 request->home_server = home;
1966 * Free the old packet, to force re-encoding
1968 free(request->proxy->data);
1969 request->proxy->data = NULL;
1970 request->proxy->data_len = 0;
1973 * This request failed over to a virtual
1974 * server. Push it back onto the queue
1977 if (request->home_server->server) {
1978 proxy_fallback_handler(request);
1983 * Try to proxy the request.
1985 if (!proxy_request(request)) {
1986 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
1987 goto no_home_servers;
1991 * This code executes in the main server
1992 * thread, so there's no need for locking.
1994 rad_assert(request->next_callback != NULL);
1995 INSERT_EVENT(request->next_callback, request);
1996 request->next_callback = NULL;
1998 } /* else the home server is still alive */
2000 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2001 inet_ntop(request->proxy->dst_ipaddr.af,
2002 &request->proxy->dst_ipaddr.ipaddr,
2003 buffer, sizeof(buffer)),
2004 request->proxy->dst_port,
2005 request->proxy->id);
2006 request->num_proxied_requests++;
2008 if (!debug_flag && request->options) {
2009 debug_packet(request, request->proxy, 1);
2012 request->proxy_listener->send(request->proxy_listener,
2017 case REQUEST_REJECT_DELAY:
2018 RDEBUG2("Waiting to send Access-Reject "
2019 "to client %s port %d - ID: %d",
2021 request->packet->src_port, request->packet->id);
2024 case REQUEST_CLEANUP_DELAY:
2026 RDEBUG2("Sending duplicate reply "
2027 "to client %s port %d - ID: %d",
2029 request->packet->src_port, request->packet->id);
2030 if (!debug_flag && request->options) {
2031 debug_packet(request, request->reply, 1);
2033 request->listener->send(request->listener, request);
2039 static void received_conflicting_request(REQUEST *request,
2040 const RADCLIENT *client)
2042 radlog(L_ERR, "Received conflicting packet from "
2043 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2045 request->packet->src_port, request->packet->id,
2049 * Nuke it from the request hash, so we can receive new
2052 remove_from_request_hash(request);
2054 switch (request->child_state) {
2055 #ifdef HAVE_PTHREAD_H
2057 * It's queued or running. Tell it to stop, and
2058 * wait for it to do so.
2060 case REQUEST_QUEUED:
2061 case REQUEST_RUNNING:
2062 request->master_state = REQUEST_STOP_PROCESSING;
2063 request->delay += request->delay >> 1;
2065 tv_add(&request->when, request->delay);
2067 INSERT_EVENT(wait_for_child_to_die, request);
2072 * It's in some other state, and therefore also
2073 * in the event queue. At some point, the
2074 * child will notice, and we can then delete it.
2077 rad_assert(request->ev != NULL);
2083 static int can_handle_new_request(RADIUS_PACKET *packet,
2085 struct main_config_t *root)
2088 * Count the total number of requests, to see if
2089 * there are too many. If so, return with an
2092 if (root->max_requests) {
2093 int request_count = fr_packet_list_num_elements(pl);
2096 * This is a new request. Let's see if
2097 * it makes us go over our configured
2100 if (request_count > root->max_requests) {
2101 radlog(L_ERR, "Dropping request (%d is too many): "
2102 "from client %s port %d - ID: %d", request_count,
2104 packet->src_port, packet->id);
2105 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2106 "\tThe value for 'max_requests' is probably set too low.\n");
2108 } /* else there were a small number of requests */
2109 } /* else there was no configured limit for requests */
2112 * FIXME: Add per-client checks. If one client is sending
2113 * too many packets, start discarding them.
2115 * We increment the counters here, and decrement them
2116 * when the response is sent... somewhere in this file.
2120 * FUTURE: Add checks for system load. If the system is
2121 * busy, start dropping requests...
2123 * We can probably keep some statistics ourselves... if
2124 * there are more requests coming in than we can handle,
2125 * start dropping some.
2132 int received_request(rad_listen_t *listener,
2133 RADIUS_PACKET *packet, REQUEST **prequest,
2136 RADIUS_PACKET **packet_p;
2137 REQUEST *request = NULL;
2138 struct main_config_t *root = &mainconfig;
2140 packet_p = fr_packet_list_find(pl, packet);
2142 request = fr_packet2myptr(REQUEST, packet, packet_p);
2143 rad_assert(request->in_request_hash);
2145 if ((request->packet->data_len == packet->data_len) &&
2146 (memcmp(request->packet->vector, packet->vector,
2147 sizeof(packet->vector)) == 0)) {
2148 received_retransmit(request, client);
2153 * The new request is different from the old one,
2154 * but maybe the old is finished. If so, delete
2157 switch (request->child_state) {
2158 struct timeval when;
2161 gettimeofday(&when, NULL);
2165 * If the cached request was received
2166 * within the last second, then we
2167 * discard the NEW request instead of the
2168 * old one. This will happen ONLY when
2169 * the client is severely broken, and is
2170 * sending conflicting packets very
2173 if (timercmp(&when, &request->received, <)) {
2174 radlog(L_ERR, "Discarding conflicting packet from "
2175 "client %s port %d - ID: %d due to recent request %d.",
2177 packet->src_port, packet->id,
2182 received_conflicting_request(request, client);
2186 case REQUEST_REJECT_DELAY:
2187 case REQUEST_CLEANUP_DELAY:
2188 request->child_state = REQUEST_DONE;
2190 cleanup_delay(request);
2197 * We may want to quench the new request.
2199 if ((listener->type != RAD_LISTEN_DETAIL) &&
2200 !can_handle_new_request(packet, client, root)) {
2205 * Create and initialize the new request.
2207 request = request_alloc(); /* never fails */
2209 if ((request->reply = rad_alloc(0)) == NULL) {
2210 radlog(L_ERR, "No memory");
2214 request->listener = listener;
2215 request->client = client;
2216 request->packet = packet;
2217 request->packet->timestamp = request->timestamp;
2218 request->number = request_num_counter++;
2219 request->priority = listener->type;
2222 * Status-Server packets go to the head of the queue.
2224 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2227 * Set virtual server identity
2229 if (client->server) {
2230 request->server = client->server;
2231 } else if (listener->server) {
2232 request->server = listener->server;
2234 request->server = NULL;
2238 * Remember the request in the list.
2240 if (!fr_packet_list_insert(pl, &request->packet)) {
2241 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2242 request_free(&request);
2246 request->in_request_hash = TRUE;
2247 request->root = root;
2251 * The request passes many of our sanity checks.
2252 * From here on in, if anything goes wrong, we
2253 * send a reject message, instead of dropping the
2258 * Build the reply template from the request.
2261 request->reply->sockfd = request->packet->sockfd;
2262 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2263 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2264 request->reply->dst_port = request->packet->src_port;
2265 request->reply->src_port = request->packet->dst_port;
2266 request->reply->id = request->packet->id;
2267 request->reply->code = 0; /* UNKNOWN code */
2268 memcpy(request->reply->vector, request->packet->vector,
2269 sizeof(request->reply->vector));
2270 request->reply->vps = NULL;
2271 request->reply->data = NULL;
2272 request->reply->data_len = 0;
2274 request->master_state = REQUEST_ACTIVE;
2275 request->child_state = REQUEST_QUEUED;
2276 request->next_callback = NULL;
2278 gettimeofday(&request->received, NULL);
2279 request->timestamp = request->received.tv_sec;
2280 request->when = request->received;
2282 request->delay = USEC;
2284 tv_add(&request->when, request->delay);
2286 INSERT_EVENT(wait_a_bit, request);
2288 *prequest = request;
2294 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2300 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
2301 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
2302 inet_ntop(packet->src_ipaddr.af,
2303 &packet->src_ipaddr.ipaddr,
2304 buffer, sizeof(buffer)),
2311 * Also removes from the proxy hash if responses == requests
2313 request = lookup_in_proxy_hash(packet);
2316 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
2317 inet_ntop(packet->src_ipaddr.af,
2318 &packet->src_ipaddr.ipaddr,
2319 buffer, sizeof(buffer)),
2320 packet->src_port, packet->id);
2325 home = request->home_server;
2327 gettimeofday(&now, NULL);
2329 home->state = HOME_STATE_ALIVE;
2331 if (request->reply && request->reply->code != 0) {
2332 RDEBUG2("We already replied to this request. Discarding response from home server.");
2338 * We had previously received a reply, so we don't need
2339 * to do anything here.
2341 if (request->proxy_reply) {
2342 if (memcmp(request->proxy_reply->vector,
2344 sizeof(request->proxy_reply->vector)) == 0) {
2345 RDEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
2346 inet_ntop(packet->src_ipaddr.af,
2347 &packet->src_ipaddr.ipaddr,
2348 buffer, sizeof(buffer)),
2349 packet->src_port, packet->id,
2353 * ? The home server gave us a new proxy
2354 * reply, which doesn't match the old
2357 RDEBUG2("Ignoring conflicting proxy reply");
2360 /* assert that there's an event queued for request? */
2366 * The average includes our time to receive packets and
2367 * look them up in the hashes, which should be the same
2370 * We update the response time only for the FIRST packet
2373 else if (home->ema.window > 0) {
2374 radius_stats_ema(&home->ema, &now, &request->proxy_when);
2379 switch (request->child_state) {
2380 case REQUEST_QUEUED:
2381 case REQUEST_RUNNING:
2382 rad_panic("Internal sanity check failed for child state");
2385 case REQUEST_REJECT_DELAY:
2386 case REQUEST_CLEANUP_DELAY:
2388 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'",
2389 inet_ntop(packet->src_ipaddr.af,
2390 &packet->src_ipaddr.ipaddr,
2391 buffer, sizeof(buffer)),
2392 packet->src_port, packet->id,
2394 /* assert that there's an event queued for request? */
2398 case REQUEST_PROXIED:
2402 request->proxy_reply = packet;
2406 * Perform RTT calculations, as per RFC 2988 (for TCP).
2407 * Note that we do so only if we sent one request, and
2408 * received one response. If we sent two requests, we
2409 * have no idea if the response is for the first, or for
2410 * the second request/
2412 if (request->num_proxied_requests == 1) {
2414 home_server *home = request->home_server;
2416 rtt = now.tv_sec - request->proxy_when.tv_sec;
2419 rtt -= request->proxy_when.tv_usec;
2421 if (!home->has_rtt) {
2422 home->has_rtt = TRUE;
2425 home->rttvar = rtt / 2;
2428 home->rttvar -= home->rttvar >> 2;
2429 home->rttvar += (home->srtt - rtt);
2430 home->srtt -= home->srtt >> 3;
2431 home->srtt += rtt >> 3;
2434 home->rto = home->srtt;
2435 if (home->rttvar > (USEC / 4)) {
2436 home->rto += home->rttvar * 4;
2444 * There's no incoming request, so it's a proxied packet
2447 if (!request->packet) {
2448 received_response_to_ping(request);
2452 request->child_state = REQUEST_QUEUED;
2453 request->when = now;
2454 request->delay = USEC;
2455 request->priority = RAD_LISTEN_PROXY;
2456 tv_add(&request->when, request->delay);
2459 * Wait a bit will take care of max_request_time
2461 INSERT_EVENT(wait_a_bit, request);
2467 void event_new_fd(rad_listen_t *this)
2471 this->print(this, buffer, sizeof(buffer));
2473 if (this->status == RAD_LISTEN_STATUS_INIT) {
2475 DEBUG("Listening on %s", buffer);
2477 DEBUG2(" ... adding new socket %s", buffer);
2479 if (!fr_event_fd_insert(el, 0, this->fd,
2480 event_socket_handler, this)) {
2481 radlog(L_ERR, "Failed remembering handle for proxy socket!");
2485 this->status = RAD_LISTEN_STATUS_KNOWN;
2489 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
2490 DEBUG2(" ... closing socket %s", buffer);
2492 fr_event_fd_delete(el, 0, this->fd);
2493 this->status = RAD_LISTEN_STATUS_FINISH;
2496 * Close the fd AFTER fixing up the requests and
2497 * listeners, so that they don't send/recv on the
2498 * wrong socket (if someone manages to open
2507 static void event_detail_timer(void *ctx)
2509 rad_listen_t *listener = ctx;
2510 RAD_REQUEST_FUNP fun;
2513 if (listener->recv(listener, &fun, &request)) {
2514 if (!thread_pool_addrequest(request, fun)) {
2515 request->child_state = REQUEST_DONE;
2521 static void handle_signal_self(int flag)
2523 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2524 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2525 fr_event_loop_exit(el, 1);
2527 fr_event_loop_exit(el, 2);
2531 } /* else exit/term flags weren't set */
2534 * Tell the even loop to stop processing.
2536 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2538 static time_t last_hup = 0;
2540 DEBUG("Received HUP signal.");
2543 if ((int) (when - last_hup) < 5) {
2544 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2549 fr_event_loop_exit(el, 0x80);
2553 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2556 for (this = mainconfig.listen;
2558 this = this->next) {
2560 struct timeval when;
2562 if (this->type != RAD_LISTEN_DETAIL) continue;
2564 delay = detail_delay(this);
2565 if (!delay) continue;
2567 fr_event_now(el, &now);
2569 tv_add(&when, delay);
2571 if (delay > 100000) {
2572 DEBUG("Delaying next detail event for %d.%01u seconds.",
2573 delay / USEC, (delay % USEC) / 100000);
2576 if (!fr_event_insert(el, event_detail_timer, this,
2578 radlog(L_ERR, "Failed remembering timer");
2585 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2588 for (this = mainconfig.listen;
2590 this = this->next) {
2591 if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
2599 void radius_signal_self(int flag)
2601 handle_signal_self(flag);
2605 * Inform ourselves that we received a signal.
2607 void radius_signal_self(int flag)
2613 * The read MUST be non-blocking for this to work.
2615 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2619 for (i = 0; i < rcode; i++) {
2620 buffer[0] |= buffer[i];
2628 write(self_pipe[1], buffer, 1);
2632 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2633 UNUSED int fd, UNUSED void *ctx)
2638 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2639 if (rcode <= 0) return;
2642 * Merge pending signals.
2644 for (i = 0; i < rcode; i++) {
2645 buffer[0] |= buffer[i];
2648 handle_signal_self(buffer[0]);
2653 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
2656 rad_listen_t *listener = ctx;
2657 RAD_REQUEST_FUNP fun;
2660 rad_assert(xel == el);
2664 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2666 if (!listener->recv(listener, &fun, &request)) return;
2668 if (!thread_pool_addrequest(request, fun)) {
2669 request->child_state = REQUEST_DONE;
2675 * This function is called periodically to see if any FD's are
2676 * available for reading.
2678 static void event_poll_detail(UNUSED void *ctx)
2681 RAD_REQUEST_FUNP fun;
2684 struct timeval when;
2686 fr_event_now(el, &now);
2690 for (this = mainconfig.listen; this != NULL; this = this->next) {
2691 if (this->type != RAD_LISTEN_DETAIL) continue;
2693 if (this->fd >= 0) continue;
2696 * Try to read something.
2698 * FIXME: This does poll AND receive.
2700 rcode = this->recv(this, &fun, &request);
2701 if (!rcode) continue;
2703 rad_assert(fun != NULL);
2704 rad_assert(request != NULL);
2706 if (!thread_pool_addrequest(request, fun)) {
2707 request->child_state = REQUEST_DONE;
2714 if (!fr_event_insert(el, event_poll_detail, NULL,
2716 radlog(L_ERR, "Failed creating handler");
2722 static void event_status(struct timeval *wake)
2724 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2728 if (debug_flag == 0) {
2730 radlog(L_INFO, "Ready to process requests.");
2731 just_started = FALSE;
2737 DEBUG("Ready to process requests.");
2739 } else if ((wake->tv_sec != 0) ||
2740 (wake->tv_usec >= 100000)) {
2741 DEBUG("Waking up in %d.%01u seconds.",
2742 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2747 * FIXME: Put this somewhere else, where it isn't called
2748 * all of the time...
2751 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2753 * If there are no child threads, then there may
2754 * be child processes. In that case, wait for
2755 * their exit status, and throw that exit status
2756 * away. This helps get rid of zxombie children.
2758 while (waitpid(-1, &argval, WNOHANG) > 0) {
2767 * Externally-visibly functions.
2769 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2771 rad_listen_t *this, *head = NULL;
2775 time(&fr_start_time);
2777 el = fr_event_list_create(event_status);
2780 pl = fr_packet_list_create(0);
2783 request_num_counter = 0;
2786 * Move all of the thread calls to this file?
2788 * It may be best for the mutexes to be in this file...
2790 have_children = spawn_flag;
2793 if (mainconfig.proxy_requests) {
2795 * Create the tree for managing proxied requests and
2798 proxy_list = fr_packet_list_create(1);
2799 if (!proxy_list) return 0;
2801 #ifdef HAVE_PTHREAD_H
2802 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2803 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2812 * Just before we spawn the child threads, force the log
2813 * subsystem to re-open the log file for every write.
2815 if (spawn_flag) force_log_reopen();
2817 #ifdef HAVE_PTHREAD_H
2818 if (thread_pool_init(cs, spawn_flag) < 0) {
2824 DEBUG("%s: #### Skipping IP addresses and Ports ####",
2831 * Child threads need a pipe to signal us, as do the
2834 if (pipe(self_pipe) < 0) {
2835 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2839 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2840 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2844 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2845 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2850 if (!fr_event_fd_insert(el, 0, self_pipe[0],
2851 event_signal_handler, el)) {
2852 radlog(L_ERR, "Failed creating handler for signals");
2859 * Mark the proxy Fd's as unused.
2864 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2868 DEBUG("%s: #### Opening IP addresses and Ports ####",
2871 if (listen_init(cs, &head) < 0) {
2876 * Add all of the sockets to the event loop.
2880 this = this->next) {
2883 this->print(this, buffer, sizeof(buffer));
2885 switch (this->type) {
2887 case RAD_LISTEN_DETAIL:
2888 DEBUG("Listening on %s", buffer);
2889 has_detail_listener = TRUE;
2894 case RAD_LISTEN_PROXY:
2895 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2896 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2898 proxy_fds[this->fd & 0x1f] = this->fd;
2899 proxy_listeners[this->fd & 0x1f] = this;
2900 if (!fr_packet_list_socket_add(proxy_list,
2912 * The file descriptor isn't ready. Poll for
2913 * when it will become ready. This is for the
2923 if (has_detail_listener) {
2924 struct timeval when;
2926 gettimeofday(&when, NULL);
2929 if (!fr_event_insert(el, event_poll_detail, NULL,
2931 radlog(L_ERR, "Failed creating handler");
2936 mainconfig.listen = head;
2942 static int request_hash_cb(UNUSED void *ctx, void *data)
2944 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2947 rad_assert(request->in_proxy_hash == FALSE);
2950 fr_event_delete(el, &request->ev);
2951 remove_from_request_hash(request);
2952 request_free(&request);
2959 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2961 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2963 fr_packet_list_yank(proxy_list, request->proxy);
2964 request->in_proxy_hash = FALSE;
2966 if (!request->in_request_hash) {
2967 fr_event_delete(el, &request->ev);
2968 request_free(&request);
2975 void radius_event_free(void)
2978 * FIXME: Stop all threads, or at least check that
2979 * they're all waiting on the semaphore, and the queues
2985 * There are requests in the proxy hash that aren't
2986 * referenced from anywhere else. Remove them first.
2989 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2990 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2991 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2992 fr_packet_list_free(proxy_list);
2997 fr_packet_list_walk(pl, NULL, request_hash_cb);
2999 fr_packet_list_free(pl);
3002 fr_event_list_free(el);
3005 int radius_event_process(void)
3009 return fr_event_loop(el);
3012 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3014 request->options = RAD_REQUEST_OPTION_DEBUG2;
3016 if (request_pre_handler(request)) {
3017 rad_assert(fun != NULL);
3018 rad_assert(request != NULL);
3020 if (request->server) RDEBUG("server %s {",
3024 if (request->server) RDEBUG("} # server %s",
3027 request_post_handler(request);
3030 DEBUG2("Going to the next request");