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);
148 request->listener->count--;
151 * The TCP socket was closed, but we've got to
152 * hang around until done.
154 if ((request->listener->status == RAD_LISTEN_STATUS_FINISH) &&
155 (request->listener->count == 0)) {
156 listen_free(&request->listener);
163 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
165 RADIUS_PACKET **proxy_p;
168 PTHREAD_MUTEX_LOCK(&proxy_mutex);
169 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
172 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
176 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
179 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
183 request->num_proxied_responses++;
186 * Catch the most common case of everything working
189 if (request->num_proxied_requests == request->num_proxied_responses) {
190 fr_packet_list_yank(proxy_list, request->proxy);
191 fr_packet_list_id_free(proxy_list, request->proxy);
192 request->in_proxy_hash = FALSE;
196 * On the FIRST reply, decrement the count of outstanding
197 * requests. Note that this is NOT the count of sent
198 * packets, but whether or not the home server has
201 if (!request->proxy_reply &&
202 request->home_server &&
203 request->home_server->currently_outstanding) {
204 request->home_server->currently_outstanding--;
207 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
213 static void remove_from_proxy_hash(REQUEST *request)
216 * Check this without grabbing the mutex because it's a
217 * lot faster that way.
219 if (!request->in_proxy_hash) return;
222 * The "not in hash" flag is definitive. However, if the
223 * flag says that it IS in the hash, there might still be
224 * a race condition where it isn't.
226 PTHREAD_MUTEX_LOCK(&proxy_mutex);
228 if (!request->in_proxy_hash) {
229 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
233 fr_packet_list_yank(proxy_list, request->proxy);
234 fr_packet_list_id_free(proxy_list, request->proxy);
237 * The home server hasn't replied, but we've given up on
238 * this request. Don't count this request against the
241 if (!request->proxy_reply &&
242 request->home_server &&
243 request->home_server->currently_outstanding) {
244 request->home_server->currently_outstanding--;
248 * Got from YES in hash, to NO, not in hash while we hold
249 * the mutex. This guarantees that when another thread
250 * grans the mutex, the "not in hash" flag is correct.
252 request->in_proxy_hash = FALSE;
254 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
257 static void ev_request_free(REQUEST **prequest)
261 if (!prequest || !*prequest) return;
268 * Divorce the child from the parent first,
269 * then clean up the child.
271 request->coa->parent = NULL;
272 ev_request_free(&request->coa);
276 * Divorce the parent from the child, and leave the
277 * parent still alive.
279 if (request->parent && (request->parent->coa == request)) {
280 request->parent->coa = NULL;
284 if (request->ev) fr_event_delete(el, &request->ev);
285 if (request->in_proxy_hash) remove_from_proxy_hash(request);
286 if (request->in_request_hash) remove_from_request_hash(request);
288 request_free(prequest);
291 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
294 rad_listen_t *proxy_listener;
296 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
299 * Allocate a new proxy fd. This function adds
300 * it to the tail of the list of listeners. With
301 * some care, this can be thread-safe.
303 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
304 if (!proxy_listener) {
305 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
313 proxy = proxy_listener->fd;
314 for (i = 0; i < 32; i++) {
316 * Found a free entry. Save the socket,
317 * and remember where we saved it.
319 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
320 found = (proxy + i) & 0x1f;
321 proxy_fds[found] = proxy;
322 proxy_listeners[found] = proxy_listener;
326 rad_assert(found >= 0);
328 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
329 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
334 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
335 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
340 * Signal the main thread to add the new FD to the list
343 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
348 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
353 rad_assert(request->proxy != NULL);
354 rad_assert(proxy_list != NULL);
356 PTHREAD_MUTEX_LOCK(&proxy_mutex);
359 * Keep track of maximum outstanding requests to a
360 * particular home server. 'max_outstanding' is
361 * enforced in home_server_ldb(), in realms.c.
363 if (request->home_server) {
364 request->home_server->currently_outstanding++;
368 RADIUS_PACKET packet;
370 packet = *request->proxy;
372 if (!proxy_id_alloc(request, &packet)) {
373 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
378 * Yank the request, free the old Id, and
379 * remember the new Id.
381 fr_packet_list_yank(proxy_list, request->proxy);
382 fr_packet_list_id_free(proxy_list, request->proxy);
383 *request->proxy = packet;
385 } else if (!proxy_id_alloc(request, request->proxy)) {
386 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
390 rad_assert(request->proxy->sockfd >= 0);
393 * FIXME: Hack until we get rid of rad_listen_t, and put
394 * the information into the packet_list.
397 for (i = 0; i < 32; i++) {
398 if (proxy_fds[i] == request->proxy->sockfd) {
405 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
406 RDEBUG2("ERROR: All sockets are full.");
410 rad_assert(proxy_fds[proxy] != -1);
411 rad_assert(proxy_listeners[proxy] != NULL);
412 request->proxy_listener = proxy_listeners[proxy];
414 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
415 fr_packet_list_id_free(proxy_list, request->proxy);
416 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
417 RDEBUG2("ERROR: Failed to insert entry into proxy list");
421 request->in_proxy_hash = TRUE;
423 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
425 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
426 inet_ntop(request->proxy->dst_ipaddr.af,
427 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
428 request->proxy->dst_port,
436 * Called as BOTH an event, and in-line from other functions.
438 static void wait_for_proxy_id_to_expire(void *ctx)
440 REQUEST *request = ctx;
442 rad_assert(request->magic == REQUEST_MAGIC);
443 rad_assert(request->proxy != NULL);
445 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
446 request->when = request->proxy_when;
449 if (((request->proxy->code == PW_COA_REQUEST) ||
450 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
451 (request->packet->code != request->proxy->code)) {
452 request->when.tv_sec += request->home_server->coa_mrd;
455 request->when.tv_sec += request->home_server->response_window;
457 if ((request->num_proxied_requests == request->num_proxied_responses) ||
458 timercmp(&now, &request->when, >)) {
459 if (request->packet) {
460 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
461 request->number, request->packet->id,
462 (unsigned int) (request->timestamp - fr_start_time));
464 RDEBUG2("Cleaning up request %d with timestamp +%d",
466 (unsigned int) (request->timestamp - fr_start_time));
469 ev_request_free(&request);
473 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
477 #ifdef HAVE_PTHREAD_H
478 static void wait_for_child_to_die(void *ctx)
480 REQUEST *request = ctx;
482 rad_assert(request->magic == REQUEST_MAGIC);
484 if ((request->child_state == REQUEST_QUEUED) |
485 (request->child_state == REQUEST_RUNNING)) {
486 request->delay += (request->delay >> 1);
487 tv_add(&request->when, request->delay);
489 RDEBUG2("Child is still stuck for request %d", request->number);
491 INSERT_EVENT(wait_for_child_to_die, request);
495 RDEBUG2("Child is finally responsive for request %d", request->number);
496 remove_from_request_hash(request);
499 if (request->proxy) {
500 wait_for_proxy_id_to_expire(request);
505 ev_request_free(&request);
509 static void cleanup_delay(void *ctx)
511 REQUEST *request = ctx;
513 rad_assert(request->magic == REQUEST_MAGIC);
514 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
515 (request->child_state == REQUEST_DONE));
517 remove_from_request_hash(request);
520 if (request->proxy && request->in_proxy_hash) {
521 wait_for_proxy_id_to_expire(request);
526 RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
527 request->number, request->packet->id,
528 (unsigned int) (request->timestamp - fr_start_time));
530 ev_request_free(&request);
535 * In daemon mode, AND this request has debug flags set.
537 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
539 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
543 const char *received, *from;
544 const fr_ipaddr_t *ip;
549 rad_assert(request->radlog != NULL);
551 if (direction == 0) {
552 received = "Received";
553 from = "from"; /* what else? */
554 ip = &packet->src_ipaddr;
555 port = packet->src_port;
558 received = "Sending";
559 from = "to"; /* hah! */
560 ip = &packet->dst_ipaddr;
561 port = packet->dst_port;
565 * Client-specific debugging re-prints the input
566 * packet into the client log.
568 * This really belongs in a utility library
570 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
571 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
572 received, fr_packet_codes[packet->code], from,
573 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
574 port, packet->id, packet->data_len);
576 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
578 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
580 packet->code, packet->id, packet->data_len);
583 for (vp = packet->vps; vp != NULL; vp = vp->next) {
584 vp_prints(buffer, sizeof(buffer), vp);
585 request->radlog(L_DBG, 0, request, "\t%s", buffer);
589 static void reject_delay(void *ctx)
591 REQUEST *request = ctx;
593 rad_assert(request->magic == REQUEST_MAGIC);
594 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
596 RDEBUG2("Sending delayed reject for request %d", request->number);
598 DEBUG_PACKET(request, request->reply, 1);
600 request->listener->send(request->listener, request);
602 request->when.tv_sec += request->root->cleanup_delay;
603 request->child_state = REQUEST_CLEANUP_DELAY;
605 INSERT_EVENT(cleanup_delay, request);
610 void revive_home_server(void *ctx)
612 home_server *home = ctx;
615 home->state = HOME_STATE_ALIVE;
616 home->currently_outstanding = 0;
617 home->revive_time = now;
620 * Delete any outstanding events.
622 if (home->ev) fr_event_delete(el, &home->ev);
624 radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
625 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
626 buffer, sizeof(buffer)),
632 static void no_response_to_ping(void *ctx)
634 REQUEST *request = ctx;
638 rad_assert(request->home_server != NULL);
640 home = request->home_server;
641 home->num_received_pings = 0;
643 RDEBUG2("No response to status check %d from home server %s port %d",
645 inet_ntop(request->proxy->dst_ipaddr.af,
646 &request->proxy->dst_ipaddr.ipaddr,
647 buffer, sizeof(buffer)),
648 request->proxy->dst_port);
650 wait_for_proxy_id_to_expire(request);
654 static void received_response_to_ping(REQUEST *request)
659 rad_assert(request->home_server != NULL);
661 home = request->home_server;
662 home->num_received_pings++;
664 RDEBUG2("Received response to status check %d (%d in current sequence)",
665 request->number, home->num_received_pings);
668 * Remove the request from any hashes
670 fr_event_delete(el, &request->ev);
671 remove_from_proxy_hash(request);
672 rad_assert(request->in_request_hash == FALSE);
675 * The control socket may have marked the home server as
676 * alive. OR, it may have suddenly started responding to
677 * requests again. If so, don't re-do the "make alive"
680 if (home->state == HOME_STATE_ALIVE) return;
683 * We haven't received enough ping responses to mark it
684 * "alive". Wait a bit.
686 if (home->num_received_pings < home->num_pings_to_alive) {
690 home->state = HOME_STATE_ALIVE;
691 home->currently_outstanding = 0;
692 home->revive_time = now;
694 if (!fr_event_delete(el, &home->ev)) {
695 RDEBUG2("Hmm... no event for home server. Oh well.");
698 radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
699 inet_ntop(request->proxy->dst_ipaddr.af,
700 &request->proxy->dst_ipaddr.ipaddr,
701 buffer, sizeof(buffer)),
702 request->proxy->dst_port);
707 * Called from start of zombie period, OR after control socket
708 * marks the home server dead.
710 static void ping_home_server(void *ctx)
713 home_server *home = ctx;
717 if ((home->state == HOME_STATE_ALIVE) ||
718 (home->ping_check == HOME_PING_CHECK_NONE) ||
719 (home->ev != NULL)) {
723 request = request_alloc();
724 request->number = request_num_counter++;
726 request->proxy = rad_alloc(1);
727 rad_assert(request->proxy != NULL);
729 fr_event_now(el, &request->when);
730 home->when = request->when;
732 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
733 request->proxy->code = PW_STATUS_SERVER;
735 radius_pairmake(request, &request->proxy->vps,
736 "Message-Authenticator", "0x00", T_OP_SET);
738 } else if (home->type == HOME_TYPE_AUTH) {
739 request->proxy->code = PW_AUTHENTICATION_REQUEST;
741 radius_pairmake(request, &request->proxy->vps,
742 "User-Name", home->ping_user_name, T_OP_SET);
743 radius_pairmake(request, &request->proxy->vps,
744 "User-Password", home->ping_user_password, T_OP_SET);
745 radius_pairmake(request, &request->proxy->vps,
746 "Service-Type", "Authenticate-Only", T_OP_SET);
747 radius_pairmake(request, &request->proxy->vps,
748 "Message-Authenticator", "0x00", T_OP_SET);
751 #ifdef WITH_ACCOUNTING
752 request->proxy->code = PW_ACCOUNTING_REQUEST;
754 radius_pairmake(request, &request->proxy->vps,
755 "User-Name", home->ping_user_name, T_OP_SET);
756 radius_pairmake(request, &request->proxy->vps,
757 "Acct-Status-Type", "Stop", T_OP_SET);
758 radius_pairmake(request, &request->proxy->vps,
759 "Acct-Session-Id", "00000000", T_OP_SET);
760 vp = radius_pairmake(request, &request->proxy->vps,
761 "Event-Timestamp", "0", T_OP_SET);
762 vp->vp_date = now.tv_sec;
764 rad_assert("Internal sanity check failed");
768 radius_pairmake(request, &request->proxy->vps,
769 "NAS-Identifier", "Status Check. Are you alive?",
772 request->proxy->dst_ipaddr = home->ipaddr;
773 request->proxy->dst_port = home->port;
774 request->home_server = home;
776 rad_assert(request->proxy_listener == NULL);
778 if (!insert_into_proxy_hash(request, FALSE)) {
779 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
781 ev_request_free(&request);
784 rad_assert(request->proxy_listener != NULL);
785 request->proxy_listener->send(request->proxy_listener,
788 request->next_callback = NULL;
789 request->child_state = REQUEST_PROXIED;
790 request->when.tv_sec += home->ping_timeout;;
792 INSERT_EVENT(no_response_to_ping, request);
795 * Add +/- 2s of jitter, as suggested in RFC 3539
796 * and in the Issues and Fixes draft.
798 home->when.tv_sec += home->ping_interval - 2;
801 jitter ^= (jitter >> 10);
802 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
804 tv_add(&home->when, jitter);
806 INSERT_EVENT(ping_home_server, home);
810 void mark_home_server_dead(home_server *home, struct timeval *when)
812 int previous_state = home->state;
815 radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
816 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
817 buffer, sizeof(buffer)),
820 home->state = HOME_STATE_IS_DEAD;
821 home->num_received_pings = 0;
823 if (home->ping_check != HOME_PING_CHECK_NONE) {
825 * If the control socket marks us dead, start
826 * pinging. Otherwise, we already started
827 * pinging when it was marked "zombie".
829 if (previous_state == HOME_STATE_ALIVE) {
830 ping_home_server(home);
835 * Revive it after a fixed period of time. This
836 * is very, very, bad.
839 home->when.tv_sec += home->revive_interval;
841 INSERT_EVENT(revive_home_server, home);
845 static void check_for_zombie_home_server(REQUEST *request)
850 home = request->home_server;
852 if (home->state != HOME_STATE_ZOMBIE) return;
854 when = home->zombie_period_start;
855 when.tv_sec += home->zombie_period;
857 fr_event_now(el, &now);
858 if (timercmp(&now, &when, <)) {
862 mark_home_server_dead(home, &request->when);
865 static int proxy_to_virtual_server(REQUEST *request);
867 static int virtual_server_handler(UNUSED REQUEST *request)
869 proxy_to_virtual_server(request);
873 static void proxy_fallback_handler(REQUEST *request)
876 * A proper time is required for wait_a_bit.
878 request->delay = USEC / 10;
879 gettimeofday(&now, NULL);
880 request->next_when = now;
881 tv_add(&request->next_when, request->delay);
882 request->next_callback = wait_a_bit;
885 * Re-queue the request.
887 request->child_state = REQUEST_QUEUED;
889 rad_assert(request->proxy != NULL);
890 if (!thread_pool_addrequest(request, virtual_server_handler)) {
891 request->child_state = REQUEST_DONE;
894 #ifdef HAVE_PTHREAD_H
896 * MAY free the request if we're over max_request_time,
897 * AND we're not in threaded mode!
899 * Note that we call this ONLY if we're threaded, as
900 * if we're NOT threaded, request_post_handler() calls
901 * wait_a_bit(), which means that "request" may not
904 if (have_children) wait_a_bit(request);
909 static int setup_post_proxy_fail(REQUEST *request)
911 DICT_VALUE *dval = NULL;
914 request->child_state = REQUEST_RUNNING;
916 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
917 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
919 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
920 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
924 * See no_response_to_coa_request
926 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
927 request->packet->code &= 0xff; /* restore it */
929 if (request->proxy->code == PW_COA_REQUEST) {
930 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
932 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
933 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
943 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
946 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
950 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
951 if (!vp) vp = radius_paircreate(request, &request->config_items,
952 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
953 vp->vp_integer = dval->value;
955 rad_assert(request->proxy_reply == NULL);
961 static int null_handler(UNUSED REQUEST *request)
966 static void post_proxy_fail_handler(REQUEST *request)
969 * A proper time is required for wait_a_bit.
971 request->delay = USEC / 10;
972 gettimeofday(&now, NULL);
975 * Not set up to run Post-Proxy-Type = Fail.
977 * Mark the request as still running, and figure out what
980 if (!setup_post_proxy_fail(request)) {
981 request_post_handler(request);
985 * Re-queue the request.
987 request->child_state = REQUEST_QUEUED;
990 * There is a post-proxy-type of fail. We run
991 * the request through the pre/post proxy
992 * handlers, just like it was a real proxied
993 * request. However, we set the per-request
994 * handler to NULL, as we don't want to do
997 * Note that when we're not threaded, this will
998 * process the request even if it's greater than
999 * max_request_time. That's not fatal.
1001 request->priority = 0;
1002 rad_assert(request->proxy != NULL);
1003 thread_pool_addrequest(request, null_handler);
1007 * MAY free the request if we're over max_request_time,
1008 * AND we're not in threaded mode!
1010 * Note that we call this ONLY if we're threaded, as
1011 * if we're NOT threaded, request_post_handler() calls
1012 * wait_a_bit(), which means that "request" may not
1015 if (have_children) wait_a_bit(request);
1019 /* maybe check this against wait_for_proxy_id_to_expire? */
1020 static void no_response_to_proxied_request(void *ctx)
1022 REQUEST *request = ctx;
1026 rad_assert(request->magic == REQUEST_MAGIC);
1027 rad_assert(request->child_state == REQUEST_PROXIED);
1030 * If we've failed over to an internal home server,
1031 * replace the callback with the correct one. This
1032 * is due to locking issues with child threads...
1034 if (request->home_server->server) {
1035 wait_a_bit(request);
1039 check_for_zombie_home_server(request);
1041 home = request->home_server;
1044 * The default as of 2.1.7 is to allow requests to
1045 * fail-over to a backup home server when this one does
1046 * not respond. The old behavior can be configured as
1049 if (home->no_response_fail) {
1050 radlog(L_ERR, "Rejecting request %d (proxy Id %d) due to lack of any response from home server %s port %d",
1051 request->number, request->proxy->id,
1052 inet_ntop(request->proxy->dst_ipaddr.af,
1053 &request->proxy->dst_ipaddr.ipaddr,
1054 buffer, sizeof(buffer)),
1055 request->proxy->dst_port);
1057 post_proxy_fail_handler(request);
1061 * Don't touch request due to race conditions
1063 if (home->state == HOME_STATE_IS_DEAD) {
1064 rad_assert(home->ev != NULL); /* or it will never wake up */
1069 * Enable the zombie period when we notice that the home
1070 * server hasn't responded. We do NOT back-date the start
1071 * of the zombie period.
1073 if (home->state == HOME_STATE_ALIVE) {
1074 home->state = HOME_STATE_ZOMBIE;
1075 home->zombie_period_start = now;
1077 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1078 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1079 buffer, sizeof(buffer)),
1083 * Start pinging the home server.
1085 ping_home_server(home);
1090 static void wait_a_bit(void *ctx)
1092 struct timeval when;
1093 REQUEST *request = ctx;
1094 fr_event_callback_t callback = NULL;
1096 rad_assert(request->magic == REQUEST_MAGIC);
1099 * The socket was closed. Tell the request that
1100 * there is no point in continuing.
1102 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
1103 goto stop_processing;
1108 * The CoA request is a new (internally generated)
1109 * request, created in a child thread. We therefore need
1110 * some way to tie its events back into the main event
1113 if (request->coa && !request->coa->proxy_reply &&
1114 request->coa->next_callback) {
1115 request->coa->when = request->coa->next_when;
1116 INSERT_EVENT(request->coa->next_callback, request->coa);
1117 request->coa->next_callback = NULL;
1118 request->coa->parent = NULL;
1119 request->coa = NULL;
1123 switch (request->child_state) {
1124 case REQUEST_QUEUED:
1125 case REQUEST_RUNNING:
1126 when = request->received;
1127 when.tv_sec += request->root->max_request_time;
1130 * Normally called from the event loop with the
1131 * proper event loop time. Otherwise, called from
1132 * post proxy fail handler, which sets "now", and
1133 * this call won't re-set it, because we're not
1134 * in the event loop.
1136 fr_event_now(el, &now);
1139 * Request still has more time. Continue
1142 if (timercmp(&now, &when, <) ||
1143 ((request->listener->type == RAD_LISTEN_DETAIL) &&
1144 (request->child_state == REQUEST_QUEUED))) {
1145 if (request->delay < (USEC / 10)) {
1146 request->delay = USEC / 10;
1148 request->delay += request->delay >> 1;
1152 * Cap wait at some sane value for detail
1155 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1156 (request->delay > (request->root->max_request_time * USEC))) {
1157 request->delay = request->root->max_request_time * USEC;
1161 request->when = now;
1162 tv_add(&request->when, request->delay);
1163 callback = wait_a_bit;
1167 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1169 * A child thread MAY still be running on the
1170 * request. Ask the thread to stop working on
1173 if (have_children) {
1174 /* FIXME: kill unresponsive children? */
1177 * Print this error message ONLY if
1178 * there's a child currently processing
1179 * the request. As we don't have thread
1180 * locks here, there may be race
1181 * conditions on this check. But it's
1182 * just an error message, so that's OK.
1184 if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1185 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1187 request->module ? request->module : "<server core>",
1188 request->component ? request->component : "<server core>");
1192 request->master_state = REQUEST_STOP_PROCESSING;
1194 request->delay = USEC / 4;
1195 tv_add(&request->when, request->delay);
1196 callback = wait_for_child_to_die;
1199 #else /* no child threads */
1204 * Else there are no child threads. We probably
1205 * should have just marked the request as 'done'
1206 * elsewhere, like in the post-proxy-fail
1207 * handler. But doing that would involve
1208 * checking for max_request_time in multiple
1209 * places, so this may be simplest.
1211 request->child_state = REQUEST_DONE;
1215 * Mark the request as no longer running,
1219 #ifdef HAVE_PTHREAD_H
1220 request->child_pid = NO_SUCH_CHILD_PID;
1225 * This is a CoA request. It's been divorced
1226 * from everything else, so we clean it up now.
1228 if (!request->in_request_hash &&
1230 (request->packet->code != request->proxy->code) &&
1231 ((request->proxy->code == PW_COA_REQUEST) ||
1232 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1234 * FIXME: Do CoA MIBs
1236 ev_request_free(&request);
1240 request_stats_final(request);
1241 cleanup_delay(request);
1244 case REQUEST_REJECT_DELAY:
1245 case REQUEST_CLEANUP_DELAY:
1246 #ifdef HAVE_PTHREAD_H
1247 request->child_pid = NO_SUCH_CHILD_PID;
1249 request_stats_final(request);
1251 case REQUEST_PROXIED:
1252 rad_assert(request->next_callback != NULL);
1253 rad_assert(request->next_callback != wait_a_bit);
1255 request->when = request->next_when;
1256 callback = request->next_callback;
1257 request->next_callback = NULL;
1261 rad_panic("Internal sanity check failure");
1266 * Something major went wrong. Discard the request, and
1269 * FIXME: No idea why this happens or how to fix it...
1270 * It seems to happen *only* when requests are proxied,
1271 * and where the home server doesn't respond. So it looks
1272 * like a race condition above, but it happens in debug
1273 * mode, with no threads...
1276 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1277 ev_request_free(&request);
1281 INSERT_EVENT(callback, request);
1285 static void no_response_to_coa_request(void *ctx)
1287 REQUEST *request = ctx;
1290 rad_assert(request->magic == REQUEST_MAGIC);
1291 rad_assert(request->child_state == REQUEST_PROXIED);
1292 rad_assert(request->home_server != NULL);
1293 rad_assert(!request->in_request_hash);
1295 radlog(L_ERR, "No response to CoA request sent to %s",
1296 inet_ntop(request->proxy->dst_ipaddr.af,
1297 &request->proxy->dst_ipaddr.ipaddr,
1298 buffer, sizeof(buffer)));
1303 request->packet->code |= (PW_COA_REQUEST << 8);
1304 post_proxy_fail_handler(request);
1308 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1312 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1319 packet->data = NULL;
1320 packet->data_len = 0;
1323 return 1; /* time stamp updated */
1328 * Called when we haven't received a response to a CoA request.
1330 static void retransmit_coa_request(void *ctx)
1334 REQUEST *request = ctx;
1336 rad_assert(request->magic == REQUEST_MAGIC);
1337 rad_assert(request->child_state == REQUEST_PROXIED);
1338 rad_assert(request->home_server != NULL);
1339 rad_assert(!request->in_request_hash);
1340 rad_assert(request->parent == NULL);
1342 fr_event_now(el, &now);
1345 * Cap count at MRC, if it is non-zero.
1347 if (request->home_server->coa_mrc &&
1348 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1349 no_response_to_coa_request(request);
1354 * RFC 5080 Section 2.2.1
1356 * RT = 2*RTprev + RAND*RTprev
1357 * = 1.9 * RTprev + rand(0,.2) * RTprev
1358 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1361 delay ^= (delay >> 16);
1363 frac = request->delay / 5;
1364 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1366 delay += (2 * request->delay) - (request->delay / 10);
1369 * Cap delay at MRT, if MRT is non-zero.
1371 if (request->home_server->coa_mrt &&
1372 (delay > (request->home_server->coa_mrt * USEC))) {
1373 int mrt_usec = request->home_server->coa_mrt * USEC;
1376 * delay = MRT + RAND * MRT
1377 * = 0.9 MRT + rand(0,.2) * MRT
1380 delay ^= (delay >> 15);
1382 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1383 delay += mrt_usec - (mrt_usec / 10);
1386 request->delay = delay;
1387 request->when = now;
1388 tv_add(&request->when, request->delay);
1389 mrd = request->proxy_when;
1390 mrd.tv_sec += request->home_server->coa_mrd;
1393 * Cap duration at MRD.
1395 if (timercmp(&mrd, &request->when, <)) {
1396 request->when = mrd;
1397 INSERT_EVENT(no_response_to_coa_request, request);
1400 INSERT_EVENT(retransmit_coa_request, request);
1403 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1404 if (!insert_into_proxy_hash(request, TRUE)) {
1405 DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1409 request->num_proxied_requests = 0;
1410 request->num_proxied_responses = 0;
1413 request->num_proxied_requests++;
1414 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1416 request->proxy_listener->send(request->proxy_listener,
1422 * The original request is either DONE, or in CLEANUP_DELAY.
1424 static int originated_coa_request(REQUEST *request)
1426 int delay, rcode, pre_proxy_type = 0;
1432 rad_assert(request->proxy == NULL);
1433 rad_assert(!request->in_proxy_hash);
1434 rad_assert(request->proxy_reply == NULL);
1436 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1437 if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1439 if (vp->vp_integer == 0) {
1440 ev_request_free(&request->coa);
1441 return 1; /* success */
1444 if (!request->coa) request_alloc_coa(request);
1445 if (!request->coa) return 0;
1451 * src_ipaddr will be set up in proxy_encode.
1453 memset(&ipaddr, 0, sizeof(ipaddr));
1454 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1456 ipaddr.af = AF_INET;
1457 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1459 } else if ((vp = pairfind(coa->proxy->vps,
1460 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1461 ipaddr.af = AF_INET6;
1462 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1464 } else if ((vp = pairfind(coa->proxy->vps,
1465 PW_HOME_SERVER_POOL)) != NULL) {
1466 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1468 if (!coa->home_pool) {
1469 RDEBUG2("WARNING: No such home_server_pool %s",
1472 ev_request_free(&request->coa);
1479 } else if (request->client->coa_pool) {
1480 coa->home_pool = request->client->coa_pool;
1482 } else if (request->client->coa_server) {
1483 coa->home_server = request->client->coa_server;
1487 * If all else fails, send it to the client that
1488 * originated this request.
1490 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1494 * Use the pool, if it exists.
1496 if (coa->home_pool) {
1497 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1498 if (!coa->home_server) {
1499 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1503 } else if (!coa->home_server) {
1504 int port = PW_COA_UDP_PORT;
1506 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1507 if (vp) port = vp->vp_integer;
1509 coa->home_server = home_server_find(&ipaddr, port);
1510 if (!coa->home_server) {
1511 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1512 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1513 buffer, sizeof(buffer)), port);
1518 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1520 switch (vp->vp_integer) {
1521 case PW_COA_REQUEST:
1522 case PW_DISCONNECT_REQUEST:
1523 coa->proxy->code = vp->vp_integer;
1527 DEBUG("Cannot set CoA Packet-Type to code %d",
1533 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1536 * The rest of the server code assumes that
1537 * request->packet && request->reply exist. Copy them
1538 * from the original request.
1540 rad_assert(coa->packet != NULL);
1541 rad_assert(coa->packet->vps == NULL);
1542 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1543 coa->packet->vps = paircopy(request->packet->vps);
1544 coa->packet->data = NULL;
1545 rad_assert(coa->reply != NULL);
1546 rad_assert(coa->reply->vps == NULL);
1547 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1548 coa->reply->vps = paircopy(request->reply->vps);
1549 coa->reply->data = NULL;
1550 coa->config_items = paircopy(request->config_items);
1553 * Call the pre-proxy routines.
1555 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1557 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1558 pre_proxy_type = vp->vp_integer;
1561 if (coa->home_pool && coa->home_pool->virtual_server) {
1562 const char *old_server = coa->server;
1564 coa->server = coa->home_pool->virtual_server;
1565 RDEBUG2(" server %s {", coa->server);
1566 rcode = module_pre_proxy(pre_proxy_type, coa);
1568 coa->server = old_server;
1570 rcode = module_pre_proxy(pre_proxy_type, coa);
1577 * Only send the CoA packet if the pre-proxy code succeeded.
1579 case RLM_MODULE_NOOP:
1581 case RLM_MODULE_UPDATED:
1586 * Source IP / port is set when the proxy socket
1589 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1590 coa->proxy->dst_port = coa->home_server->port;
1592 if (!insert_into_proxy_hash(coa, FALSE)) {
1593 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1598 * We CANNOT divorce the CoA request from the parent
1599 * request. This function is running in a child thread,
1600 * and we need access to the main event loop in order to
1601 * to add the timers for the CoA packet. See
1606 * Forget about the original request completely at this
1611 gettimeofday(&request->proxy_when, NULL);
1612 request->received = request->next_when = request->proxy_when;
1613 rad_assert(request->proxy_reply == NULL);
1616 * Implement re-transmit algorithm as per RFC 5080
1619 * We want IRT + RAND*IRT
1620 * or 0.9 IRT + rand(0,.2) IRT
1622 * 2^20 ~ USEC, and we want 2.
1623 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1625 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1626 request->delay = delay * request->home_server->coa_irt;
1627 delay = request->home_server->coa_irt * USEC;
1628 delay -= delay / 10;
1629 delay += request->delay;
1631 request->delay = delay;
1632 tv_add(&request->next_when, delay);
1633 request->next_callback = retransmit_coa_request;
1636 * Note that we set proxied BEFORE sending the packet.
1638 * Once we send it, the request is tainted, as
1639 * another thread may have picked it up. Don't
1642 request->num_proxied_requests = 1;
1643 request->num_proxied_responses = 0;
1644 request->child_pid = NO_SUCH_CHILD_PID;
1646 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1648 request->child_state = REQUEST_PROXIED;
1650 DEBUG_PACKET(request, request->proxy, 1);
1652 request->proxy_listener->send(request->proxy_listener,
1656 #endif /* WITH_COA */
1659 static int process_proxy_reply(REQUEST *request)
1662 int post_proxy_type = 0;
1666 * Delete any reply we had accumulated until now.
1668 pairfree(&request->reply->vps);
1671 * Run the packet through the post-proxy stage,
1672 * BEFORE playing games with the attributes.
1674 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1676 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1677 post_proxy_type = vp->vp_integer;
1680 if (request->home_pool && request->home_pool->virtual_server) {
1681 const char *old_server = request->server;
1683 request->server = request->home_pool->virtual_server;
1684 RDEBUG2(" server %s {", request->server);
1685 rcode = module_post_proxy(post_proxy_type, request);
1687 request->server = old_server;
1689 rcode = module_post_proxy(post_proxy_type, request);
1693 if (request->packet->code == request->proxy->code)
1695 * Don't run the next bit if we originated a CoA
1696 * packet, after receiving an Access-Request or
1697 * Accounting-Request.
1702 * There may NOT be a proxy reply, as we may be
1703 * running Post-Proxy-Type = Fail.
1705 if (request->proxy_reply) {
1707 * Delete the Proxy-State Attributes from
1708 * the reply. These include Proxy-State
1709 * attributes from us and remote server.
1711 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1714 * Add the attributes left in the proxy
1715 * reply to the reply list.
1717 pairadd(&request->reply->vps, request->proxy_reply->vps);
1718 request->proxy_reply->vps = NULL;
1721 * Free proxy request pairs.
1723 pairfree(&request->proxy->vps);
1727 default: /* Don't do anything */
1729 case RLM_MODULE_FAIL:
1730 /* FIXME: debug print stuff */
1731 request->child_state = REQUEST_DONE;
1734 case RLM_MODULE_HANDLED:
1735 /* FIXME: debug print stuff */
1736 request->child_state = REQUEST_DONE;
1744 static int request_pre_handler(REQUEST *request)
1748 rad_assert(request->magic == REQUEST_MAGIC);
1749 rad_assert(request->packet != NULL);
1751 request->child_state = REQUEST_RUNNING;
1754 * Don't decode the packet if it's an internal "fake"
1755 * request. Instead, just return so that the caller can
1758 if (request->packet->dst_port == 0) {
1759 request->username = pairfind(request->packet->vps,
1761 request->password = pairfind(request->packet->vps,
1768 * Put the decoded packet into it's proper place.
1770 if (request->proxy_reply != NULL) {
1771 rcode = request->proxy_listener->decode(request->proxy_listener,
1773 DEBUG_PACKET(request, request->proxy_reply, 0);
1776 if (request->packet->vps == NULL) {
1777 rcode = request->listener->decode(request->listener, request);
1779 if (debug_condition) {
1781 const char *my_debug = debug_condition;
1784 * Ignore parse errors.
1786 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1790 request->options = 2;
1791 request->radlog = radlog_request;
1795 DEBUG_PACKET(request, request->packet, 0);
1801 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1802 request->child_state = REQUEST_DONE;
1806 if (!request->username) {
1807 request->username = pairfind(request->packet->vps,
1812 if (request->proxy) {
1813 return process_proxy_reply(request);
1823 * Do state handling when we proxy a request.
1825 static int proxy_request(REQUEST *request)
1827 struct timeval when;
1830 if (request->home_server->server) {
1831 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1835 if (!insert_into_proxy_hash(request, FALSE)) {
1836 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1840 request->proxy_listener->encode(request->proxy_listener, request);
1842 when = request->received;
1843 when.tv_sec += request->root->max_request_time;
1845 gettimeofday(&request->proxy_when, NULL);
1847 request->next_when = request->proxy_when;
1848 request->next_when.tv_sec += request->home_server->response_window;
1850 rad_assert(request->home_server->response_window > 0);
1852 if (timercmp(&when, &request->next_when, <)) {
1853 request->next_when = when;
1855 request->next_callback = no_response_to_proxied_request;
1857 RDEBUG2("Proxying request %d to home server %s port %d",
1859 inet_ntop(request->proxy->dst_ipaddr.af,
1860 &request->proxy->dst_ipaddr.ipaddr,
1861 buffer, sizeof(buffer)),
1862 request->proxy->dst_port);
1865 * Note that we set proxied BEFORE sending the packet.
1867 * Once we send it, the request is tainted, as
1868 * another thread may have picked it up. Don't
1871 request->num_proxied_requests = 1;
1872 request->num_proxied_responses = 0;
1873 #ifdef HAVE_PTHREAD_H
1874 request->child_pid = NO_SUCH_CHILD_PID;
1876 request->child_state = REQUEST_PROXIED;
1878 DEBUG_PACKET(request, request->proxy, 1);
1880 request->proxy_listener->send(request->proxy_listener,
1887 * "Proxy" the request by sending it to a new virtual server.
1889 static int proxy_to_virtual_server(REQUEST *request)
1892 RAD_REQUEST_FUNP fun;
1894 if (!request->home_server || !request->home_server->server) return 0;
1896 if (request->parent) {
1897 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1901 fake = request_alloc_fake(request);
1903 RDEBUG2("WARNING: Out of memory");
1907 fake->packet->vps = paircopy(request->proxy->vps);
1908 fake->server = request->home_server->server;
1910 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1911 fun = rad_authenticate;
1913 #ifdef WITH_ACCOUNTING
1914 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1915 fun = rad_accounting;
1919 RDEBUG2("Unknown packet type %d", request->proxy->code);
1920 ev_request_free(&fake);
1924 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1925 radius_handle_request(fake, fun);
1926 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1928 if (fake->reply->code != 0) {
1929 request->proxy_reply = fake->reply;
1933 * There was no response
1935 setup_post_proxy_fail(request);
1938 ev_request_free(&fake);
1940 process_proxy_reply(request);
1943 * Process it through the normal section again, but ONLY
1944 * if we received a proxy reply..
1946 if (request->proxy_reply) {
1947 if (request->server) RDEBUG("server %s {",
1948 request->server != NULL ?
1949 request->server : "");
1952 if (request->server) RDEBUG("} # server %s",
1953 request->server != NULL ?
1954 request->server : "");
1957 return 2; /* success, but NOT '1' !*/
1961 * Return 1 if we did proxy it, or the proxy attempt failed
1962 * completely. Either way, the caller doesn't touch the request
1963 * any more if we return 1.
1965 static int successfully_proxied_request(REQUEST *request)
1968 int pre_proxy_type = 0;
1969 VALUE_PAIR *realmpair;
1970 VALUE_PAIR *strippedname;
1972 char *realmname = NULL;
1974 REALM *realm = NULL;
1978 * If it was already proxied, do nothing.
1980 * FIXME: This should really be a serious error.
1982 if (request->in_proxy_hash ||
1983 (request->proxy_reply && (request->proxy_reply->code != 0))) {
1987 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1988 if (!realmpair || (realmpair->length == 0)) {
1991 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
1994 switch (request->packet->code) {
1995 case PW_AUTHENTICATION_REQUEST:
1996 pool_type = HOME_TYPE_AUTH;
1999 #ifdef WITH_ACCOUNTING
2000 case PW_ACCOUNTING_REQUEST:
2001 pool_type = HOME_TYPE_ACCT;
2006 case PW_COA_REQUEST:
2007 case PW_DISCONNECT_REQUEST:
2008 pool_type = HOME_TYPE_COA;
2016 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2018 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2023 realmname = NULL; /* no realms */
2028 realmname = (char *) realmpair->vp_strvalue;
2030 realm = realm_find2(realmname);
2032 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2037 * Figure out which pool to use.
2039 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2040 pool = realm->auth_pool;
2042 #ifdef WITH_ACCOUNTING
2043 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2044 pool = realm->acct_pool;
2048 } else if ((request->packet->code == PW_COA_REQUEST) ||
2049 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2050 pool = realm->acct_pool;
2054 rad_panic("Internal sanity check failed");
2058 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2064 home = home_server_ldb(realmname, pool, request);
2066 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2070 request->home_pool = pool;
2074 * Once we've decided to proxy a request, we cannot send
2075 * a CoA packet. So we free up any CoA packet here.
2077 ev_request_free(&request->coa);
2080 * Remember that we sent the request to a Realm.
2082 if (realmname) pairadd(&request->packet->vps,
2083 pairmake("Realm", realmname, T_OP_EQ));
2086 * Strip the name, if told to.
2088 * Doing it here catches the case of proxied tunneled
2091 if (realm && (realm->striprealm == TRUE) &&
2092 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2094 * If there's a Stripped-User-Name attribute in
2095 * the request, then use THAT as the User-Name
2096 * for the proxied request, instead of the
2099 * This is done by making a copy of the
2100 * Stripped-User-Name attribute, turning it into
2101 * a User-Name attribute, deleting the
2102 * Stripped-User-Name and User-Name attributes
2103 * from the vps list, and making the new
2104 * User-Name the head of the vps list.
2106 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2108 vp = radius_paircreate(request, NULL,
2109 PW_USER_NAME, PW_TYPE_STRING);
2110 rad_assert(vp != NULL); /* handled by above function */
2111 /* Insert at the START of the list */
2112 vp->next = request->proxy->vps;
2113 request->proxy->vps = vp;
2115 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2116 sizeof(vp->vp_strvalue));
2117 vp->length = strippedname->length;
2120 * Do NOT delete Stripped-User-Name.
2125 * If there is no PW_CHAP_CHALLENGE attribute but
2126 * there is a PW_CHAP_PASSWORD we need to add it
2127 * since we can't use the request authenticator
2128 * anymore - we changed it.
2130 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2131 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2132 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2133 vp = radius_paircreate(request, &request->proxy->vps,
2134 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2135 vp->length = AUTH_VECTOR_LEN;
2136 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2140 * The RFC's say we have to do this, but FreeRADIUS
2143 vp = radius_paircreate(request, &request->proxy->vps,
2144 PW_PROXY_STATE, PW_TYPE_OCTETS);
2145 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2146 request->packet->id);
2147 vp->length = strlen(vp->vp_strvalue);
2150 * Should be done BEFORE inserting into proxy hash, as
2151 * pre-proxy may use this information, or change it.
2153 request->proxy->code = request->packet->code;
2156 * Call the pre-proxy routines.
2158 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2160 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2161 pre_proxy_type = vp->vp_integer;
2164 rad_assert(request->home_pool != NULL);
2166 if (request->home_pool->virtual_server) {
2167 const char *old_server = request->server;
2169 request->server = request->home_pool->virtual_server;
2170 RDEBUG2(" server %s {", request->server);
2171 rcode = module_pre_proxy(pre_proxy_type, request);
2173 request->server = old_server;
2175 rcode = module_pre_proxy(pre_proxy_type, request);
2178 case RLM_MODULE_FAIL:
2179 case RLM_MODULE_INVALID:
2180 case RLM_MODULE_NOTFOUND:
2181 case RLM_MODULE_USERLOCK:
2183 /* FIXME: debug print failed stuff */
2186 case RLM_MODULE_REJECT:
2187 case RLM_MODULE_HANDLED:
2191 * Only proxy the packet if the pre-proxy code succeeded.
2193 case RLM_MODULE_NOOP:
2195 case RLM_MODULE_UPDATED:
2200 * If it's a fake request, don't send the proxy
2201 * packet. The outer tunnel session will take
2202 * care of doing that.
2204 if (request->packet->dst_port == 0) {
2205 request->home_server = NULL;
2209 if (request->home_server->server) {
2210 return proxy_to_virtual_server(request);
2213 if (!proxy_request(request)) {
2214 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2222 static void request_post_handler(REQUEST *request)
2224 int child_state = -1;
2225 struct timeval when;
2228 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2230 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2231 RDEBUG2("Request %d was cancelled.", request->number);
2232 #ifdef HAVE_PTHREAD_H
2233 request->child_pid = NO_SUCH_CHILD_PID;
2235 child_state = REQUEST_DONE;
2239 if (request->child_state != REQUEST_RUNNING) {
2240 rad_panic("Internal sanity check failed");
2245 * If it's not in the request hash, it's a CoA request.
2248 if (!request->in_request_hash &&
2250 ((request->proxy->code == PW_COA_REQUEST) ||
2251 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2252 request->next_callback = NULL;
2253 child_state = REQUEST_DONE;
2259 * Catch Auth-Type := Reject BEFORE proxying the packet.
2261 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2262 (request->reply->code == 0) &&
2263 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2264 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2265 request->reply->code = PW_AUTHENTICATION_REJECT;
2269 if (request->root->proxy_requests &&
2270 !request->in_proxy_hash &&
2271 (request->reply->code == 0) &&
2272 (request->packet->dst_port != 0) &&
2273 (request->packet->code != PW_STATUS_SERVER)) {
2274 int rcode = successfully_proxied_request(request);
2276 if (rcode == 1) return; /* request is invalid */
2279 * Failed proxying it (dead home servers, etc.)
2280 * Run it through Post-Proxy-Type = Fail, and
2281 * respond to the request.
2283 * Note that we're in a child thread here, so we
2284 * do NOT re-schedule the request. Instead, we
2285 * do what we would have done, which is run the
2286 * pre-handler, a NULL request handler, and then
2289 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2290 request_pre_handler(request);
2294 * Else we weren't supposed to proxy it,
2295 * OR we proxied it internally to a virutal server.
2301 * Fake requests don't get encoded or signed. The caller
2302 * also requires the reply VP's, so we don't free them
2305 if (request->packet->dst_port == 0) {
2306 /* FIXME: RDEBUG going to the next request */
2307 #ifdef HAVE_PTHREAD_H
2308 request->child_pid = NO_SUCH_CHILD_PID;
2310 request->child_state = REQUEST_DONE;
2316 * Copy Proxy-State from the request to the reply.
2318 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2319 if (vp) pairadd(&request->reply->vps, vp);
2323 * Access-Requests get delayed or cached.
2325 switch (request->packet->code) {
2326 case PW_AUTHENTICATION_REQUEST:
2327 gettimeofday(&request->next_when, NULL);
2329 if (request->reply->code == 0) {
2331 * Check if the lack of response is intentional.
2333 vp = pairfind(request->config_items,
2334 PW_RESPONSE_PACKET_TYPE);
2336 RDEBUG2("There was no response configured: rejecting request %d",
2338 request->reply->code = PW_AUTHENTICATION_REJECT;
2340 } else if (vp->vp_integer == 256) {
2341 RDEBUG2("Not responding to request %d",
2345 * Force cleanup after a long
2346 * time, so that we don't
2347 * re-process the packet.
2349 request->next_when.tv_sec += request->root->max_request_time;
2350 request->next_callback = cleanup_delay;
2351 child_state = REQUEST_CLEANUP_DELAY;
2354 request->reply->code = vp->vp_integer;
2360 * Run rejected packets through
2362 * Post-Auth-Type = Reject
2364 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2365 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2366 vp = radius_pairmake(request, &request->config_items,
2367 "Post-Auth-Type", "Reject",
2369 if (vp) rad_postauth(request);
2372 * If configured, delay Access-Reject packets.
2374 * If request->root->reject_delay = 0, we discover
2375 * that we have to send the packet now.
2377 when = request->received;
2378 when.tv_sec += request->root->reject_delay;
2380 if (timercmp(&when, &request->next_when, >)) {
2381 RDEBUG2("Delaying reject of request %d for %d seconds",
2383 request->root->reject_delay);
2384 request->next_when = when;
2385 request->next_callback = reject_delay;
2386 #ifdef HAVE_PTHREAD_H
2387 request->child_pid = NO_SUCH_CHILD_PID;
2389 request->child_state = REQUEST_REJECT_DELAY;
2395 case PW_COA_REQUEST:
2396 case PW_DISCONNECT_REQUEST:
2398 request->next_when.tv_sec += request->root->cleanup_delay;
2399 request->next_callback = cleanup_delay;
2400 child_state = REQUEST_CLEANUP_DELAY;
2403 case PW_ACCOUNTING_REQUEST:
2404 request->next_callback = NULL; /* just to be safe */
2405 child_state = REQUEST_DONE;
2409 * FIXME: Status-Server should probably not be
2412 case PW_STATUS_SERVER:
2413 request->next_callback = NULL;
2414 child_state = REQUEST_DONE;
2421 request->next_callback = NULL;
2422 child_state = REQUEST_DONE;
2427 * Suppress "no reply" packets here, unless we're reading
2428 * from the "detail" file. In that case, we've got to
2429 * tell the detail file handler that the request is dead,
2430 * and it should re-send it.
2431 * If configured, encode, sign, and send.
2433 if ((request->reply->code != 0) ||
2434 (request->listener->type == RAD_LISTEN_DETAIL)) {
2435 DEBUG_PACKET(request, request->reply, 1);
2436 request->listener->send(request->listener, request);
2441 * Now that we've completely processed the request,
2442 * see if we need to originate a CoA request.
2445 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2446 if (!originated_coa_request(request)) {
2447 RDEBUG2("Do CoA Fail handler here");
2449 /* request->coa is stil set, so we can update events */
2455 * Clean up. These are no longer needed.
2457 pairfree(&request->config_items);
2459 pairfree(&request->packet->vps);
2460 request->username = NULL;
2461 request->password = NULL;
2463 pairfree(&request->reply->vps);
2466 if (request->proxy) {
2467 pairfree(&request->proxy->vps);
2469 if (request->proxy_reply) {
2470 pairfree(&request->proxy_reply->vps);
2475 * We're not tracking responses from the home
2476 * server, we can therefore free this memory in
2479 if (!request->in_proxy_hash) {
2480 rad_free(&request->proxy);
2481 rad_free(&request->proxy_reply);
2482 request->home_server = NULL;
2488 RDEBUG2("Finished request %d.", request->number);
2489 rad_assert(child_state >= 0);
2490 request->child_state = child_state;
2493 * Single threaded mode: update timers now.
2495 if (!have_children) wait_a_bit(request);
2499 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2505 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2506 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2508 switch (request->child_state) {
2509 case REQUEST_QUEUED:
2510 case REQUEST_RUNNING:
2514 radlog(L_ERR, "Discarding duplicate request from "
2515 "client %s port %d - ID: %d due to unfinished request %d",
2517 request->packet->src_port,request->packet->id,
2522 case REQUEST_PROXIED:
2524 * We're not supposed to have duplicate
2525 * accounting packets. The other states handle
2526 * duplicates fine (discard, or send duplicate
2527 * reply). But we do NOT want to retransmit an
2528 * accounting request here, because that would
2529 * involve updating the Acct-Delay-Time, and
2530 * therefore changing the packet Id, etc.
2532 * Instead, we just discard the packet. We may
2533 * eventually respond, or the client will send a
2534 * new accounting packet.
2536 * The same comments go for Status-Server, and
2537 * other packet types.
2539 * FIXME: coa: when we proxy CoA && Disconnect
2540 * packets, this logic has to be fixed.
2542 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2546 check_for_zombie_home_server(request);
2549 * If we've just discovered that the home server
2550 * is dead, OR the socket has been closed, look for
2551 * another connection to a home server.
2553 if (((request->packet->dst_port != 0) &&
2554 (request->home_server->state == HOME_STATE_IS_DEAD)) ||
2555 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
2558 remove_from_proxy_hash(request);
2560 home = home_server_ldb(NULL, request->home_pool, request);
2562 RDEBUG2("Failed to find live home server for request %d", request->number);
2565 * Do post-request processing,
2566 * and any insertion of necessary
2569 post_proxy_fail_handler(request);
2573 request->proxy->code = request->packet->code;
2576 * Free the old packet, to force re-encoding
2578 free(request->proxy->data);
2579 request->proxy->data = NULL;
2580 request->proxy->data_len = 0;
2583 * This request failed over to a virtual
2584 * server. Push it back onto the queue
2587 if (request->home_server->server) {
2588 proxy_fallback_handler(request);
2593 * Try to proxy the request.
2595 if (!proxy_request(request)) {
2596 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2597 goto no_home_servers;
2601 * This code executes in the main server
2602 * thread, so there's no need for locking.
2604 rad_assert(request->next_callback != NULL);
2605 INSERT_EVENT(request->next_callback, request);
2606 request->next_callback = NULL;
2608 } /* else the home server is still alive */
2610 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2611 inet_ntop(request->proxy->dst_ipaddr.af,
2612 &request->proxy->dst_ipaddr.ipaddr,
2613 buffer, sizeof(buffer)),
2614 request->proxy->dst_port,
2615 request->proxy->id);
2616 request->num_proxied_requests++;
2618 DEBUG_PACKET(request, request->proxy, 1);
2619 request->proxy_listener->send(request->proxy_listener,
2624 case REQUEST_REJECT_DELAY:
2625 RDEBUG2("Waiting to send Access-Reject "
2626 "to client %s port %d - ID: %d",
2628 request->packet->src_port, request->packet->id);
2631 case REQUEST_CLEANUP_DELAY:
2633 if (request->reply->code == 0) {
2634 RDEBUG2("Ignoring retransmit from client %s port %d "
2635 "- ID: %d, no reply was configured",
2637 request->packet->src_port, request->packet->id);
2642 * FIXME: This sends duplicate replies to
2643 * accounting requests, even if Acct-Delay-Time
2644 * or Event-Timestamp is in the packet. In those
2645 * cases, the Id should be changed, and the packet
2648 RDEBUG2("Sending duplicate reply "
2649 "to client %s port %d - ID: %d",
2651 request->packet->src_port, request->packet->id);
2652 DEBUG_PACKET(request, request->reply, 1);
2653 request->listener->send(request->listener, request);
2659 static void received_conflicting_request(REQUEST *request,
2660 const RADCLIENT *client)
2662 radlog(L_ERR, "Received conflicting packet from "
2663 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
2665 request->packet->src_port, request->packet->id,
2669 * Nuke it from the request hash, so we can receive new
2672 remove_from_request_hash(request);
2674 switch (request->child_state) {
2675 #ifdef HAVE_PTHREAD_H
2677 * It's queued or running. Tell it to stop, and
2678 * wait for it to do so.
2680 case REQUEST_QUEUED:
2681 case REQUEST_RUNNING:
2682 request->master_state = REQUEST_STOP_PROCESSING;
2683 request->delay += request->delay >> 1;
2685 tv_add(&request->when, request->delay);
2687 INSERT_EVENT(wait_for_child_to_die, request);
2692 * Catch race conditions. It may have switched
2693 * from running to done while this code is being
2696 case REQUEST_REJECT_DELAY:
2697 case REQUEST_CLEANUP_DELAY:
2702 * It's in some other state, and therefore also
2703 * in the event queue. At some point, the
2704 * child will notice, and we can then delete it.
2706 case REQUEST_PROXIED:
2708 rad_assert(request->ev != NULL);
2714 static int can_handle_new_request(RADIUS_PACKET *packet,
2716 struct main_config_t *root)
2719 * Count the total number of requests, to see if
2720 * there are too many. If so, return with an
2723 if (root->max_requests) {
2724 int request_count = fr_packet_list_num_elements(pl);
2727 * This is a new request. Let's see if
2728 * it makes us go over our configured
2731 if (request_count > root->max_requests) {
2732 radlog(L_ERR, "Dropping request (%d is too many): "
2733 "from client %s port %d - ID: %d", request_count,
2735 packet->src_port, packet->id);
2736 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2737 "\tThe value for 'max_requests' is probably set too low.\n");
2739 } /* else there were a small number of requests */
2740 } /* else there was no configured limit for requests */
2743 * FIXME: Add per-client checks. If one client is sending
2744 * too many packets, start discarding them.
2746 * We increment the counters here, and decrement them
2747 * when the response is sent... somewhere in this file.
2751 * FUTURE: Add checks for system load. If the system is
2752 * busy, start dropping requests...
2754 * We can probably keep some statistics ourselves... if
2755 * there are more requests coming in than we can handle,
2756 * start dropping some.
2763 int received_request(rad_listen_t *listener,
2764 RADIUS_PACKET *packet, REQUEST **prequest,
2767 RADIUS_PACKET **packet_p;
2768 REQUEST *request = NULL;
2769 struct main_config_t *root = &mainconfig;
2771 packet_p = fr_packet_list_find(pl, packet);
2773 request = fr_packet2myptr(REQUEST, packet, packet_p);
2774 rad_assert(request->in_request_hash);
2776 if ((request->packet->data_len == packet->data_len) &&
2777 (memcmp(request->packet->vector, packet->vector,
2778 sizeof(packet->vector)) == 0)) {
2779 received_retransmit(request, client);
2784 * The new request is different from the old one,
2785 * but maybe the old is finished. If so, delete
2788 switch (request->child_state) {
2789 struct timeval when;
2793 * Special hacks for race conditions.
2794 * The reply is encoded, and therefore
2795 * likely sent. We received a *new*
2796 * packet from the client, likely before
2797 * the next line or two of code which
2798 * updated the child state. In this
2799 * case, just accept the new request.
2801 if ((request->reply->code != 0) &&
2802 request->reply->data) {
2803 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2805 packet->src_port, packet->id,
2807 remove_from_request_hash(request);
2812 gettimeofday(&when, NULL);
2816 * If the cached request was received
2817 * within the last second, then we
2818 * discard the NEW request instead of the
2819 * old one. This will happen ONLY when
2820 * the client is severely broken, and is
2821 * sending conflicting packets very
2824 if (timercmp(&when, &request->received, <)) {
2825 radlog(L_ERR, "Discarding conflicting packet from "
2826 "client %s port %d - ID: %d due to recent request %d.",
2828 packet->src_port, packet->id,
2833 received_conflicting_request(request, client);
2837 case REQUEST_REJECT_DELAY:
2838 case REQUEST_CLEANUP_DELAY:
2839 request->child_state = REQUEST_DONE;
2841 cleanup_delay(request);
2848 * We may want to quench the new request.
2850 if ((listener->type != RAD_LISTEN_DETAIL) &&
2851 !can_handle_new_request(packet, client, root)) {
2856 * Create and initialize the new request.
2858 request = request_alloc(); /* never fails */
2860 if ((request->reply = rad_alloc(0)) == NULL) {
2861 radlog(L_ERR, "No memory");
2865 request->listener = listener;
2866 request->client = client;
2867 request->packet = packet;
2868 request->packet->timestamp = request->timestamp;
2869 request->number = request_num_counter++;
2870 request->priority = listener->type;
2871 #ifdef HAVE_PTHREAD_H
2872 request->child_pid = NO_SUCH_CHILD_PID;
2876 * Status-Server packets go to the head of the queue.
2878 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2881 * Set virtual server identity
2883 if (client->server) {
2884 request->server = client->server;
2885 } else if (listener->server) {
2886 request->server = listener->server;
2888 request->server = NULL;
2892 * Remember the request in the list.
2894 if (!fr_packet_list_insert(pl, &request->packet)) {
2895 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2896 ev_request_free(&request);
2900 request->in_request_hash = TRUE;
2901 request->root = root;
2904 request->listener->count++;
2908 * The request passes many of our sanity checks.
2909 * From here on in, if anything goes wrong, we
2910 * send a reject message, instead of dropping the
2915 * Build the reply template from the request.
2918 request->reply->sockfd = request->packet->sockfd;
2919 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2920 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2921 request->reply->dst_port = request->packet->src_port;
2922 request->reply->src_port = request->packet->dst_port;
2923 request->reply->id = request->packet->id;
2924 request->reply->code = 0; /* UNKNOWN code */
2925 memcpy(request->reply->vector, request->packet->vector,
2926 sizeof(request->reply->vector));
2927 request->reply->vps = NULL;
2928 request->reply->data = NULL;
2929 request->reply->data_len = 0;
2931 request->master_state = REQUEST_ACTIVE;
2932 request->child_state = REQUEST_QUEUED;
2933 request->next_callback = NULL;
2935 gettimeofday(&request->received, NULL);
2936 request->timestamp = request->received.tv_sec;
2937 request->when = request->received;
2939 request->delay = USEC;
2941 tv_add(&request->when, request->delay);
2943 INSERT_EVENT(wait_a_bit, request);
2945 *prequest = request;
2951 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2957 * Also removes from the proxy hash if responses == requests
2959 request = lookup_in_proxy_hash(packet);
2962 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2963 inet_ntop(packet->src_ipaddr.af,
2964 &packet->src_ipaddr.ipaddr,
2965 buffer, sizeof(buffer)),
2966 packet->src_port, packet->id);
2971 * We haven't replied to the NAS, but we have seen an
2972 * earlier reply from the home server. Ignore this packet,
2973 * as we're likely still processing the previous reply.
2975 if (request->proxy_reply) {
2976 if (memcmp(request->proxy_reply->vector,
2978 sizeof(request->proxy_reply->vector)) == 0) {
2979 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %d",
2980 inet_ntop(packet->src_ipaddr.af,
2981 &packet->src_ipaddr.ipaddr,
2982 buffer, sizeof(buffer)),
2983 packet->src_port, packet->id,
2987 * ? The home server gave us a new proxy
2988 * reply which doesn't match the old
2991 RDEBUG2("Ignoring conflicting proxy reply");
2994 /* assert that there's an event queued for request? */
2999 * Verify the packet before doing ANYTHING with it. This
3000 * means we're doing more MD5 checks in the server core.
3001 * However, we can fix that by moving to multiple threads
3002 * listening on sockets.
3004 * We do this AFTER looking the request up in the hash,
3005 * and AFTER vhecking if we saw a previous request. This
3006 * helps minimize the DoS effect of people attacking us
3007 * with spoofed packets.
3009 if (rad_verify(packet, request->proxy,
3010 request->home_server->secret) != 0) {
3011 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3015 gettimeofday(&now, NULL);
3018 * Maybe move this earlier in the decision process?
3019 * Having it here means that late or duplicate proxy
3020 * replies no longer get the home server marked as
3021 * "alive". This might be good for stability, though.
3023 * FIXME: Do we really want to do this whenever we
3024 * receive a packet? Setting this here means that we
3025 * mark it alive on *any* packet, even if it's lost all
3026 * of the *other* packets in the last 10s.
3028 request->home_server->state = HOME_STATE_ALIVE;
3032 * When originating CoA, the "proxy" reply is the reply
3033 * to the CoA request that we originated. At this point,
3034 * the original request is finished, and it has a reply.
3036 * However, if we haven't separated the two requests, do
3037 * so now. This is done so that cleaning up the original
3038 * request won't cause the CoA request to be free'd. See
3039 * util.c, request_free()
3041 if (request->parent && (request->parent->coa == request)) {
3042 request->parent->coa = NULL;
3043 request->parent = NULL;
3047 * Skip the next set of checks, as the original
3048 * reply is cached. We want to be able to still
3049 * process the CoA reply, AND to reference the
3050 * original request/reply.
3052 * This is getting to be really quite a bit of a
3058 * If there's a reply to the NAS, ignore everything
3059 * related to proxy responses
3061 if (request->reply && request->reply->code != 0) {
3062 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3068 * The average includes our time to receive packets and
3069 * look them up in the hashes, which should be the same
3072 * We update the response time only for the FIRST packet
3075 if (request->home_server->ema.window > 0) {
3076 radius_stats_ema(&request->home_server->ema,
3077 &now, &request->proxy_when);
3081 switch (request->child_state) {
3082 case REQUEST_QUEUED:
3083 case REQUEST_RUNNING:
3084 radlog(L_ERR, "Internal sanity check failed for child state");
3087 case REQUEST_REJECT_DELAY:
3088 case REQUEST_CLEANUP_DELAY:
3090 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'",
3091 inet_ntop(packet->src_ipaddr.af,
3092 &packet->src_ipaddr.ipaddr,
3093 buffer, sizeof(buffer)),
3094 packet->src_port, packet->id,
3096 /* assert that there's an event queued for request? */
3099 case REQUEST_PROXIED:
3103 request->proxy_reply = packet;
3107 * Perform RTT calculations, as per RFC 2988 (for TCP).
3108 * Note that we only do so on the first response.
3110 if ((request->num_proxied_responses == 1)
3112 home_server *home = request->home_server;
3114 rtt = now.tv_sec - request->proxy_when.tv_sec;
3117 rtt -= request->proxy_when.tv_usec;
3119 if (!home->has_rtt) {
3120 home->has_rtt = TRUE;
3123 home->rttvar = rtt / 2;
3126 home->rttvar -= home->rttvar >> 2;
3127 home->rttvar += (home->srtt - rtt);
3128 home->srtt -= home->srtt >> 3;
3129 home->srtt += rtt >> 3;
3132 home->rto = home->srtt;
3133 if (home->rttvar > (USEC / 4)) {
3134 home->rto += home->rttvar * 4;
3142 * There's no incoming request, so it's a proxied packet
3145 if (!request->packet) {
3146 received_response_to_ping(request);
3147 request->proxy_reply = NULL; /* caller will free it */
3148 ev_request_free(&request);
3152 request->child_state = REQUEST_QUEUED;
3153 request->when = now;
3154 request->delay = USEC;
3155 request->priority = RAD_LISTEN_PROXY;
3156 tv_add(&request->when, request->delay);
3159 * Wait a bit will take care of max_request_time
3161 INSERT_EVENT(wait_a_bit, request);
3167 void event_new_fd(rad_listen_t *this)
3171 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3173 this->print(this, buffer, sizeof(buffer));
3175 if (this->status == RAD_LISTEN_STATUS_INIT) {
3177 DEBUG("Listening on %s", buffer);
3179 DEBUG2(" ... adding new socket %s", buffer);
3181 if (!fr_event_fd_insert(el, 0, this->fd,
3182 event_socket_handler, this)) {
3183 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3187 this->status = RAD_LISTEN_STATUS_KNOWN;
3191 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3192 DEBUG2(" ... closing socket %s", buffer);
3194 fr_event_fd_delete(el, 0, this->fd);
3195 this->status = RAD_LISTEN_STATUS_FINISH;
3198 * Close the fd AFTER fixing up the requests and
3199 * listeners, so that they don't send/recv on the
3200 * wrong socket (if someone manages to open
3208 static void handle_signal_self(int flag)
3210 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3211 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3212 fr_event_loop_exit(el, 1);
3214 fr_event_loop_exit(el, 2);
3218 } /* else exit/term flags weren't set */
3221 * Tell the even loop to stop processing.
3223 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3225 static time_t last_hup = 0;
3227 DEBUG("Received HUP signal.");
3230 if ((int) (when - last_hup) < 5) {
3231 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3236 fr_event_loop_exit(el, 0x80);
3240 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3244 * FIXME: O(N) loops suck.
3246 for (this = mainconfig.listen;
3248 this = this->next) {
3249 if (this->type != RAD_LISTEN_DETAIL) continue;
3252 * This one didn't send the signal, skip
3255 if (!this->decode(this, NULL)) continue;
3258 * Go service the interrupt.
3260 event_poll_detail(this);
3265 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3268 for (this = mainconfig.listen;
3270 this = this->next) {
3276 #ifndef WITH_SELF_PIPE
3277 void radius_signal_self(int flag)
3279 handle_signal_self(flag);
3283 * Inform ourselves that we received a signal.
3285 void radius_signal_self(int flag)
3291 * The read MUST be non-blocking for this to work.
3293 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3297 for (i = 0; i < rcode; i++) {
3298 buffer[0] |= buffer[i];
3306 write(self_pipe[1], buffer, 1);
3310 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3311 UNUSED int fd, UNUSED void *ctx)
3316 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3317 if (rcode <= 0) return;
3320 * Merge pending signals.
3322 for (i = 0; i < rcode; i++) {
3323 buffer[0] |= buffer[i];
3326 handle_signal_self(buffer[0]);
3331 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3334 rad_listen_t *listener = ctx;
3335 RAD_REQUEST_FUNP fun;
3338 rad_assert(xel == el);
3342 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3344 if (!listener->recv(listener, &fun, &request)) return;
3346 if (!thread_pool_addrequest(request, fun)) {
3347 request->child_state = REQUEST_DONE;
3351 typedef struct listen_detail_t {
3356 * This function is called periodically to see if this detail
3357 * file is available for reading.
3359 static void event_poll_detail(void *ctx)
3362 RAD_REQUEST_FUNP fun;
3364 rad_listen_t *this = ctx;
3365 struct timeval when;
3366 listen_detail_t *detail = this->data;
3368 rad_assert(this->type == RAD_LISTEN_DETAIL);
3371 * Try to read something.
3373 * FIXME: This does poll AND receive.
3375 rcode = this->recv(this, &fun, &request);
3377 rad_assert(fun != NULL);
3378 rad_assert(request != NULL);
3380 if (!thread_pool_addrequest(request, fun)) {
3381 request->child_state = REQUEST_DONE;
3385 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3389 * Backdoor API to get the delay until the next poll
3392 delay = this->encode(this, NULL);
3393 tv_add(&when, delay);
3395 if (!fr_event_insert(el, event_poll_detail, this,
3396 &when, &detail->ev)) {
3397 radlog(L_ERR, "Failed creating handler");
3403 static void event_status(struct timeval *wake)
3405 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3409 if (debug_flag == 0) {
3411 radlog(L_INFO, "Ready to process requests.");
3412 just_started = FALSE;
3418 DEBUG("Ready to process requests.");
3420 } else if ((wake->tv_sec != 0) ||
3421 (wake->tv_usec >= 100000)) {
3422 DEBUG("Waking up in %d.%01u seconds.",
3423 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3428 * FIXME: Put this somewhere else, where it isn't called
3429 * all of the time...
3432 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3434 * If there are no child threads, then there may
3435 * be child processes. In that case, wait for
3436 * their exit status, and throw that exit status
3437 * away. This helps get rid of zxombie children.
3439 while (waitpid(-1, &argval, WNOHANG) > 0) {
3447 * Externally-visibly functions.
3449 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3451 rad_listen_t *this, *head = NULL;
3455 time(&fr_start_time);
3457 el = fr_event_list_create(event_status);
3460 pl = fr_packet_list_create(0);
3461 if (!pl) return 0; /* leak el */
3463 request_num_counter = 0;
3466 if (mainconfig.proxy_requests) {
3467 pthread_mutexattr_t attr;
3470 * Create the tree for managing proxied requests and
3473 proxy_list = fr_packet_list_create(1);
3474 if (!proxy_list) return 0;
3476 #ifdef HAVE_PTHREAD_H
3477 pthread_mutexattr_init(&attr);
3479 #ifdef PTHREAD_MUTEX_RECURSIVE
3480 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) < 0) {
3481 radlog(L_ERR, "FATAL: Failed to set type for proxy mutex: %s",
3487 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3488 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3493 pthread_mutexattr_destroy(&attr);
3499 * Just before we spawn the child threads, force the log
3500 * subsystem to re-open the log file for every write.
3502 if (spawn_flag) force_log_reopen();
3504 #ifdef HAVE_PTHREAD_H
3506 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3508 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3511 * Initialize the threads ONLY if we're spawning, AND
3512 * we're running normally.
3514 if (spawn_flag && !check_config &&
3515 (thread_pool_init(cs, &spawn_flag) < 0)) {
3521 * Move all of the thread calls to this file?
3523 * It may be best for the mutexes to be in this file...
3525 have_children = spawn_flag;
3528 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3533 #ifdef WITH_SELF_PIPE
3535 * Child threads need a pipe to signal us, as do the
3538 if (pipe(self_pipe) < 0) {
3539 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3543 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3544 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3548 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3549 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3554 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3555 event_signal_handler, el)) {
3556 radlog(L_ERR, "Failed creating handler for signals");
3559 #endif /* WITH_SELF_PIPE */
3563 * Mark the proxy Fd's as unused.
3568 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3572 DEBUG("%s: #### Opening IP addresses and Ports ####",
3576 * The server temporarily switches to an unprivileged
3577 * user very early in the bootstrapping process.
3578 * However, some sockets MAY require privileged access
3579 * (bind to device, or to port < 1024, or to raw
3580 * sockets). Those sockets need to call suid up/down
3581 * themselves around the functions that need a privileged
3584 if (listen_init(cs, &head) < 0) {
3589 * At this point, no one has any business *ever* going
3592 fr_suid_down_permanent();
3595 * Add all of the sockets to the event loop.
3599 this = this->next) {
3602 this->print(this, buffer, sizeof(buffer));
3604 switch (this->type) {
3606 case RAD_LISTEN_DETAIL:
3607 DEBUG("Listening on %s", buffer);
3610 * Detail files are always known, and aren't
3611 * put into the socket event loop.
3613 this->status = RAD_LISTEN_STATUS_KNOWN;
3616 * Set up the first poll interval.
3618 event_poll_detail(this);
3623 case RAD_LISTEN_PROXY:
3624 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3625 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3627 proxy_fds[this->fd & 0x1f] = this->fd;
3628 proxy_listeners[this->fd & 0x1f] = this;
3629 if (!fr_packet_list_socket_add(proxy_list,
3642 this->status = RAD_LISTEN_STATUS_KNOWN;
3645 mainconfig.listen = head;
3651 static int request_hash_cb(UNUSED void *ctx, void *data)
3653 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3656 rad_assert(request->in_proxy_hash == FALSE);
3659 ev_request_free(&request);
3666 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3668 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3670 ev_request_free(&request);
3676 void radius_event_free(void)
3679 * FIXME: Stop all threads, or at least check that
3680 * they're all waiting on the semaphore, and the queues
3686 * There are requests in the proxy hash that aren't
3687 * referenced from anywhere else. Remove them first.
3690 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3691 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3692 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3693 fr_packet_list_free(proxy_list);
3698 fr_packet_list_walk(pl, NULL, request_hash_cb);
3700 fr_packet_list_free(pl);
3703 fr_event_list_free(el);
3706 int radius_event_process(void)
3710 return fr_event_loop(el);
3713 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3715 request->options = RAD_REQUEST_OPTION_DEBUG2;
3717 if (request_pre_handler(request)) {
3718 rad_assert(fun != NULL);
3719 rad_assert(request != NULL);
3721 if (request->server) RDEBUG("server %s {",
3722 request->server != NULL ?
3723 request->server : "");
3726 if (request->server) RDEBUG("} # server %s",
3727 request->server != NULL ?
3728 request->server : "");
3730 request_post_handler(request);
3733 DEBUG2("Going to the next request");