2 * event.c Server event handling
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2007 The FreeRADIUS server project
21 * Copyright 2007 Alan DeKok <aland@deployingradius.com>
24 #include <freeradius-devel/ident.h>
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/detail.h>
32 #include <freeradius-devel/rad_assert.h>
37 #ifdef HAVE_SYS_WAIT_H
38 # include <sys/wait.h>
41 #define USEC (1000000)
43 extern pid_t radius_pid;
45 extern int check_config;
46 extern void force_log_reopen(void);
47 extern char *debug_condition;
50 * Ridiculous amounts of local state.
52 static fr_event_list_t *el = NULL;
53 static fr_packet_list_t *pl = NULL;
54 static int request_num_counter = 0;
55 static struct timeval now;
57 static int have_children;
58 static int just_started = TRUE;
62 #define WITH_SELF_PIPE (1)
67 static int self_pipe[2];
72 static pthread_mutex_t proxy_mutex;
75 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
76 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
78 static pthread_t NO_SUCH_CHILD_PID;
81 * This is easier than ifdef's throughout the code.
83 #define PTHREAD_MUTEX_LOCK(_x)
84 #define PTHREAD_MUTEX_UNLOCK(_x)
85 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
87 radius_handle_request(request, fun);
92 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
95 static fr_packet_list_t *proxy_list = NULL;
98 * We keep the proxy FD's here. The RADIUS Id's are marked
99 * "allocated" per Id, via a bit per proxy FD.
101 static int proxy_fds[32];
102 static rad_listen_t *proxy_listeners[32];
104 #define remove_from_proxy_hash(foo)
107 static void request_post_handler(REQUEST *request);
108 static void wait_a_bit(void *ctx);
109 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
111 static void event_poll_detail(void *ctx);
114 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
117 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
121 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
124 static void tv_add(struct timeval *tv, int usec_delay)
126 if (usec_delay > USEC) {
127 tv->tv_sec += usec_delay / USEC;
130 tv->tv_usec += usec_delay;
132 if (tv->tv_usec > USEC) {
138 static void remove_from_request_hash(REQUEST *request)
140 if (!request->in_request_hash) return;
142 fr_packet_list_yank(pl, request->packet);
143 request->in_request_hash = FALSE;
145 request_stats_final(request);
150 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
152 RADIUS_PACKET **proxy_p;
155 PTHREAD_MUTEX_LOCK(&proxy_mutex);
156 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
159 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
163 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
166 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
170 request->num_proxied_responses++;
173 * Catch the most common case of everything working
176 if (request->num_proxied_requests == request->num_proxied_responses) {
177 fr_packet_list_yank(proxy_list, request->proxy);
178 fr_packet_list_id_free(proxy_list, request->proxy);
179 request->in_proxy_hash = FALSE;
183 * On the FIRST reply, decrement the count of outstanding
184 * requests. Note that this is NOT the count of sent
185 * packets, but whether or not the home server has
188 if (!request->proxy_reply &&
189 request->home_server &&
190 request->home_server->currently_outstanding) {
191 request->home_server->currently_outstanding--;
194 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
200 static void remove_from_proxy_hash(REQUEST *request)
203 * Check this without grabbing the mutex because it's a
204 * lot faster that way.
206 if (!request->in_proxy_hash) return;
209 * The "not in hash" flag is definitive. However, if the
210 * flag says that it IS in the hash, there might still be
211 * a race condition where it isn't.
213 PTHREAD_MUTEX_LOCK(&proxy_mutex);
215 if (!request->in_proxy_hash) {
216 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
220 fr_packet_list_yank(proxy_list, request->proxy);
221 fr_packet_list_id_free(proxy_list, request->proxy);
224 * The home server hasn't replied, but we've given up on
225 * this request. Don't count this request against the
228 if (!request->proxy_reply &&
229 request->home_server &&
230 request->home_server->currently_outstanding) {
231 request->home_server->currently_outstanding--;
235 * Got from YES in hash, to NO, not in hash while we hold
236 * the mutex. This guarantees that when another thread
237 * grans the mutex, the "not in hash" flag is correct.
239 request->in_proxy_hash = FALSE;
241 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
244 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
247 rad_listen_t *proxy_listener;
249 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
252 * Allocate a new proxy fd. This function adds
253 * it to the tail of the list of listeners. With
254 * some care, this can be thread-safe.
256 proxy_listener = proxy_new_listener();
257 if (!proxy_listener) {
258 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
266 proxy = proxy_listener->fd;
267 for (i = 0; i < 32; i++) {
269 * Found a free entry. Save the socket,
270 * and remember where we saved it.
272 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
273 found = (proxy + i) & 0x1f;
274 proxy_fds[found] = proxy;
275 proxy_listeners[found] = proxy_listener;
279 rad_assert(found >= 0);
281 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
282 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
287 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
288 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
293 * Signal the main thread to add the new FD to the list
296 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
301 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
306 rad_assert(request->proxy != NULL);
307 rad_assert(proxy_list != NULL);
309 PTHREAD_MUTEX_LOCK(&proxy_mutex);
312 * Keep track of maximum outstanding requests to a
313 * particular home server. 'max_outstanding' is
314 * enforced in home_server_ldb(), in realms.c.
316 if (request->home_server) {
317 request->home_server->currently_outstanding++;
318 request->home_server->stats.total_requests++;
322 RADIUS_PACKET packet;
324 packet = *request->proxy;
326 if (!proxy_id_alloc(request, &packet)) {
327 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
332 * Yank the request, free the old Id, and
333 * remember the new Id.
335 fr_packet_list_yank(proxy_list, request->proxy);
336 fr_packet_list_id_free(proxy_list, request->proxy);
337 *request->proxy = packet;
339 } else if (!proxy_id_alloc(request, request->proxy)) {
340 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
344 rad_assert(request->proxy->sockfd >= 0);
347 * FIXME: Hack until we get rid of rad_listen_t, and put
348 * the information into the packet_list.
351 for (i = 0; i < 32; i++) {
352 if (proxy_fds[i] == request->proxy->sockfd) {
359 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
360 RDEBUG2("ERROR: All sockets are full.");
364 rad_assert(proxy_fds[proxy] != -1);
365 rad_assert(proxy_listeners[proxy] != NULL);
366 request->proxy_listener = proxy_listeners[proxy];
368 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
369 fr_packet_list_id_free(proxy_list, request->proxy);
370 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
371 RDEBUG2("ERROR: Failed to insert entry into proxy list");
375 request->in_proxy_hash = TRUE;
377 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
379 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
380 inet_ntop(request->proxy->dst_ipaddr.af,
381 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
382 request->proxy->dst_port,
390 * Called as BOTH an event, and in-line from other functions.
392 static void wait_for_proxy_id_to_expire(void *ctx)
394 REQUEST *request = ctx;
396 rad_assert(request->magic == REQUEST_MAGIC);
397 rad_assert(request->proxy != NULL);
399 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
400 request->when = request->proxy_when;
403 if ((request->proxy->code == PW_COA_REQUEST) ||
404 (request->proxy->code == PW_DISCONNECT_REQUEST)) {
405 request->when.tv_sec += request->home_server->coa_mrd;
408 request->when.tv_sec += request->home_server->response_window;
410 if ((request->num_proxied_requests == request->num_proxied_responses) ||
411 timercmp(&now, &request->when, >)) {
412 if (request->packet) {
413 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
414 request->number, request->packet->id,
415 (unsigned int) (request->timestamp - fr_start_time));
417 RDEBUG2("Cleaning up request %d with timestamp +%d",
419 (unsigned int) (request->timestamp - fr_start_time));
422 fr_event_delete(el, &request->ev);
423 remove_from_proxy_hash(request);
424 remove_from_request_hash(request);
425 request_free(&request);
429 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
433 #ifdef HAVE_PTHREAD_H
434 static void wait_for_child_to_die(void *ctx)
436 REQUEST *request = ctx;
438 rad_assert(request->magic == REQUEST_MAGIC);
440 if ((request->child_state == REQUEST_QUEUED) |
441 (request->child_state == REQUEST_RUNNING)) {
442 request->delay += (request->delay >> 1);
443 tv_add(&request->when, request->delay);
445 RDEBUG2("Child is still stuck for request %d", request->number);
447 INSERT_EVENT(wait_for_child_to_die, request);
451 RDEBUG2("Child is finally responsive for request %d", request->number);
452 remove_from_request_hash(request);
455 if (request->proxy) {
456 wait_for_proxy_id_to_expire(request);
461 request_free(&request);
465 static void cleanup_delay(void *ctx)
467 REQUEST *request = ctx;
469 rad_assert(request->magic == REQUEST_MAGIC);
470 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
471 (request->child_state == REQUEST_DONE));
473 remove_from_request_hash(request);
476 if (request->proxy && request->in_proxy_hash) {
477 wait_for_proxy_id_to_expire(request);
482 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
483 request->number, request->packet->id,
484 (unsigned int) (request->timestamp - fr_start_time));
486 fr_event_delete(el, &request->ev);
487 request_free(&request);
492 * FIXME: Put into a libradius function.
494 #define MAX_PACKET_CODE (52)
495 static const char *packet_codes[] = {
500 "Accounting-Request",
501 "Accounting-Response",
506 "Accounting-Message",
517 "Resource-Free-Request",
518 "Resource-Free-Response",
519 "Resource-Query-Request",
520 "Resource-Query-Response",
521 "Alternate-Resource-Reclaim-Request",
522 "NAS-Reboot-Request",
523 "NAS-Reboot-Response",
536 "Disconnect-Request",
546 "IP-Address-Allocate",
552 * In daemon mode, AND this request has debug flags set.
554 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
556 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
560 const char *received, *from;
561 const fr_ipaddr_t *ip;
566 rad_assert(debug_flag != 0);
567 rad_assert(request->radlog != NULL);
569 if (direction == 0) {
570 received = "Received";
571 from = "from"; /* what else? */
572 ip = &packet->src_ipaddr;
573 port = packet->src_port;
576 received = "Sending";
577 from = "to"; /* hah! */
578 ip = &packet->dst_ipaddr;
579 port = packet->dst_port;
583 * Client-specific debugging re-prints the input
584 * packet into the client log.
586 * This really belongs in a utility library
588 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
589 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
590 received, packet_codes[packet->code], from,
591 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
592 port, packet->id, packet->data_len);
594 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
596 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
598 packet->code, packet->id, packet->data_len);
601 for (vp = packet->vps; vp != NULL; vp = vp->next) {
602 vp_prints(buffer, sizeof(buffer), vp);
603 request->radlog(L_DBG, 0, request, "\t%s", buffer);
607 static void reject_delay(void *ctx)
609 REQUEST *request = ctx;
611 rad_assert(request->magic == REQUEST_MAGIC);
612 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
614 RDEBUG2("Sending delayed reject for request %d", request->number);
616 DEBUG_PACKET(request, request->reply, 1);
618 request->listener->send(request->listener, request);
620 request->when.tv_sec += request->root->cleanup_delay;
621 request->child_state = REQUEST_CLEANUP_DELAY;
623 INSERT_EVENT(cleanup_delay, request);
628 void revive_home_server(void *ctx)
630 home_server *home = ctx;
633 home->state = HOME_STATE_ALIVE;
634 home->currently_outstanding = 0;
635 home->revive_time = now;
638 * Delete any outstanding events.
640 if (home->ev) fr_event_delete(el, &home->ev);
642 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
643 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
644 buffer, sizeof(buffer)),
650 static void no_response_to_ping(void *ctx)
652 REQUEST *request = ctx;
656 rad_assert(request->home_server != NULL);
658 home = request->home_server;
659 home->num_received_pings = 0;
661 RDEBUG2("No response to status check %d from home server %s port %d",
663 inet_ntop(request->proxy->dst_ipaddr.af,
664 &request->proxy->dst_ipaddr.ipaddr,
665 buffer, sizeof(buffer)),
666 request->proxy->dst_port);
668 wait_for_proxy_id_to_expire(request);
672 static void received_response_to_ping(REQUEST *request)
677 rad_assert(request->home_server != NULL);
679 if (rad_verify(request->proxy_reply, request->proxy,
680 request->home_server->secret) != 0) {
681 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
685 home = request->home_server;
686 home->num_received_pings++;
688 RDEBUG2("Received response to status check %d (%d in current sequence)",
689 request->number, home->num_received_pings);
692 * Remove the request from any hashes
694 fr_event_delete(el, &request->ev);
695 remove_from_proxy_hash(request);
696 rad_assert(request->in_request_hash == FALSE);
699 * The control socket may have marked the home server as
700 * alive. OR, it may have suddenly started responding to
701 * requests again. If so, don't re-do the "make alive"
704 if (home->state == HOME_STATE_ALIVE) return;
707 * We haven't received enough ping responses to mark it
708 * "alive". Wait a bit.
710 if (home->num_received_pings < home->num_pings_to_alive) {
714 home->state = HOME_STATE_ALIVE;
715 home->currently_outstanding = 0;
716 home->revive_time = now;
718 if (!fr_event_delete(el, &home->ev)) {
719 RDEBUG2("Hmm... no event for home server. Oh well.");
722 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
723 inet_ntop(request->proxy->dst_ipaddr.af,
724 &request->proxy->dst_ipaddr.ipaddr,
725 buffer, sizeof(buffer)),
726 request->proxy->dst_port);
731 * Called from start of zombie period, OR after control socket
732 * marks the home server dead.
734 static void ping_home_server(void *ctx)
737 home_server *home = ctx;
741 if (home->state == HOME_STATE_ALIVE) {
742 radlog(L_INFO, "Suspicious proxy state... continuing");
746 request = request_alloc();
747 request->number = request_num_counter++;
749 request->proxy = rad_alloc(1);
750 rad_assert(request->proxy != NULL);
752 fr_event_now(el, &request->when);
753 home->when = request->when;
755 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
756 request->proxy->code = PW_STATUS_SERVER;
758 radius_pairmake(request, &request->proxy->vps,
759 "Message-Authenticator", "0x00", T_OP_SET);
761 } else if (home->type == HOME_TYPE_AUTH) {
762 request->proxy->code = PW_AUTHENTICATION_REQUEST;
764 radius_pairmake(request, &request->proxy->vps,
765 "User-Name", home->ping_user_name, T_OP_SET);
766 radius_pairmake(request, &request->proxy->vps,
767 "User-Password", home->ping_user_password, T_OP_SET);
768 radius_pairmake(request, &request->proxy->vps,
769 "Service-Type", "Authenticate-Only", T_OP_SET);
770 radius_pairmake(request, &request->proxy->vps,
771 "Message-Authenticator", "0x00", T_OP_SET);
774 #ifdef WITH_ACCOUNTING
775 request->proxy->code = PW_ACCOUNTING_REQUEST;
777 radius_pairmake(request, &request->proxy->vps,
778 "User-Name", home->ping_user_name, T_OP_SET);
779 radius_pairmake(request, &request->proxy->vps,
780 "Acct-Status-Type", "Stop", T_OP_SET);
781 radius_pairmake(request, &request->proxy->vps,
782 "Acct-Session-Id", "00000000", T_OP_SET);
783 vp = radius_pairmake(request, &request->proxy->vps,
784 "Event-Timestamp", "0", T_OP_SET);
785 vp->vp_date = now.tv_sec;
787 rad_assert("Internal sanity check failed");
791 radius_pairmake(request, &request->proxy->vps,
792 "NAS-Identifier", "Status Check. Are you alive?",
795 request->proxy->dst_ipaddr = home->ipaddr;
796 request->proxy->dst_port = home->port;
797 request->home_server = home;
799 rad_assert(request->proxy_listener == NULL);
801 if (!insert_into_proxy_hash(request, FALSE)) {
802 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
804 request_free(&request);
807 rad_assert(request->proxy_listener != NULL);
808 request->proxy_listener->send(request->proxy_listener,
811 request->next_callback = NULL;
812 request->child_state = REQUEST_PROXIED;
813 request->when.tv_sec += home->ping_timeout;;
815 INSERT_EVENT(no_response_to_ping, request);
818 * Add +/- 2s of jitter, as suggested in RFC 3539
819 * and in the Issues and Fixes draft.
821 home->when.tv_sec += home->ping_interval - 2;
824 jitter ^= (jitter >> 10);
825 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
827 tv_add(&home->when, jitter);
829 INSERT_EVENT(ping_home_server, home);
833 void mark_home_server_dead(home_server *home, struct timeval *when)
835 int previous_state = home->state;
838 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
839 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
840 buffer, sizeof(buffer)),
843 home->state = HOME_STATE_IS_DEAD;
844 home->num_received_pings = 0;
846 if (home->ping_check != HOME_PING_CHECK_NONE) {
848 * If the control socket marks us dead, start
849 * pinging. Otherwise, we already started
850 * pinging when it was marked "zombie".
852 if (previous_state == HOME_STATE_ALIVE) {
853 ping_home_server(home);
858 * Revive it after a fixed period of time. This
859 * is very, very, bad.
862 home->when.tv_sec += home->revive_interval;
864 INSERT_EVENT(revive_home_server, home);
868 static void check_for_zombie_home_server(REQUEST *request)
873 home = request->home_server;
875 if (home->state != HOME_STATE_ZOMBIE) return;
877 when = home->zombie_period_start;
878 when.tv_sec += home->zombie_period;
880 fr_event_now(el, &now);
881 if (timercmp(&now, &when, <)) {
885 mark_home_server_dead(home, &request->when);
888 static int proxy_to_virtual_server(REQUEST *request);
890 static int virtual_server_handler(UNUSED REQUEST *request)
892 proxy_to_virtual_server(request);
896 static void proxy_fallback_handler(REQUEST *request)
899 * A proper time is required for wait_a_bit.
901 request->delay = USEC / 10;
902 gettimeofday(&now, NULL);
903 request->next_when = now;
904 tv_add(&request->next_when, request->delay);
905 request->next_callback = wait_a_bit;
908 * Re-queue the request.
910 request->child_state = REQUEST_QUEUED;
912 rad_assert(request->proxy != NULL);
913 if (!thread_pool_addrequest(request, virtual_server_handler)) {
914 request->child_state = REQUEST_DONE;
917 #ifdef HAVE_PTHREAD_H
919 * MAY free the request if we're over max_request_time,
920 * AND we're not in threaded mode!
922 * Note that we call this ONLY if we're threaded, as
923 * if we're NOT threaded, request_post_handler() calls
924 * wait_a_bit(), which means that "request" may not
927 if (have_children) wait_a_bit(request);
932 static int setup_post_proxy_fail(REQUEST *request)
934 DICT_VALUE *dval = NULL;
937 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
938 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
940 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
941 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
945 * See no_response_to_coa_request
947 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
948 request->packet->code &= 0xff; /* restore it */
950 if (request->proxy->code == PW_COA_REQUEST) {
951 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
953 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
954 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
964 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
967 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
971 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
972 if (!vp) vp = radius_paircreate(request, &request->config_items,
973 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
974 vp->vp_integer = dval->value;
976 rad_assert(request->proxy_reply == NULL);
982 static int null_handler(UNUSED REQUEST *request)
987 static void post_proxy_fail_handler(REQUEST *request)
990 * A proper time is required for wait_a_bit.
992 request->delay = USEC / 10;
993 gettimeofday(&now, NULL);
996 * Not set up to run Post-Proxy-Type = Fail.
998 * Mark the request as still running, and figure out what
1001 if (!setup_post_proxy_fail(request)) {
1002 request->child_state = REQUEST_RUNNING;
1003 request_post_handler(request);
1007 * Re-queue the request.
1009 request->child_state = REQUEST_QUEUED;
1012 * There is a post-proxy-type of fail. We run
1013 * the request through the pre/post proxy
1014 * handlers, just like it was a real proxied
1015 * request. However, we set the per-request
1016 * handler to NULL, as we don't want to do
1019 * Note that when we're not threaded, this will
1020 * process the request even if it's greater than
1021 * max_request_time. That's not fatal.
1023 request->priority = 0;
1024 rad_assert(request->proxy != NULL);
1025 thread_pool_addrequest(request, null_handler);
1029 * MAY free the request if we're over max_request_time,
1030 * AND we're not in threaded mode!
1032 * Note that we call this ONLY if we're threaded, as
1033 * if we're NOT threaded, request_post_handler() calls
1034 * wait_a_bit(), which means that "request" may not
1037 if (have_children) wait_a_bit(request);
1041 /* maybe check this against wait_for_proxy_id_to_expire? */
1042 static void no_response_to_proxied_request(void *ctx)
1044 REQUEST *request = ctx;
1048 rad_assert(request->magic == REQUEST_MAGIC);
1049 rad_assert(request->child_state == REQUEST_PROXIED);
1052 * If we've failed over to an internal home server,
1053 * replace the callback with the correct one. This
1054 * is due to locking issues with child threads...
1056 if (request->home_server->server) {
1057 wait_a_bit(request);
1061 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
1063 inet_ntop(request->proxy->dst_ipaddr.af,
1064 &request->proxy->dst_ipaddr.ipaddr,
1065 buffer, sizeof(buffer)),
1066 request->proxy->dst_port);
1068 check_for_zombie_home_server(request);
1070 home = request->home_server;
1072 post_proxy_fail_handler(request);
1075 * Don't touch request due to race conditions
1077 if (home->state == HOME_STATE_IS_DEAD) {
1078 rad_assert(home->ev != NULL); /* or it will never wake up */
1083 * Enable the zombie period when we notice that the home
1084 * server hasn't responded. We do NOT back-date the start
1085 * of the zombie period.
1087 if (home->state == HOME_STATE_ALIVE) {
1088 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1089 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1090 buffer, sizeof(buffer)),
1092 home->state = HOME_STATE_ZOMBIE;
1093 home->zombie_period_start = now;
1096 * Start pinging the home server.
1098 ping_home_server(home);
1103 static void wait_a_bit(void *ctx)
1105 struct timeval when;
1106 REQUEST *request = ctx;
1107 fr_event_callback_t callback = NULL;
1109 rad_assert(request->magic == REQUEST_MAGIC);
1113 * The CoA request is a new (internally generated)
1114 * request, created in a child thread. We therefore need
1115 * some way to tie its events back into the main event
1118 if (request->coa && !request->coa->proxy_reply &&
1119 request->coa->next_callback) {
1120 request->coa->when = request->coa->next_when;
1121 INSERT_EVENT(request->coa->next_callback, request->coa);
1122 request->coa->next_callback = NULL;
1123 request->coa->parent = NULL;
1124 request->coa = NULL;
1128 switch (request->child_state) {
1129 case REQUEST_QUEUED:
1130 case REQUEST_RUNNING:
1131 when = request->received;
1132 when.tv_sec += request->root->max_request_time;
1135 * Normally called from the event loop with the
1136 * proper event loop time. Otherwise, called from
1137 * post proxy fail handler, which sets "now", and
1138 * this call won't re-set it, because we're not
1139 * in the event loop.
1141 fr_event_now(el, &now);
1144 * Request still has more time. Continue
1147 if (timercmp(&now, &when, <) ||
1148 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1149 (request->child_state == REQUEST_QUEUED))) {
1150 if (request->delay < (USEC / 10)) {
1151 request->delay = USEC / 10;
1153 request->delay += request->delay >> 1;
1157 * Cap wait at some sane value for detail
1160 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1161 (request->delay > (request->root->max_request_time * USEC))) {
1162 request->delay = request->root->max_request_time * USEC;
1166 request->when = now;
1167 tv_add(&request->when, request->delay);
1168 callback = wait_a_bit;
1172 #if defined(HAVE_PTHREAD_H)
1174 * A child thread MAY still be running on the
1175 * request. Ask the thread to stop working on
1178 if (have_children) {
1179 /* FIXME: kill unresponsive children? */
1182 * Print this error message ONLY if
1183 * there's a child currently processing
1184 * the request. As we don't have thread
1185 * locks here, there may be race
1186 * conditions on this check. But it's
1187 * just an error message, so that's OK.
1189 if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1190 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1192 request->module ? request->module : "<server core>",
1193 request->component ? request->component : "<server core>");
1196 request->master_state = REQUEST_STOP_PROCESSING;
1198 request->delay = USEC / 4;
1199 tv_add(&request->when, request->delay);
1200 callback = wait_for_child_to_die;
1206 * Else there are no child threads. We probably
1207 * should have just marked the request as 'done'
1208 * elsewhere, like in the post-proxy-fail
1209 * handler. But doing that would involve
1210 * checking for max_request_time in multiple
1211 * places, so this may be simplest.
1213 request->child_state = REQUEST_DONE;
1217 * Mark the request as no longer running,
1221 #ifdef HAVE_PTHREAD_H
1222 request->child_pid = NO_SUCH_CHILD_PID;
1227 * This is a CoA request. It's been divorced
1228 * from everything else, so we clean it up now.
1230 if (!request->in_request_hash &&
1232 (request->packet->code != request->proxy->code) &&
1233 ((request->proxy->code == PW_COA_REQUEST) ||
1234 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1236 * FIXME: Do CoA MIBs
1238 fr_event_delete(el, &request->ev);
1239 remove_from_proxy_hash(request);
1240 request_free(&request);
1244 request_stats_final(request);
1245 cleanup_delay(request);
1248 case REQUEST_REJECT_DELAY:
1249 case REQUEST_CLEANUP_DELAY:
1250 #ifdef HAVE_PTHREAD_H
1251 request->child_pid = NO_SUCH_CHILD_PID;
1253 request_stats_final(request);
1255 case REQUEST_PROXIED:
1256 rad_assert(request->next_callback != NULL);
1257 rad_assert(request->next_callback != wait_a_bit);
1259 request->when = request->next_when;
1260 callback = request->next_callback;
1261 request->next_callback = NULL;
1265 rad_panic("Internal sanity check failure");
1270 * Something major went wrong. Discard the request, and
1273 * FIXME: No idea why this happens or how to fix it...
1274 * It seems to happen *only* when requests are proxied,
1275 * and where the home server doesn't respond. So it looks
1276 * like a race condition above, but it happens in debug
1277 * mode, with no threads...
1280 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1281 fr_event_delete(el, &request->ev);
1282 remove_from_proxy_hash(request);
1283 remove_from_request_hash(request);
1284 request_free(&request);
1288 INSERT_EVENT(callback, request);
1292 static void no_response_to_coa_request(void *ctx)
1294 REQUEST *request = ctx;
1297 rad_assert(request->magic == REQUEST_MAGIC);
1298 rad_assert(request->child_state == REQUEST_PROXIED);
1299 rad_assert(request->home_server != NULL);
1300 rad_assert(!request->in_request_hash);
1302 radlog(L_ERR, "No response to CoA request sent to %s",
1303 inet_ntop(request->proxy->dst_ipaddr.af,
1304 &request->proxy->dst_ipaddr.ipaddr,
1305 buffer, sizeof(buffer)));
1310 request->packet->code |= (PW_COA_REQUEST << 8);
1311 post_proxy_fail_handler(request);
1315 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1319 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1326 packet->data = NULL;
1327 packet->data_len = 0;
1330 return 1; /* time stamp updated */
1335 * Called when we haven't received a response to a CoA request.
1337 static void retransmit_coa_request(void *ctx)
1341 REQUEST *request = ctx;
1343 rad_assert(request->magic == REQUEST_MAGIC);
1344 rad_assert(request->child_state == REQUEST_PROXIED);
1345 rad_assert(request->home_server != NULL);
1346 rad_assert(!request->in_request_hash);
1347 rad_assert(request->parent == NULL);
1349 fr_event_now(el, &now);
1352 * Cap count at MRC, if it is non-zero.
1354 if (request->home_server->coa_mrc &&
1355 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1356 no_response_to_coa_request(request);
1361 * RFC 5080 Section 2.2.1
1363 * RT = 2*RTprev + RAND*RTprev
1364 * = 1.9 * RTprev + rand(0,.2) * RTprev
1365 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1368 delay ^= (delay >> 16);
1370 frac = request->delay / 5;
1371 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1373 delay += (2 * request->delay) - (request->delay / 10);
1376 * Cap delay at MRT, if MRT is non-zero.
1378 if (request->home_server->coa_mrt &&
1379 (delay > (request->home_server->coa_mrt * USEC))) {
1380 int mrt_usec = request->home_server->coa_mrt * USEC;
1383 * delay = MRT + RAND * MRT
1384 * = 0.9 MRT + rand(0,.2) * MRT
1387 delay ^= (delay >> 15);
1389 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1390 delay += mrt_usec - (mrt_usec / 10);
1393 request->delay = delay;
1394 request->when = now;
1395 tv_add(&request->when, request->delay);
1396 mrd = request->proxy_when;
1397 mrd.tv_sec += request->home_server->coa_mrd;
1400 * Cap duration at MRD.
1402 if (timercmp(&mrd, &request->when, <)) {
1403 request->when = mrd;
1404 INSERT_EVENT(no_response_to_coa_request, request);
1407 INSERT_EVENT(retransmit_coa_request, request);
1410 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1411 if (!insert_into_proxy_hash(request, TRUE)) {
1412 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1416 request->num_proxied_requests = 0;
1417 request->num_proxied_responses = 0;
1420 request->num_proxied_requests++;
1421 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1423 request->proxy_listener->send(request->proxy_listener,
1429 * The original request is either DONE, or in CLEANUP_DELAY.
1431 static int originated_coa_request(REQUEST *request)
1433 int delay, rcode, pre_proxy_type = 0;
1439 rad_assert(request->proxy == NULL);
1440 rad_assert(!request->in_proxy_hash);
1441 rad_assert(request->proxy_reply == NULL);
1443 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1444 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1446 if (vp->vp_integer == 0) {
1447 request_free(&request->coa);
1448 return 1; /* success */
1451 if (!request->coa) request_alloc_coa(request);
1452 if (!request->coa) return 0;
1458 * src_ipaddr will be set up in proxy_encode.
1460 memset(&ipaddr, 0, sizeof(ipaddr));
1461 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1463 ipaddr.af = AF_INET;
1464 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1466 } else if ((vp = pairfind(coa->proxy->vps,
1467 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1468 ipaddr.af = AF_INET6;
1469 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1471 } else if ((vp = pairfind(coa->proxy->vps,
1472 PW_HOME_SERVER_POOL)) != NULL) {
1473 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1475 if (!coa->home_pool) {
1476 RDEBUG2("WARNING: No such home_server_pool %s",
1479 request_free(&request->coa);
1486 } else if (request->client->coa_pool) {
1487 coa->home_pool = request->client->coa_pool;
1489 } else if (request->client->coa_server) {
1490 coa->home_server = request->client->coa_server;
1494 * If all else fails, send it to the client that
1495 * originated this request.
1497 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1501 * Use the pool, if it exists.
1503 if (coa->home_pool) {
1504 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1505 if (!coa->home_server) {
1506 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1510 } else if (!coa->home_server) {
1511 int port = PW_COA_UDP_PORT;
1513 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1514 if (vp) port = vp->vp_integer;
1516 coa->home_server = home_server_find(&ipaddr, port);
1517 if (!coa->home_server) {
1518 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1519 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1520 buffer, sizeof(buffer)), port);
1525 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1527 switch (vp->vp_integer) {
1528 case PW_COA_REQUEST:
1529 case PW_DISCONNECT_REQUEST:
1530 coa->proxy->code = vp->vp_integer;
1534 DEBUG("Cannot set CoA Packet-Type to code %d",
1540 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1543 * The rest of the server code assumes that
1544 * request->packet && request->reply exist. Copy them
1545 * from the original request.
1547 rad_assert(coa->packet != NULL);
1548 rad_assert(coa->packet->vps == NULL);
1549 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1550 coa->packet->vps = paircopy(request->packet->vps);
1551 coa->packet->data = NULL;
1552 rad_assert(coa->reply != NULL);
1553 rad_assert(coa->reply->vps == NULL);
1554 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1555 coa->reply->vps = paircopy(request->reply->vps);
1556 coa->reply->data = NULL;
1557 coa->config_items = paircopy(request->config_items);
1560 * Call the pre-proxy routines.
1562 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1564 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1565 pre_proxy_type = vp->vp_integer;
1568 if (coa->home_pool && coa->home_pool->virtual_server) {
1569 const char *old_server = coa->server;
1571 coa->server = coa->home_pool->virtual_server;
1572 RDEBUG2(" server %s {", coa->server);
1573 rcode = module_pre_proxy(pre_proxy_type, coa);
1575 coa->server = old_server;
1577 rcode = module_pre_proxy(pre_proxy_type, coa);
1584 * Only send the CoA packet if the pre-proxy code succeeded.
1586 case RLM_MODULE_NOOP:
1588 case RLM_MODULE_UPDATED:
1593 * Source IP / port is set when the proxy socket
1596 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1597 coa->proxy->dst_port = coa->home_server->port;
1599 if (!insert_into_proxy_hash(coa, FALSE)) {
1600 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1605 * We CANNOT divorce the CoA request from the parent
1606 * request. This function is running in a child thread,
1607 * and we need access to the main event loop in order to
1608 * to add the timers for the CoA packet. See
1613 * Forget about the original request completely at this
1618 gettimeofday(&request->proxy_when, NULL);
1619 request->received = request->next_when = request->proxy_when;
1620 rad_assert(request->proxy_reply == NULL);
1623 * Implement re-transmit algorithm as per RFC 5080
1626 * We want IRT + RAND*IRT
1627 * or 0.9 IRT + rand(0,.2) IRT
1629 * 2^20 ~ USEC, and we want 2.
1630 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1632 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1633 request->delay = delay * request->home_server->coa_irt;
1634 delay = request->home_server->coa_irt * USEC;
1635 delay -= delay / 10;
1636 delay += request->delay;
1638 request->delay = delay;
1639 tv_add(&request->next_when, delay);
1640 request->next_callback = retransmit_coa_request;
1643 * Note that we set proxied BEFORE sending the packet.
1645 * Once we send it, the request is tainted, as
1646 * another thread may have picked it up. Don't
1649 request->num_proxied_requests = 1;
1650 request->num_proxied_responses = 0;
1651 request->child_pid = NO_SUCH_CHILD_PID;
1653 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1655 request->child_state = REQUEST_PROXIED;
1657 DEBUG_PACKET(request, request->proxy, 1);
1659 request->proxy_listener->send(request->proxy_listener,
1663 #endif /* WITH_COA */
1666 static int process_proxy_reply(REQUEST *request)
1669 int post_proxy_type = 0;
1673 * Delete any reply we had accumulated until now.
1675 pairfree(&request->reply->vps);
1678 * Run the packet through the post-proxy stage,
1679 * BEFORE playing games with the attributes.
1681 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1683 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1684 post_proxy_type = vp->vp_integer;
1687 if (request->home_pool && request->home_pool->virtual_server) {
1688 const char *old_server = request->server;
1690 request->server = request->home_pool->virtual_server;
1691 RDEBUG2(" server %s {", request->server);
1692 rcode = module_post_proxy(post_proxy_type, request);
1694 request->server = old_server;
1696 rcode = module_post_proxy(post_proxy_type, request);
1700 if (request->packet->code == request->proxy->code)
1702 * Don't run the next bit if we originated a CoA
1703 * packet, after receiving an Access-Request or
1704 * Accounting-Request.
1709 * There may NOT be a proxy reply, as we may be
1710 * running Post-Proxy-Type = Fail.
1712 if (request->proxy_reply) {
1714 * Delete the Proxy-State Attributes from
1715 * the reply. These include Proxy-State
1716 * attributes from us and remote server.
1718 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1721 * Add the attributes left in the proxy
1722 * reply to the reply list.
1724 pairadd(&request->reply->vps, request->proxy_reply->vps);
1725 request->proxy_reply->vps = NULL;
1728 * Free proxy request pairs.
1730 pairfree(&request->proxy->vps);
1734 default: /* Don't do anything */
1736 case RLM_MODULE_FAIL:
1737 /* FIXME: debug print stuff */
1738 request->child_state = REQUEST_DONE;
1741 case RLM_MODULE_HANDLED:
1742 /* FIXME: debug print stuff */
1743 request->child_state = REQUEST_DONE;
1751 static int request_pre_handler(REQUEST *request)
1755 rad_assert(request->magic == REQUEST_MAGIC);
1756 rad_assert(request->packet != NULL);
1758 request->child_state = REQUEST_RUNNING;
1761 * Don't decode the packet if it's an internal "fake"
1762 * request. Instead, just return so that the caller can
1765 if (request->packet->dst_port == 0) {
1766 request->username = pairfind(request->packet->vps,
1768 request->password = pairfind(request->packet->vps,
1775 * Put the decoded packet into it's proper place.
1777 if (request->proxy_reply != NULL) {
1778 rcode = request->proxy_listener->decode(request->proxy_listener,
1780 DEBUG_PACKET(request, request->proxy_reply, 0);
1783 if (request->packet->vps == NULL) {
1784 rcode = request->listener->decode(request->listener, request);
1786 if (debug_condition) {
1788 const char *my_debug = debug_condition;
1791 * Ignore parse errors.
1793 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1797 request->options = 2;
1798 request->radlog = radlog_request;
1802 DEBUG_PACKET(request, request->packet, 0);
1808 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1809 request->child_state = REQUEST_DONE;
1813 if (!request->username) {
1814 request->username = pairfind(request->packet->vps,
1819 if (request->proxy) {
1820 return process_proxy_reply(request);
1830 * Do state handling when we proxy a request.
1832 static int proxy_request(REQUEST *request)
1834 struct timeval when;
1837 if (request->home_server->server) {
1838 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1842 if (!insert_into_proxy_hash(request, FALSE)) {
1843 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1847 request->proxy_listener->encode(request->proxy_listener, request);
1849 when = request->received;
1850 when.tv_sec += request->root->max_request_time;
1852 gettimeofday(&request->proxy_when, NULL);
1854 request->next_when = request->proxy_when;
1855 request->next_when.tv_sec += request->home_server->response_window;
1857 rad_assert(request->home_server->response_window > 0);
1859 if (timercmp(&when, &request->next_when, <)) {
1860 request->next_when = when;
1862 request->next_callback = no_response_to_proxied_request;
1864 RDEBUG2("Proxying request %d to home server %s port %d",
1866 inet_ntop(request->proxy->dst_ipaddr.af,
1867 &request->proxy->dst_ipaddr.ipaddr,
1868 buffer, sizeof(buffer)),
1869 request->proxy->dst_port);
1872 * Note that we set proxied BEFORE sending the packet.
1874 * Once we send it, the request is tainted, as
1875 * another thread may have picked it up. Don't
1878 request->num_proxied_requests = 1;
1879 request->num_proxied_responses = 0;
1880 #ifdef HAVE_PTHREAD_H
1881 request->child_pid = NO_SUCH_CHILD_PID;
1883 request->child_state = REQUEST_PROXIED;
1885 DEBUG_PACKET(request, request->proxy, 1);
1887 request->proxy_listener->send(request->proxy_listener,
1894 * "Proxy" the request by sending it to a new virtual server.
1896 static int proxy_to_virtual_server(REQUEST *request)
1899 RAD_REQUEST_FUNP fun;
1901 if (!request->home_server || !request->home_server->server) return 0;
1903 if (request->parent) {
1904 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1908 fake = request_alloc_fake(request);
1910 RDEBUG2("WARNING: Out of memory");
1914 fake->packet->vps = paircopy(request->proxy->vps);
1915 fake->server = request->home_server->server;
1917 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1918 fun = rad_authenticate;
1920 #ifdef WITH_ACCOUNTING
1921 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1922 fun = rad_accounting;
1926 RDEBUG2("Unknown packet type %d", request->proxy->code);
1927 request_free(&fake);
1931 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1932 radius_handle_request(fake, fun);
1933 RDEBUG2("<<< Received proxied response from internal virtual server.");
1935 request->proxy_reply = fake->reply;
1938 request_free(&fake);
1940 process_proxy_reply(request);
1942 if (request->server) RDEBUG("server %s {",
1943 request->server != NULL ?
1944 request->server : "");
1947 if (request->server) RDEBUG("} # server %s",
1948 request->server != NULL ?
1949 request->server : "");
1951 return 2; /* success, but NOT '1' !*/
1955 * Return 1 if we did proxy it, or the proxy attempt failed
1956 * completely. Either way, the caller doesn't touch the request
1957 * any more if we return 1.
1959 static int successfully_proxied_request(REQUEST *request)
1962 int pre_proxy_type = 0;
1963 VALUE_PAIR *realmpair;
1964 VALUE_PAIR *strippedname;
1966 char *realmname = NULL;
1968 REALM *realm = NULL;
1972 * If it was already proxied, do nothing.
1974 * FIXME: This should really be a serious error.
1976 if (request->in_proxy_hash) {
1980 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1981 if (!realmpair || (realmpair->length == 0)) {
1985 realmname = (char *) realmpair->vp_strvalue;
1987 realm = realm_find2(realmname);
1989 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1994 * Figure out which pool to use.
1996 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1997 pool = realm->auth_pool;
1999 #ifdef WITH_ACCOUNTING
2000 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2001 pool = realm->acct_pool;
2005 rad_panic("Internal sanity check failed");
2009 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2014 home = home_server_ldb(realmname, pool, request);
2016 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2020 request->home_pool = pool;
2024 * Once we've decided to proxy a request, we cannot send
2025 * a CoA packet. So we free up any CoA packet here.
2027 request_free(&request->coa);
2030 * Remember that we sent the request to a Realm.
2032 pairadd(&request->packet->vps,
2033 pairmake("Realm", realmname, T_OP_EQ));
2036 * Strip the name, if told to.
2038 * Doing it here catches the case of proxied tunneled
2041 if (realm->striprealm == TRUE &&
2042 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2044 * If there's a Stripped-User-Name attribute in
2045 * the request, then use THAT as the User-Name
2046 * for the proxied request, instead of the
2049 * This is done by making a copy of the
2050 * Stripped-User-Name attribute, turning it into
2051 * a User-Name attribute, deleting the
2052 * Stripped-User-Name and User-Name attributes
2053 * from the vps list, and making the new
2054 * User-Name the head of the vps list.
2056 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2058 vp = radius_paircreate(request, NULL,
2059 PW_USER_NAME, PW_TYPE_STRING);
2060 rad_assert(vp != NULL); /* handled by above function */
2061 /* Insert at the START of the list */
2062 vp->next = request->proxy->vps;
2063 request->proxy->vps = vp;
2065 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2066 sizeof(vp->vp_strvalue));
2067 vp->length = strippedname->length;
2070 * Do NOT delete Stripped-User-Name.
2075 * If there is no PW_CHAP_CHALLENGE attribute but
2076 * there is a PW_CHAP_PASSWORD we need to add it
2077 * since we can't use the request authenticator
2078 * anymore - we changed it.
2080 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2081 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2082 vp = radius_paircreate(request, &request->proxy->vps,
2083 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2084 vp->length = AUTH_VECTOR_LEN;
2085 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2089 * The RFC's say we have to do this, but FreeRADIUS
2092 vp = radius_paircreate(request, &request->proxy->vps,
2093 PW_PROXY_STATE, PW_TYPE_OCTETS);
2094 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2095 request->packet->id);
2096 vp->length = strlen(vp->vp_strvalue);
2099 * Should be done BEFORE inserting into proxy hash, as
2100 * pre-proxy may use this information, or change it.
2102 request->proxy->code = request->packet->code;
2105 * Call the pre-proxy routines.
2107 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2109 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2110 pre_proxy_type = vp->vp_integer;
2113 rad_assert(request->home_pool != NULL);
2115 if (request->home_pool->virtual_server) {
2116 const char *old_server = request->server;
2118 request->server = request->home_pool->virtual_server;
2119 RDEBUG2(" server %s {", request->server);
2120 rcode = module_pre_proxy(pre_proxy_type, request);
2122 request->server = old_server;
2124 rcode = module_pre_proxy(pre_proxy_type, request);
2127 case RLM_MODULE_FAIL:
2128 case RLM_MODULE_INVALID:
2129 case RLM_MODULE_NOTFOUND:
2130 case RLM_MODULE_USERLOCK:
2132 /* FIXME: debug print failed stuff */
2135 case RLM_MODULE_REJECT:
2136 case RLM_MODULE_HANDLED:
2140 * Only proxy the packet if the pre-proxy code succeeded.
2142 case RLM_MODULE_NOOP:
2144 case RLM_MODULE_UPDATED:
2149 * If it's a fake request, don't send the proxy
2150 * packet. The outer tunnel session will take
2151 * care of doing that.
2153 if (request->packet->dst_port == 0) {
2154 request->home_server = NULL;
2158 if (request->home_server->server) {
2159 return proxy_to_virtual_server(request);
2162 if (!proxy_request(request)) {
2163 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2171 static void request_post_handler(REQUEST *request)
2173 int child_state = -1;
2174 struct timeval when;
2177 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2179 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2180 RDEBUG2("Request %d was cancelled.", request->number);
2181 #ifdef HAVE_PTHREAD_H
2182 request->child_pid = NO_SUCH_CHILD_PID;
2184 child_state = REQUEST_DONE;
2188 if (request->child_state != REQUEST_RUNNING) {
2189 rad_panic("Internal sanity check failed");
2194 * If it's not in the request hash, it's a CoA request.
2197 if (!request->in_request_hash &&
2199 ((request->proxy->code == PW_COA_REQUEST) ||
2200 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2201 request->next_callback = NULL;
2202 child_state = REQUEST_DONE;
2207 if ((request->reply->code == 0) &&
2208 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2209 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2210 request->reply->code = PW_AUTHENTICATION_REJECT;
2214 if (request->root->proxy_requests &&
2215 !request->in_proxy_hash &&
2216 (request->reply->code == 0) &&
2217 (request->packet->dst_port != 0) &&
2218 (request->packet->code != PW_STATUS_SERVER)) {
2219 int rcode = successfully_proxied_request(request);
2221 if (rcode == 1) return; /* request is invalid */
2224 * Failed proxying it (dead home servers, etc.)
2225 * Run it through Post-Proxy-Type = Fail, and
2226 * respond to the request.
2228 * Note that we're in a child thread here, so we
2229 * do NOT re-schedule the request. Instead, we
2230 * do what we would have done, which is run the
2231 * pre-handler, a NULL request handler, and then
2234 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2235 request_pre_handler(request);
2239 * Else we weren't supposed to proxy it,
2240 * OR we proxied it internally to a virutal server.
2246 * Fake requests don't get encoded or signed. The caller
2247 * also requires the reply VP's, so we don't free them
2250 if (request->packet->dst_port == 0) {
2251 /* FIXME: RDEBUG going to the next request */
2252 #ifdef HAVE_PTHREAD_H
2253 request->child_pid = NO_SUCH_CHILD_PID;
2255 request->child_state = REQUEST_DONE;
2261 * Copy Proxy-State from the request to the reply.
2263 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2264 if (vp) pairadd(&request->reply->vps, vp);
2268 * Access-Requests get delayed or cached.
2270 switch (request->packet->code) {
2271 case PW_AUTHENTICATION_REQUEST:
2272 gettimeofday(&request->next_when, NULL);
2274 if (request->reply->code == 0) {
2276 * Check if the lack of response is intentional.
2278 vp = pairfind(request->config_items,
2279 PW_RESPONSE_PACKET_TYPE);
2281 RDEBUG2("There was no response configured: rejecting request %d",
2283 request->reply->code = PW_AUTHENTICATION_REJECT;
2285 } else if (vp->vp_integer == 256) {
2286 RDEBUG2("Not responding to request %d",
2290 * Force cleanup after a long
2291 * time, so that we don't
2292 * re-process the packet.
2294 request->next_when.tv_sec += request->root->max_request_time;
2295 request->next_callback = cleanup_delay;
2296 child_state = REQUEST_CLEANUP_DELAY;
2299 request->reply->code = vp->vp_integer;
2305 * Run rejected packets through
2307 * Post-Auth-Type = Reject
2309 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2310 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2311 vp = radius_pairmake(request, &request->config_items,
2312 "Post-Auth-Type", "Reject",
2314 if (vp) rad_postauth(request);
2317 * If configured, delay Access-Reject packets.
2319 * If request->root->reject_delay = 0, we discover
2320 * that we have to send the packet now.
2322 when = request->received;
2323 when.tv_sec += request->root->reject_delay;
2325 if (timercmp(&when, &request->next_when, >)) {
2326 RDEBUG2("Delaying reject of request %d for %d seconds",
2328 request->root->reject_delay);
2329 request->next_when = when;
2330 request->next_callback = reject_delay;
2331 #ifdef HAVE_PTHREAD_H
2332 request->child_pid = NO_SUCH_CHILD_PID;
2334 request->child_state = REQUEST_REJECT_DELAY;
2339 request->next_when.tv_sec += request->root->cleanup_delay;
2340 request->next_callback = cleanup_delay;
2341 child_state = REQUEST_CLEANUP_DELAY;
2344 case PW_ACCOUNTING_REQUEST:
2345 request->next_callback = NULL; /* just to be safe */
2346 child_state = REQUEST_DONE;
2350 * FIXME: Status-Server should probably not be
2353 case PW_STATUS_SERVER:
2354 request->next_callback = NULL;
2355 child_state = REQUEST_DONE;
2359 if ((request->packet->code > 1024) &&
2360 (request->packet->code < (1024 + 254 + 1))) {
2361 request->next_callback = NULL;
2362 child_state = REQUEST_DONE;
2366 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
2367 request->next_callback = NULL;
2368 child_state = REQUEST_DONE;
2373 * Suppress "no reply" packets here, unless we're reading
2374 * from the "detail" file. In that case, we've got to
2375 * tell the detail file handler that the request is dead,
2376 * and it should re-send it.
2377 * If configured, encode, sign, and send.
2379 if ((request->reply->code != 0) ||
2380 (request->listener->type == RAD_LISTEN_DETAIL)) {
2381 DEBUG_PACKET(request, request->reply, 1);
2382 request->listener->send(request->listener, request);
2387 * Now that we've completely processed the request,
2388 * see if we need to originate a CoA request.
2391 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2392 if (!originated_coa_request(request)) {
2393 RDEBUG2("Do CoA Fail handler here");
2395 /* request->coa is stil set, so we can update events */
2401 * Clean up. These are no longer needed.
2403 pairfree(&request->config_items);
2405 pairfree(&request->packet->vps);
2406 request->username = NULL;
2407 request->password = NULL;
2409 pairfree(&request->reply->vps);
2412 if (request->proxy) {
2413 pairfree(&request->proxy->vps);
2415 if (request->proxy_reply) {
2416 pairfree(&request->proxy_reply->vps);
2421 * We're not tracking responses from the home
2422 * server, we can therefore free this memory in
2425 if (!request->in_proxy_hash) {
2426 rad_free(&request->proxy);
2427 rad_free(&request->proxy_reply);
2428 request->home_server = NULL;
2434 RDEBUG2("Finished request %d.", request->number);
2435 rad_assert(child_state >= 0);
2436 request->child_state = child_state;
2439 * Single threaded mode: update timers now.
2441 if (!have_children) wait_a_bit(request);
2445 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2451 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2452 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2454 switch (request->child_state) {
2455 case REQUEST_QUEUED:
2456 case REQUEST_RUNNING:
2460 radlog(L_ERR, "Discarding duplicate request from "
2461 "client %s port %d - ID: %d due to unfinished request %d",
2463 request->packet->src_port,request->packet->id,
2468 case REQUEST_PROXIED:
2470 * We're not supposed to have duplicate
2471 * accounting packets. The other states handle
2472 * duplicates fine (discard, or send duplicate
2473 * reply). But we do NOT want to retransmit an
2474 * accounting request here, because that would
2475 * involve updating the Acct-Delay-Time, and
2476 * therefore changing the packet Id, etc.
2478 * Instead, we just discard the packet. We may
2479 * eventually respond, or the client will send a
2480 * new accounting packet.
2482 * The same comments go for Status-Server, and
2483 * other packet types.
2485 * FIXME: coa: when we proxy CoA && Disconnect
2486 * packets, this logic has to be fixed.
2488 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2492 check_for_zombie_home_server(request);
2495 * If we've just discovered that the home server is
2496 * dead, send the packet to another one.
2498 if ((request->packet->dst_port != 0) &&
2499 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2502 remove_from_proxy_hash(request);
2504 home = home_server_ldb(NULL, request->home_pool, request);
2506 RDEBUG2("Failed to find live home server for request %d", request->number);
2509 * Do post-request processing,
2510 * and any insertion of necessary
2513 post_proxy_fail_handler(request);
2517 request->proxy->code = request->packet->code;
2520 * Free the old packet, to force re-encoding
2522 free(request->proxy->data);
2523 request->proxy->data = NULL;
2524 request->proxy->data_len = 0;
2527 * This request failed over to a virtual
2528 * server. Push it back onto the queue
2531 if (request->home_server->server) {
2532 proxy_fallback_handler(request);
2537 * Try to proxy the request.
2539 if (!proxy_request(request)) {
2540 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2541 goto no_home_servers;
2545 * This code executes in the main server
2546 * thread, so there's no need for locking.
2548 rad_assert(request->next_callback != NULL);
2549 INSERT_EVENT(request->next_callback, request);
2550 request->next_callback = NULL;
2552 } /* else the home server is still alive */
2554 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2555 inet_ntop(request->proxy->dst_ipaddr.af,
2556 &request->proxy->dst_ipaddr.ipaddr,
2557 buffer, sizeof(buffer)),
2558 request->proxy->dst_port,
2559 request->proxy->id);
2560 request->num_proxied_requests++;
2562 DEBUG_PACKET(request, request->proxy, 1);
2563 request->proxy_listener->send(request->proxy_listener,
2568 case REQUEST_REJECT_DELAY:
2569 RDEBUG2("Waiting to send Access-Reject "
2570 "to client %s port %d - ID: %d",
2572 request->packet->src_port, request->packet->id);
2575 case REQUEST_CLEANUP_DELAY:
2577 if (request->reply->code == 0) {
2578 RDEBUG2("Ignoring retransmit from client %s port %d "
2579 "- ID: %d, no reply was configured",
2581 request->packet->src_port, request->packet->id);
2586 * FIXME: This sends duplicate replies to
2587 * accounting requests, even if Acct-Delay-Time
2588 * or Event-Timestamp is in the packet. In those
2589 * cases, the Id should be changed, and the packet
2592 RDEBUG2("Sending duplicate reply "
2593 "to client %s port %d - ID: %d",
2595 request->packet->src_port, request->packet->id);
2596 DEBUG_PACKET(request, request->reply, 1);
2597 request->listener->send(request->listener, request);
2603 static void received_conflicting_request(REQUEST *request,
2604 const RADCLIENT *client)
2606 radlog(L_ERR, "Received conflicting packet from "
2607 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2609 request->packet->src_port, request->packet->id,
2613 * Nuke it from the request hash, so we can receive new
2616 remove_from_request_hash(request);
2618 switch (request->child_state) {
2619 #ifdef HAVE_PTHREAD_H
2621 * It's queued or running. Tell it to stop, and
2622 * wait for it to do so.
2624 case REQUEST_QUEUED:
2625 case REQUEST_RUNNING:
2626 request->master_state = REQUEST_STOP_PROCESSING;
2627 request->delay += request->delay >> 1;
2629 tv_add(&request->when, request->delay);
2631 INSERT_EVENT(wait_for_child_to_die, request);
2636 * It's in some other state, and therefore also
2637 * in the event queue. At some point, the
2638 * child will notice, and we can then delete it.
2641 rad_assert(request->ev != NULL);
2647 static int can_handle_new_request(RADIUS_PACKET *packet,
2649 struct main_config_t *root)
2652 * Count the total number of requests, to see if
2653 * there are too many. If so, return with an
2656 if (root->max_requests) {
2657 int request_count = fr_packet_list_num_elements(pl);
2660 * This is a new request. Let's see if
2661 * it makes us go over our configured
2664 if (request_count > root->max_requests) {
2665 radlog(L_ERR, "Dropping request (%d is too many): "
2666 "from client %s port %d - ID: %d", request_count,
2668 packet->src_port, packet->id);
2669 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2670 "\tThe value for 'max_requests' is probably set too low.\n");
2672 } /* else there were a small number of requests */
2673 } /* else there was no configured limit for requests */
2676 * FIXME: Add per-client checks. If one client is sending
2677 * too many packets, start discarding them.
2679 * We increment the counters here, and decrement them
2680 * when the response is sent... somewhere in this file.
2684 * FUTURE: Add checks for system load. If the system is
2685 * busy, start dropping requests...
2687 * We can probably keep some statistics ourselves... if
2688 * there are more requests coming in than we can handle,
2689 * start dropping some.
2696 int received_request(rad_listen_t *listener,
2697 RADIUS_PACKET *packet, REQUEST **prequest,
2700 RADIUS_PACKET **packet_p;
2701 REQUEST *request = NULL;
2702 struct main_config_t *root = &mainconfig;
2704 packet_p = fr_packet_list_find(pl, packet);
2706 request = fr_packet2myptr(REQUEST, packet, packet_p);
2707 rad_assert(request->in_request_hash);
2709 if ((request->packet->data_len == packet->data_len) &&
2710 (memcmp(request->packet->vector, packet->vector,
2711 sizeof(packet->vector)) == 0)) {
2712 received_retransmit(request, client);
2717 * The new request is different from the old one,
2718 * but maybe the old is finished. If so, delete
2721 switch (request->child_state) {
2722 struct timeval when;
2726 * Special hacks for race conditions.
2727 * The reply is encoded, and therefore
2728 * likely sent. We received a *new*
2729 * packet from the client, likely before
2730 * the next line or two of code which
2731 * updated the child state. In this
2732 * case, just accept the new request.
2734 if ((request->reply->code != 0) &&
2735 request->reply->data) {
2736 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2738 packet->src_port, packet->id,
2740 remove_from_request_hash(request);
2745 gettimeofday(&when, NULL);
2749 * If the cached request was received
2750 * within the last second, then we
2751 * discard the NEW request instead of the
2752 * old one. This will happen ONLY when
2753 * the client is severely broken, and is
2754 * sending conflicting packets very
2757 if (timercmp(&when, &request->received, <)) {
2758 radlog(L_ERR, "Discarding conflicting packet from "
2759 "client %s port %d - ID: %d due to recent request %d.",
2761 packet->src_port, packet->id,
2766 received_conflicting_request(request, client);
2770 case REQUEST_REJECT_DELAY:
2771 case REQUEST_CLEANUP_DELAY:
2772 request->child_state = REQUEST_DONE;
2774 cleanup_delay(request);
2781 * We may want to quench the new request.
2783 if ((listener->type != RAD_LISTEN_DETAIL) &&
2784 !can_handle_new_request(packet, client, root)) {
2789 * Create and initialize the new request.
2791 request = request_alloc(); /* never fails */
2793 if ((request->reply = rad_alloc(0)) == NULL) {
2794 radlog(L_ERR, "No memory");
2798 request->listener = listener;
2799 request->client = client;
2800 request->packet = packet;
2801 request->packet->timestamp = request->timestamp;
2802 request->number = request_num_counter++;
2803 request->priority = listener->type;
2804 #ifdef HAVE_PTHREAD_H
2805 request->child_pid = NO_SUCH_CHILD_PID;
2809 * Status-Server packets go to the head of the queue.
2811 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2814 * Set virtual server identity
2816 if (client->server) {
2817 request->server = client->server;
2818 } else if (listener->server) {
2819 request->server = listener->server;
2821 request->server = NULL;
2825 * Remember the request in the list.
2827 if (!fr_packet_list_insert(pl, &request->packet)) {
2828 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2829 request_free(&request);
2833 request->in_request_hash = TRUE;
2834 request->root = root;
2838 * The request passes many of our sanity checks.
2839 * From here on in, if anything goes wrong, we
2840 * send a reject message, instead of dropping the
2845 * Build the reply template from the request.
2848 request->reply->sockfd = request->packet->sockfd;
2849 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2850 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2851 request->reply->dst_port = request->packet->src_port;
2852 request->reply->src_port = request->packet->dst_port;
2853 request->reply->id = request->packet->id;
2854 request->reply->code = 0; /* UNKNOWN code */
2855 memcpy(request->reply->vector, request->packet->vector,
2856 sizeof(request->reply->vector));
2857 request->reply->vps = NULL;
2858 request->reply->data = NULL;
2859 request->reply->data_len = 0;
2861 request->master_state = REQUEST_ACTIVE;
2862 request->child_state = REQUEST_QUEUED;
2863 request->next_callback = NULL;
2865 gettimeofday(&request->received, NULL);
2866 request->timestamp = request->received.tv_sec;
2867 request->when = request->received;
2869 request->delay = USEC;
2871 tv_add(&request->when, request->delay);
2873 INSERT_EVENT(wait_a_bit, request);
2875 *prequest = request;
2881 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2887 * Also removes from the proxy hash if responses == requests
2889 request = lookup_in_proxy_hash(packet);
2892 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2893 inet_ntop(packet->src_ipaddr.af,
2894 &packet->src_ipaddr.ipaddr,
2895 buffer, sizeof(buffer)),
2896 packet->src_port, packet->id);
2901 * We haven't replied to the NAS, but we have seen an
2902 * earlier reply from the home server. Ignore this packet,
2903 * as we're likely still processing the previous reply.
2905 if (request->proxy_reply) {
2906 if (memcmp(request->proxy_reply->vector,
2908 sizeof(request->proxy_reply->vector)) == 0) {
2909 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2910 inet_ntop(packet->src_ipaddr.af,
2911 &packet->src_ipaddr.ipaddr,
2912 buffer, sizeof(buffer)),
2913 packet->src_port, packet->id,
2917 * ? The home server gave us a new proxy
2918 * reply which doesn't match the old
2921 RDEBUG2("Ignoring conflicting proxy reply");
2924 /* assert that there's an event queued for request? */
2928 gettimeofday(&now, NULL);
2931 * Maybe move this earlier in the decision process?
2932 * Having it here means that late or duplicate proxy
2933 * replies no longer get the home server marked as
2934 * "alive". This might be good for stability, though.
2936 request->home_server->state = HOME_STATE_ALIVE;
2940 * When originating CoA, the "proxy" reply is the reply
2941 * to the CoA request that we originated. At this point,
2942 * the original request is finished, and it has a reply.
2944 * However, if we haven't separated the two requests, do
2945 * so now. This is done so that cleaning up the original
2946 * request won't cause the CoA request to be free'd. See
2947 * util.c, request_free()
2949 if (request->parent && (request->parent->coa == request)) {
2950 request->parent->coa = NULL;
2951 request->parent = NULL;
2955 * Skip the next set of checks, as the original
2956 * reply is cached. We want to be able to still
2957 * process the CoA reply, AND to reference the
2958 * original request/reply.
2960 * This is getting to be really quite a bit of a
2966 * If there's a reply to the NAS, ignore everything
2967 * related to proxy responses
2969 if (request->reply && request->reply->code != 0) {
2970 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
2976 * The average includes our time to receive packets and
2977 * look them up in the hashes, which should be the same
2980 * We update the response time only for the FIRST packet
2983 if (request->home_server->ema.window > 0) {
2984 radius_stats_ema(&request->home_server->ema,
2985 &now, &request->proxy_when);
2989 switch (request->child_state) {
2990 case REQUEST_QUEUED:
2991 case REQUEST_RUNNING:
2992 radlog(L_ERR, "Internal sanity check failed for child state");
2995 case REQUEST_REJECT_DELAY:
2996 case REQUEST_CLEANUP_DELAY:
2998 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'",
2999 inet_ntop(packet->src_ipaddr.af,
3000 &packet->src_ipaddr.ipaddr,
3001 buffer, sizeof(buffer)),
3002 packet->src_port, packet->id,
3004 /* assert that there's an event queued for request? */
3007 case REQUEST_PROXIED:
3011 request->proxy_reply = packet;
3015 * Perform RTT calculations, as per RFC 2988 (for TCP).
3016 * Note that we only do so on the first response.
3018 if ((request->num_proxied_responses == 1)
3020 home_server *home = request->home_server;
3022 rtt = now.tv_sec - request->proxy_when.tv_sec;
3025 rtt -= request->proxy_when.tv_usec;
3027 if (!home->has_rtt) {
3028 home->has_rtt = TRUE;
3031 home->rttvar = rtt / 2;
3034 home->rttvar -= home->rttvar >> 2;
3035 home->rttvar += (home->srtt - rtt);
3036 home->srtt -= home->srtt >> 3;
3037 home->srtt += rtt >> 3;
3040 home->rto = home->srtt;
3041 if (home->rttvar > (USEC / 4)) {
3042 home->rto += home->rttvar * 4;
3050 * There's no incoming request, so it's a proxied packet
3053 if (!request->packet) {
3054 received_response_to_ping(request);
3055 request->proxy_reply = NULL; /* caller will free it */
3056 request_free(&request);
3060 request->child_state = REQUEST_QUEUED;
3061 request->when = now;
3062 request->delay = USEC;
3063 request->priority = RAD_LISTEN_PROXY;
3064 tv_add(&request->when, request->delay);
3067 * Wait a bit will take care of max_request_time
3069 INSERT_EVENT(wait_a_bit, request);
3075 void event_new_fd(rad_listen_t *this)
3079 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3081 this->print(this, buffer, sizeof(buffer));
3083 if (this->status == RAD_LISTEN_STATUS_INIT) {
3085 DEBUG("Listening on %s", buffer);
3087 DEBUG2(" ... adding new socket %s", buffer);
3089 if (!fr_event_fd_insert(el, 0, this->fd,
3090 event_socket_handler, this)) {
3091 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3095 this->status = RAD_LISTEN_STATUS_KNOWN;
3099 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3100 DEBUG2(" ... closing socket %s", buffer);
3102 fr_event_fd_delete(el, 0, this->fd);
3103 this->status = RAD_LISTEN_STATUS_FINISH;
3106 * Close the fd AFTER fixing up the requests and
3107 * listeners, so that they don't send/recv on the
3108 * wrong socket (if someone manages to open
3116 static void handle_signal_self(int flag)
3118 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3119 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3120 fr_event_loop_exit(el, 1);
3122 fr_event_loop_exit(el, 2);
3126 } /* else exit/term flags weren't set */
3129 * Tell the even loop to stop processing.
3131 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3133 static time_t last_hup = 0;
3135 DEBUG("Received HUP signal.");
3138 if ((int) (when - last_hup) < 5) {
3139 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3144 fr_event_loop_exit(el, 0x80);
3148 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3152 * FIXME: O(N) loops suck.
3154 for (this = mainconfig.listen;
3156 this = this->next) {
3157 if (this->type != RAD_LISTEN_DETAIL) continue;
3160 * This one didn't send the signal, skip
3163 if (!this->decode(this, NULL)) continue;
3166 * Go service the interrupt.
3168 event_poll_detail(this);
3173 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3176 for (this = mainconfig.listen;
3178 this = this->next) {
3184 #ifndef WITH_SELF_PIPE
3185 void radius_signal_self(int flag)
3187 handle_signal_self(flag);
3191 * Inform ourselves that we received a signal.
3193 void radius_signal_self(int flag)
3199 * The read MUST be non-blocking for this to work.
3201 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3205 for (i = 0; i < rcode; i++) {
3206 buffer[0] |= buffer[i];
3214 write(self_pipe[1], buffer, 1);
3218 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3219 UNUSED int fd, UNUSED void *ctx)
3224 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3225 if (rcode <= 0) return;
3228 * Merge pending signals.
3230 for (i = 0; i < rcode; i++) {
3231 buffer[0] |= buffer[i];
3234 handle_signal_self(buffer[0]);
3239 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3242 rad_listen_t *listener = ctx;
3243 RAD_REQUEST_FUNP fun;
3246 rad_assert(xel == el);
3250 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3252 if (!listener->recv(listener, &fun, &request)) return;
3254 if (!thread_pool_addrequest(request, fun)) {
3255 request->child_state = REQUEST_DONE;
3259 typedef struct listen_detail_t {
3264 * This function is called periodically to see if this detail
3265 * file is available for reading.
3267 static void event_poll_detail(void *ctx)
3270 RAD_REQUEST_FUNP fun;
3272 rad_listen_t *this = ctx;
3273 struct timeval when;
3274 listen_detail_t *detail = this->data;
3276 rad_assert(this->type == RAD_LISTEN_DETAIL);
3279 * Try to read something.
3281 * FIXME: This does poll AND receive.
3283 rcode = this->recv(this, &fun, &request);
3285 rad_assert(fun != NULL);
3286 rad_assert(request != NULL);
3288 if (!thread_pool_addrequest(request, fun)) {
3289 request->child_state = REQUEST_DONE;
3293 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3297 * Backdoor API to get the delay until the next poll time.
3299 delay = this->encode(this, NULL);
3300 tv_add(&when, delay);
3302 if (!fr_event_insert(el, event_poll_detail, this,
3303 &when, &detail->ev)) {
3304 radlog(L_ERR, "Failed creating handler");
3310 static void event_status(struct timeval *wake)
3312 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3316 if (debug_flag == 0) {
3318 radlog(L_INFO, "Ready to process requests.");
3319 just_started = FALSE;
3325 DEBUG("Ready to process requests.");
3327 } else if ((wake->tv_sec != 0) ||
3328 (wake->tv_usec >= 100000)) {
3329 DEBUG("Waking up in %d.%01u seconds.",
3330 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3335 * FIXME: Put this somewhere else, where it isn't called
3336 * all of the time...
3339 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3341 * If there are no child threads, then there may
3342 * be child processes. In that case, wait for
3343 * their exit status, and throw that exit status
3344 * away. This helps get rid of zxombie children.
3346 while (waitpid(-1, &argval, WNOHANG) > 0) {
3354 * Externally-visibly functions.
3356 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3358 rad_listen_t *this, *head = NULL;
3362 time(&fr_start_time);
3364 el = fr_event_list_create(event_status);
3367 pl = fr_packet_list_create(0);
3368 if (!pl) return 0; /* leak el */
3370 request_num_counter = 0;
3373 * Move all of the thread calls to this file?
3375 * It may be best for the mutexes to be in this file...
3377 have_children = spawn_flag;
3380 if (mainconfig.proxy_requests) {
3382 * Create the tree for managing proxied requests and
3385 proxy_list = fr_packet_list_create(1);
3386 if (!proxy_list) return 0;
3388 #ifdef HAVE_PTHREAD_H
3389 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3390 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3399 * Just before we spawn the child threads, force the log
3400 * subsystem to re-open the log file for every write.
3402 if (spawn_flag) force_log_reopen();
3404 #ifdef HAVE_PTHREAD_H
3406 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3408 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3410 if (thread_pool_init(cs, spawn_flag) < 0) {
3416 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3421 #ifdef WITH_SELF_PIPE
3423 * Child threads need a pipe to signal us, as do the
3426 if (pipe(self_pipe) < 0) {
3427 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3431 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3432 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3436 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3437 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3442 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3443 event_signal_handler, el)) {
3444 radlog(L_ERR, "Failed creating handler for signals");
3447 #endif /* WITH_SELF_PIPE */
3451 * Mark the proxy Fd's as unused.
3456 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3460 DEBUG("%s: #### Opening IP addresses and Ports ####",
3464 * The server temporarily switches to an unprivileged
3465 * user very early in the bootstrapping process.
3466 * However, some sockets MAY require privileged access
3467 * (bind to device, or to port < 1024, or to raw
3468 * sockets). Those sockets need to call suid up/down
3469 * themselves around the functions that need a privileged
3472 if (listen_init(cs, &head) < 0) {
3477 * At this point, no one has any business *ever* going
3480 fr_suid_down_permanent();
3483 * Add all of the sockets to the event loop.
3487 this = this->next) {
3490 this->print(this, buffer, sizeof(buffer));
3492 switch (this->type) {
3494 case RAD_LISTEN_DETAIL:
3495 DEBUG("Listening on %s", buffer);
3498 * Detail files are always known, and aren't
3499 * put into the socket event loop.
3501 this->status = RAD_LISTEN_STATUS_KNOWN;
3504 * Set up the first poll interval.
3506 event_poll_detail(this);
3511 case RAD_LISTEN_PROXY:
3512 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3513 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3515 proxy_fds[this->fd & 0x1f] = this->fd;
3516 proxy_listeners[this->fd & 0x1f] = this;
3517 if (!fr_packet_list_socket_add(proxy_list,
3531 mainconfig.listen = head;
3537 static int request_hash_cb(UNUSED void *ctx, void *data)
3539 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3542 rad_assert(request->in_proxy_hash == FALSE);
3545 fr_event_delete(el, &request->ev);
3546 remove_from_request_hash(request);
3547 request_free(&request);
3554 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3556 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3558 fr_packet_list_yank(proxy_list, request->proxy);
3559 request->in_proxy_hash = FALSE;
3561 if (!request->in_request_hash) {
3562 fr_event_delete(el, &request->ev);
3563 request_free(&request);
3570 void radius_event_free(void)
3573 * FIXME: Stop all threads, or at least check that
3574 * they're all waiting on the semaphore, and the queues
3580 * There are requests in the proxy hash that aren't
3581 * referenced from anywhere else. Remove them first.
3584 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3585 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3586 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3587 fr_packet_list_free(proxy_list);
3592 fr_packet_list_walk(pl, NULL, request_hash_cb);
3594 fr_packet_list_free(pl);
3597 fr_event_list_free(el);
3600 int radius_event_process(void)
3604 return fr_event_loop(el);
3607 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3609 request->options = RAD_REQUEST_OPTION_DEBUG2;
3611 if (request_pre_handler(request)) {
3612 rad_assert(fun != NULL);
3613 rad_assert(request != NULL);
3615 if (request->server) RDEBUG("server %s {",
3616 request->server != NULL ?
3617 request->server : "");
3620 if (request->server) RDEBUG("} # server %s",
3621 request->server != NULL ?
3622 request->server : "");
3624 request_post_handler(request);
3627 DEBUG2("Going to the next request");