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 * In daemon mode, AND this request has debug flags set.
484 #define DEBUG_PACKET if (!debug_flag && request->options) debug_packet
486 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
490 const char *received, *from;
491 const fr_ipaddr_t *ip;
496 if (direction == 0) {
497 received = "Received";
498 from = "from"; /* what else? */
499 ip = &packet->src_ipaddr;
500 port = packet->src_port;
503 received = "Sending";
504 from = "to"; /* hah! */
505 ip = &packet->dst_ipaddr;
506 port = packet->dst_port;
510 * Client-specific debugging re-prints the input
511 * packet into the client log.
513 * This really belongs in a utility library
515 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
516 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
517 received, packet_codes[packet->code], from,
518 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
519 port, packet->id, packet->data_len);
521 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
523 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
525 packet->code, packet->id, packet->data_len);
528 for (vp = packet->vps; vp != NULL; vp = vp->next) {
529 vp_prints(buffer, sizeof(buffer), vp);
530 request->radlog(L_DBG, 0, request, "\t%s", buffer);
534 static void reject_delay(void *ctx)
536 REQUEST *request = ctx;
538 rad_assert(request->magic == REQUEST_MAGIC);
539 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
541 RDEBUG2("Sending delayed reject for request %d", request->number);
543 if (!debug_flag && request->options) {
544 debug_packet(request, request->reply, 1);
546 request->listener->send(request->listener, request);
548 request->when.tv_sec += request->root->cleanup_delay;
549 request->child_state = REQUEST_CLEANUP_DELAY;
551 INSERT_EVENT(cleanup_delay, request);
556 static void revive_home_server(void *ctx)
558 home_server *home = ctx;
561 home->state = HOME_STATE_ALIVE;
562 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
563 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
564 buffer, sizeof(buffer)),
566 home->currently_outstanding = 0;
567 home->revive_time = now;
571 static void no_response_to_ping(void *ctx)
573 REQUEST *request = ctx;
574 home_server *home = request->home_server;
577 home->num_received_pings = 0;
579 RDEBUG2("No response to status check %d from home server %s port %d",
581 inet_ntop(request->proxy->dst_ipaddr.af,
582 &request->proxy->dst_ipaddr.ipaddr,
583 buffer, sizeof(buffer)),
584 request->proxy->dst_port);
586 wait_for_proxy_id_to_expire(request);
590 static void received_response_to_ping(REQUEST *request)
592 home_server *home = request->home_server;
595 home->num_received_pings++;
597 RDEBUG2("Received response to status check %d (%d in current sequence)",
598 request->number, home->num_received_pings);
600 if (home->num_received_pings < home->num_pings_to_alive) {
601 wait_for_proxy_id_to_expire(request);
605 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
606 inet_ntop(request->proxy->dst_ipaddr.af,
607 &request->proxy->dst_ipaddr.ipaddr,
608 buffer, sizeof(buffer)),
609 request->proxy->dst_port);
611 if (!fr_event_delete(el, &home->ev)) {
612 RDEBUG2("Hmm... no event for home server, WTF?");
615 if (!fr_event_delete(el, &request->ev)) {
616 RDEBUG2("Hmm... no event for request, WTF?");
619 wait_for_proxy_id_to_expire(request);
621 home->state = HOME_STATE_ALIVE;
622 home->currently_outstanding = 0;
623 home->revive_time = now;
627 static void ping_home_server(void *ctx)
630 home_server *home = ctx;
634 if (home->state == HOME_STATE_ALIVE) {
635 radlog(L_INFO, "Suspicious proxy state... continuing");
639 request = request_alloc();
640 request->number = request_num_counter++;
642 request->proxy = rad_alloc(1);
643 rad_assert(request->proxy != NULL);
645 fr_event_now(el, &request->when);
646 home->when = request->when;
648 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
649 request->proxy->code = PW_STATUS_SERVER;
651 radius_pairmake(request, &request->proxy->vps,
652 "Message-Authenticator", "0x00", T_OP_SET);
654 } else if (home->type == HOME_TYPE_AUTH) {
655 request->proxy->code = PW_AUTHENTICATION_REQUEST;
657 radius_pairmake(request, &request->proxy->vps,
658 "User-Name", home->ping_user_name, T_OP_SET);
659 radius_pairmake(request, &request->proxy->vps,
660 "User-Password", home->ping_user_password, T_OP_SET);
661 radius_pairmake(request, &request->proxy->vps,
662 "Service-Type", "Authenticate-Only", T_OP_SET);
663 radius_pairmake(request, &request->proxy->vps,
664 "Message-Authenticator", "0x00", T_OP_SET);
667 #ifdef WITH_ACCOUNTING
668 request->proxy->code = PW_ACCOUNTING_REQUEST;
670 radius_pairmake(request, &request->proxy->vps,
671 "User-Name", home->ping_user_name, T_OP_SET);
672 radius_pairmake(request, &request->proxy->vps,
673 "Acct-Status-Type", "Stop", T_OP_SET);
674 radius_pairmake(request, &request->proxy->vps,
675 "Acct-Session-Id", "00000000", T_OP_SET);
676 vp = radius_pairmake(request, &request->proxy->vps,
677 "Event-Timestamp", "0", T_OP_SET);
678 vp->vp_date = now.tv_sec;
680 rad_assert("Internal sanity check failed");
684 radius_pairmake(request, &request->proxy->vps,
685 "NAS-Identifier", "Status Check. Are you alive?",
688 request->proxy->dst_ipaddr = home->ipaddr;
689 request->proxy->dst_port = home->port;
690 request->home_server = home;
692 rad_assert(request->proxy_listener == NULL);
694 if (!insert_into_proxy_hash(request)) {
695 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
697 request_free(&request);
700 rad_assert(request->proxy_listener != NULL);
701 request->proxy_listener->send(request->proxy_listener,
704 request->next_callback = NULL;
705 request->child_state = REQUEST_PROXIED;
706 request->when.tv_sec += home->ping_timeout;;
708 INSERT_EVENT(no_response_to_ping, request);
711 * Add +/- 2s of jitter, as suggested in RFC 3539
712 * and in the Issues and Fixes draft.
714 home->when.tv_sec += home->ping_interval - 2;
717 jitter ^= (jitter >> 10);
718 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
720 tv_add(&home->when, jitter);
723 INSERT_EVENT(ping_home_server, home);
727 static void check_for_zombie_home_server(REQUEST *request)
733 home = request->home_server;
735 if (home->state != HOME_STATE_ZOMBIE) return;
737 when = home->zombie_period_start;
738 when.tv_sec += home->zombie_period;
740 fr_event_now(el, &now);
741 if (timercmp(&now, &when, <)) {
746 * It's been a zombie for too long, mark it as
749 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
750 inet_ntop(request->proxy->dst_ipaddr.af,
751 &request->proxy->dst_ipaddr.ipaddr,
752 buffer, sizeof(buffer)),
753 request->proxy->dst_port);
754 home->state = HOME_STATE_IS_DEAD;
755 home->num_received_pings = 0;
756 home->when = request->when;
758 if (home->ping_check != HOME_PING_CHECK_NONE) {
759 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
760 (home->ping_user_name != NULL));
761 home->when.tv_sec += home->ping_interval;
763 INSERT_EVENT(ping_home_server, home);
765 home->when.tv_sec += home->revive_interval;
767 INSERT_EVENT(revive_home_server, home);
771 static int proxy_to_virtual_server(REQUEST *request);
773 static int virtual_server_handler(UNUSED REQUEST *request)
775 proxy_to_virtual_server(request);
779 static void proxy_fallback_handler(REQUEST *request)
782 * A proper time is required for wait_a_bit.
784 request->delay = USEC / 10;
785 gettimeofday(&now, NULL);
786 request->next_when = now;
787 tv_add(&request->next_when, request->delay);
788 request->next_callback = wait_a_bit;
791 * Re-queue the request.
793 request->child_state = REQUEST_QUEUED;
795 rad_assert(request->proxy != NULL);
796 if (!thread_pool_addrequest(request, virtual_server_handler)) {
797 request->child_state = REQUEST_DONE;
800 #ifdef HAVE_PTHREAD_H
802 * MAY free the request if we're over max_request_time,
803 * AND we're not in threaded mode!
805 * Note that we call this ONLY if we're threaded, as
806 * if we're NOT threaded, request_post_handler() calls
807 * wait_a_bit(), which means that "request" may not
810 if (have_children) wait_a_bit(request);
815 static int setup_post_proxy_fail(REQUEST *request)
817 DICT_VALUE *dval = NULL;
820 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
821 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
823 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
824 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
830 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
833 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
837 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
838 if (!vp) vp = radius_paircreate(request, &request->config_items,
839 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
840 vp->vp_integer = dval->value;
842 rad_assert(request->proxy_reply == NULL);
848 static int null_handler(UNUSED REQUEST *request)
853 static void post_proxy_fail_handler(REQUEST *request)
856 * A proper time is required for wait_a_bit.
858 request->delay = USEC / 10;
859 gettimeofday(&now, NULL);
862 * Not set up to run Post-Proxy-Type = Fail.
864 * Mark the request as still running, and figure out what
867 if (!setup_post_proxy_fail(request)) {
868 request->child_state = REQUEST_RUNNING;
869 request_post_handler(request);
873 * Re-queue the request.
875 request->child_state = REQUEST_QUEUED;
878 * There is a post-proxy-type of fail. We run
879 * the request through the pre/post proxy
880 * handlers, just like it was a real proxied
881 * request. However, we set the per-request
882 * handler to NULL, as we don't want to do
885 * Note that when we're not threaded, this will
886 * process the request even if it's greater than
887 * max_request_time. That's not fatal.
889 request->priority = 0;
890 rad_assert(request->proxy != NULL);
891 thread_pool_addrequest(request, null_handler);
895 * MAY free the request if we're over max_request_time,
896 * AND we're not in threaded mode!
898 * Note that we call this ONLY if we're threaded, as
899 * if we're NOT threaded, request_post_handler() calls
900 * wait_a_bit(), which means that "request" may not
903 if (have_children) wait_a_bit(request);
907 /* maybe check this against wait_for_proxy_id_to_expire? */
908 static void no_response_to_proxied_request(void *ctx)
910 REQUEST *request = ctx;
914 rad_assert(request->magic == REQUEST_MAGIC);
915 rad_assert(request->child_state == REQUEST_PROXIED);
918 * If we've failed over to an internal home server,
919 * replace the callback with the correct one. This
920 * is due to locking issues with child threads...
922 if (request->home_server->server) {
927 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
929 inet_ntop(request->proxy->dst_ipaddr.af,
930 &request->proxy->dst_ipaddr.ipaddr,
931 buffer, sizeof(buffer)),
932 request->proxy->dst_port);
934 check_for_zombie_home_server(request);
936 home = request->home_server;
938 post_proxy_fail_handler(request);
941 * Don't touch request due to race conditions
943 if (home->state == HOME_STATE_IS_DEAD) {
944 rad_assert(home->ev != NULL); /* or it will never wake up */
949 * Enable the zombie period when we notice that the home
950 * server hasn't responded. We also back-date the start
951 * of the zombie period to when the proxied request was
954 if (home->state == HOME_STATE_ALIVE) {
955 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
956 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
957 buffer, sizeof(buffer)),
959 home->state = HOME_STATE_ZOMBIE;
960 home->zombie_period_start = now;
961 home->zombie_period_start.tv_sec -= home->response_window;
967 static void wait_a_bit(void *ctx)
970 REQUEST *request = ctx;
971 fr_event_callback_t callback = NULL;
973 rad_assert(request->magic == REQUEST_MAGIC);
975 switch (request->child_state) {
977 case REQUEST_RUNNING:
978 when = request->received;
979 when.tv_sec += request->root->max_request_time;
982 * Normally called from the event loop with the
983 * proper event loop time. Otherwise, called from
984 * post proxy fail handler, which sets "now", and
985 * this call won't re-set it, because we're not
988 fr_event_now(el, &now);
991 * Request still has more time. Continue
994 if (timercmp(&now, &when, <) ||
995 ((request->listener->type == RAD_LISTEN_DETAIL) &&
996 (request->child_state == REQUEST_QUEUED))) {
997 if (request->delay < (USEC / 10)) {
998 request->delay = USEC / 10;
1000 request->delay += request->delay >> 1;
1004 * Cap wait at some sane value for detail
1007 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1008 (request->delay > (request->root->max_request_time * USEC))) {
1009 request->delay = request->root->max_request_time * USEC;
1013 request->when = now;
1014 tv_add(&request->when, request->delay);
1015 callback = wait_a_bit;
1019 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1021 * A child thread MAY still be running on the
1022 * request. Ask the thread to stop working on
1025 if (have_children) {
1026 /* FIXME: kill unresponsive children? */
1029 * Print this error message ONLY if
1030 * there's a child currently processing
1031 * the request. As we don't have thread
1032 * locks here, there may be race
1033 * conditions on this check. But it's
1034 * just an error message, so that's OK.
1036 if (request->child_pid != NO_SUCH_CHILD_PID) {
1037 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
1038 (unsigned long)request->child_pid, request->number,
1039 request->module ? request->module : "<server core>",
1040 request->component ? request->component : "<server core>");
1043 request->master_state = REQUEST_STOP_PROCESSING;
1045 request->delay = USEC / 4;
1046 tv_add(&request->when, request->delay);
1047 callback = wait_for_child_to_die;
1053 * Else there are no child threads. We probably
1054 * should have just marked the request as 'done'
1055 * elsewhere, like in the post-proxy-fail
1056 * handler. But doing that would involve
1057 * checking for max_request_time in multiple
1058 * places, so this may be simplest.
1060 request->child_state = REQUEST_DONE;
1064 * Mark the request as no longer running,
1068 #ifdef HAVE_PTHREAD_H
1069 request->child_pid = NO_SUCH_CHILD_PID;
1071 request_stats_final(request);
1072 cleanup_delay(request);
1075 case REQUEST_REJECT_DELAY:
1076 case REQUEST_CLEANUP_DELAY:
1077 #ifdef HAVE_PTHREAD_H
1078 request->child_pid = NO_SUCH_CHILD_PID;
1080 request_stats_final(request);
1082 case REQUEST_PROXIED:
1083 rad_assert(request->next_callback != NULL);
1084 rad_assert(request->next_callback != wait_a_bit);
1086 request->when = request->next_when;
1087 callback = request->next_callback;
1088 request->next_callback = NULL;
1092 rad_panic("Internal sanity check failure");
1097 * Something major went wrong. Discard the request, and
1100 * FIXME: No idea why this happens or how to fix it...
1101 * It seems to happen *only* when requests are proxied,
1102 * and where the home server doesn't respond. So it looks
1103 * like a race condition above, but it happens in debug
1104 * mode, with no threads...
1107 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1108 fr_event_delete(el, &request->ev);
1109 remove_from_proxy_hash(request);
1110 remove_from_request_hash(request);
1111 request_free(&request);
1115 INSERT_EVENT(callback, request);
1120 static int process_proxy_reply(REQUEST *request)
1123 int post_proxy_type = 0;
1127 * Delete any reply we had accumulated until now.
1129 pairfree(&request->reply->vps);
1132 * Run the packet through the post-proxy stage,
1133 * BEFORE playing games with the attributes.
1135 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1137 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1138 post_proxy_type = vp->vp_integer;
1141 rad_assert(request->home_pool != NULL);
1143 if (request->home_pool->virtual_server) {
1144 const char *old_server = request->server;
1146 request->server = request->home_pool->virtual_server;
1147 RDEBUG2(" server %s {", request->server);
1148 rcode = module_post_proxy(post_proxy_type, request);
1150 request->server = old_server;
1152 rcode = module_post_proxy(post_proxy_type, request);
1156 * There may NOT be a proxy reply, as we may be
1157 * running Post-Proxy-Type = Fail.
1159 if (request->proxy_reply) {
1161 * Delete the Proxy-State Attributes from
1162 * the reply. These include Proxy-State
1163 * attributes from us and remote server.
1165 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1168 * Add the attributes left in the proxy
1169 * reply to the reply list.
1171 pairadd(&request->reply->vps, request->proxy_reply->vps);
1172 request->proxy_reply->vps = NULL;
1175 * Free proxy request pairs.
1177 pairfree(&request->proxy->vps);
1181 default: /* Don't do anything */
1183 case RLM_MODULE_FAIL:
1184 /* FIXME: debug print stuff */
1185 request->child_state = REQUEST_DONE;
1188 case RLM_MODULE_HANDLED:
1189 /* FIXME: debug print stuff */
1190 request->child_state = REQUEST_DONE;
1198 static int request_pre_handler(REQUEST *request)
1202 rad_assert(request->magic == REQUEST_MAGIC);
1203 rad_assert(request->packet != NULL);
1205 request->child_state = REQUEST_RUNNING;
1208 * Don't decode the packet if it's an internal "fake"
1209 * request. Instead, just return so that the caller can
1212 if (request->packet->dst_port == 0) {
1213 request->username = pairfind(request->packet->vps,
1215 request->password = pairfind(request->packet->vps,
1222 * Put the decoded packet into it's proper place.
1224 if (request->proxy_reply != NULL) {
1225 rcode = request->proxy_listener->decode(request->proxy_listener,
1227 DEBUG_PACKET(request, request->proxy_reply, 0);
1230 if (request->packet->vps == NULL) {
1231 rcode = request->listener->decode(request->listener, request);
1233 if (debug_condition) {
1237 * Ignore parse errors.
1239 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1240 &debug_condition, 1,
1243 request->priority = 2;
1244 request->radlog = radlog_request;
1248 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 DEBUG_PACKET(request, request->reply, 1);
1844 request->listener->send(request->listener, request);
1848 * Clean up. These are no longer needed.
1850 pairfree(&request->config_items);
1852 pairfree(&request->packet->vps);
1853 request->username = NULL;
1854 request->password = NULL;
1856 pairfree(&request->reply->vps);
1859 if (request->proxy) {
1860 pairfree(&request->proxy->vps);
1862 if (request->proxy_reply) {
1863 pairfree(&request->proxy_reply->vps);
1868 * We're not tracking responses from the home
1869 * server, we can therefore free this memory in
1872 if (!request->in_proxy_hash) {
1873 rad_free(&request->proxy);
1874 rad_free(&request->proxy_reply);
1875 request->home_server = NULL;
1881 RDEBUG2("Finished request %d.", request->number);
1883 request->child_state = child_state;
1886 * Single threaded mode: update timers now.
1888 if (!have_children) wait_a_bit(request);
1892 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1898 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
1899 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
1901 switch (request->child_state) {
1902 case REQUEST_QUEUED:
1903 case REQUEST_RUNNING:
1907 radlog(L_ERR, "Discarding duplicate request from "
1908 "client %s port %d - ID: %d due to unfinished request %d",
1910 request->packet->src_port,request->packet->id,
1915 case REQUEST_PROXIED:
1917 * We're not supposed to have duplicate
1918 * accounting packets. The other states handle
1919 * duplicates fine (discard, or send duplicate
1920 * reply). But we do NOT want to retransmit an
1921 * accounting request here, because that would
1922 * involve updating the Acct-Delay-Time, and
1923 * therefore changing the packet Id, etc.
1925 * Instead, we just discard the packet. We may
1926 * eventually respond, or the client will send a
1927 * new accounting packet.
1929 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1933 check_for_zombie_home_server(request);
1936 * If we've just discovered that the home server is
1937 * dead, send the packet to another one.
1939 if ((request->packet->dst_port != 0) &&
1940 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1943 remove_from_proxy_hash(request);
1945 home = home_server_ldb(NULL, request->home_pool, request);
1947 RDEBUG2("Failed to find live home server for request %d", request->number);
1950 * Do post-request processing,
1951 * and any insertion of necessary
1954 post_proxy_fail_handler(request);
1958 request->proxy->code = request->packet->code;
1959 request->proxy->dst_ipaddr = home->ipaddr;
1960 request->proxy->dst_port = home->port;
1961 request->home_server = home;
1964 * Free the old packet, to force re-encoding
1966 free(request->proxy->data);
1967 request->proxy->data = NULL;
1968 request->proxy->data_len = 0;
1971 * This request failed over to a virtual
1972 * server. Push it back onto the queue
1975 if (request->home_server->server) {
1976 proxy_fallback_handler(request);
1981 * Try to proxy the request.
1983 if (!proxy_request(request)) {
1984 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
1985 goto no_home_servers;
1989 * This code executes in the main server
1990 * thread, so there's no need for locking.
1992 rad_assert(request->next_callback != NULL);
1993 INSERT_EVENT(request->next_callback, request);
1994 request->next_callback = NULL;
1996 } /* else the home server is still alive */
1998 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1999 inet_ntop(request->proxy->dst_ipaddr.af,
2000 &request->proxy->dst_ipaddr.ipaddr,
2001 buffer, sizeof(buffer)),
2002 request->proxy->dst_port,
2003 request->proxy->id);
2004 request->num_proxied_requests++;
2006 DEBUG_PACKET(request, request->proxy, 1);
2007 request->proxy_listener->send(request->proxy_listener,
2012 case REQUEST_REJECT_DELAY:
2013 RDEBUG2("Waiting to send Access-Reject "
2014 "to client %s port %d - ID: %d",
2016 request->packet->src_port, request->packet->id);
2019 case REQUEST_CLEANUP_DELAY:
2021 RDEBUG2("Sending duplicate reply "
2022 "to client %s port %d - ID: %d",
2024 request->packet->src_port, request->packet->id);
2025 DEBUG_PACKET(request, request->reply, 1);
2026 request->listener->send(request->listener, request);
2032 static void received_conflicting_request(REQUEST *request,
2033 const RADCLIENT *client)
2035 radlog(L_ERR, "Received conflicting packet from "
2036 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2038 request->packet->src_port, request->packet->id,
2042 * Nuke it from the request hash, so we can receive new
2045 remove_from_request_hash(request);
2047 switch (request->child_state) {
2048 #ifdef HAVE_PTHREAD_H
2050 * It's queued or running. Tell it to stop, and
2051 * wait for it to do so.
2053 case REQUEST_QUEUED:
2054 case REQUEST_RUNNING:
2055 request->master_state = REQUEST_STOP_PROCESSING;
2056 request->delay += request->delay >> 1;
2058 tv_add(&request->when, request->delay);
2060 INSERT_EVENT(wait_for_child_to_die, request);
2065 * It's in some other state, and therefore also
2066 * in the event queue. At some point, the
2067 * child will notice, and we can then delete it.
2070 rad_assert(request->ev != NULL);
2076 static int can_handle_new_request(RADIUS_PACKET *packet,
2078 struct main_config_t *root)
2081 * Count the total number of requests, to see if
2082 * there are too many. If so, return with an
2085 if (root->max_requests) {
2086 int request_count = fr_packet_list_num_elements(pl);
2089 * This is a new request. Let's see if
2090 * it makes us go over our configured
2093 if (request_count > root->max_requests) {
2094 radlog(L_ERR, "Dropping request (%d is too many): "
2095 "from client %s port %d - ID: %d", request_count,
2097 packet->src_port, packet->id);
2098 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2099 "\tThe value for 'max_requests' is probably set too low.\n");
2101 } /* else there were a small number of requests */
2102 } /* else there was no configured limit for requests */
2105 * FIXME: Add per-client checks. If one client is sending
2106 * too many packets, start discarding them.
2108 * We increment the counters here, and decrement them
2109 * when the response is sent... somewhere in this file.
2113 * FUTURE: Add checks for system load. If the system is
2114 * busy, start dropping requests...
2116 * We can probably keep some statistics ourselves... if
2117 * there are more requests coming in than we can handle,
2118 * start dropping some.
2125 int received_request(rad_listen_t *listener,
2126 RADIUS_PACKET *packet, REQUEST **prequest,
2129 RADIUS_PACKET **packet_p;
2130 REQUEST *request = NULL;
2131 struct main_config_t *root = &mainconfig;
2133 packet_p = fr_packet_list_find(pl, packet);
2135 request = fr_packet2myptr(REQUEST, packet, packet_p);
2136 rad_assert(request->in_request_hash);
2138 if ((request->packet->data_len == packet->data_len) &&
2139 (memcmp(request->packet->vector, packet->vector,
2140 sizeof(packet->vector)) == 0)) {
2141 received_retransmit(request, client);
2146 * The new request is different from the old one,
2147 * but maybe the old is finished. If so, delete
2150 switch (request->child_state) {
2151 struct timeval when;
2154 gettimeofday(&when, NULL);
2158 * If the cached request was received
2159 * within the last second, then we
2160 * discard the NEW request instead of the
2161 * old one. This will happen ONLY when
2162 * the client is severely broken, and is
2163 * sending conflicting packets very
2166 if (timercmp(&when, &request->received, <)) {
2167 radlog(L_ERR, "Discarding conflicting packet from "
2168 "client %s port %d - ID: %d due to recent request %d.",
2170 packet->src_port, packet->id,
2175 received_conflicting_request(request, client);
2179 case REQUEST_REJECT_DELAY:
2180 case REQUEST_CLEANUP_DELAY:
2181 request->child_state = REQUEST_DONE;
2183 cleanup_delay(request);
2190 * We may want to quench the new request.
2192 if ((listener->type != RAD_LISTEN_DETAIL) &&
2193 !can_handle_new_request(packet, client, root)) {
2198 * Create and initialize the new request.
2200 request = request_alloc(); /* never fails */
2202 if ((request->reply = rad_alloc(0)) == NULL) {
2203 radlog(L_ERR, "No memory");
2207 request->listener = listener;
2208 request->client = client;
2209 request->packet = packet;
2210 request->packet->timestamp = request->timestamp;
2211 request->number = request_num_counter++;
2212 request->priority = listener->type;
2215 * Status-Server packets go to the head of the queue.
2217 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2220 * Set virtual server identity
2222 if (client->server) {
2223 request->server = client->server;
2224 } else if (listener->server) {
2225 request->server = listener->server;
2227 request->server = NULL;
2231 * Remember the request in the list.
2233 if (!fr_packet_list_insert(pl, &request->packet)) {
2234 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2235 request_free(&request);
2239 request->in_request_hash = TRUE;
2240 request->root = root;
2244 * The request passes many of our sanity checks.
2245 * From here on in, if anything goes wrong, we
2246 * send a reject message, instead of dropping the
2251 * Build the reply template from the request.
2254 request->reply->sockfd = request->packet->sockfd;
2255 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2256 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2257 request->reply->dst_port = request->packet->src_port;
2258 request->reply->src_port = request->packet->dst_port;
2259 request->reply->id = request->packet->id;
2260 request->reply->code = 0; /* UNKNOWN code */
2261 memcpy(request->reply->vector, request->packet->vector,
2262 sizeof(request->reply->vector));
2263 request->reply->vps = NULL;
2264 request->reply->data = NULL;
2265 request->reply->data_len = 0;
2267 request->master_state = REQUEST_ACTIVE;
2268 request->child_state = REQUEST_QUEUED;
2269 request->next_callback = NULL;
2271 gettimeofday(&request->received, NULL);
2272 request->timestamp = request->received.tv_sec;
2273 request->when = request->received;
2275 request->delay = USEC;
2277 tv_add(&request->when, request->delay);
2279 INSERT_EVENT(wait_a_bit, request);
2281 *prequest = request;
2287 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2293 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
2294 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
2295 inet_ntop(packet->src_ipaddr.af,
2296 &packet->src_ipaddr.ipaddr,
2297 buffer, sizeof(buffer)),
2304 * Also removes from the proxy hash if responses == requests
2306 request = lookup_in_proxy_hash(packet);
2309 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
2310 inet_ntop(packet->src_ipaddr.af,
2311 &packet->src_ipaddr.ipaddr,
2312 buffer, sizeof(buffer)),
2313 packet->src_port, packet->id);
2318 home = request->home_server;
2320 gettimeofday(&now, NULL);
2322 home->state = HOME_STATE_ALIVE;
2324 if (request->reply && request->reply->code != 0) {
2325 RDEBUG2("We already replied to this request. Discarding response from home server.");
2331 * We had previously received a reply, so we don't need
2332 * to do anything here.
2334 if (request->proxy_reply) {
2335 if (memcmp(request->proxy_reply->vector,
2337 sizeof(request->proxy_reply->vector)) == 0) {
2338 RDEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
2339 inet_ntop(packet->src_ipaddr.af,
2340 &packet->src_ipaddr.ipaddr,
2341 buffer, sizeof(buffer)),
2342 packet->src_port, packet->id,
2346 * ? The home server gave us a new proxy
2347 * reply, which doesn't match the old
2350 RDEBUG2("Ignoring conflicting proxy reply");
2353 /* assert that there's an event queued for request? */
2359 * The average includes our time to receive packets and
2360 * look them up in the hashes, which should be the same
2363 * We update the response time only for the FIRST packet
2366 else if (home->ema.window > 0) {
2367 radius_stats_ema(&home->ema, &now, &request->proxy_when);
2372 switch (request->child_state) {
2373 case REQUEST_QUEUED:
2374 case REQUEST_RUNNING:
2375 rad_panic("Internal sanity check failed for child state");
2378 case REQUEST_REJECT_DELAY:
2379 case REQUEST_CLEANUP_DELAY:
2381 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'",
2382 inet_ntop(packet->src_ipaddr.af,
2383 &packet->src_ipaddr.ipaddr,
2384 buffer, sizeof(buffer)),
2385 packet->src_port, packet->id,
2387 /* assert that there's an event queued for request? */
2391 case REQUEST_PROXIED:
2395 request->proxy_reply = packet;
2399 * Perform RTT calculations, as per RFC 2988 (for TCP).
2400 * Note that we do so only if we sent one request, and
2401 * received one response. If we sent two requests, we
2402 * have no idea if the response is for the first, or for
2403 * the second request/
2405 if (request->num_proxied_requests == 1) {
2407 home_server *home = request->home_server;
2409 rtt = now.tv_sec - request->proxy_when.tv_sec;
2412 rtt -= request->proxy_when.tv_usec;
2414 if (!home->has_rtt) {
2415 home->has_rtt = TRUE;
2418 home->rttvar = rtt / 2;
2421 home->rttvar -= home->rttvar >> 2;
2422 home->rttvar += (home->srtt - rtt);
2423 home->srtt -= home->srtt >> 3;
2424 home->srtt += rtt >> 3;
2427 home->rto = home->srtt;
2428 if (home->rttvar > (USEC / 4)) {
2429 home->rto += home->rttvar * 4;
2437 * There's no incoming request, so it's a proxied packet
2440 if (!request->packet) {
2441 received_response_to_ping(request);
2445 request->child_state = REQUEST_QUEUED;
2446 request->when = now;
2447 request->delay = USEC;
2448 request->priority = RAD_LISTEN_PROXY;
2449 tv_add(&request->when, request->delay);
2452 * Wait a bit will take care of max_request_time
2454 INSERT_EVENT(wait_a_bit, request);
2460 void event_new_fd(rad_listen_t *this)
2464 this->print(this, buffer, sizeof(buffer));
2466 if (this->status == RAD_LISTEN_STATUS_INIT) {
2468 DEBUG("Listening on %s", buffer);
2470 DEBUG2(" ... adding new socket %s", buffer);
2472 if (!fr_event_fd_insert(el, 0, this->fd,
2473 event_socket_handler, this)) {
2474 radlog(L_ERR, "Failed remembering handle for proxy socket!");
2478 this->status = RAD_LISTEN_STATUS_KNOWN;
2482 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
2483 DEBUG2(" ... closing socket %s", buffer);
2485 fr_event_fd_delete(el, 0, this->fd);
2486 this->status = RAD_LISTEN_STATUS_FINISH;
2489 * Close the fd AFTER fixing up the requests and
2490 * listeners, so that they don't send/recv on the
2491 * wrong socket (if someone manages to open
2500 static void event_detail_timer(void *ctx)
2502 rad_listen_t *listener = ctx;
2503 RAD_REQUEST_FUNP fun;
2506 if (listener->recv(listener, &fun, &request)) {
2507 if (!thread_pool_addrequest(request, fun)) {
2508 request->child_state = REQUEST_DONE;
2514 static void handle_signal_self(int flag)
2516 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2517 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2518 fr_event_loop_exit(el, 1);
2520 fr_event_loop_exit(el, 2);
2524 } /* else exit/term flags weren't set */
2527 * Tell the even loop to stop processing.
2529 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2531 static time_t last_hup = 0;
2533 DEBUG("Received HUP signal.");
2536 if ((int) (when - last_hup) < 5) {
2537 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2542 fr_event_loop_exit(el, 0x80);
2546 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2549 for (this = mainconfig.listen;
2551 this = this->next) {
2553 struct timeval when;
2555 if (this->type != RAD_LISTEN_DETAIL) continue;
2557 delay = detail_delay(this);
2558 if (!delay) continue;
2560 fr_event_now(el, &now);
2562 tv_add(&when, delay);
2564 if (delay > 100000) {
2565 DEBUG("Delaying next detail event for %d.%01u seconds.",
2566 delay / USEC, (delay % USEC) / 100000);
2569 if (!fr_event_insert(el, event_detail_timer, this,
2571 radlog(L_ERR, "Failed remembering timer");
2578 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2581 for (this = mainconfig.listen;
2583 this = this->next) {
2584 if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
2592 void radius_signal_self(int flag)
2594 handle_signal_self(flag);
2598 * Inform ourselves that we received a signal.
2600 void radius_signal_self(int flag)
2606 * The read MUST be non-blocking for this to work.
2608 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2612 for (i = 0; i < rcode; i++) {
2613 buffer[0] |= buffer[i];
2621 write(self_pipe[1], buffer, 1);
2625 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2626 UNUSED int fd, UNUSED void *ctx)
2631 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2632 if (rcode <= 0) return;
2635 * Merge pending signals.
2637 for (i = 0; i < rcode; i++) {
2638 buffer[0] |= buffer[i];
2641 handle_signal_self(buffer[0]);
2646 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
2649 rad_listen_t *listener = ctx;
2650 RAD_REQUEST_FUNP fun;
2653 rad_assert(xel == el);
2657 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2659 if (!listener->recv(listener, &fun, &request)) return;
2661 if (!thread_pool_addrequest(request, fun)) {
2662 request->child_state = REQUEST_DONE;
2668 * This function is called periodically to see if any FD's are
2669 * available for reading.
2671 static void event_poll_detail(UNUSED void *ctx)
2674 RAD_REQUEST_FUNP fun;
2677 struct timeval when;
2679 fr_event_now(el, &now);
2683 for (this = mainconfig.listen; this != NULL; this = this->next) {
2684 if (this->type != RAD_LISTEN_DETAIL) continue;
2686 if (this->fd >= 0) continue;
2689 * Try to read something.
2691 * FIXME: This does poll AND receive.
2693 rcode = this->recv(this, &fun, &request);
2694 if (!rcode) continue;
2696 rad_assert(fun != NULL);
2697 rad_assert(request != NULL);
2699 if (!thread_pool_addrequest(request, fun)) {
2700 request->child_state = REQUEST_DONE;
2707 if (!fr_event_insert(el, event_poll_detail, NULL,
2709 radlog(L_ERR, "Failed creating handler");
2715 static void event_status(struct timeval *wake)
2717 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2721 if (debug_flag == 0) {
2723 radlog(L_INFO, "Ready to process requests.");
2724 just_started = FALSE;
2730 DEBUG("Ready to process requests.");
2732 } else if ((wake->tv_sec != 0) ||
2733 (wake->tv_usec >= 100000)) {
2734 DEBUG("Waking up in %d.%01u seconds.",
2735 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2740 * FIXME: Put this somewhere else, where it isn't called
2741 * all of the time...
2744 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2746 * If there are no child threads, then there may
2747 * be child processes. In that case, wait for
2748 * their exit status, and throw that exit status
2749 * away. This helps get rid of zxombie children.
2751 while (waitpid(-1, &argval, WNOHANG) > 0) {
2760 * Externally-visibly functions.
2762 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2764 rad_listen_t *this, *head = NULL;
2768 time(&fr_start_time);
2770 el = fr_event_list_create(event_status);
2773 pl = fr_packet_list_create(0);
2776 request_num_counter = 0;
2779 * Move all of the thread calls to this file?
2781 * It may be best for the mutexes to be in this file...
2783 have_children = spawn_flag;
2786 if (mainconfig.proxy_requests) {
2788 * Create the tree for managing proxied requests and
2791 proxy_list = fr_packet_list_create(1);
2792 if (!proxy_list) return 0;
2794 #ifdef HAVE_PTHREAD_H
2795 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2796 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2805 * Just before we spawn the child threads, force the log
2806 * subsystem to re-open the log file for every write.
2808 if (spawn_flag) force_log_reopen();
2810 #ifdef HAVE_PTHREAD_H
2811 if (thread_pool_init(cs, spawn_flag) < 0) {
2817 DEBUG("%s: #### Skipping IP addresses and Ports ####",
2824 * Child threads need a pipe to signal us, as do the
2827 if (pipe(self_pipe) < 0) {
2828 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2832 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2833 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2837 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2838 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2843 if (!fr_event_fd_insert(el, 0, self_pipe[0],
2844 event_signal_handler, el)) {
2845 radlog(L_ERR, "Failed creating handler for signals");
2852 * Mark the proxy Fd's as unused.
2857 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2861 DEBUG("%s: #### Opening IP addresses and Ports ####",
2864 if (listen_init(cs, &head) < 0) {
2869 * Add all of the sockets to the event loop.
2873 this = this->next) {
2876 this->print(this, buffer, sizeof(buffer));
2878 switch (this->type) {
2880 case RAD_LISTEN_DETAIL:
2881 DEBUG("Listening on %s", buffer);
2882 has_detail_listener = TRUE;
2887 case RAD_LISTEN_PROXY:
2888 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2889 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2891 proxy_fds[this->fd & 0x1f] = this->fd;
2892 proxy_listeners[this->fd & 0x1f] = this;
2893 if (!fr_packet_list_socket_add(proxy_list,
2905 * The file descriptor isn't ready. Poll for
2906 * when it will become ready. This is for the
2916 if (has_detail_listener) {
2917 struct timeval when;
2919 gettimeofday(&when, NULL);
2922 if (!fr_event_insert(el, event_poll_detail, NULL,
2924 radlog(L_ERR, "Failed creating handler");
2929 mainconfig.listen = head;
2935 static int request_hash_cb(UNUSED void *ctx, void *data)
2937 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2940 rad_assert(request->in_proxy_hash == FALSE);
2943 fr_event_delete(el, &request->ev);
2944 remove_from_request_hash(request);
2945 request_free(&request);
2952 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2954 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2956 fr_packet_list_yank(proxy_list, request->proxy);
2957 request->in_proxy_hash = FALSE;
2959 if (!request->in_request_hash) {
2960 fr_event_delete(el, &request->ev);
2961 request_free(&request);
2968 void radius_event_free(void)
2971 * FIXME: Stop all threads, or at least check that
2972 * they're all waiting on the semaphore, and the queues
2978 * There are requests in the proxy hash that aren't
2979 * referenced from anywhere else. Remove them first.
2982 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2983 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2984 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2985 fr_packet_list_free(proxy_list);
2990 fr_packet_list_walk(pl, NULL, request_hash_cb);
2992 fr_packet_list_free(pl);
2995 fr_event_list_free(el);
2998 int radius_event_process(void)
3002 return fr_event_loop(el);
3005 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3007 request->options = RAD_REQUEST_OPTION_DEBUG2;
3009 if (request_pre_handler(request)) {
3010 rad_assert(fun != NULL);
3011 rad_assert(request != NULL);
3013 if (request->server) RDEBUG("server %s {",
3017 if (request->server) RDEBUG("} # server %s",
3020 request_post_handler(request);
3023 DEBUG2("Going to the next request");