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;
2023 * Remember that we sent the request to a Realm.
2025 pairadd(&request->packet->vps,
2026 pairmake("Realm", realmname, T_OP_EQ));
2029 * Strip the name, if told to.
2031 * Doing it here catches the case of proxied tunneled
2034 if (realm->striprealm == TRUE &&
2035 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2037 * If there's a Stripped-User-Name attribute in
2038 * the request, then use THAT as the User-Name
2039 * for the proxied request, instead of the
2042 * This is done by making a copy of the
2043 * Stripped-User-Name attribute, turning it into
2044 * a User-Name attribute, deleting the
2045 * Stripped-User-Name and User-Name attributes
2046 * from the vps list, and making the new
2047 * User-Name the head of the vps list.
2049 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2051 vp = radius_paircreate(request, NULL,
2052 PW_USER_NAME, PW_TYPE_STRING);
2053 rad_assert(vp != NULL); /* handled by above function */
2054 /* Insert at the START of the list */
2055 vp->next = request->proxy->vps;
2056 request->proxy->vps = vp;
2058 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2059 sizeof(vp->vp_strvalue));
2060 vp->length = strippedname->length;
2063 * Do NOT delete Stripped-User-Name.
2068 * If there is no PW_CHAP_CHALLENGE attribute but
2069 * there is a PW_CHAP_PASSWORD we need to add it
2070 * since we can't use the request authenticator
2071 * anymore - we changed it.
2073 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2074 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2075 vp = radius_paircreate(request, &request->proxy->vps,
2076 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2077 vp->length = AUTH_VECTOR_LEN;
2078 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2082 * The RFC's say we have to do this, but FreeRADIUS
2085 vp = radius_paircreate(request, &request->proxy->vps,
2086 PW_PROXY_STATE, PW_TYPE_OCTETS);
2087 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2088 request->packet->id);
2089 vp->length = strlen(vp->vp_strvalue);
2092 * Should be done BEFORE inserting into proxy hash, as
2093 * pre-proxy may use this information, or change it.
2095 request->proxy->code = request->packet->code;
2098 * Call the pre-proxy routines.
2100 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2102 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2103 pre_proxy_type = vp->vp_integer;
2106 rad_assert(request->home_pool != NULL);
2108 if (request->home_pool->virtual_server) {
2109 const char *old_server = request->server;
2111 request->server = request->home_pool->virtual_server;
2112 RDEBUG2(" server %s {", request->server);
2113 rcode = module_pre_proxy(pre_proxy_type, request);
2115 request->server = old_server;
2117 rcode = module_pre_proxy(pre_proxy_type, request);
2120 case RLM_MODULE_FAIL:
2121 case RLM_MODULE_INVALID:
2122 case RLM_MODULE_NOTFOUND:
2123 case RLM_MODULE_USERLOCK:
2125 /* FIXME: debug print failed stuff */
2128 case RLM_MODULE_REJECT:
2129 case RLM_MODULE_HANDLED:
2133 * Only proxy the packet if the pre-proxy code succeeded.
2135 case RLM_MODULE_NOOP:
2137 case RLM_MODULE_UPDATED:
2142 * If it's a fake request, don't send the proxy
2143 * packet. The outer tunnel session will take
2144 * care of doing that.
2146 if (request->packet->dst_port == 0) {
2147 request->home_server = NULL;
2151 if (request->home_server->server) {
2152 return proxy_to_virtual_server(request);
2155 if (!proxy_request(request)) {
2156 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2164 static void request_post_handler(REQUEST *request)
2166 int child_state = -1;
2167 struct timeval when;
2170 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2172 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2173 RDEBUG2("Request %d was cancelled.", request->number);
2174 #ifdef HAVE_PTHREAD_H
2175 request->child_pid = NO_SUCH_CHILD_PID;
2177 child_state = REQUEST_DONE;
2181 if (request->child_state != REQUEST_RUNNING) {
2182 rad_panic("Internal sanity check failed");
2187 * If it's not in the request hash, it's a CoA request.
2190 if (!request->in_request_hash &&
2192 ((request->proxy->code == PW_COA_REQUEST) ||
2193 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2194 request->next_callback = NULL;
2195 child_state = REQUEST_DONE;
2200 if ((request->reply->code == 0) &&
2201 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2202 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2203 request->reply->code = PW_AUTHENTICATION_REJECT;
2207 if (request->root->proxy_requests &&
2208 !request->in_proxy_hash &&
2209 (request->reply->code == 0) &&
2210 (request->packet->dst_port != 0) &&
2211 (request->packet->code != PW_STATUS_SERVER)) {
2212 int rcode = successfully_proxied_request(request);
2216 * If we proxy it, we CANNOT originate a CoA
2217 * request at the same time.
2219 if (rcode != 0) request_free(&request->coa);
2222 if (rcode == 1) return;
2225 * Failed proxying it (dead home servers, etc.)
2226 * Run it through Post-Proxy-Type = Fail, and
2227 * respond to the request.
2229 * Note that we're in a child thread here, so we
2230 * do NOT re-schedule the request. Instead, we
2231 * do what we would have done, which is run the
2232 * pre-handler, a NULL request handler, and then
2235 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2236 request_pre_handler(request);
2240 * Else we weren't supposed to proxy it,
2241 * OR we proxied it internally to a virutal server.
2247 * Fake requests don't get encoded or signed. The caller
2248 * also requires the reply VP's, so we don't free them
2251 if (request->packet->dst_port == 0) {
2252 /* FIXME: RDEBUG going to the next request */
2253 #ifdef HAVE_PTHREAD_H
2254 request->child_pid = NO_SUCH_CHILD_PID;
2256 request->child_state = REQUEST_DONE;
2262 * Copy Proxy-State from the request to the reply.
2264 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2265 if (vp) pairadd(&request->reply->vps, vp);
2269 * Access-Requests get delayed or cached.
2271 switch (request->packet->code) {
2272 case PW_AUTHENTICATION_REQUEST:
2273 gettimeofday(&request->next_when, NULL);
2275 if (request->reply->code == 0) {
2277 * Check if the lack of response is intentional.
2279 vp = pairfind(request->config_items,
2280 PW_RESPONSE_PACKET_TYPE);
2282 RDEBUG2("There was no response configured: rejecting request %d",
2284 request->reply->code = PW_AUTHENTICATION_REJECT;
2286 } else if (vp->vp_integer == 256) {
2287 RDEBUG2("Not responding to request %d",
2291 * Force cleanup after a long
2292 * time, so that we don't
2293 * re-process the packet.
2295 request->next_when.tv_sec += request->root->max_request_time;
2296 request->next_callback = cleanup_delay;
2297 child_state = REQUEST_CLEANUP_DELAY;
2300 request->reply->code = vp->vp_integer;
2306 * Run rejected packets through
2308 * Post-Auth-Type = Reject
2310 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2311 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2312 vp = radius_pairmake(request, &request->config_items,
2313 "Post-Auth-Type", "Reject",
2315 if (vp) rad_postauth(request);
2318 * If configured, delay Access-Reject packets.
2320 * If request->root->reject_delay = 0, we discover
2321 * that we have to send the packet now.
2323 when = request->received;
2324 when.tv_sec += request->root->reject_delay;
2326 if (timercmp(&when, &request->next_when, >)) {
2327 RDEBUG2("Delaying reject of request %d for %d seconds",
2329 request->root->reject_delay);
2330 request->next_when = when;
2331 request->next_callback = reject_delay;
2332 #ifdef HAVE_PTHREAD_H
2333 request->child_pid = NO_SUCH_CHILD_PID;
2335 request->child_state = REQUEST_REJECT_DELAY;
2340 request->next_when.tv_sec += request->root->cleanup_delay;
2341 request->next_callback = cleanup_delay;
2342 child_state = REQUEST_CLEANUP_DELAY;
2345 case PW_ACCOUNTING_REQUEST:
2346 request->next_callback = NULL; /* just to be safe */
2347 child_state = REQUEST_DONE;
2351 * FIXME: Status-Server should probably not be
2354 case PW_STATUS_SERVER:
2355 request->next_callback = NULL;
2356 child_state = REQUEST_DONE;
2360 if ((request->packet->code > 1024) &&
2361 (request->packet->code < (1024 + 254 + 1))) {
2362 request->next_callback = NULL;
2363 child_state = REQUEST_DONE;
2367 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
2368 request->next_callback = NULL;
2369 child_state = REQUEST_DONE;
2374 * Suppress "no reply" packets here, unless we're reading
2375 * from the "detail" file. In that case, we've got to
2376 * tell the detail file handler that the request is dead,
2377 * and it should re-send it.
2378 * If configured, encode, sign, and send.
2380 if ((request->reply->code != 0) ||
2381 (request->listener->type == RAD_LISTEN_DETAIL)) {
2382 DEBUG_PACKET(request, request->reply, 1);
2383 request->listener->send(request->listener, request);
2388 * Now that we've completely processed the request,
2389 * see if we need to originate a CoA request.
2392 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2393 if (!originated_coa_request(request)) {
2394 RDEBUG2("Do CoA Fail handler here");
2396 /* request->coa is stil set, so we can update events */
2402 * Clean up. These are no longer needed.
2404 pairfree(&request->config_items);
2406 pairfree(&request->packet->vps);
2407 request->username = NULL;
2408 request->password = NULL;
2410 pairfree(&request->reply->vps);
2413 if (request->proxy) {
2414 pairfree(&request->proxy->vps);
2416 if (request->proxy_reply) {
2417 pairfree(&request->proxy_reply->vps);
2422 * We're not tracking responses from the home
2423 * server, we can therefore free this memory in
2426 if (!request->in_proxy_hash) {
2427 rad_free(&request->proxy);
2428 rad_free(&request->proxy_reply);
2429 request->home_server = NULL;
2435 RDEBUG2("Finished request %d.", request->number);
2436 rad_assert(child_state >= 0);
2437 request->child_state = child_state;
2440 * Single threaded mode: update timers now.
2442 if (!have_children) wait_a_bit(request);
2446 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2452 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2453 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2455 switch (request->child_state) {
2456 case REQUEST_QUEUED:
2457 case REQUEST_RUNNING:
2461 radlog(L_ERR, "Discarding duplicate request from "
2462 "client %s port %d - ID: %d due to unfinished request %d",
2464 request->packet->src_port,request->packet->id,
2469 case REQUEST_PROXIED:
2471 * We're not supposed to have duplicate
2472 * accounting packets. The other states handle
2473 * duplicates fine (discard, or send duplicate
2474 * reply). But we do NOT want to retransmit an
2475 * accounting request here, because that would
2476 * involve updating the Acct-Delay-Time, and
2477 * therefore changing the packet Id, etc.
2479 * Instead, we just discard the packet. We may
2480 * eventually respond, or the client will send a
2481 * new accounting packet.
2483 * The same comments go for Status-Server, and
2484 * other packet types.
2486 * FIXME: coa: when we proxy CoA && Disconnect
2487 * packets, this logic has to be fixed.
2489 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2493 check_for_zombie_home_server(request);
2496 * If we've just discovered that the home server is
2497 * dead, send the packet to another one.
2499 if ((request->packet->dst_port != 0) &&
2500 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2503 remove_from_proxy_hash(request);
2505 home = home_server_ldb(NULL, request->home_pool, request);
2507 RDEBUG2("Failed to find live home server for request %d", request->number);
2510 * Do post-request processing,
2511 * and any insertion of necessary
2514 post_proxy_fail_handler(request);
2518 request->proxy->code = request->packet->code;
2521 * Free the old packet, to force re-encoding
2523 free(request->proxy->data);
2524 request->proxy->data = NULL;
2525 request->proxy->data_len = 0;
2528 * This request failed over to a virtual
2529 * server. Push it back onto the queue
2532 if (request->home_server->server) {
2533 proxy_fallback_handler(request);
2538 * Try to proxy the request.
2540 if (!proxy_request(request)) {
2541 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2542 goto no_home_servers;
2546 * This code executes in the main server
2547 * thread, so there's no need for locking.
2549 rad_assert(request->next_callback != NULL);
2550 INSERT_EVENT(request->next_callback, request);
2551 request->next_callback = NULL;
2553 } /* else the home server is still alive */
2555 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2556 inet_ntop(request->proxy->dst_ipaddr.af,
2557 &request->proxy->dst_ipaddr.ipaddr,
2558 buffer, sizeof(buffer)),
2559 request->proxy->dst_port,
2560 request->proxy->id);
2561 request->num_proxied_requests++;
2563 DEBUG_PACKET(request, request->proxy, 1);
2564 request->proxy_listener->send(request->proxy_listener,
2569 case REQUEST_REJECT_DELAY:
2570 RDEBUG2("Waiting to send Access-Reject "
2571 "to client %s port %d - ID: %d",
2573 request->packet->src_port, request->packet->id);
2576 case REQUEST_CLEANUP_DELAY:
2578 if (request->reply->code == 0) {
2579 RDEBUG2("Ignoring retransmit from client %s port %d "
2580 "- ID: %d, no reply was configured",
2582 request->packet->src_port, request->packet->id);
2587 * FIXME: This sends duplicate replies to
2588 * accounting requests, even if Acct-Delay-Time
2589 * or Event-Timestamp is in the packet. In those
2590 * cases, the Id should be changed, and the packet
2593 RDEBUG2("Sending duplicate reply "
2594 "to client %s port %d - ID: %d",
2596 request->packet->src_port, request->packet->id);
2597 DEBUG_PACKET(request, request->reply, 1);
2598 request->listener->send(request->listener, request);
2604 static void received_conflicting_request(REQUEST *request,
2605 const RADCLIENT *client)
2607 radlog(L_ERR, "Received conflicting packet from "
2608 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2610 request->packet->src_port, request->packet->id,
2614 * Nuke it from the request hash, so we can receive new
2617 remove_from_request_hash(request);
2619 switch (request->child_state) {
2620 #ifdef HAVE_PTHREAD_H
2622 * It's queued or running. Tell it to stop, and
2623 * wait for it to do so.
2625 case REQUEST_QUEUED:
2626 case REQUEST_RUNNING:
2627 request->master_state = REQUEST_STOP_PROCESSING;
2628 request->delay += request->delay >> 1;
2630 tv_add(&request->when, request->delay);
2632 INSERT_EVENT(wait_for_child_to_die, request);
2637 * It's in some other state, and therefore also
2638 * in the event queue. At some point, the
2639 * child will notice, and we can then delete it.
2642 rad_assert(request->ev != NULL);
2648 static int can_handle_new_request(RADIUS_PACKET *packet,
2650 struct main_config_t *root)
2653 * Count the total number of requests, to see if
2654 * there are too many. If so, return with an
2657 if (root->max_requests) {
2658 int request_count = fr_packet_list_num_elements(pl);
2661 * This is a new request. Let's see if
2662 * it makes us go over our configured
2665 if (request_count > root->max_requests) {
2666 radlog(L_ERR, "Dropping request (%d is too many): "
2667 "from client %s port %d - ID: %d", request_count,
2669 packet->src_port, packet->id);
2670 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2671 "\tThe value for 'max_requests' is probably set too low.\n");
2673 } /* else there were a small number of requests */
2674 } /* else there was no configured limit for requests */
2677 * FIXME: Add per-client checks. If one client is sending
2678 * too many packets, start discarding them.
2680 * We increment the counters here, and decrement them
2681 * when the response is sent... somewhere in this file.
2685 * FUTURE: Add checks for system load. If the system is
2686 * busy, start dropping requests...
2688 * We can probably keep some statistics ourselves... if
2689 * there are more requests coming in than we can handle,
2690 * start dropping some.
2697 int received_request(rad_listen_t *listener,
2698 RADIUS_PACKET *packet, REQUEST **prequest,
2701 RADIUS_PACKET **packet_p;
2702 REQUEST *request = NULL;
2703 struct main_config_t *root = &mainconfig;
2705 packet_p = fr_packet_list_find(pl, packet);
2707 request = fr_packet2myptr(REQUEST, packet, packet_p);
2708 rad_assert(request->in_request_hash);
2710 if ((request->packet->data_len == packet->data_len) &&
2711 (memcmp(request->packet->vector, packet->vector,
2712 sizeof(packet->vector)) == 0)) {
2713 received_retransmit(request, client);
2718 * The new request is different from the old one,
2719 * but maybe the old is finished. If so, delete
2722 switch (request->child_state) {
2723 struct timeval when;
2727 * Special hacks for race conditions.
2728 * The reply is encoded, and therefore
2729 * likely sent. We received a *new*
2730 * packet from the client, likely before
2731 * the next line or two of code which
2732 * updated the child state. In this
2733 * case, just accept the new request.
2735 if ((request->reply->code != 0) &&
2736 request->reply->data) {
2737 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2739 packet->src_port, packet->id,
2741 remove_from_request_hash(request);
2746 gettimeofday(&when, NULL);
2750 * If the cached request was received
2751 * within the last second, then we
2752 * discard the NEW request instead of the
2753 * old one. This will happen ONLY when
2754 * the client is severely broken, and is
2755 * sending conflicting packets very
2758 if (timercmp(&when, &request->received, <)) {
2759 radlog(L_ERR, "Discarding conflicting packet from "
2760 "client %s port %d - ID: %d due to recent request %d.",
2762 packet->src_port, packet->id,
2767 received_conflicting_request(request, client);
2771 case REQUEST_REJECT_DELAY:
2772 case REQUEST_CLEANUP_DELAY:
2773 request->child_state = REQUEST_DONE;
2775 cleanup_delay(request);
2782 * We may want to quench the new request.
2784 if ((listener->type != RAD_LISTEN_DETAIL) &&
2785 !can_handle_new_request(packet, client, root)) {
2790 * Create and initialize the new request.
2792 request = request_alloc(); /* never fails */
2794 if ((request->reply = rad_alloc(0)) == NULL) {
2795 radlog(L_ERR, "No memory");
2799 request->listener = listener;
2800 request->client = client;
2801 request->packet = packet;
2802 request->packet->timestamp = request->timestamp;
2803 request->number = request_num_counter++;
2804 request->priority = listener->type;
2805 #ifdef HAVE_PTHREAD_H
2806 request->child_pid = NO_SUCH_CHILD_PID;
2810 * Status-Server packets go to the head of the queue.
2812 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2815 * Set virtual server identity
2817 if (client->server) {
2818 request->server = client->server;
2819 } else if (listener->server) {
2820 request->server = listener->server;
2822 request->server = NULL;
2826 * Remember the request in the list.
2828 if (!fr_packet_list_insert(pl, &request->packet)) {
2829 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2830 request_free(&request);
2834 request->in_request_hash = TRUE;
2835 request->root = root;
2839 * The request passes many of our sanity checks.
2840 * From here on in, if anything goes wrong, we
2841 * send a reject message, instead of dropping the
2846 * Build the reply template from the request.
2849 request->reply->sockfd = request->packet->sockfd;
2850 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2851 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2852 request->reply->dst_port = request->packet->src_port;
2853 request->reply->src_port = request->packet->dst_port;
2854 request->reply->id = request->packet->id;
2855 request->reply->code = 0; /* UNKNOWN code */
2856 memcpy(request->reply->vector, request->packet->vector,
2857 sizeof(request->reply->vector));
2858 request->reply->vps = NULL;
2859 request->reply->data = NULL;
2860 request->reply->data_len = 0;
2862 request->master_state = REQUEST_ACTIVE;
2863 request->child_state = REQUEST_QUEUED;
2864 request->next_callback = NULL;
2866 gettimeofday(&request->received, NULL);
2867 request->timestamp = request->received.tv_sec;
2868 request->when = request->received;
2870 request->delay = USEC;
2872 tv_add(&request->when, request->delay);
2874 INSERT_EVENT(wait_a_bit, request);
2876 *prequest = request;
2882 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2888 * Also removes from the proxy hash if responses == requests
2890 request = lookup_in_proxy_hash(packet);
2893 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2894 inet_ntop(packet->src_ipaddr.af,
2895 &packet->src_ipaddr.ipaddr,
2896 buffer, sizeof(buffer)),
2897 packet->src_port, packet->id);
2902 * We haven't replied to the NAS, but we have seen an
2903 * earlier reply from the home server. Ignore this packet,
2904 * as we're likely still processing the previous reply.
2906 if (request->proxy_reply) {
2907 if (memcmp(request->proxy_reply->vector,
2909 sizeof(request->proxy_reply->vector)) == 0) {
2910 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2911 inet_ntop(packet->src_ipaddr.af,
2912 &packet->src_ipaddr.ipaddr,
2913 buffer, sizeof(buffer)),
2914 packet->src_port, packet->id,
2918 * ? The home server gave us a new proxy
2919 * reply which doesn't match the old
2922 RDEBUG2("Ignoring conflicting proxy reply");
2925 /* assert that there's an event queued for request? */
2929 gettimeofday(&now, NULL);
2932 * Maybe move this earlier in the decision process?
2933 * Having it here means that late or duplicate proxy
2934 * replies no longer get the home server marked as
2935 * "alive". This might be good for stability, though.
2937 request->home_server->state = HOME_STATE_ALIVE;
2941 * When originating CoA, the "proxy" reply is the reply
2942 * to the CoA request that we originated. At this point,
2943 * the original request is finished, and it has a reply.
2945 * However, if we haven't separated the two requests, do
2946 * so now. This is done so that cleaning up the original
2947 * request won't cause the CoA request to be free'd. See
2948 * util.c, request_free()
2950 if (request->parent && (request->parent->coa == request)) {
2951 request->parent->coa = NULL;
2952 request->parent = NULL;
2956 * Skip the next set of checks, as the original
2957 * reply is cached. We want to be able to still
2958 * process the CoA reply, AND to reference the
2959 * original request/reply.
2961 * This is getting to be really quite a bit of a
2967 * If there's a reply to the NAS, ignore everything
2968 * related to proxy responses
2970 if (request->reply && request->reply->code != 0) {
2971 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
2977 * The average includes our time to receive packets and
2978 * look them up in the hashes, which should be the same
2981 * We update the response time only for the FIRST packet
2984 if (request->home_server->ema.window > 0) {
2985 radius_stats_ema(&request->home_server->ema,
2986 &now, &request->proxy_when);
2990 switch (request->child_state) {
2991 case REQUEST_QUEUED:
2992 case REQUEST_RUNNING:
2993 radlog(L_ERR, "Internal sanity check failed for child state");
2996 case REQUEST_REJECT_DELAY:
2997 case REQUEST_CLEANUP_DELAY:
2999 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'",
3000 inet_ntop(packet->src_ipaddr.af,
3001 &packet->src_ipaddr.ipaddr,
3002 buffer, sizeof(buffer)),
3003 packet->src_port, packet->id,
3005 /* assert that there's an event queued for request? */
3008 case REQUEST_PROXIED:
3012 request->proxy_reply = packet;
3016 * Perform RTT calculations, as per RFC 2988 (for TCP).
3017 * Note that we only do so on the first response.
3019 if ((request->num_proxied_responses == 1)
3021 home_server *home = request->home_server;
3023 rtt = now.tv_sec - request->proxy_when.tv_sec;
3026 rtt -= request->proxy_when.tv_usec;
3028 if (!home->has_rtt) {
3029 home->has_rtt = TRUE;
3032 home->rttvar = rtt / 2;
3035 home->rttvar -= home->rttvar >> 2;
3036 home->rttvar += (home->srtt - rtt);
3037 home->srtt -= home->srtt >> 3;
3038 home->srtt += rtt >> 3;
3041 home->rto = home->srtt;
3042 if (home->rttvar > (USEC / 4)) {
3043 home->rto += home->rttvar * 4;
3051 * There's no incoming request, so it's a proxied packet
3054 if (!request->packet) {
3055 received_response_to_ping(request);
3056 request->proxy_reply = NULL; /* caller will free it */
3057 request_free(&request);
3061 request->child_state = REQUEST_QUEUED;
3062 request->when = now;
3063 request->delay = USEC;
3064 request->priority = RAD_LISTEN_PROXY;
3065 tv_add(&request->when, request->delay);
3068 * Wait a bit will take care of max_request_time
3070 INSERT_EVENT(wait_a_bit, request);
3076 void event_new_fd(rad_listen_t *this)
3080 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3082 this->print(this, buffer, sizeof(buffer));
3084 if (this->status == RAD_LISTEN_STATUS_INIT) {
3086 DEBUG("Listening on %s", buffer);
3088 DEBUG2(" ... adding new socket %s", buffer);
3090 if (!fr_event_fd_insert(el, 0, this->fd,
3091 event_socket_handler, this)) {
3092 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3096 this->status = RAD_LISTEN_STATUS_KNOWN;
3100 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3101 DEBUG2(" ... closing socket %s", buffer);
3103 fr_event_fd_delete(el, 0, this->fd);
3104 this->status = RAD_LISTEN_STATUS_FINISH;
3107 * Close the fd AFTER fixing up the requests and
3108 * listeners, so that they don't send/recv on the
3109 * wrong socket (if someone manages to open
3117 static void handle_signal_self(int flag)
3119 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3120 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3121 fr_event_loop_exit(el, 1);
3123 fr_event_loop_exit(el, 2);
3127 } /* else exit/term flags weren't set */
3130 * Tell the even loop to stop processing.
3132 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3134 static time_t last_hup = 0;
3136 DEBUG("Received HUP signal.");
3139 if ((int) (when - last_hup) < 5) {
3140 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3145 fr_event_loop_exit(el, 0x80);
3149 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3153 * FIXME: O(N) loops suck.
3155 for (this = mainconfig.listen;
3157 this = this->next) {
3158 if (this->type != RAD_LISTEN_DETAIL) continue;
3161 * This one didn't send the signal, skip
3164 if (!this->decode(this, NULL)) continue;
3167 * Go service the interrupt.
3169 event_poll_detail(this);
3174 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3177 for (this = mainconfig.listen;
3179 this = this->next) {
3185 #ifndef WITH_SELF_PIPE
3186 void radius_signal_self(int flag)
3188 handle_signal_self(flag);
3192 * Inform ourselves that we received a signal.
3194 void radius_signal_self(int flag)
3200 * The read MUST be non-blocking for this to work.
3202 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3206 for (i = 0; i < rcode; i++) {
3207 buffer[0] |= buffer[i];
3215 write(self_pipe[1], buffer, 1);
3219 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3220 UNUSED int fd, UNUSED void *ctx)
3225 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3226 if (rcode <= 0) return;
3229 * Merge pending signals.
3231 for (i = 0; i < rcode; i++) {
3232 buffer[0] |= buffer[i];
3235 handle_signal_self(buffer[0]);
3240 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3243 rad_listen_t *listener = ctx;
3244 RAD_REQUEST_FUNP fun;
3247 rad_assert(xel == el);
3251 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3253 if (!listener->recv(listener, &fun, &request)) return;
3255 if (!thread_pool_addrequest(request, fun)) {
3256 request->child_state = REQUEST_DONE;
3260 typedef struct listen_detail_t {
3265 * This function is called periodically to see if this detail
3266 * file is available for reading.
3268 static void event_poll_detail(void *ctx)
3271 RAD_REQUEST_FUNP fun;
3273 rad_listen_t *this = ctx;
3274 struct timeval when;
3275 listen_detail_t *detail = this->data;
3277 rad_assert(this->type == RAD_LISTEN_DETAIL);
3280 * Try to read something.
3282 * FIXME: This does poll AND receive.
3284 rcode = this->recv(this, &fun, &request);
3286 rad_assert(fun != NULL);
3287 rad_assert(request != NULL);
3289 if (!thread_pool_addrequest(request, fun)) {
3290 request->child_state = REQUEST_DONE;
3294 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3298 * Backdoor API to get the delay until the next poll time.
3300 delay = this->encode(this, NULL);
3301 tv_add(&when, delay);
3303 if (!fr_event_insert(el, event_poll_detail, this,
3304 &when, &detail->ev)) {
3305 radlog(L_ERR, "Failed creating handler");
3311 static void event_status(struct timeval *wake)
3313 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3317 if (debug_flag == 0) {
3319 radlog(L_INFO, "Ready to process requests.");
3320 just_started = FALSE;
3326 DEBUG("Ready to process requests.");
3328 } else if ((wake->tv_sec != 0) ||
3329 (wake->tv_usec >= 100000)) {
3330 DEBUG("Waking up in %d.%01u seconds.",
3331 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3336 * FIXME: Put this somewhere else, where it isn't called
3337 * all of the time...
3340 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3342 * If there are no child threads, then there may
3343 * be child processes. In that case, wait for
3344 * their exit status, and throw that exit status
3345 * away. This helps get rid of zxombie children.
3347 while (waitpid(-1, &argval, WNOHANG) > 0) {
3355 * Externally-visibly functions.
3357 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3359 rad_listen_t *this, *head = NULL;
3363 time(&fr_start_time);
3365 el = fr_event_list_create(event_status);
3368 pl = fr_packet_list_create(0);
3369 if (!pl) return 0; /* leak el */
3371 request_num_counter = 0;
3374 * Move all of the thread calls to this file?
3376 * It may be best for the mutexes to be in this file...
3378 have_children = spawn_flag;
3381 if (mainconfig.proxy_requests) {
3383 * Create the tree for managing proxied requests and
3386 proxy_list = fr_packet_list_create(1);
3387 if (!proxy_list) return 0;
3389 #ifdef HAVE_PTHREAD_H
3390 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3391 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3400 * Just before we spawn the child threads, force the log
3401 * subsystem to re-open the log file for every write.
3403 if (spawn_flag) force_log_reopen();
3405 #ifdef HAVE_PTHREAD_H
3407 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3409 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3411 if (thread_pool_init(cs, spawn_flag) < 0) {
3417 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3422 #ifdef WITH_SELF_PIPE
3424 * Child threads need a pipe to signal us, as do the
3427 if (pipe(self_pipe) < 0) {
3428 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3432 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3433 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3437 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3438 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3443 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3444 event_signal_handler, el)) {
3445 radlog(L_ERR, "Failed creating handler for signals");
3448 #endif /* WITH_SELF_PIPE */
3452 * Mark the proxy Fd's as unused.
3457 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3461 DEBUG("%s: #### Opening IP addresses and Ports ####",
3465 * The server temporarily switches to an unprivileged
3466 * user very early in the bootstrapping process.
3467 * However, some sockets MAY require privileged access
3468 * (bind to device, or to port < 1024, or to raw
3469 * sockets). Those sockets need to call suid up/down
3470 * themselves around the functions that need a privileged
3473 if (listen_init(cs, &head) < 0) {
3478 * At this point, no one has any business *ever* going
3481 fr_suid_down_permanent();
3484 * Add all of the sockets to the event loop.
3488 this = this->next) {
3491 this->print(this, buffer, sizeof(buffer));
3493 switch (this->type) {
3495 case RAD_LISTEN_DETAIL:
3496 DEBUG("Listening on %s", buffer);
3499 * Detail files are always known, and aren't
3500 * put into the socket event loop.
3502 this->status = RAD_LISTEN_STATUS_KNOWN;
3505 * Set up the first poll interval.
3507 event_poll_detail(this);
3512 case RAD_LISTEN_PROXY:
3513 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3514 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3516 proxy_fds[this->fd & 0x1f] = this->fd;
3517 proxy_listeners[this->fd & 0x1f] = this;
3518 if (!fr_packet_list_socket_add(proxy_list,
3532 mainconfig.listen = head;
3538 static int request_hash_cb(UNUSED void *ctx, void *data)
3540 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3543 rad_assert(request->in_proxy_hash == FALSE);
3546 fr_event_delete(el, &request->ev);
3547 remove_from_request_hash(request);
3548 request_free(&request);
3555 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3557 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3559 fr_packet_list_yank(proxy_list, request->proxy);
3560 request->in_proxy_hash = FALSE;
3562 if (!request->in_request_hash) {
3563 fr_event_delete(el, &request->ev);
3564 request_free(&request);
3571 void radius_event_free(void)
3574 * FIXME: Stop all threads, or at least check that
3575 * they're all waiting on the semaphore, and the queues
3581 * There are requests in the proxy hash that aren't
3582 * referenced from anywhere else. Remove them first.
3585 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3586 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3587 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3588 fr_packet_list_free(proxy_list);
3593 fr_packet_list_walk(pl, NULL, request_hash_cb);
3595 fr_packet_list_free(pl);
3598 fr_event_list_free(el);
3601 int radius_event_process(void)
3605 return fr_event_loop(el);
3608 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3610 request->options = RAD_REQUEST_OPTION_DEBUG2;
3612 if (request_pre_handler(request)) {
3613 rad_assert(fun != NULL);
3614 rad_assert(request != NULL);
3616 if (request->server) RDEBUG("server %s {",
3617 request->server != NULL ?
3618 request->server : "");
3621 if (request->server) RDEBUG("} # server %s",
3622 request->server != NULL ?
3623 request->server : "");
3625 request_post_handler(request);
3628 DEBUG2("Going to the next request");