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];
103 static void check_for_zombie_home_server(REQUEST *request);
105 #define remove_from_proxy_hash(foo)
108 static void request_post_handler(REQUEST *request);
109 static void wait_a_bit(void *ctx);
110 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
112 static void event_poll_detail(void *ctx);
115 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
118 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
122 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
125 static void tv_add(struct timeval *tv, int usec_delay)
127 if (usec_delay > USEC) {
128 tv->tv_sec += usec_delay / USEC;
131 tv->tv_usec += usec_delay;
133 if (tv->tv_usec > USEC) {
139 static void remove_from_request_hash(REQUEST *request)
141 if (!request->in_request_hash) return;
143 fr_packet_list_yank(pl, request->packet);
144 request->in_request_hash = FALSE;
146 request_stats_final(request);
151 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
153 RADIUS_PACKET **proxy_p;
156 PTHREAD_MUTEX_LOCK(&proxy_mutex);
157 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
160 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
164 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
167 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
171 request->num_proxied_responses++;
174 * Catch the most common case of everything working
177 if (request->num_proxied_requests == request->num_proxied_responses) {
178 fr_packet_list_yank(proxy_list, request->proxy);
179 fr_packet_list_id_free(proxy_list, request->proxy);
180 request->in_proxy_hash = FALSE;
184 * On the FIRST reply, decrement the count of outstanding
185 * requests. Note that this is NOT the count of sent
186 * packets, but whether or not the home server has
189 if (!request->proxy_reply &&
190 request->home_server &&
191 request->home_server->currently_outstanding) {
192 request->home_server->currently_outstanding--;
195 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
201 static void remove_from_proxy_hash(REQUEST *request)
204 * Check this without grabbing the mutex because it's a
205 * lot faster that way.
207 if (!request->in_proxy_hash) return;
210 * The "not in hash" flag is definitive. However, if the
211 * flag says that it IS in the hash, there might still be
212 * a race condition where it isn't.
214 PTHREAD_MUTEX_LOCK(&proxy_mutex);
216 if (!request->in_proxy_hash) {
217 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
221 fr_packet_list_yank(proxy_list, request->proxy);
222 fr_packet_list_id_free(proxy_list, request->proxy);
225 * The home server hasn't replied, but we've given up on
226 * this request. Don't count this request against the
229 if (!request->proxy_reply &&
230 request->home_server &&
231 request->home_server->currently_outstanding) {
232 request->home_server->currently_outstanding--;
236 * Got from YES in hash, to NO, not in hash while we hold
237 * the mutex. This guarantees that when another thread
238 * grans the mutex, the "not in hash" flag is correct.
240 request->in_proxy_hash = FALSE;
242 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
245 static void ev_request_free(REQUEST **prequest)
249 if (!prequest || !*prequest) return;
256 * Divorce the child from the parent first,
257 * then clean up the child.
259 request->coa->parent = NULL;
260 ev_request_free(&request->coa);
264 * Divorce the parent from the child, and leave the
265 * parent still alive.
267 if (request->parent && (request->parent->coa == request)) {
268 request->parent->coa = NULL;
272 if (request->ev) fr_event_delete(el, &request->ev);
273 if (request->in_proxy_hash) remove_from_proxy_hash(request);
274 if (request->in_request_hash) remove_from_request_hash(request);
276 request_free(prequest);
279 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
282 rad_listen_t *proxy_listener;
284 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
287 * Allocate a new proxy fd. This function adds
288 * it to the tail of the list of listeners. With
289 * some care, this can be thread-safe.
291 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
292 if (!proxy_listener) {
293 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
301 proxy = proxy_listener->fd;
302 for (i = 0; i < 32; i++) {
304 * Found a free entry. Save the socket,
305 * and remember where we saved it.
307 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
308 found = (proxy + i) & 0x1f;
309 proxy_fds[found] = proxy;
310 proxy_listeners[found] = proxy_listener;
314 rad_assert(found >= 0);
316 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
317 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
322 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
323 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
328 * Signal the main thread to add the new FD to the list
331 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
336 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
341 rad_assert(request->proxy != NULL);
342 rad_assert(proxy_list != NULL);
344 PTHREAD_MUTEX_LOCK(&proxy_mutex);
347 * Keep track of maximum outstanding requests to a
348 * particular home server. 'max_outstanding' is
349 * enforced in home_server_ldb(), in realms.c.
351 if (request->home_server) {
352 request->home_server->currently_outstanding++;
356 RADIUS_PACKET packet;
358 packet = *request->proxy;
360 if (!proxy_id_alloc(request, &packet)) {
361 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
366 * Yank the request, free the old Id, and
367 * remember the new Id.
369 fr_packet_list_yank(proxy_list, request->proxy);
370 fr_packet_list_id_free(proxy_list, request->proxy);
371 *request->proxy = packet;
373 } else if (!proxy_id_alloc(request, request->proxy)) {
374 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
378 rad_assert(request->proxy->sockfd >= 0);
381 * FIXME: Hack until we get rid of rad_listen_t, and put
382 * the information into the packet_list.
385 for (i = 0; i < 32; i++) {
386 if (proxy_fds[i] == request->proxy->sockfd) {
393 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
394 RDEBUG2("ERROR: All sockets are full.");
398 rad_assert(proxy_fds[proxy] != -1);
399 rad_assert(proxy_listeners[proxy] != NULL);
400 request->proxy_listener = proxy_listeners[proxy];
402 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
403 fr_packet_list_id_free(proxy_list, request->proxy);
404 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
405 RDEBUG2("ERROR: Failed to insert entry into proxy list");
409 request->in_proxy_hash = TRUE;
411 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
413 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
414 inet_ntop(request->proxy->dst_ipaddr.af,
415 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
416 request->proxy->dst_port,
424 * Called as BOTH an event, and in-line from other functions.
426 static void wait_for_proxy_id_to_expire(void *ctx)
428 REQUEST *request = ctx;
430 rad_assert(request->magic == REQUEST_MAGIC);
431 rad_assert(request->proxy != NULL);
433 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
434 request->when = request->proxy_when;
437 if (((request->proxy->code == PW_COA_REQUEST) ||
438 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
439 (request->packet->code != request->proxy->code)) {
440 request->when.tv_sec += request->home_server->coa_mrd;
443 request->when.tv_sec += request->home_server->response_window;
445 if ((request->num_proxied_requests == request->num_proxied_responses) ||
446 timercmp(&now, &request->when, >)) {
447 if (request->packet) {
448 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
449 request->number, request->packet->id,
450 (unsigned int) (request->timestamp - fr_start_time));
452 RDEBUG2("Cleaning up request %d with timestamp +%d",
454 (unsigned int) (request->timestamp - fr_start_time));
457 ev_request_free(&request);
461 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
465 #ifdef HAVE_PTHREAD_H
466 static void wait_for_child_to_die(void *ctx)
468 REQUEST *request = ctx;
470 rad_assert(request->magic == REQUEST_MAGIC);
472 if ((request->child_state == REQUEST_QUEUED) |
473 (request->child_state == REQUEST_RUNNING)) {
474 request->delay += (request->delay >> 1);
475 tv_add(&request->when, request->delay);
477 RDEBUG2("Child is still stuck for request %d", request->number);
479 INSERT_EVENT(wait_for_child_to_die, request);
483 RDEBUG2("Child is finally responsive for request %d", request->number);
484 remove_from_request_hash(request);
487 if (request->proxy) {
488 wait_for_proxy_id_to_expire(request);
493 ev_request_free(&request);
497 static void cleanup_delay(void *ctx)
499 REQUEST *request = ctx;
501 rad_assert(request->magic == REQUEST_MAGIC);
502 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
503 (request->child_state == REQUEST_DONE));
505 remove_from_request_hash(request);
508 if (request->proxy && request->in_proxy_hash) {
509 wait_for_proxy_id_to_expire(request);
514 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
515 request->number, request->packet->id,
516 (unsigned int) (request->timestamp - fr_start_time));
518 ev_request_free(&request);
523 * In daemon mode, AND this request has debug flags set.
525 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
527 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
531 const char *received, *from;
532 const fr_ipaddr_t *ip;
537 rad_assert(request->radlog != NULL);
539 if (direction == 0) {
540 received = "Received";
541 from = "from"; /* what else? */
542 ip = &packet->src_ipaddr;
543 port = packet->src_port;
546 received = "Sending";
547 from = "to"; /* hah! */
548 ip = &packet->dst_ipaddr;
549 port = packet->dst_port;
553 * Client-specific debugging re-prints the input
554 * packet into the client log.
556 * This really belongs in a utility library
558 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
559 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
560 received, fr_packet_codes[packet->code], from,
561 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
562 port, packet->id, packet->data_len);
564 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
566 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
568 packet->code, packet->id, packet->data_len);
571 for (vp = packet->vps; vp != NULL; vp = vp->next) {
572 vp_prints(buffer, sizeof(buffer), vp);
573 request->radlog(L_DBG, 0, request, "\t%s", buffer);
577 static void reject_delay(void *ctx)
579 REQUEST *request = ctx;
581 rad_assert(request->magic == REQUEST_MAGIC);
582 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
584 RDEBUG2("Sending delayed reject for request %d", request->number);
586 DEBUG_PACKET(request, request->reply, 1);
588 request->listener->send(request->listener, request);
590 request->when.tv_sec += request->root->cleanup_delay;
591 request->child_state = REQUEST_CLEANUP_DELAY;
593 INSERT_EVENT(cleanup_delay, request);
598 void revive_home_server(void *ctx)
600 home_server *home = ctx;
603 home->state = HOME_STATE_ALIVE;
604 home->currently_outstanding = 0;
605 home->revive_time = now;
608 * Delete any outstanding events.
610 if (home->ev) fr_event_delete(el, &home->ev);
612 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
613 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
614 buffer, sizeof(buffer)),
620 static void no_response_to_ping(void *ctx)
622 REQUEST *request = ctx;
626 rad_assert(request->home_server != NULL);
628 home = request->home_server;
629 home->num_received_pings = 0;
631 radlog(L_ERR, "No response to status check %d for home server %s port %d",
633 inet_ntop(request->proxy->dst_ipaddr.af,
634 &request->proxy->dst_ipaddr.ipaddr,
635 buffer, sizeof(buffer)),
636 request->proxy->dst_port);
638 check_for_zombie_home_server(request);
640 wait_for_proxy_id_to_expire(request);
644 static void received_response_to_ping(REQUEST *request)
649 rad_assert(request->home_server != NULL);
651 home = request->home_server;
652 home->num_received_pings++;
654 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
655 request->number, home->num_received_pings);
658 * Remove the request from any hashes
660 fr_event_delete(el, &request->ev);
661 remove_from_proxy_hash(request);
662 rad_assert(request->in_request_hash == FALSE);
665 * The control socket may have marked the home server as
666 * alive. OR, it may have suddenly started responding to
667 * requests again. If so, don't re-do the "make alive"
670 if (home->state == HOME_STATE_ALIVE) return;
673 * We haven't received enough ping responses to mark it
674 * "alive". Wait a bit.
676 if (home->num_received_pings < home->num_pings_to_alive) {
680 home->state = HOME_STATE_ALIVE;
681 home->currently_outstanding = 0;
682 home->revive_time = now;
684 if (!fr_event_delete(el, &home->ev)) {
685 RDEBUG2("Hmm... no event for home server. Oh well.");
688 radlog(L_PROXY, "Marking home server %s port %d alive",
689 inet_ntop(request->proxy->dst_ipaddr.af,
690 &request->proxy->dst_ipaddr.ipaddr,
691 buffer, sizeof(buffer)),
692 request->proxy->dst_port);
697 * Called from start of zombie period, OR after control socket
698 * marks the home server dead.
700 static void ping_home_server(void *ctx)
703 home_server *home = ctx;
707 if ((home->state == HOME_STATE_ALIVE) ||
708 (home->ping_check == HOME_PING_CHECK_NONE) ||
709 (home->ev != NULL)) {
713 request = request_alloc();
714 request->number = request_num_counter++;
716 request->proxy = rad_alloc(1);
717 rad_assert(request->proxy != NULL);
719 fr_event_now(el, &request->when);
720 home->when = request->when;
722 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
723 request->proxy->code = PW_STATUS_SERVER;
725 radius_pairmake(request, &request->proxy->vps,
726 "Message-Authenticator", "0x00", T_OP_SET);
728 } else if (home->type == HOME_TYPE_AUTH) {
729 request->proxy->code = PW_AUTHENTICATION_REQUEST;
731 radius_pairmake(request, &request->proxy->vps,
732 "User-Name", home->ping_user_name, T_OP_SET);
733 radius_pairmake(request, &request->proxy->vps,
734 "User-Password", home->ping_user_password, T_OP_SET);
735 radius_pairmake(request, &request->proxy->vps,
736 "Service-Type", "Authenticate-Only", T_OP_SET);
737 radius_pairmake(request, &request->proxy->vps,
738 "Message-Authenticator", "0x00", T_OP_SET);
741 #ifdef WITH_ACCOUNTING
742 request->proxy->code = PW_ACCOUNTING_REQUEST;
744 radius_pairmake(request, &request->proxy->vps,
745 "User-Name", home->ping_user_name, T_OP_SET);
746 radius_pairmake(request, &request->proxy->vps,
747 "Acct-Status-Type", "Stop", T_OP_SET);
748 radius_pairmake(request, &request->proxy->vps,
749 "Acct-Session-Id", "00000000", T_OP_SET);
750 vp = radius_pairmake(request, &request->proxy->vps,
751 "Event-Timestamp", "0", T_OP_SET);
752 vp->vp_date = now.tv_sec;
754 rad_assert("Internal sanity check failed");
758 radius_pairmake(request, &request->proxy->vps,
759 "NAS-Identifier", "Status Check. Are you alive?",
762 request->proxy->dst_ipaddr = home->ipaddr;
763 request->proxy->dst_port = home->port;
764 request->home_server = home;
766 rad_assert(request->proxy_listener == NULL);
768 if (!insert_into_proxy_hash(request, FALSE)) {
769 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
771 ev_request_free(&request);
774 rad_assert(request->proxy_listener != NULL);
775 request->proxy_listener->send(request->proxy_listener,
778 request->next_callback = NULL;
779 request->child_state = REQUEST_PROXIED;
780 request->when.tv_sec += home->ping_timeout;;
782 INSERT_EVENT(no_response_to_ping, request);
785 * Add +/- 2s of jitter, as suggested in RFC 3539
786 * and in the Issues and Fixes draft.
788 home->when.tv_sec += home->ping_interval - 2;
791 jitter ^= (jitter >> 10);
792 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
794 tv_add(&home->when, jitter);
796 INSERT_EVENT(ping_home_server, home);
800 void mark_home_server_dead(home_server *home, struct timeval *when)
802 int previous_state = home->state;
805 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
806 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
807 buffer, sizeof(buffer)),
810 home->state = HOME_STATE_IS_DEAD;
811 home->num_received_pings = 0;
813 if (home->ping_check != HOME_PING_CHECK_NONE) {
815 * If the control socket marks us dead, start
816 * pinging. Otherwise, we already started
817 * pinging when it was marked "zombie".
819 if (previous_state == HOME_STATE_ALIVE) {
820 ping_home_server(home);
825 * Revive it after a fixed period of time. This
826 * is very, very, bad.
829 home->when.tv_sec += home->revive_interval;
831 INSERT_EVENT(revive_home_server, home);
835 static void check_for_zombie_home_server(REQUEST *request)
840 home = request->home_server;
842 if (home->state != HOME_STATE_ZOMBIE) return;
844 when = home->zombie_period_start;
845 when.tv_sec += home->zombie_period;
847 fr_event_now(el, &now);
848 if (timercmp(&now, &when, <)) {
852 mark_home_server_dead(home, &request->when);
855 static int proxy_to_virtual_server(REQUEST *request);
857 static int virtual_server_handler(UNUSED REQUEST *request)
859 proxy_to_virtual_server(request);
863 static void proxy_fallback_handler(REQUEST *request)
866 * A proper time is required for wait_a_bit.
868 request->delay = USEC / 10;
869 gettimeofday(&now, NULL);
870 request->next_when = now;
871 tv_add(&request->next_when, request->delay);
872 request->next_callback = wait_a_bit;
875 * Re-queue the request.
877 request->child_state = REQUEST_QUEUED;
879 rad_assert(request->proxy != NULL);
880 if (!thread_pool_addrequest(request, virtual_server_handler)) {
881 request->child_state = REQUEST_DONE;
884 #ifdef HAVE_PTHREAD_H
886 * MAY free the request if we're over max_request_time,
887 * AND we're not in threaded mode!
889 * Note that we call this ONLY if we're threaded, as
890 * if we're NOT threaded, request_post_handler() calls
891 * wait_a_bit(), which means that "request" may not
894 if (have_children) wait_a_bit(request);
899 static int setup_post_proxy_fail(REQUEST *request)
901 DICT_VALUE *dval = NULL;
904 request->child_state = REQUEST_RUNNING;
906 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
907 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
909 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
910 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
914 * See no_response_to_coa_request
916 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
917 request->packet->code &= 0xff; /* restore it */
919 if (request->proxy->code == PW_COA_REQUEST) {
920 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
922 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
923 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
933 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
936 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
940 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
941 if (!vp) vp = radius_paircreate(request, &request->config_items,
942 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
943 vp->vp_integer = dval->value;
945 rad_assert(request->proxy_reply == NULL);
951 static int null_handler(UNUSED REQUEST *request)
956 static void post_proxy_fail_handler(REQUEST *request)
959 * A proper time is required for wait_a_bit.
961 request->delay = USEC / 10;
962 gettimeofday(&now, NULL);
965 * Not set up to run Post-Proxy-Type = Fail.
967 * Mark the request as still running, and figure out what
970 if (!setup_post_proxy_fail(request)) {
971 request_post_handler(request);
975 * Re-queue the request.
977 request->child_state = REQUEST_QUEUED;
980 * There is a post-proxy-type of fail. We run
981 * the request through the pre/post proxy
982 * handlers, just like it was a real proxied
983 * request. However, we set the per-request
984 * handler to NULL, as we don't want to do
987 * Note that when we're not threaded, this will
988 * process the request even if it's greater than
989 * max_request_time. That's not fatal.
991 request->priority = 0;
992 rad_assert(request->proxy != NULL);
993 thread_pool_addrequest(request, null_handler);
997 * MAY free the request if we're over max_request_time,
998 * AND we're not in threaded mode!
1000 * Note that we call this ONLY if we're threaded, as
1001 * if we're NOT threaded, request_post_handler() calls
1002 * wait_a_bit(), which means that "request" may not
1005 if (have_children) wait_a_bit(request);
1009 /* maybe check this against wait_for_proxy_id_to_expire? */
1010 static void no_response_to_proxied_request(void *ctx)
1012 REQUEST *request = ctx;
1016 rad_assert(request->magic == REQUEST_MAGIC);
1017 rad_assert(request->child_state == REQUEST_PROXIED);
1020 * If we've failed over to an internal home server,
1021 * replace the callback with the correct one. This
1022 * is due to locking issues with child threads...
1024 if (request->home_server->server) {
1025 wait_a_bit(request);
1029 check_for_zombie_home_server(request);
1031 home = request->home_server;
1034 * The default as of 2.1.7 is to allow requests to
1035 * fail-over to a backup home server when this one does
1036 * not respond. The old behavior can be configured as
1039 if (home->no_response_fail) {
1040 radlog(L_ERR, "Rejecting request %d (proxy Id %d) due to lack of any response from home server %s port %d",
1041 request->number, request->proxy->id,
1042 inet_ntop(request->proxy->dst_ipaddr.af,
1043 &request->proxy->dst_ipaddr.ipaddr,
1044 buffer, sizeof(buffer)),
1045 request->proxy->dst_port);
1047 post_proxy_fail_handler(request);
1050 * Ensure that there is a callback for the request.
1052 request->child_state = REQUEST_RUNNING;
1053 wait_a_bit(request);
1057 * Don't touch request due to race conditions
1059 if (home->state == HOME_STATE_IS_DEAD) {
1060 rad_assert(home->ev != NULL); /* or it will never wake up */
1065 * Enable the zombie period when we notice that the home
1066 * server hasn't responded. We do NOT back-date the start
1067 * of the zombie period.
1069 if (home->state == HOME_STATE_ALIVE) {
1070 home->state = HOME_STATE_ZOMBIE;
1071 home->zombie_period_start = now;
1073 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1074 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1075 buffer, sizeof(buffer)),
1079 * Start pinging the home server.
1081 ping_home_server(home);
1086 static void wait_a_bit(void *ctx)
1088 struct timeval when;
1089 REQUEST *request = ctx;
1090 fr_event_callback_t callback = NULL;
1092 rad_assert(request->magic == REQUEST_MAGIC);
1096 * The CoA request is a new (internally generated)
1097 * request, created in a child thread. We therefore need
1098 * some way to tie its events back into the main event
1101 if (request->coa && !request->coa->proxy_reply &&
1102 request->coa->next_callback) {
1103 request->coa->when = request->coa->next_when;
1104 INSERT_EVENT(request->coa->next_callback, request->coa);
1105 request->coa->next_callback = NULL;
1106 request->coa->parent = NULL;
1107 request->coa = NULL;
1111 switch (request->child_state) {
1112 case REQUEST_QUEUED:
1113 case REQUEST_RUNNING:
1114 when = request->received;
1115 when.tv_sec += request->root->max_request_time;
1118 * Normally called from the event loop with the
1119 * proper event loop time. Otherwise, called from
1120 * post proxy fail handler, which sets "now", and
1121 * this call won't re-set it, because we're not
1122 * in the event loop.
1124 fr_event_now(el, &now);
1127 * Request still has more time. Continue
1130 if (timercmp(&now, &when, <) ||
1131 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1132 (request->child_state == REQUEST_QUEUED))) {
1133 if (request->delay < (USEC / 10)) {
1134 request->delay = USEC / 10;
1136 request->delay += request->delay >> 1;
1140 * Cap wait at some sane value for detail
1143 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1144 (request->delay > (request->root->max_request_time * USEC))) {
1145 request->delay = request->root->max_request_time * USEC;
1149 request->when = now;
1150 tv_add(&request->when, request->delay);
1151 callback = wait_a_bit;
1155 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1157 * A child thread MAY still be running on the
1158 * request. Ask the thread to stop working on
1161 if (have_children) {
1162 /* FIXME: kill unresponsive children? */
1165 * Print this error message ONLY if
1166 * there's a child currently processing
1167 * the request. As we don't have thread
1168 * locks here, there may be race
1169 * conditions on this check. But it's
1170 * just an error message, so that's OK.
1172 if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1173 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1175 request->module ? request->module : "<server core>",
1176 request->component ? request->component : "<server core>");
1179 request->master_state = REQUEST_STOP_PROCESSING;
1181 request->delay = USEC / 4;
1182 tv_add(&request->when, request->delay);
1183 callback = wait_for_child_to_die;
1189 * Else there are no child threads. We probably
1190 * should have just marked the request as 'done'
1191 * elsewhere, like in the post-proxy-fail
1192 * handler. But doing that would involve
1193 * checking for max_request_time in multiple
1194 * places, so this may be simplest.
1196 request->child_state = REQUEST_DONE;
1200 * Mark the request as no longer running,
1204 #ifdef HAVE_PTHREAD_H
1205 request->child_pid = NO_SUCH_CHILD_PID;
1210 * This is a CoA request. It's been divorced
1211 * from everything else, so we clean it up now.
1213 if (!request->in_request_hash &&
1215 (request->packet->code != request->proxy->code) &&
1216 ((request->proxy->code == PW_COA_REQUEST) ||
1217 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1219 * FIXME: Do CoA MIBs
1221 ev_request_free(&request);
1225 request_stats_final(request);
1226 cleanup_delay(request);
1229 case REQUEST_REJECT_DELAY:
1230 case REQUEST_CLEANUP_DELAY:
1231 #ifdef HAVE_PTHREAD_H
1232 request->child_pid = NO_SUCH_CHILD_PID;
1234 request_stats_final(request);
1236 case REQUEST_PROXIED:
1237 rad_assert(request->next_callback != NULL);
1238 rad_assert(request->next_callback != wait_a_bit);
1240 request->when = request->next_when;
1241 callback = request->next_callback;
1242 request->next_callback = NULL;
1246 rad_panic("Internal sanity check failure");
1251 * Something major went wrong. Discard the request, and
1254 * FIXME: No idea why this happens or how to fix it...
1255 * It seems to happen *only* when requests are proxied,
1256 * and where the home server doesn't respond. So it looks
1257 * like a race condition above, but it happens in debug
1258 * mode, with no threads...
1261 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1262 ev_request_free(&request);
1266 INSERT_EVENT(callback, request);
1270 static void no_response_to_coa_request(void *ctx)
1272 REQUEST *request = ctx;
1275 rad_assert(request->magic == REQUEST_MAGIC);
1276 rad_assert(request->child_state == REQUEST_PROXIED);
1277 rad_assert(request->home_server != NULL);
1278 rad_assert(!request->in_request_hash);
1280 radlog(L_ERR, "No response to CoA request sent to %s",
1281 inet_ntop(request->proxy->dst_ipaddr.af,
1282 &request->proxy->dst_ipaddr.ipaddr,
1283 buffer, sizeof(buffer)));
1288 request->packet->code |= (PW_COA_REQUEST << 8);
1289 post_proxy_fail_handler(request);
1293 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1297 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1304 packet->data = NULL;
1305 packet->data_len = 0;
1308 return 1; /* time stamp updated */
1313 * Called when we haven't received a response to a CoA request.
1315 static void retransmit_coa_request(void *ctx)
1319 REQUEST *request = ctx;
1321 rad_assert(request->magic == REQUEST_MAGIC);
1322 rad_assert(request->child_state == REQUEST_PROXIED);
1323 rad_assert(request->home_server != NULL);
1324 rad_assert(!request->in_request_hash);
1325 rad_assert(request->parent == NULL);
1327 fr_event_now(el, &now);
1330 * Cap count at MRC, if it is non-zero.
1332 if (request->home_server->coa_mrc &&
1333 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1334 no_response_to_coa_request(request);
1339 * RFC 5080 Section 2.2.1
1341 * RT = 2*RTprev + RAND*RTprev
1342 * = 1.9 * RTprev + rand(0,.2) * RTprev
1343 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1346 delay ^= (delay >> 16);
1348 frac = request->delay / 5;
1349 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1351 delay += (2 * request->delay) - (request->delay / 10);
1354 * Cap delay at MRT, if MRT is non-zero.
1356 if (request->home_server->coa_mrt &&
1357 (delay > (request->home_server->coa_mrt * USEC))) {
1358 int mrt_usec = request->home_server->coa_mrt * USEC;
1361 * delay = MRT + RAND * MRT
1362 * = 0.9 MRT + rand(0,.2) * MRT
1365 delay ^= (delay >> 15);
1367 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1368 delay += mrt_usec - (mrt_usec / 10);
1371 request->delay = delay;
1372 request->when = now;
1373 tv_add(&request->when, request->delay);
1374 mrd = request->proxy_when;
1375 mrd.tv_sec += request->home_server->coa_mrd;
1378 * Cap duration at MRD.
1380 if (timercmp(&mrd, &request->when, <)) {
1381 request->when = mrd;
1382 INSERT_EVENT(no_response_to_coa_request, request);
1385 INSERT_EVENT(retransmit_coa_request, request);
1388 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1389 if (!insert_into_proxy_hash(request, TRUE)) {
1390 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1394 request->num_proxied_requests = 0;
1395 request->num_proxied_responses = 0;
1398 request->num_proxied_requests++;
1399 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1401 request->proxy_listener->send(request->proxy_listener,
1407 * The original request is either DONE, or in CLEANUP_DELAY.
1409 static int originated_coa_request(REQUEST *request)
1411 int delay, rcode, pre_proxy_type = 0;
1417 rad_assert(request->proxy == NULL);
1418 rad_assert(!request->in_proxy_hash);
1419 rad_assert(request->proxy_reply == NULL);
1421 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1422 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1424 if (vp->vp_integer == 0) {
1425 ev_request_free(&request->coa);
1426 return 1; /* success */
1429 if (!request->coa) request_alloc_coa(request);
1430 if (!request->coa) return 0;
1436 * src_ipaddr will be set up in proxy_encode.
1438 memset(&ipaddr, 0, sizeof(ipaddr));
1439 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1441 ipaddr.af = AF_INET;
1442 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1444 } else if ((vp = pairfind(coa->proxy->vps,
1445 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1446 ipaddr.af = AF_INET6;
1447 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1449 } else if ((vp = pairfind(coa->proxy->vps,
1450 PW_HOME_SERVER_POOL)) != NULL) {
1451 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1453 if (!coa->home_pool) {
1454 RDEBUG2("WARNING: No such home_server_pool %s",
1457 ev_request_free(&request->coa);
1464 } else if (request->client->coa_pool) {
1465 coa->home_pool = request->client->coa_pool;
1467 } else if (request->client->coa_server) {
1468 coa->home_server = request->client->coa_server;
1472 * If all else fails, send it to the client that
1473 * originated this request.
1475 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1479 * Use the pool, if it exists.
1481 if (coa->home_pool) {
1482 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1483 if (!coa->home_server) {
1484 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1488 } else if (!coa->home_server) {
1489 int port = PW_COA_UDP_PORT;
1491 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1492 if (vp) port = vp->vp_integer;
1494 coa->home_server = home_server_find(&ipaddr, port);
1495 if (!coa->home_server) {
1496 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1497 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1498 buffer, sizeof(buffer)), port);
1503 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1505 switch (vp->vp_integer) {
1506 case PW_COA_REQUEST:
1507 case PW_DISCONNECT_REQUEST:
1508 coa->proxy->code = vp->vp_integer;
1512 DEBUG("Cannot set CoA Packet-Type to code %d",
1518 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1521 * The rest of the server code assumes that
1522 * request->packet && request->reply exist. Copy them
1523 * from the original request.
1525 rad_assert(coa->packet != NULL);
1526 rad_assert(coa->packet->vps == NULL);
1527 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1528 coa->packet->vps = paircopy(request->packet->vps);
1529 coa->packet->data = NULL;
1530 rad_assert(coa->reply != NULL);
1531 rad_assert(coa->reply->vps == NULL);
1532 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1533 coa->reply->vps = paircopy(request->reply->vps);
1534 coa->reply->data = NULL;
1535 coa->config_items = paircopy(request->config_items);
1538 * Call the pre-proxy routines.
1540 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1542 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1543 pre_proxy_type = vp->vp_integer;
1546 if (coa->home_pool && coa->home_pool->virtual_server) {
1547 const char *old_server = coa->server;
1549 coa->server = coa->home_pool->virtual_server;
1550 RDEBUG2(" server %s {", coa->server);
1551 rcode = module_pre_proxy(pre_proxy_type, coa);
1553 coa->server = old_server;
1555 rcode = module_pre_proxy(pre_proxy_type, coa);
1562 * Only send the CoA packet if the pre-proxy code succeeded.
1564 case RLM_MODULE_NOOP:
1566 case RLM_MODULE_UPDATED:
1571 * Source IP / port is set when the proxy socket
1574 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1575 coa->proxy->dst_port = coa->home_server->port;
1577 if (!insert_into_proxy_hash(coa, FALSE)) {
1578 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1583 * We CANNOT divorce the CoA request from the parent
1584 * request. This function is running in a child thread,
1585 * and we need access to the main event loop in order to
1586 * to add the timers for the CoA packet. See
1591 * Forget about the original request completely at this
1596 gettimeofday(&request->proxy_when, NULL);
1597 request->received = request->next_when = request->proxy_when;
1598 rad_assert(request->proxy_reply == NULL);
1601 * Implement re-transmit algorithm as per RFC 5080
1604 * We want IRT + RAND*IRT
1605 * or 0.9 IRT + rand(0,.2) IRT
1607 * 2^20 ~ USEC, and we want 2.
1608 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1610 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1611 request->delay = delay * request->home_server->coa_irt;
1612 delay = request->home_server->coa_irt * USEC;
1613 delay -= delay / 10;
1614 delay += request->delay;
1616 request->delay = delay;
1617 tv_add(&request->next_when, delay);
1618 request->next_callback = retransmit_coa_request;
1621 * Note that we set proxied BEFORE sending the packet.
1623 * Once we send it, the request is tainted, as
1624 * another thread may have picked it up. Don't
1627 request->num_proxied_requests = 1;
1628 request->num_proxied_responses = 0;
1629 request->child_pid = NO_SUCH_CHILD_PID;
1631 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1633 request->child_state = REQUEST_PROXIED;
1635 DEBUG_PACKET(request, request->proxy, 1);
1637 request->proxy_listener->send(request->proxy_listener,
1641 #endif /* WITH_COA */
1644 static int process_proxy_reply(REQUEST *request)
1647 int post_proxy_type = 0;
1651 * Delete any reply we had accumulated until now.
1653 pairfree(&request->reply->vps);
1656 * Run the packet through the post-proxy stage,
1657 * BEFORE playing games with the attributes.
1659 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1661 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1662 post_proxy_type = vp->vp_integer;
1665 if (request->home_pool && request->home_pool->virtual_server) {
1666 const char *old_server = request->server;
1668 request->server = request->home_pool->virtual_server;
1669 RDEBUG2(" server %s {", request->server);
1670 rcode = module_post_proxy(post_proxy_type, request);
1672 request->server = old_server;
1674 rcode = module_post_proxy(post_proxy_type, request);
1678 if (request->packet->code == request->proxy->code)
1680 * Don't run the next bit if we originated a CoA
1681 * packet, after receiving an Access-Request or
1682 * Accounting-Request.
1687 * There may NOT be a proxy reply, as we may be
1688 * running Post-Proxy-Type = Fail.
1690 if (request->proxy_reply) {
1692 * Delete the Proxy-State Attributes from
1693 * the reply. These include Proxy-State
1694 * attributes from us and remote server.
1696 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1699 * Add the attributes left in the proxy
1700 * reply to the reply list.
1702 pairadd(&request->reply->vps, request->proxy_reply->vps);
1703 request->proxy_reply->vps = NULL;
1706 * Free proxy request pairs.
1708 pairfree(&request->proxy->vps);
1712 default: /* Don't do anything */
1714 case RLM_MODULE_FAIL:
1715 /* FIXME: debug print stuff */
1716 request->child_state = REQUEST_DONE;
1719 case RLM_MODULE_HANDLED:
1720 /* FIXME: debug print stuff */
1721 request->child_state = REQUEST_DONE;
1729 static int request_pre_handler(REQUEST *request)
1733 rad_assert(request->magic == REQUEST_MAGIC);
1734 rad_assert(request->packet != NULL);
1736 request->child_state = REQUEST_RUNNING;
1739 * Don't decode the packet if it's an internal "fake"
1740 * request. Instead, just return so that the caller can
1743 if (request->packet->dst_port == 0) {
1744 request->username = pairfind(request->packet->vps,
1746 request->password = pairfind(request->packet->vps,
1753 * Put the decoded packet into it's proper place.
1755 if (request->proxy_reply != NULL) {
1756 rcode = request->proxy_listener->decode(request->proxy_listener,
1758 DEBUG_PACKET(request, request->proxy_reply, 0);
1761 if (request->packet->vps == NULL) {
1762 rcode = request->listener->decode(request->listener, request);
1764 if (debug_condition) {
1766 const char *my_debug = debug_condition;
1769 * Ignore parse errors.
1771 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1775 request->options = 2;
1776 request->radlog = radlog_request;
1780 DEBUG_PACKET(request, request->packet, 0);
1786 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1787 request->child_state = REQUEST_DONE;
1791 if (!request->username) {
1792 request->username = pairfind(request->packet->vps,
1797 if (request->proxy) {
1798 return process_proxy_reply(request);
1808 * Do state handling when we proxy a request.
1810 static int proxy_request(REQUEST *request)
1812 struct timeval when;
1815 if (request->home_server->server) {
1816 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1820 if (!insert_into_proxy_hash(request, FALSE)) {
1821 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1825 request->proxy_listener->encode(request->proxy_listener, request);
1827 when = request->received;
1828 when.tv_sec += request->root->max_request_time;
1830 gettimeofday(&request->proxy_when, NULL);
1832 request->next_when = request->proxy_when;
1833 request->next_when.tv_sec += request->home_server->response_window;
1835 rad_assert(request->home_server->response_window > 0);
1837 if (timercmp(&when, &request->next_when, <)) {
1838 request->next_when = when;
1840 request->next_callback = no_response_to_proxied_request;
1842 RDEBUG2("Proxying request %d to home server %s port %d",
1844 inet_ntop(request->proxy->dst_ipaddr.af,
1845 &request->proxy->dst_ipaddr.ipaddr,
1846 buffer, sizeof(buffer)),
1847 request->proxy->dst_port);
1850 * Note that we set proxied BEFORE sending the packet.
1852 * Once we send it, the request is tainted, as
1853 * another thread may have picked it up. Don't
1856 request->num_proxied_requests = 1;
1857 request->num_proxied_responses = 0;
1858 #ifdef HAVE_PTHREAD_H
1859 request->child_pid = NO_SUCH_CHILD_PID;
1861 request->child_state = REQUEST_PROXIED;
1863 DEBUG_PACKET(request, request->proxy, 1);
1865 request->proxy_listener->send(request->proxy_listener,
1872 * "Proxy" the request by sending it to a new virtual server.
1874 static int proxy_to_virtual_server(REQUEST *request)
1877 RAD_REQUEST_FUNP fun;
1879 if (!request->home_server || !request->home_server->server) return 0;
1881 if (request->parent) {
1882 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1886 fake = request_alloc_fake(request);
1888 RDEBUG2("WARNING: Out of memory");
1892 fake->packet->vps = paircopy(request->proxy->vps);
1893 fake->server = request->home_server->server;
1895 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1896 fun = rad_authenticate;
1898 #ifdef WITH_ACCOUNTING
1899 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1900 fun = rad_accounting;
1904 RDEBUG2("Unknown packet type %d", request->proxy->code);
1905 ev_request_free(&fake);
1909 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1910 radius_handle_request(fake, fun);
1911 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1913 if (fake->reply->code != 0) {
1914 request->proxy_reply = fake->reply;
1918 * There was no response
1920 setup_post_proxy_fail(request);
1923 ev_request_free(&fake);
1925 process_proxy_reply(request);
1928 * Process it through the normal section again, but ONLY
1929 * if we received a proxy reply..
1931 if (request->proxy_reply) {
1932 if (request->server) RDEBUG("server %s {",
1933 request->server != NULL ?
1934 request->server : "");
1937 if (request->server) RDEBUG("} # server %s",
1938 request->server != NULL ?
1939 request->server : "");
1942 return 2; /* success, but NOT '1' !*/
1946 * Return 1 if we did proxy it, or the proxy attempt failed
1947 * completely. Either way, the caller doesn't touch the request
1948 * any more if we return 1.
1950 static int successfully_proxied_request(REQUEST *request)
1953 int pre_proxy_type = 0;
1954 VALUE_PAIR *realmpair;
1955 VALUE_PAIR *strippedname;
1957 char *realmname = NULL;
1959 REALM *realm = NULL;
1963 * If it was already proxied, do nothing.
1965 * FIXME: This should really be a serious error.
1967 if (request->in_proxy_hash ||
1968 (request->proxy_reply && (request->proxy_reply->code != 0))) {
1972 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1973 if (!realmpair || (realmpair->length == 0)) {
1976 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
1979 switch (request->packet->code) {
1980 case PW_AUTHENTICATION_REQUEST:
1981 pool_type = HOME_TYPE_AUTH;
1984 #ifdef WITH_ACCOUNTING
1985 case PW_ACCOUNTING_REQUEST:
1986 pool_type = HOME_TYPE_ACCT;
1991 case PW_COA_REQUEST:
1992 case PW_DISCONNECT_REQUEST:
1993 pool_type = HOME_TYPE_COA;
2001 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2003 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2008 realmname = NULL; /* no realms */
2013 realmname = (char *) realmpair->vp_strvalue;
2015 realm = realm_find2(realmname);
2017 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2022 * Figure out which pool to use.
2024 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2025 pool = realm->auth_pool;
2027 #ifdef WITH_ACCOUNTING
2028 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2029 pool = realm->acct_pool;
2033 } else if ((request->packet->code == PW_COA_REQUEST) ||
2034 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2035 pool = realm->acct_pool;
2039 rad_panic("Internal sanity check failed");
2043 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2049 home = home_server_ldb(realmname, pool, request);
2051 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2055 request->home_pool = pool;
2059 * Once we've decided to proxy a request, we cannot send
2060 * a CoA packet. So we free up any CoA packet here.
2062 ev_request_free(&request->coa);
2065 * Remember that we sent the request to a Realm.
2067 if (realmname) pairadd(&request->packet->vps,
2068 pairmake("Realm", realmname, T_OP_EQ));
2071 * Strip the name, if told to.
2073 * Doing it here catches the case of proxied tunneled
2076 if (realm && (realm->striprealm == TRUE) &&
2077 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2079 * If there's a Stripped-User-Name attribute in
2080 * the request, then use THAT as the User-Name
2081 * for the proxied request, instead of the
2084 * This is done by making a copy of the
2085 * Stripped-User-Name attribute, turning it into
2086 * a User-Name attribute, deleting the
2087 * Stripped-User-Name and User-Name attributes
2088 * from the vps list, and making the new
2089 * User-Name the head of the vps list.
2091 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2093 vp = radius_paircreate(request, NULL,
2094 PW_USER_NAME, PW_TYPE_STRING);
2095 rad_assert(vp != NULL); /* handled by above function */
2096 /* Insert at the START of the list */
2097 vp->next = request->proxy->vps;
2098 request->proxy->vps = vp;
2100 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2101 sizeof(vp->vp_strvalue));
2102 vp->length = strippedname->length;
2105 * Do NOT delete Stripped-User-Name.
2110 * If there is no PW_CHAP_CHALLENGE attribute but
2111 * there is a PW_CHAP_PASSWORD we need to add it
2112 * since we can't use the request authenticator
2113 * anymore - we changed it.
2115 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2116 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2117 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2118 vp = radius_paircreate(request, &request->proxy->vps,
2119 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2120 vp->length = AUTH_VECTOR_LEN;
2121 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2125 * The RFC's say we have to do this, but FreeRADIUS
2128 vp = radius_paircreate(request, &request->proxy->vps,
2129 PW_PROXY_STATE, PW_TYPE_OCTETS);
2130 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2131 request->packet->id);
2132 vp->length = strlen(vp->vp_strvalue);
2135 * Should be done BEFORE inserting into proxy hash, as
2136 * pre-proxy may use this information, or change it.
2138 request->proxy->code = request->packet->code;
2141 * Call the pre-proxy routines.
2143 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2145 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2146 pre_proxy_type = vp->vp_integer;
2149 rad_assert(request->home_pool != NULL);
2151 if (request->home_pool->virtual_server) {
2152 const char *old_server = request->server;
2154 request->server = request->home_pool->virtual_server;
2155 RDEBUG2(" server %s {", request->server);
2156 rcode = module_pre_proxy(pre_proxy_type, request);
2158 request->server = old_server;
2160 rcode = module_pre_proxy(pre_proxy_type, request);
2163 case RLM_MODULE_FAIL:
2164 case RLM_MODULE_INVALID:
2165 case RLM_MODULE_NOTFOUND:
2166 case RLM_MODULE_USERLOCK:
2168 /* FIXME: debug print failed stuff */
2171 case RLM_MODULE_REJECT:
2172 case RLM_MODULE_HANDLED:
2176 * Only proxy the packet if the pre-proxy code succeeded.
2178 case RLM_MODULE_NOOP:
2180 case RLM_MODULE_UPDATED:
2185 * If it's a fake request, don't send the proxy
2186 * packet. The outer tunnel session will take
2187 * care of doing that.
2189 if (request->packet->dst_port == 0) {
2190 request->home_server = NULL;
2194 if (request->home_server->server) {
2195 return proxy_to_virtual_server(request);
2198 if (!proxy_request(request)) {
2199 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2207 static void request_post_handler(REQUEST *request)
2209 int child_state = -1;
2210 struct timeval when;
2213 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2215 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2216 RDEBUG2("Request %d was cancelled.", request->number);
2217 #ifdef HAVE_PTHREAD_H
2218 request->child_pid = NO_SUCH_CHILD_PID;
2220 child_state = REQUEST_DONE;
2224 if (request->child_state != REQUEST_RUNNING) {
2225 rad_panic("Internal sanity check failed");
2230 * If it's not in the request hash, it's a CoA request.
2233 if (!request->in_request_hash &&
2235 ((request->proxy->code == PW_COA_REQUEST) ||
2236 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2237 request->next_callback = NULL;
2238 child_state = REQUEST_DONE;
2244 * Catch Auth-Type := Reject BEFORE proxying the packet.
2246 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2247 (request->reply->code == 0) &&
2248 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2249 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2250 request->reply->code = PW_AUTHENTICATION_REJECT;
2254 if (request->root->proxy_requests &&
2255 !request->in_proxy_hash &&
2256 (request->reply->code == 0) &&
2257 (request->packet->dst_port != 0) &&
2258 (request->packet->code != PW_STATUS_SERVER)) {
2259 int rcode = successfully_proxied_request(request);
2261 if (rcode == 1) return; /* request is invalid */
2264 * Failed proxying it (dead home servers, etc.)
2265 * Run it through Post-Proxy-Type = Fail, and
2266 * respond to the request.
2268 * Note that we're in a child thread here, so we
2269 * do NOT re-schedule the request. Instead, we
2270 * do what we would have done, which is run the
2271 * pre-handler, a NULL request handler, and then
2274 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2275 request_pre_handler(request);
2279 * Else we weren't supposed to proxy it,
2280 * OR we proxied it internally to a virutal server.
2286 * Fake requests don't get encoded or signed. The caller
2287 * also requires the reply VP's, so we don't free them
2290 if (request->packet->dst_port == 0) {
2291 /* FIXME: RDEBUG going to the next request */
2292 #ifdef HAVE_PTHREAD_H
2293 request->child_pid = NO_SUCH_CHILD_PID;
2295 request->child_state = REQUEST_DONE;
2301 * Copy Proxy-State from the request to the reply.
2303 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2304 if (vp) pairadd(&request->reply->vps, vp);
2308 * Access-Requests get delayed or cached.
2310 switch (request->packet->code) {
2311 case PW_AUTHENTICATION_REQUEST:
2312 gettimeofday(&request->next_when, NULL);
2314 if (request->reply->code == 0) {
2316 * Check if the lack of response is intentional.
2318 vp = pairfind(request->config_items,
2319 PW_RESPONSE_PACKET_TYPE);
2321 RDEBUG2("There was no response configured: rejecting request %d",
2323 request->reply->code = PW_AUTHENTICATION_REJECT;
2325 } else if (vp->vp_integer == 256) {
2326 RDEBUG2("Not responding to request %d",
2330 * Force cleanup after a long
2331 * time, so that we don't
2332 * re-process the packet.
2334 request->next_when.tv_sec += request->root->max_request_time;
2335 request->next_callback = cleanup_delay;
2336 child_state = REQUEST_CLEANUP_DELAY;
2339 request->reply->code = vp->vp_integer;
2345 * Run rejected packets through
2347 * Post-Auth-Type = Reject
2349 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2350 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2351 vp = radius_pairmake(request, &request->config_items,
2352 "Post-Auth-Type", "Reject",
2354 if (vp) rad_postauth(request);
2357 * If configured, delay Access-Reject packets.
2359 * If request->root->reject_delay = 0, we discover
2360 * that we have to send the packet now.
2362 when = request->received;
2363 when.tv_sec += request->root->reject_delay;
2365 if (timercmp(&when, &request->next_when, >)) {
2366 RDEBUG2("Delaying reject of request %d for %d seconds",
2368 request->root->reject_delay);
2369 request->next_when = when;
2370 request->next_callback = reject_delay;
2371 #ifdef HAVE_PTHREAD_H
2372 request->child_pid = NO_SUCH_CHILD_PID;
2374 request->child_state = REQUEST_REJECT_DELAY;
2380 case PW_COA_REQUEST:
2381 case PW_DISCONNECT_REQUEST:
2383 request->next_when.tv_sec += request->root->cleanup_delay;
2384 request->next_callback = cleanup_delay;
2385 child_state = REQUEST_CLEANUP_DELAY;
2388 case PW_ACCOUNTING_REQUEST:
2389 request->next_callback = NULL; /* just to be safe */
2390 child_state = REQUEST_DONE;
2394 * FIXME: Status-Server should probably not be
2397 case PW_STATUS_SERVER:
2398 request->next_callback = NULL;
2399 child_state = REQUEST_DONE;
2406 request->next_callback = NULL;
2407 child_state = REQUEST_DONE;
2412 * Suppress "no reply" packets here, unless we're reading
2413 * from the "detail" file. In that case, we've got to
2414 * tell the detail file handler that the request is dead,
2415 * and it should re-send it.
2416 * If configured, encode, sign, and send.
2418 if ((request->reply->code != 0) ||
2419 (request->listener->type == RAD_LISTEN_DETAIL)) {
2420 DEBUG_PACKET(request, request->reply, 1);
2421 request->listener->send(request->listener, request);
2426 * Now that we've completely processed the request,
2427 * see if we need to originate a CoA request.
2430 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2431 if (!originated_coa_request(request)) {
2432 RDEBUG2("Do CoA Fail handler here");
2434 /* request->coa is stil set, so we can update events */
2440 * Clean up. These are no longer needed.
2442 pairfree(&request->config_items);
2444 pairfree(&request->packet->vps);
2445 request->username = NULL;
2446 request->password = NULL;
2448 pairfree(&request->reply->vps);
2451 if (request->proxy) {
2452 pairfree(&request->proxy->vps);
2454 if (request->proxy_reply) {
2455 pairfree(&request->proxy_reply->vps);
2460 * We're not tracking responses from the home
2461 * server, we can therefore free this memory in
2464 if (!request->in_proxy_hash) {
2465 rad_free(&request->proxy);
2466 rad_free(&request->proxy_reply);
2467 request->home_server = NULL;
2473 RDEBUG2("Finished request %d.", request->number);
2474 rad_assert(child_state >= 0);
2475 request->child_state = child_state;
2478 * Single threaded mode: update timers now.
2480 if (!have_children) wait_a_bit(request);
2484 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2490 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2491 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2493 switch (request->child_state) {
2494 case REQUEST_QUEUED:
2495 case REQUEST_RUNNING:
2499 radlog(L_ERR, "Discarding duplicate request from "
2500 "client %s port %d - ID: %d due to unfinished request %d",
2502 request->packet->src_port,request->packet->id,
2507 case REQUEST_PROXIED:
2509 * We're not supposed to have duplicate
2510 * accounting packets. The other states handle
2511 * duplicates fine (discard, or send duplicate
2512 * reply). But we do NOT want to retransmit an
2513 * accounting request here, because that would
2514 * involve updating the Acct-Delay-Time, and
2515 * therefore changing the packet Id, etc.
2517 * Instead, we just discard the packet. We may
2518 * eventually respond, or the client will send a
2519 * new accounting packet.
2521 * The same comments go for Status-Server, and
2522 * other packet types.
2524 * FIXME: coa: when we proxy CoA && Disconnect
2525 * packets, this logic has to be fixed.
2527 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2531 check_for_zombie_home_server(request);
2534 * If we've just discovered that the home server is
2535 * dead, send the packet to another one.
2537 if ((request->packet->dst_port != 0) &&
2538 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2541 remove_from_proxy_hash(request);
2543 home = home_server_ldb(NULL, request->home_pool, request);
2545 RDEBUG2("Failed to find live home server for request %d", request->number);
2548 * Do post-request processing,
2549 * and any insertion of necessary
2552 post_proxy_fail_handler(request);
2556 request->proxy->code = request->packet->code;
2559 * Free the old packet, to force re-encoding
2561 free(request->proxy->data);
2562 request->proxy->data = NULL;
2563 request->proxy->data_len = 0;
2566 * This request failed over to a virtual
2567 * server. Push it back onto the queue
2570 if (request->home_server->server) {
2571 proxy_fallback_handler(request);
2576 * Try to proxy the request.
2578 if (!proxy_request(request)) {
2579 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2580 goto no_home_servers;
2584 * This code executes in the main server
2585 * thread, so there's no need for locking.
2587 rad_assert(request->next_callback != NULL);
2588 INSERT_EVENT(request->next_callback, request);
2589 request->next_callback = NULL;
2591 } /* else the home server is still alive */
2593 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2594 inet_ntop(request->proxy->dst_ipaddr.af,
2595 &request->proxy->dst_ipaddr.ipaddr,
2596 buffer, sizeof(buffer)),
2597 request->proxy->dst_port,
2598 request->proxy->id);
2599 request->num_proxied_requests++;
2601 DEBUG_PACKET(request, request->proxy, 1);
2602 request->proxy_listener->send(request->proxy_listener,
2607 case REQUEST_REJECT_DELAY:
2608 RDEBUG2("Waiting to send Access-Reject "
2609 "to client %s port %d - ID: %d",
2611 request->packet->src_port, request->packet->id);
2614 case REQUEST_CLEANUP_DELAY:
2616 if (request->reply->code == 0) {
2617 RDEBUG2("Ignoring retransmit from client %s port %d "
2618 "- ID: %d, no reply was configured",
2620 request->packet->src_port, request->packet->id);
2625 * FIXME: This sends duplicate replies to
2626 * accounting requests, even if Acct-Delay-Time
2627 * or Event-Timestamp is in the packet. In those
2628 * cases, the Id should be changed, and the packet
2631 RDEBUG2("Sending duplicate reply "
2632 "to client %s port %d - ID: %d",
2634 request->packet->src_port, request->packet->id);
2635 DEBUG_PACKET(request, request->reply, 1);
2636 request->listener->send(request->listener, request);
2642 static void received_conflicting_request(REQUEST *request,
2643 const RADCLIENT *client)
2645 radlog(L_ERR, "Received conflicting packet from "
2646 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2648 request->packet->src_port, request->packet->id,
2652 * Nuke it from the request hash, so we can receive new
2655 remove_from_request_hash(request);
2657 switch (request->child_state) {
2658 #ifdef HAVE_PTHREAD_H
2660 * It's queued or running. Tell it to stop, and
2661 * wait for it to do so.
2663 case REQUEST_QUEUED:
2664 case REQUEST_RUNNING:
2665 request->master_state = REQUEST_STOP_PROCESSING;
2666 request->delay += request->delay >> 1;
2668 tv_add(&request->when, request->delay);
2670 INSERT_EVENT(wait_for_child_to_die, request);
2675 * Catch race conditions. It may have switched
2676 * from running to done while this code is being
2679 case REQUEST_REJECT_DELAY:
2680 case REQUEST_CLEANUP_DELAY:
2685 * It's in some other state, and therefore also
2686 * in the event queue. At some point, the
2687 * child will notice, and we can then delete it.
2689 case REQUEST_PROXIED:
2691 rad_assert(request->ev != NULL);
2697 static int can_handle_new_request(RADIUS_PACKET *packet,
2699 struct main_config_t *root)
2702 * Count the total number of requests, to see if
2703 * there are too many. If so, return with an
2706 if (root->max_requests) {
2707 int request_count = fr_packet_list_num_elements(pl);
2710 * This is a new request. Let's see if
2711 * it makes us go over our configured
2714 if (request_count > root->max_requests) {
2715 radlog(L_ERR, "Dropping request (%d is too many): "
2716 "from client %s port %d - ID: %d", request_count,
2718 packet->src_port, packet->id);
2719 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2720 "\tThe value for 'max_requests' is probably set too low.\n");
2722 } /* else there were a small number of requests */
2723 } /* else there was no configured limit for requests */
2726 * FIXME: Add per-client checks. If one client is sending
2727 * too many packets, start discarding them.
2729 * We increment the counters here, and decrement them
2730 * when the response is sent... somewhere in this file.
2734 * FUTURE: Add checks for system load. If the system is
2735 * busy, start dropping requests...
2737 * We can probably keep some statistics ourselves... if
2738 * there are more requests coming in than we can handle,
2739 * start dropping some.
2746 int received_request(rad_listen_t *listener,
2747 RADIUS_PACKET *packet, REQUEST **prequest,
2750 RADIUS_PACKET **packet_p;
2751 REQUEST *request = NULL;
2752 struct main_config_t *root = &mainconfig;
2754 packet_p = fr_packet_list_find(pl, packet);
2756 request = fr_packet2myptr(REQUEST, packet, packet_p);
2757 rad_assert(request->in_request_hash);
2759 if ((request->packet->data_len == packet->data_len) &&
2760 (memcmp(request->packet->vector, packet->vector,
2761 sizeof(packet->vector)) == 0)) {
2762 received_retransmit(request, client);
2767 * The new request is different from the old one,
2768 * but maybe the old is finished. If so, delete
2771 switch (request->child_state) {
2772 struct timeval when;
2776 * Special hacks for race conditions.
2777 * The reply is encoded, and therefore
2778 * likely sent. We received a *new*
2779 * packet from the client, likely before
2780 * the next line or two of code which
2781 * updated the child state. In this
2782 * case, just accept the new request.
2784 if ((request->reply->code != 0) &&
2785 request->reply->data) {
2786 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2788 packet->src_port, packet->id,
2790 remove_from_request_hash(request);
2795 gettimeofday(&when, NULL);
2799 * If the cached request was received
2800 * within the last second, then we
2801 * discard the NEW request instead of the
2802 * old one. This will happen ONLY when
2803 * the client is severely broken, and is
2804 * sending conflicting packets very
2807 if (timercmp(&when, &request->received, <)) {
2808 radlog(L_ERR, "Discarding conflicting packet from "
2809 "client %s port %d - ID: %d due to recent request %d.",
2811 packet->src_port, packet->id,
2816 received_conflicting_request(request, client);
2820 case REQUEST_REJECT_DELAY:
2821 case REQUEST_CLEANUP_DELAY:
2822 request->child_state = REQUEST_DONE;
2824 cleanup_delay(request);
2831 * We may want to quench the new request.
2833 if ((listener->type != RAD_LISTEN_DETAIL) &&
2834 !can_handle_new_request(packet, client, root)) {
2839 * Create and initialize the new request.
2841 request = request_alloc(); /* never fails */
2843 if ((request->reply = rad_alloc(0)) == NULL) {
2844 radlog(L_ERR, "No memory");
2848 request->listener = listener;
2849 request->client = client;
2850 request->packet = packet;
2851 request->packet->timestamp = request->timestamp;
2852 request->number = request_num_counter++;
2853 request->priority = listener->type;
2854 #ifdef HAVE_PTHREAD_H
2855 request->child_pid = NO_SUCH_CHILD_PID;
2859 * Status-Server packets go to the head of the queue.
2861 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2864 * Set virtual server identity
2866 if (client->server) {
2867 request->server = client->server;
2868 } else if (listener->server) {
2869 request->server = listener->server;
2871 request->server = NULL;
2875 * Remember the request in the list.
2877 if (!fr_packet_list_insert(pl, &request->packet)) {
2878 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2879 ev_request_free(&request);
2883 request->in_request_hash = TRUE;
2884 request->root = root;
2888 * The request passes many of our sanity checks.
2889 * From here on in, if anything goes wrong, we
2890 * send a reject message, instead of dropping the
2895 * Build the reply template from the request.
2898 request->reply->sockfd = request->packet->sockfd;
2899 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2900 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2901 request->reply->dst_port = request->packet->src_port;
2902 request->reply->src_port = request->packet->dst_port;
2903 request->reply->id = request->packet->id;
2904 request->reply->code = 0; /* UNKNOWN code */
2905 memcpy(request->reply->vector, request->packet->vector,
2906 sizeof(request->reply->vector));
2907 request->reply->vps = NULL;
2908 request->reply->data = NULL;
2909 request->reply->data_len = 0;
2911 request->master_state = REQUEST_ACTIVE;
2912 request->child_state = REQUEST_QUEUED;
2913 request->next_callback = NULL;
2915 gettimeofday(&request->received, NULL);
2916 request->timestamp = request->received.tv_sec;
2917 request->when = request->received;
2919 request->delay = USEC;
2921 tv_add(&request->when, request->delay);
2923 INSERT_EVENT(wait_a_bit, request);
2925 *prequest = request;
2931 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2937 * Also removes from the proxy hash if responses == requests
2939 request = lookup_in_proxy_hash(packet);
2942 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2943 inet_ntop(packet->src_ipaddr.af,
2944 &packet->src_ipaddr.ipaddr,
2945 buffer, sizeof(buffer)),
2946 packet->src_port, packet->id);
2951 * We haven't replied to the NAS, but we have seen an
2952 * earlier reply from the home server. Ignore this packet,
2953 * as we're likely still processing the previous reply.
2955 if (request->proxy_reply) {
2956 if (memcmp(request->proxy_reply->vector,
2958 sizeof(request->proxy_reply->vector)) == 0) {
2959 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2960 inet_ntop(packet->src_ipaddr.af,
2961 &packet->src_ipaddr.ipaddr,
2962 buffer, sizeof(buffer)),
2963 packet->src_port, packet->id,
2967 * ? The home server gave us a new proxy
2968 * reply which doesn't match the old
2971 RDEBUG2("Ignoring conflicting proxy reply");
2974 /* assert that there's an event queued for request? */
2979 * Verify the packet before doing ANYTHING with it. This
2980 * means we're doing more MD5 checks in the server core.
2981 * However, we can fix that by moving to multiple threads
2982 * listening on sockets.
2984 * We do this AFTER looking the request up in the hash,
2985 * and AFTER vhecking if we saw a previous request. This
2986 * helps minimize the DoS effect of people attacking us
2987 * with spoofed packets.
2989 if (rad_verify(packet, request->proxy,
2990 request->home_server->secret) != 0) {
2991 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2995 gettimeofday(&now, NULL);
2998 * Maybe move this earlier in the decision process?
2999 * Having it here means that late or duplicate proxy
3000 * replies no longer get the home server marked as
3001 * "alive". This might be good for stability, though.
3003 * FIXME: Do we really want to do this whenever we
3004 * receive a packet? Setting this here means that we
3005 * mark it alive on *any* packet, even if it's lost all
3006 * of the *other* packets in the last 10s.
3008 request->home_server->state = HOME_STATE_ALIVE;
3012 * When originating CoA, the "proxy" reply is the reply
3013 * to the CoA request that we originated. At this point,
3014 * the original request is finished, and it has a reply.
3016 * However, if we haven't separated the two requests, do
3017 * so now. This is done so that cleaning up the original
3018 * request won't cause the CoA request to be free'd. See
3019 * util.c, request_free()
3021 if (request->parent && (request->parent->coa == request)) {
3022 request->parent->coa = NULL;
3023 request->parent = NULL;
3027 * Skip the next set of checks, as the original
3028 * reply is cached. We want to be able to still
3029 * process the CoA reply, AND to reference the
3030 * original request/reply.
3032 * This is getting to be really quite a bit of a
3038 * If there's a reply to the NAS, ignore everything
3039 * related to proxy responses
3041 if (request->reply && request->reply->code != 0) {
3042 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3048 * The average includes our time to receive packets and
3049 * look them up in the hashes, which should be the same
3052 * We update the response time only for the FIRST packet
3055 if (request->home_server->ema.window > 0) {
3056 radius_stats_ema(&request->home_server->ema,
3057 &now, &request->proxy_when);
3061 switch (request->child_state) {
3062 case REQUEST_QUEUED:
3063 case REQUEST_RUNNING:
3064 radlog(L_ERR, "Internal sanity check failed for child state");
3067 case REQUEST_REJECT_DELAY:
3068 case REQUEST_CLEANUP_DELAY:
3070 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'",
3071 inet_ntop(packet->src_ipaddr.af,
3072 &packet->src_ipaddr.ipaddr,
3073 buffer, sizeof(buffer)),
3074 packet->src_port, packet->id,
3076 /* assert that there's an event queued for request? */
3079 case REQUEST_PROXIED:
3083 request->proxy_reply = packet;
3087 * Perform RTT calculations, as per RFC 2988 (for TCP).
3088 * Note that we only do so on the first response.
3090 if ((request->num_proxied_responses == 1)
3092 home_server *home = request->home_server;
3094 rtt = now.tv_sec - request->proxy_when.tv_sec;
3097 rtt -= request->proxy_when.tv_usec;
3099 if (!home->has_rtt) {
3100 home->has_rtt = TRUE;
3103 home->rttvar = rtt / 2;
3106 home->rttvar -= home->rttvar >> 2;
3107 home->rttvar += (home->srtt - rtt);
3108 home->srtt -= home->srtt >> 3;
3109 home->srtt += rtt >> 3;
3112 home->rto = home->srtt;
3113 if (home->rttvar > (USEC / 4)) {
3114 home->rto += home->rttvar * 4;
3122 * There's no incoming request, so it's a proxied packet
3125 if (!request->packet) {
3126 received_response_to_ping(request);
3127 request->proxy_reply = NULL; /* caller will free it */
3128 ev_request_free(&request);
3132 request->child_state = REQUEST_QUEUED;
3133 request->when = now;
3134 request->delay = USEC;
3135 request->priority = RAD_LISTEN_PROXY;
3136 tv_add(&request->when, request->delay);
3139 * Wait a bit will take care of max_request_time
3141 INSERT_EVENT(wait_a_bit, request);
3147 void event_new_fd(rad_listen_t *this)
3151 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3153 this->print(this, buffer, sizeof(buffer));
3155 if (this->status == RAD_LISTEN_STATUS_INIT) {
3157 DEBUG("Listening on %s", buffer);
3159 radlog(L_INFO, " ... adding new socket %s", buffer);
3161 if (!fr_event_fd_insert(el, 0, this->fd,
3162 event_socket_handler, this)) {
3163 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3167 this->status = RAD_LISTEN_STATUS_KNOWN;
3171 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3172 radlog(L_INFO, " ... closing socket %s", buffer);
3174 fr_event_fd_delete(el, 0, this->fd);
3175 this->status = RAD_LISTEN_STATUS_FINISH;
3178 * Close the fd AFTER fixing up the requests and
3179 * listeners, so that they don't send/recv on the
3180 * wrong socket (if someone manages to open
3188 static void handle_signal_self(int flag)
3190 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3191 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3192 fr_event_loop_exit(el, 1);
3194 fr_event_loop_exit(el, 2);
3198 } /* else exit/term flags weren't set */
3201 * Tell the even loop to stop processing.
3203 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3205 static time_t last_hup = 0;
3207 radlog(L_INFO, "Received HUP signal.");
3210 if ((int) (when - last_hup) < 5) {
3211 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3216 fr_event_loop_exit(el, 0x80);
3220 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3224 * FIXME: O(N) loops suck.
3226 for (this = mainconfig.listen;
3228 this = this->next) {
3229 if (this->type != RAD_LISTEN_DETAIL) continue;
3232 * This one didn't send the signal, skip
3235 if (!this->decode(this, NULL)) continue;
3238 * Go service the interrupt.
3240 event_poll_detail(this);
3245 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3248 for (this = mainconfig.listen;
3250 this = this->next) {
3256 #ifndef WITH_SELF_PIPE
3257 void radius_signal_self(int flag)
3259 handle_signal_self(flag);
3263 * Inform ourselves that we received a signal.
3265 void radius_signal_self(int flag)
3271 * The read MUST be non-blocking for this to work.
3273 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3277 for (i = 0; i < rcode; i++) {
3278 buffer[0] |= buffer[i];
3286 write(self_pipe[1], buffer, 1);
3290 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3291 UNUSED int fd, UNUSED void *ctx)
3296 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3297 if (rcode <= 0) return;
3300 * Merge pending signals.
3302 for (i = 0; i < rcode; i++) {
3303 buffer[0] |= buffer[i];
3306 handle_signal_self(buffer[0]);
3311 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3314 rad_listen_t *listener = ctx;
3315 RAD_REQUEST_FUNP fun;
3318 rad_assert(xel == el);
3322 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3324 if (!listener->recv(listener, &fun, &request)) return;
3326 if (!thread_pool_addrequest(request, fun)) {
3327 request->child_state = REQUEST_DONE;
3331 typedef struct listen_detail_t {
3336 * This function is called periodically to see if this detail
3337 * file is available for reading.
3339 static void event_poll_detail(void *ctx)
3342 RAD_REQUEST_FUNP fun;
3344 rad_listen_t *this = ctx;
3345 struct timeval when;
3346 listen_detail_t *detail = this->data;
3348 rad_assert(this->type == RAD_LISTEN_DETAIL);
3351 * Try to read something.
3353 * FIXME: This does poll AND receive.
3355 rcode = this->recv(this, &fun, &request);
3357 rad_assert(fun != NULL);
3358 rad_assert(request != NULL);
3360 if (!thread_pool_addrequest(request, fun)) {
3361 request->child_state = REQUEST_DONE;
3365 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3369 * Backdoor API to get the delay until the next poll
3372 delay = this->encode(this, NULL);
3373 tv_add(&when, delay);
3375 if (!fr_event_insert(el, event_poll_detail, this,
3376 &when, &detail->ev)) {
3377 radlog(L_ERR, "Failed creating handler");
3383 static void event_status(struct timeval *wake)
3385 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3389 if (debug_flag == 0) {
3391 radlog(L_INFO, "Ready to process requests.");
3392 just_started = FALSE;
3398 radlog(L_INFO, "Ready to process requests.");
3400 } else if ((wake->tv_sec != 0) ||
3401 (wake->tv_usec >= 100000)) {
3402 DEBUG("Waking up in %d.%01u seconds.",
3403 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3408 * FIXME: Put this somewhere else, where it isn't called
3409 * all of the time...
3412 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3414 * If there are no child threads, then there may
3415 * be child processes. In that case, wait for
3416 * their exit status, and throw that exit status
3417 * away. This helps get rid of zxombie children.
3419 while (waitpid(-1, &argval, WNOHANG) > 0) {
3427 * Externally-visibly functions.
3429 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3431 rad_listen_t *this, *head = NULL;
3435 time(&fr_start_time);
3437 el = fr_event_list_create(event_status);
3440 pl = fr_packet_list_create(0);
3441 if (!pl) return 0; /* leak el */
3443 request_num_counter = 0;
3446 if (mainconfig.proxy_requests) {
3448 * Create the tree for managing proxied requests and
3451 proxy_list = fr_packet_list_create(1);
3452 if (!proxy_list) return 0;
3454 #ifdef HAVE_PTHREAD_H
3455 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3456 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3465 * Just before we spawn the child threads, force the log
3466 * subsystem to re-open the log file for every write.
3468 if (spawn_flag) force_log_reopen();
3470 #ifdef HAVE_PTHREAD_H
3472 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3474 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3477 * Initialize the threads ONLY if we're spawning, AND
3478 * we're running normally.
3480 if (spawn_flag && !check_config &&
3481 (thread_pool_init(cs, &spawn_flag) < 0)) {
3487 * Move all of the thread calls to this file?
3489 * It may be best for the mutexes to be in this file...
3491 have_children = spawn_flag;
3494 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3499 #ifdef WITH_SELF_PIPE
3501 * Child threads need a pipe to signal us, as do the
3504 if (pipe(self_pipe) < 0) {
3505 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3509 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3510 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3514 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3515 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3520 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3521 event_signal_handler, el)) {
3522 radlog(L_ERR, "Failed creating handler for signals");
3525 #endif /* WITH_SELF_PIPE */
3529 * Mark the proxy Fd's as unused.
3534 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3538 DEBUG("%s: #### Opening IP addresses and Ports ####",
3542 * The server temporarily switches to an unprivileged
3543 * user very early in the bootstrapping process.
3544 * However, some sockets MAY require privileged access
3545 * (bind to device, or to port < 1024, or to raw
3546 * sockets). Those sockets need to call suid up/down
3547 * themselves around the functions that need a privileged
3550 if (listen_init(cs, &head) < 0) {
3555 * At this point, no one has any business *ever* going
3558 fr_suid_down_permanent();
3561 * Add all of the sockets to the event loop.
3565 this = this->next) {
3568 this->print(this, buffer, sizeof(buffer));
3570 switch (this->type) {
3572 case RAD_LISTEN_DETAIL:
3573 DEBUG("Listening on %s", buffer);
3576 * Detail files are always known, and aren't
3577 * put into the socket event loop.
3579 this->status = RAD_LISTEN_STATUS_KNOWN;
3582 * Set up the first poll interval.
3584 event_poll_detail(this);
3589 case RAD_LISTEN_PROXY:
3590 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3591 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3593 proxy_fds[this->fd & 0x1f] = this->fd;
3594 proxy_listeners[this->fd & 0x1f] = this;
3595 if (!fr_packet_list_socket_add(proxy_list,
3609 mainconfig.listen = head;
3615 static int request_hash_cb(UNUSED void *ctx, void *data)
3617 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3620 rad_assert(request->in_proxy_hash == FALSE);
3623 ev_request_free(&request);
3630 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3632 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3634 ev_request_free(&request);
3640 void radius_event_free(void)
3643 * FIXME: Stop all threads, or at least check that
3644 * they're all waiting on the semaphore, and the queues
3650 * There are requests in the proxy hash that aren't
3651 * referenced from anywhere else. Remove them first.
3654 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3655 fr_packet_list_free(proxy_list);
3660 fr_packet_list_walk(pl, NULL, request_hash_cb);
3662 fr_packet_list_free(pl);
3665 fr_event_list_free(el);
3668 int radius_event_process(void)
3672 return fr_event_loop(el);
3675 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3677 request->options = RAD_REQUEST_OPTION_DEBUG2;
3679 if (request_pre_handler(request)) {
3680 rad_assert(fun != NULL);
3681 rad_assert(request != NULL);
3683 if (request->server) RDEBUG("server %s {",
3684 request->server != NULL ?
3685 request->server : "");
3688 if (request->server) RDEBUG("} # server %s",
3689 request->server != NULL ?
3690 request->server : "");
3692 request_post_handler(request);
3695 DEBUG2("Going to the next request");