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 char *debug_condition;
49 * Ridiculous amounts of local state.
51 static fr_event_list_t *el = NULL;
52 static fr_packet_list_t *pl = NULL;
53 static int request_num_counter = 0;
54 static struct timeval now;
56 static int have_children;
57 static int just_started = TRUE;
61 #define WITH_SELF_PIPE (1)
66 static int self_pipe[2];
71 static pthread_mutex_t proxy_mutex;
74 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
75 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
77 static pthread_t NO_SUCH_CHILD_PID;
80 * This is easier than ifdef's throughout the code.
82 #define PTHREAD_MUTEX_LOCK(_x)
83 #define PTHREAD_MUTEX_UNLOCK(_x)
84 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
86 radius_handle_request(request, fun);
91 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
94 static fr_packet_list_t *proxy_list = NULL;
97 * We keep the proxy FD's here. The RADIUS Id's are marked
98 * "allocated" per Id, via a bit per proxy FD.
100 static int proxy_all_used = FALSE;
101 static int proxy_fds[32];
102 static rad_listen_t *proxy_listeners[32];
103 static void check_for_zombie_home_server(REQUEST *request);
104 static void remove_from_proxy_hash(REQUEST *request);
106 #define remove_from_proxy_hash(foo)
109 static void request_post_handler(REQUEST *request);
110 static void wait_a_bit(void *ctx);
111 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
113 static void event_poll_detail(void *ctx);
116 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
119 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
123 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
126 static void tv_add(struct timeval *tv, int usec_delay)
128 if (usec_delay > USEC) {
129 tv->tv_sec += usec_delay / USEC;
132 tv->tv_usec += usec_delay;
134 if (tv->tv_usec > USEC) {
135 tv->tv_sec += tv->tv_usec / USEC;
140 static void remove_from_request_hash(REQUEST *request)
142 if (!request->in_request_hash) return;
144 fr_packet_list_yank(pl, request->packet);
145 request->in_request_hash = FALSE;
147 request_stats_final(request);
151 static void ev_request_free(REQUEST **prequest)
155 if (!prequest || !*prequest) return;
162 * Divorce the child from the parent first,
163 * then clean up the child.
165 request->coa->parent = NULL;
166 ev_request_free(&request->coa);
170 * Divorce the parent from the child, and leave the
171 * parent still alive.
173 if (request->parent && (request->parent->coa == request)) {
174 request->parent->coa = NULL;
178 if (request->ev) fr_event_delete(el, &request->ev);
180 if (request->in_proxy_hash) remove_from_proxy_hash(request);
182 if (request->in_request_hash) remove_from_request_hash(request);
184 request_free(prequest);
188 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
190 RADIUS_PACKET **proxy_p;
193 PTHREAD_MUTEX_LOCK(&proxy_mutex);
194 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
197 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
201 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
204 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
208 request->num_proxied_responses++;
211 * Catch the most common case of everything working
214 if (request->num_proxied_requests == request->num_proxied_responses) {
215 fr_packet_list_yank(proxy_list, request->proxy);
216 fr_packet_list_id_free(proxy_list, request->proxy);
217 request->in_proxy_hash = FALSE;
221 * On the FIRST reply, decrement the count of outstanding
222 * requests. Note that this is NOT the count of sent
223 * packets, but whether or not the home server has
226 if (!request->proxy_reply &&
227 request->home_server &&
228 request->home_server->currently_outstanding) {
229 request->home_server->currently_outstanding--;
232 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
238 static void remove_from_proxy_hash(REQUEST *request)
241 * Check this without grabbing the mutex because it's a
242 * lot faster that way.
244 if (!request->in_proxy_hash) return;
247 * The "not in hash" flag is definitive. However, if the
248 * flag says that it IS in the hash, there might still be
249 * a race condition where it isn't.
251 PTHREAD_MUTEX_LOCK(&proxy_mutex);
253 if (!request->in_proxy_hash) {
254 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
258 fr_packet_list_yank(proxy_list, request->proxy);
259 fr_packet_list_id_free(proxy_list, request->proxy);
262 * The home server hasn't replied, but we've given up on
263 * this request. Don't count this request against the
266 if (!request->proxy_reply &&
267 request->home_server &&
268 request->home_server->currently_outstanding) {
269 request->home_server->currently_outstanding--;
273 * Got from YES in hash, to NO, not in hash while we hold
274 * the mutex. This guarantees that when another thread
275 * grans the mutex, the "not in hash" flag is correct.
277 request->in_proxy_hash = FALSE;
279 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
282 static int proxy_add_fds(rad_listen_t *proxy_listener)
284 int i, proxy, found = -1;
286 proxy = proxy_listener->fd;
287 for (i = 0; i < 32; i++) {
289 * Found a free entry. Save the socket,
290 * and remember where we saved it.
292 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
293 found = (proxy + i) & 0x1f;
294 proxy_fds[found] = proxy;
295 proxy_listeners[found] = proxy_listener;
303 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
305 rad_listen_t *proxy_listener;
307 if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
309 if (proxy_all_used) return 0;
312 * Allocate a new proxy fd. This function adds
313 * it to the tail of the list of listeners. With
314 * some care, this can be thread-safe.
316 proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
317 if (!proxy_listener) {
318 radlog(L_PROXY, "Failed to create a new socket for proxying requests.");
325 if (proxy_add_fds(proxy_listener) < 0) {
326 proxy_all_used = TRUE;
327 listen_free(&proxy_listener);
328 radlog(L_ERR, "Failed creating new proxy socket: server is too busy and home servers appear to be down");
333 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
334 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
339 if (!fr_packet_list_id_alloc(proxy_list, packet)) {
340 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
345 * Signal the main thread to add the new FD to the list
348 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
353 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
358 rad_assert(request->proxy != NULL);
359 rad_assert(proxy_list != NULL);
361 PTHREAD_MUTEX_LOCK(&proxy_mutex);
364 * Keep track of maximum outstanding requests to a
365 * particular home server. 'max_outstanding' is
366 * enforced in home_server_ldb(), in realms.c.
368 if (request->home_server) {
369 request->home_server->currently_outstanding++;
373 RADIUS_PACKET packet;
375 packet = *request->proxy;
377 if (!proxy_id_alloc(request, &packet)) {
378 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
383 * Yank the request, free the old Id, and
384 * remember the new Id.
386 fr_packet_list_yank(proxy_list, request->proxy);
387 fr_packet_list_id_free(proxy_list, request->proxy);
388 *request->proxy = packet;
390 } else if (!proxy_id_alloc(request, request->proxy)) {
391 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
395 rad_assert(request->proxy->sockfd >= 0);
398 * FIXME: Hack until we get rid of rad_listen_t, and put
399 * the information into the packet_list.
402 for (i = 0; i < 32; i++) {
403 if (proxy_fds[i] == request->proxy->sockfd) {
410 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
411 RDEBUG2("ERROR: All sockets are full.");
415 rad_assert(proxy_fds[proxy] != -1);
416 rad_assert(proxy_listeners[proxy] != NULL);
417 request->proxy_listener = proxy_listeners[proxy];
419 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
420 fr_packet_list_id_free(proxy_list, request->proxy);
421 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
422 RDEBUG2("ERROR: Failed to insert entry into proxy list.");
426 request->in_proxy_hash = TRUE;
428 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
430 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
431 inet_ntop(request->proxy->dst_ipaddr.af,
432 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
433 request->proxy->dst_port,
441 * Called as BOTH an event, and in-line from other functions.
443 static void wait_for_proxy_id_to_expire(void *ctx)
445 REQUEST *request = ctx;
447 rad_assert(request->magic == REQUEST_MAGIC);
448 rad_assert(request->proxy != NULL);
450 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
451 request->when = request->proxy_when;
454 if (((request->proxy->code == PW_COA_REQUEST) ||
455 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
456 (request->packet->code != request->proxy->code)) {
457 request->when.tv_sec += request->home_server->coa_mrd;
460 request->when.tv_sec += request->home_server->response_window;
462 if ((request->num_proxied_requests == request->num_proxied_responses) ||
463 timercmp(&now, &request->when, >)) {
464 if (request->packet) {
465 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
466 request->number, request->packet->id,
467 (unsigned int) (request->timestamp - fr_start_time));
469 RDEBUG2("Cleaning up request %u with timestamp +%d",
471 (unsigned int) (request->timestamp - fr_start_time));
474 ev_request_free(&request);
478 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
482 #ifdef HAVE_PTHREAD_H
483 static void wait_for_child_to_die(void *ctx)
485 REQUEST *request = ctx;
487 rad_assert(request->magic == REQUEST_MAGIC);
488 remove_from_request_hash(request);
491 * If it's still queued (waiting for a thread to pick it
492 * up) OR, it's running AND there's still a child thread
493 * handling it, THEN delay some more.
495 if ((request->child_state == REQUEST_QUEUED) ||
496 ((request->child_state == REQUEST_RUNNING) &&
497 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0))) {
500 * Cap delay at max_request_time
502 if (request->delay < (USEC * request->root->max_request_time)) {
503 request->delay += (request->delay >> 1);
504 radlog(L_INFO, "WARNING: Child is hung for request %u in component %s module %s.",
505 request->number, request->component, request->module);
507 request->delay = USEC * request->root->max_request_time;
508 RDEBUG2("WARNING: Child is hung after \"max_request_time\" for request %u",
511 tv_add(&request->when, request->delay);
513 INSERT_EVENT(wait_for_child_to_die, request);
517 RDEBUG2("Child is finally responsive for request %u", request->number);
520 if (request->proxy) {
521 wait_for_proxy_id_to_expire(request);
526 ev_request_free(&request);
530 static void cleanup_delay(void *ctx)
532 REQUEST *request = ctx;
534 rad_assert(request->magic == REQUEST_MAGIC);
535 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
536 (request->child_state == REQUEST_DONE));
538 remove_from_request_hash(request);
541 if (request->proxy && request->in_proxy_hash) {
542 wait_for_proxy_id_to_expire(request);
547 RDEBUG2("Cleaning up request %u ID %d with timestamp +%d",
548 request->number, request->packet->id,
549 (unsigned int) (request->timestamp - fr_start_time));
551 ev_request_free(&request);
556 * In daemon mode, AND this request has debug flags set.
558 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
560 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
564 const char *received, *from;
565 const fr_ipaddr_t *ip;
570 rad_assert(request->radlog != NULL);
572 if (direction == 0) {
573 received = "Received";
574 from = "from"; /* what else? */
575 ip = &packet->src_ipaddr;
576 port = packet->src_port;
579 received = "Sending";
580 from = "to"; /* hah! */
581 ip = &packet->dst_ipaddr;
582 port = packet->dst_port;
586 * Client-specific debugging re-prints the input
587 * packet into the client log.
589 * This really belongs in a utility library
591 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
592 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
593 received, fr_packet_codes[packet->code], from,
594 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
595 port, packet->id, packet->data_len);
597 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
599 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
601 packet->code, packet->id, packet->data_len);
604 for (vp = packet->vps; vp != NULL; vp = vp->next) {
605 vp_prints(buffer, sizeof(buffer), vp);
606 request->radlog(L_DBG, 0, request, "\t%s", buffer);
610 static void reject_delay(void *ctx)
612 REQUEST *request = ctx;
614 rad_assert(request->magic == REQUEST_MAGIC);
615 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
617 RDEBUG2("Sending delayed reject for request %u", request->number);
619 DEBUG_PACKET(request, request->reply, 1);
621 request->listener->send(request->listener, request);
623 request->when.tv_sec += request->root->cleanup_delay;
624 request->child_state = REQUEST_CLEANUP_DELAY;
626 INSERT_EVENT(cleanup_delay, request);
631 void revive_home_server(void *ctx)
633 home_server *home = ctx;
636 home->state = HOME_STATE_ALIVE;
637 home->currently_outstanding = 0;
638 home->revive_time = now;
641 * Delete any outstanding events.
643 if (home->ev) fr_event_delete(el, &home->ev);
645 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
646 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
647 buffer, sizeof(buffer)),
653 static void no_response_to_ping(void *ctx)
655 REQUEST *request = ctx;
659 rad_assert(request->home_server != NULL);
661 home = request->home_server;
662 home->num_received_pings = 0;
664 radlog(L_ERR, "No response to status check %d for home server %s port %d",
666 inet_ntop(request->proxy->dst_ipaddr.af,
667 &request->proxy->dst_ipaddr.ipaddr,
668 buffer, sizeof(buffer)),
669 request->proxy->dst_port);
671 check_for_zombie_home_server(request);
673 wait_for_proxy_id_to_expire(request);
677 static void received_response_to_ping(REQUEST *request)
682 rad_assert(request->home_server != NULL);
684 home = request->home_server;
685 home->num_received_pings++;
687 radlog(L_PROXY, "Received response to status check %d (%d in current sequence)",
688 request->number, home->num_received_pings);
691 * Remove the request from any hashes
693 fr_event_delete(el, &request->ev);
694 remove_from_proxy_hash(request);
695 rad_assert(request->in_request_hash == FALSE);
698 * The control socket may have marked the home server as
699 * alive. OR, it may have suddenly started responding to
700 * requests again. If so, don't re-do the "make alive"
703 if (home->state == HOME_STATE_ALIVE) return;
706 * We haven't received enough ping responses to mark it
707 * "alive". Wait a bit.
709 if (home->num_received_pings < home->num_pings_to_alive) {
713 home->state = HOME_STATE_ALIVE;
714 home->currently_outstanding = 0;
715 home->revive_time = now;
717 if (!fr_event_delete(el, &home->ev)) {
718 RDEBUG2("Hmm... no event for home server. Oh well.");
721 radlog(L_PROXY, "Marking home server %s port %d alive",
722 inet_ntop(request->proxy->dst_ipaddr.af,
723 &request->proxy->dst_ipaddr.ipaddr,
724 buffer, sizeof(buffer)),
725 request->proxy->dst_port);
730 * Called from start of zombie period, OR after control socket
731 * marks the home server dead.
733 static void ping_home_server(void *ctx)
736 home_server *home = ctx;
740 if ((home->state == HOME_STATE_ALIVE) ||
741 (home->ping_check == HOME_PING_CHECK_NONE) ||
742 (home->ev != NULL)) {
746 request = request_alloc();
747 request->number = request_num_counter++;
749 request->proxy = rad_alloc(1);
750 rad_assert(request->proxy != NULL);
752 fr_event_now(el, &request->when);
753 home->when = request->when;
755 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
756 request->proxy->code = PW_STATUS_SERVER;
758 radius_pairmake(request, &request->proxy->vps,
759 "Message-Authenticator", "0x00", T_OP_SET);
761 } else if (home->type == HOME_TYPE_AUTH) {
762 request->proxy->code = PW_AUTHENTICATION_REQUEST;
764 radius_pairmake(request, &request->proxy->vps,
765 "User-Name", home->ping_user_name, T_OP_SET);
766 radius_pairmake(request, &request->proxy->vps,
767 "User-Password", home->ping_user_password, T_OP_SET);
768 radius_pairmake(request, &request->proxy->vps,
769 "Service-Type", "Authenticate-Only", T_OP_SET);
770 radius_pairmake(request, &request->proxy->vps,
771 "Message-Authenticator", "0x00", T_OP_SET);
774 #ifdef WITH_ACCOUNTING
775 request->proxy->code = PW_ACCOUNTING_REQUEST;
777 radius_pairmake(request, &request->proxy->vps,
778 "User-Name", home->ping_user_name, T_OP_SET);
779 radius_pairmake(request, &request->proxy->vps,
780 "Acct-Status-Type", "Stop", T_OP_SET);
781 radius_pairmake(request, &request->proxy->vps,
782 "Acct-Session-Id", "00000000", T_OP_SET);
783 vp = radius_pairmake(request, &request->proxy->vps,
784 "Event-Timestamp", "0", T_OP_SET);
785 vp->vp_date = now.tv_sec;
787 rad_assert("Internal sanity check failed");
791 radius_pairmake(request, &request->proxy->vps,
792 "NAS-Identifier", "Status Check. Are you alive?",
795 request->proxy->dst_ipaddr = home->ipaddr;
796 request->proxy->dst_port = home->port;
797 request->home_server = home;
799 rad_assert(request->proxy_listener == NULL);
801 if (!insert_into_proxy_hash(request, FALSE)) {
802 RDEBUG2("ERROR: Failed to insert status check %d into proxy list. Discarding it.",
804 ev_request_free(&request);
807 rad_assert(request->proxy_listener != NULL);
808 request->proxy_listener->send(request->proxy_listener,
811 request->next_callback = NULL;
812 request->child_state = REQUEST_PROXIED;
813 gettimeofday(&request->when, NULL);
814 home->when = request->when;
815 request->when.tv_sec += home->ping_timeout;;
817 INSERT_EVENT(no_response_to_ping, request);
820 * Add +/- 2s of jitter, as suggested in RFC 3539
821 * and in the Issues and Fixes draft.
823 home->when.tv_sec += home->ping_interval - 2;
826 jitter ^= (jitter >> 10);
827 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
829 tv_add(&home->when, jitter);
831 INSERT_EVENT(ping_home_server, home);
835 void mark_home_server_dead(home_server *home, struct timeval *when)
837 int previous_state = home->state;
840 radlog(L_PROXY, "Marking home server %s port %d as dead.",
841 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
842 buffer, sizeof(buffer)),
845 home->state = HOME_STATE_IS_DEAD;
846 home->num_received_pings = 0;
848 if (home->ping_check != HOME_PING_CHECK_NONE) {
850 * If the control socket marks us dead, start
851 * pinging. Otherwise, we already started
852 * pinging when it was marked "zombie".
854 if (previous_state == HOME_STATE_ALIVE) {
855 ping_home_server(home);
860 * Revive it after a fixed period of time. This
861 * is very, very, bad.
864 home->when.tv_sec += home->revive_interval;
866 INSERT_EVENT(revive_home_server, home);
870 static void check_for_zombie_home_server(REQUEST *request)
875 home = request->home_server;
877 if (home->state != HOME_STATE_ZOMBIE) return;
879 when = home->zombie_period_start;
880 when.tv_sec += home->zombie_period;
882 fr_event_now(el, &now);
883 if (timercmp(&now, &when, <)) {
887 mark_home_server_dead(home, &request->when);
890 static int proxy_to_virtual_server(REQUEST *request);
892 static int virtual_server_handler(UNUSED REQUEST *request)
894 proxy_to_virtual_server(request);
898 static void proxy_fallback_handler(REQUEST *request)
901 * A proper time is required for wait_a_bit.
903 request->delay = USEC / 10;
904 gettimeofday(&now, NULL);
905 request->next_when = now;
906 tv_add(&request->next_when, request->delay);
907 request->next_callback = wait_a_bit;
910 * Re-queue the request.
912 request->child_state = REQUEST_QUEUED;
914 rad_assert(request->proxy != NULL);
915 if (!thread_pool_addrequest(request, virtual_server_handler)) {
916 request->child_state = REQUEST_DONE;
919 #ifdef HAVE_PTHREAD_H
921 * MAY free the request if we're over max_request_time,
922 * AND we're not in threaded mode!
924 * Note that we call this ONLY if we're threaded, as
925 * if we're NOT threaded, request_post_handler() calls
926 * wait_a_bit(), which means that "request" may not
929 if (have_children) wait_a_bit(request);
934 static int setup_post_proxy_fail(REQUEST *request)
936 DICT_VALUE *dval = NULL;
939 request->child_state = REQUEST_RUNNING;
941 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
942 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
944 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
945 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
949 * See no_response_to_coa_request
951 } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
952 request->packet->code &= 0xff; /* restore it */
954 if (request->proxy->code == PW_COA_REQUEST) {
955 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
957 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
958 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
968 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
971 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
975 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
976 if (!vp) vp = radius_paircreate(request, &request->config_items,
977 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
978 vp->vp_integer = dval->value;
980 rad_assert(request->proxy_reply == NULL);
986 static int null_handler(UNUSED REQUEST *request)
991 static void post_proxy_fail_handler(REQUEST *request)
994 * A proper time is required for wait_a_bit.
996 request->delay = USEC / 10;
997 gettimeofday(&now, NULL);
1000 * Not set up to run Post-Proxy-Type = Fail.
1002 * Mark the request as still running, and figure out what
1005 if (!setup_post_proxy_fail(request)) {
1006 request_post_handler(request);
1010 * Re-queue the request.
1012 request->child_state = REQUEST_QUEUED;
1015 * There is a post-proxy-type of fail. We run
1016 * the request through the pre/post proxy
1017 * handlers, just like it was a real proxied
1018 * request. However, we set the per-request
1019 * handler to NULL, as we don't want to do
1022 * Note that when we're not threaded, this will
1023 * process the request even if it's greater than
1024 * max_request_time. That's not fatal.
1026 request->priority = 0;
1027 rad_assert(request->proxy != NULL);
1028 thread_pool_addrequest(request, null_handler);
1032 * MAY free the request if we're over max_request_time,
1033 * AND we're not in threaded mode!
1035 * Note that we call this ONLY if we're threaded, as
1036 * if we're NOT threaded, request_post_handler() calls
1037 * wait_a_bit(), which means that "request" may not
1040 if (have_children) wait_a_bit(request);
1044 /* maybe check this against wait_for_proxy_id_to_expire? */
1045 static void no_response_to_proxied_request(void *ctx)
1047 REQUEST *request = ctx;
1051 rad_assert(request->magic == REQUEST_MAGIC);
1052 rad_assert(request->child_state == REQUEST_PROXIED);
1055 * If we've failed over to an internal home server,
1056 * replace the callback with the correct one. This
1057 * is due to locking issues with child threads...
1059 if (request->home_server->server) {
1060 wait_a_bit(request);
1064 check_for_zombie_home_server(request);
1066 home = request->home_server;
1069 * The default as of 2.1.7 is to allow requests to
1070 * fail-over to a backup home server when this one does
1071 * not respond. The old behavior can be configured as
1074 if (home->no_response_fail) {
1075 radlog(L_ERR, "Rejecting request %u (proxy Id %d) due to lack of any response from home server %s port %d",
1076 request->number, request->proxy->id,
1077 inet_ntop(request->proxy->dst_ipaddr.af,
1078 &request->proxy->dst_ipaddr.ipaddr,
1079 buffer, sizeof(buffer)),
1080 request->proxy->dst_port);
1082 post_proxy_fail_handler(request);
1084 rad_assert(request->ev == NULL);
1085 request->child_state = REQUEST_RUNNING;
1086 wait_a_bit(request);
1090 * Don't touch request due to race conditions
1094 * If it's not alive, don't try to make it a zombie.
1096 if (home->state != HOME_STATE_ALIVE) {
1098 * Don't check home->ev due to race conditions.
1104 * We've received a real packet recently. Don't mark the
1105 * server as zombie until we've received NO packets for a
1106 * while. The "1/4" of zombie period was chosen rather
1107 * arbitrarily. It's a balance between too short, which
1108 * gives quick fail-over and fail-back, or too long,
1109 * where the proxy still sends packets to an unresponsive
1112 if ((home->last_packet + ((home->zombie_period + 3) / 4)) >= now.tv_sec) {
1117 * Enable the zombie period when we notice that the home
1118 * server hasn't responded for a while. We back-date the
1119 * zombie period to when we last received a response from
1122 home->state = HOME_STATE_ZOMBIE;
1124 home->zombie_period_start.tv_sec = home->last_packet;
1125 home->zombie_period_start.tv_sec = USEC / 2;
1127 fr_event_delete(el, &home->ev);
1128 home->currently_outstanding = 0;
1129 home->num_received_pings = 0;
1131 radlog(L_PROXY, "Marking home server %s port %d as zombie (it looks like it is dead).",
1132 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1133 buffer, sizeof(buffer)),
1137 * Start pinging the home server.
1139 ping_home_server(home);
1143 static void wait_a_bit(void *ctx)
1145 struct timeval when;
1146 REQUEST *request = ctx;
1147 fr_event_callback_t callback = NULL;
1149 rad_assert(request->magic == REQUEST_MAGIC);
1153 * The CoA request is a new (internally generated)
1154 * request, created in a child thread. We therefore need
1155 * some way to tie its events back into the main event
1158 if (request->coa && !request->coa->proxy_reply &&
1159 request->coa->next_callback) {
1160 request->coa->when = request->coa->next_when;
1161 INSERT_EVENT(request->coa->next_callback, request->coa);
1162 request->coa->next_callback = NULL;
1163 request->coa->parent = NULL;
1164 request->coa = NULL;
1168 switch (request->child_state) {
1169 case REQUEST_QUEUED:
1170 case REQUEST_RUNNING:
1172 * If we're not thread-capable, OR we're capable,
1173 * but have been told to run without threads,
1174 * complain when the requests is queued for a
1175 * thread, or running in a child thread.
1177 #ifdef HAVE_PTHREAD_H
1181 rad_assert("We do not have threads, but the request is marked as queued or running in a child thread" == NULL);
1185 #ifdef HAVE_PTHREAD_H
1187 * If we have threads, wait for the child thread
1190 when = request->received;
1191 when.tv_sec += request->root->max_request_time;
1194 * Normally called from the event loop with the
1195 * proper event loop time. Otherwise, called from
1196 * post proxy fail handler, which sets "now", and
1197 * this call won't re-set it, because we're not
1198 * in the event loop.
1200 fr_event_now(el, &now);
1203 * Request still has more time. Continue
1206 if (timercmp(&now, &when, <)) {
1207 if (request->delay < (USEC / 10)) {
1208 request->delay = USEC / 10;
1210 request->delay += request->delay >> 1;
1213 * Cap delays at something reasonable.
1215 if (request->delay > (request->root->max_request_time * USEC)) {
1216 request->delay = request->root->max_request_time * USEC;
1219 request->when = now;
1220 tv_add(&request->when, request->delay);
1221 callback = wait_a_bit;
1225 request->master_state = REQUEST_STOP_PROCESSING;
1228 * A child thread MAY still be running on the
1229 * request. Ask the thread to stop working on
1232 if (have_children &&
1233 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
1234 radlog(L_ERR, "WARNING: Unresponsive child for request %u, in component %s module %s",
1236 request->component ? request->component : "<server core>",
1237 request->module ? request->module : "<server core>");
1241 request->delay = USEC;
1242 tv_add(&request->when, request->delay);
1243 callback = wait_for_child_to_die;
1248 * Mark the request as no longer running,
1252 #ifdef HAVE_PTHREAD_H
1253 request->child_pid = NO_SUCH_CHILD_PID;
1258 * This is a CoA request. It's been divorced
1259 * from everything else, so we clean it up now.
1261 if (!request->in_request_hash &&
1263 (request->packet->code != request->proxy->code) &&
1264 ((request->proxy->code == PW_COA_REQUEST) ||
1265 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1267 * FIXME: Do CoA MIBs
1269 ev_request_free(&request);
1273 request_stats_final(request);
1274 cleanup_delay(request);
1277 case REQUEST_REJECT_DELAY:
1278 case REQUEST_CLEANUP_DELAY:
1279 #ifdef HAVE_PTHREAD_H
1280 request->child_pid = NO_SUCH_CHILD_PID;
1282 request_stats_final(request);
1284 case REQUEST_PROXIED:
1285 rad_assert(request->next_callback != NULL);
1286 rad_assert(request->next_callback != wait_a_bit);
1288 request->when = request->next_when;
1289 callback = request->next_callback;
1290 request->next_callback = NULL;
1294 rad_panic("Internal sanity check failure");
1299 * Something major went wrong. Discard the request, and
1302 * FIXME: No idea why this happens or how to fix it...
1303 * It seems to happen *only* when requests are proxied,
1304 * and where the home server doesn't respond. So it looks
1305 * like a race condition above, but it happens in debug
1306 * mode, with no threads...
1309 RDEBUG("WARNING: Internal sanity check failed in event handler for request %u: Discarding the request!", request->number);
1310 ev_request_free(&request);
1314 INSERT_EVENT(callback, request);
1318 static void no_response_to_coa_request(void *ctx)
1320 REQUEST *request = ctx;
1323 rad_assert(request->magic == REQUEST_MAGIC);
1324 rad_assert(request->child_state == REQUEST_PROXIED);
1325 rad_assert(request->home_server != NULL);
1326 rad_assert(!request->in_request_hash);
1328 radlog(L_ERR, "No response to CoA request sent to %s",
1329 inet_ntop(request->proxy->dst_ipaddr.af,
1330 &request->proxy->dst_ipaddr.ipaddr,
1331 buffer, sizeof(buffer)));
1336 request->packet->code |= (PW_COA_REQUEST << 8);
1337 post_proxy_fail_handler(request);
1341 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1345 vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1352 packet->data = NULL;
1353 packet->data_len = 0;
1356 return 1; /* time stamp updated */
1361 * Called when we haven't received a response to a CoA request.
1363 static void retransmit_coa_request(void *ctx)
1367 REQUEST *request = ctx;
1369 rad_assert(request->magic == REQUEST_MAGIC);
1370 rad_assert(request->child_state == REQUEST_PROXIED);
1371 rad_assert(request->home_server != NULL);
1372 rad_assert(!request->in_request_hash);
1373 rad_assert(request->parent == NULL);
1375 fr_event_now(el, &now);
1378 * Cap count at MRC, if it is non-zero.
1380 if (request->home_server->coa_mrc &&
1381 (request->num_coa_requests >= request->home_server->coa_mrc)) {
1382 no_response_to_coa_request(request);
1387 * RFC 5080 Section 2.2.1
1389 * RT = 2*RTprev + RAND*RTprev
1390 * = 1.9 * RTprev + rand(0,.2) * RTprev
1391 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1394 delay ^= (delay >> 16);
1396 frac = request->delay / 5;
1397 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1399 delay += (2 * request->delay) - (request->delay / 10);
1402 * Cap delay at MRT, if MRT is non-zero.
1404 if (request->home_server->coa_mrt &&
1405 (delay > (request->home_server->coa_mrt * USEC))) {
1406 int mrt_usec = request->home_server->coa_mrt * USEC;
1409 * delay = MRT + RAND * MRT
1410 * = 0.9 MRT + rand(0,.2) * MRT
1413 delay ^= (delay >> 15);
1415 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1416 delay += mrt_usec - (mrt_usec / 10);
1419 request->delay = delay;
1420 request->when = now;
1421 tv_add(&request->when, request->delay);
1422 mrd = request->proxy_when;
1423 mrd.tv_sec += request->home_server->coa_mrd;
1426 * Cap duration at MRD.
1428 if (timercmp(&mrd, &request->when, <)) {
1429 request->when = mrd;
1430 INSERT_EVENT(no_response_to_coa_request, request);
1433 INSERT_EVENT(retransmit_coa_request, request);
1436 if (update_event_timestamp(request->proxy, now.tv_sec)) {
1437 if (!insert_into_proxy_hash(request, TRUE)) {
1438 DEBUG("ERROR: Failed to insert retransmission of CoA request into proxy list.");
1442 request->num_proxied_requests = 0;
1443 request->num_proxied_responses = 0;
1446 request->num_proxied_requests++;
1447 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1449 request->proxy_listener->send(request->proxy_listener,
1455 * The original request is either DONE, or in CLEANUP_DELAY.
1457 static int originated_coa_request(REQUEST *request)
1459 int delay, rcode, pre_proxy_type = 0;
1465 rad_assert(request->proxy == NULL);
1466 rad_assert(!request->in_proxy_hash);
1467 rad_assert(request->proxy_reply == NULL);
1470 * Check whether we want to originate one, or cancel one.
1472 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1473 if (!vp && request->coa) {
1474 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1478 if (vp->vp_integer == 0) {
1479 ev_request_free(&request->coa);
1480 return 1; /* success */
1484 if (!request->coa) request_alloc_coa(request);
1485 if (!request->coa) return 0;
1490 * src_ipaddr will be set up in proxy_encode.
1492 memset(&ipaddr, 0, sizeof(ipaddr));
1493 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1495 ipaddr.af = AF_INET;
1496 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1498 } else if ((vp = pairfind(coa->proxy->vps,
1499 PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1500 ipaddr.af = AF_INET6;
1501 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1503 } else if ((vp = pairfind(coa->proxy->vps,
1504 PW_HOME_SERVER_POOL)) != NULL) {
1505 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1507 if (!coa->home_pool) {
1508 RDEBUG2("WARNING: No such home_server_pool %s",
1511 ev_request_free(&request->coa);
1518 } else if (request->client->coa_pool) {
1519 coa->home_pool = request->client->coa_pool;
1521 } else if (request->client->coa_server) {
1522 coa->home_server = request->client->coa_server;
1526 * If all else fails, send it to the client that
1527 * originated this request.
1529 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1533 * Use the pool, if it exists.
1535 if (coa->home_pool) {
1536 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1537 if (!coa->home_server) {
1538 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1542 } else if (!coa->home_server) {
1543 int port = PW_COA_UDP_PORT;
1545 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1546 if (vp) port = vp->vp_integer;
1548 coa->home_server = home_server_find(&ipaddr, port);
1549 if (!coa->home_server) {
1550 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1551 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1552 buffer, sizeof(buffer)), port);
1557 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1559 switch (vp->vp_integer) {
1560 case PW_COA_REQUEST:
1561 case PW_DISCONNECT_REQUEST:
1562 coa->proxy->code = vp->vp_integer;
1566 DEBUG("Cannot set CoA Packet-Type to code %d",
1572 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1575 * The rest of the server code assumes that
1576 * request->packet && request->reply exist. Copy them
1577 * from the original request.
1579 rad_assert(coa->packet != NULL);
1580 rad_assert(coa->packet->vps == NULL);
1581 memcpy(coa->packet, request->packet, sizeof(*request->packet));
1582 coa->packet->vps = paircopy(request->packet->vps);
1583 coa->packet->data = NULL;
1584 rad_assert(coa->reply != NULL);
1585 rad_assert(coa->reply->vps == NULL);
1586 memcpy(coa->reply, request->reply, sizeof(*request->reply));
1587 coa->reply->vps = paircopy(request->reply->vps);
1588 coa->reply->data = NULL;
1589 coa->config_items = paircopy(request->config_items);
1592 * Call the pre-proxy routines.
1594 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1596 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1597 pre_proxy_type = vp->vp_integer;
1600 if (coa->home_pool && coa->home_pool->virtual_server) {
1601 const char *old_server = coa->server;
1603 coa->server = coa->home_pool->virtual_server;
1604 RDEBUG2(" server %s {", coa->server);
1605 rcode = module_pre_proxy(pre_proxy_type, coa);
1607 coa->server = old_server;
1609 rcode = module_pre_proxy(pre_proxy_type, coa);
1616 * Only send the CoA packet if the pre-proxy code succeeded.
1618 case RLM_MODULE_NOOP:
1620 case RLM_MODULE_UPDATED:
1625 * Source IP / port is set when the proxy socket
1628 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1629 coa->proxy->dst_port = coa->home_server->port;
1631 if (!insert_into_proxy_hash(coa, FALSE)) {
1632 DEBUG("ERROR: Failed to insert CoA request into proxy list.");
1637 * We CANNOT divorce the CoA request from the parent
1638 * request. This function is running in a child thread,
1639 * and we need access to the main event loop in order to
1640 * to add the timers for the CoA packet. See
1645 * Forget about the original request completely at this
1650 gettimeofday(&request->proxy_when, NULL);
1651 request->received = request->next_when = request->proxy_when;
1652 rad_assert(request->proxy_reply == NULL);
1655 * Implement re-transmit algorithm as per RFC 5080
1658 * We want IRT + RAND*IRT
1659 * or 0.9 IRT + rand(0,.2) IRT
1661 * 2^20 ~ USEC, and we want 2.
1662 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1664 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1665 request->delay = delay * request->home_server->coa_irt;
1666 delay = request->home_server->coa_irt * USEC;
1667 delay -= delay / 10;
1668 delay += request->delay;
1670 request->delay = delay;
1671 tv_add(&request->next_when, delay);
1672 request->next_callback = retransmit_coa_request;
1675 * Note that we set proxied BEFORE sending the packet.
1677 * Once we send it, the request is tainted, as
1678 * another thread may have picked it up. Don't
1681 request->num_proxied_requests = 1;
1682 request->num_proxied_responses = 0;
1683 #ifdef HAVE_PTHREAD_H
1684 request->child_pid = NO_SUCH_CHILD_PID;
1687 update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1689 request->child_state = REQUEST_PROXIED;
1691 DEBUG_PACKET(request, request->proxy, 1);
1693 request->proxy_listener->send(request->proxy_listener,
1697 #endif /* WITH_COA */
1700 static int process_proxy_reply(REQUEST *request)
1703 int post_proxy_type = 0;
1707 * Delete any reply we had accumulated until now.
1709 pairfree(&request->reply->vps);
1712 * Run the packet through the post-proxy stage,
1713 * BEFORE playing games with the attributes.
1715 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1717 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1718 post_proxy_type = vp->vp_integer;
1721 if (request->home_pool && request->home_pool->virtual_server) {
1722 const char *old_server = request->server;
1724 request->server = request->home_pool->virtual_server;
1725 RDEBUG2(" server %s {", request->server);
1726 rcode = module_post_proxy(post_proxy_type, request);
1728 request->server = old_server;
1730 rcode = module_post_proxy(post_proxy_type, request);
1734 if (request->packet->code == request->proxy->code)
1736 * Don't run the next bit if we originated a CoA
1737 * packet, after receiving an Access-Request or
1738 * Accounting-Request.
1743 * There may NOT be a proxy reply, as we may be
1744 * running Post-Proxy-Type = Fail.
1746 if (request->proxy_reply) {
1748 * Delete the Proxy-State Attributes from
1749 * the reply. These include Proxy-State
1750 * attributes from us and remote server.
1752 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1755 * Add the attributes left in the proxy
1756 * reply to the reply list.
1758 pairadd(&request->reply->vps, request->proxy_reply->vps);
1759 request->proxy_reply->vps = NULL;
1762 * Free proxy request pairs.
1764 pairfree(&request->proxy->vps);
1768 default: /* Don't do anything */
1770 case RLM_MODULE_FAIL:
1771 /* FIXME: debug print stuff */
1772 request->child_state = REQUEST_DONE;
1775 case RLM_MODULE_HANDLED:
1776 /* FIXME: debug print stuff */
1777 request->child_state = REQUEST_DONE;
1785 static int request_pre_handler(REQUEST *request)
1789 rad_assert(request->magic == REQUEST_MAGIC);
1790 rad_assert(request->packet != NULL);
1792 request->child_state = REQUEST_RUNNING;
1795 * Don't decode the packet if it's an internal "fake"
1796 * request. Instead, just return so that the caller can
1799 if (request->packet->dst_port == 0) {
1800 request->username = pairfind(request->packet->vps,
1802 request->password = pairfind(request->packet->vps,
1809 * Put the decoded packet into it's proper place.
1811 if (request->proxy_reply != NULL) {
1812 rcode = request->proxy_listener->decode(request->proxy_listener,
1814 DEBUG_PACKET(request, request->proxy_reply, 0);
1817 if (request->packet->vps == NULL) {
1818 rcode = request->listener->decode(request->listener, request);
1820 if (debug_condition) {
1822 const char *my_debug = debug_condition;
1825 * Ignore parse errors.
1827 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1831 request->options = 2;
1832 request->radlog = radlog_request;
1836 DEBUG_PACKET(request, request->packet, 0);
1842 RDEBUG("%s Dropping packet without response.", fr_strerror());
1843 request->reply->offset = -2; /* bad authenticator */
1844 request->child_state = REQUEST_DONE;
1848 if (!request->username) {
1849 request->username = pairfind(request->packet->vps,
1854 if (request->proxy) {
1855 return process_proxy_reply(request);
1865 * Do state handling when we proxy a request.
1867 static int proxy_request(REQUEST *request)
1869 struct timeval when;
1874 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
1875 ev_request_free(&request->coa);
1879 if (request->home_server->server) {
1880 RDEBUG("ERROR: Cannot proxy to a virtual server.");
1884 if (!insert_into_proxy_hash(request, FALSE)) {
1885 RDEBUG("ERROR: Failed to insert entry into proxy list.");
1889 request->proxy_listener->encode(request->proxy_listener, request);
1891 when = request->received;
1892 when.tv_sec += request->root->max_request_time;
1894 gettimeofday(&request->proxy_when, NULL);
1896 request->next_when = request->proxy_when;
1897 request->next_when.tv_sec += request->home_server->response_window;
1899 rad_assert(request->home_server->response_window > 0);
1901 if (timercmp(&when, &request->next_when, <)) {
1902 request->next_when = when;
1904 request->next_callback = no_response_to_proxied_request;
1906 RDEBUG2("Proxying request %u to home server %s port %d",
1908 inet_ntop(request->proxy->dst_ipaddr.af,
1909 &request->proxy->dst_ipaddr.ipaddr,
1910 buffer, sizeof(buffer)),
1911 request->proxy->dst_port);
1914 * Note that we set proxied BEFORE sending the packet.
1916 * Once we send it, the request is tainted, as
1917 * another thread may have picked it up. Don't
1920 request->num_proxied_requests = 1;
1921 request->num_proxied_responses = 0;
1922 #ifdef HAVE_PTHREAD_H
1923 request->child_pid = NO_SUCH_CHILD_PID;
1925 request->child_state = REQUEST_PROXIED;
1927 DEBUG_PACKET(request, request->proxy, 1);
1929 request->proxy_listener->send(request->proxy_listener,
1936 * "Proxy" the request by sending it to a new virtual server.
1938 static int proxy_to_virtual_server(REQUEST *request)
1941 RAD_REQUEST_FUNP fun;
1943 if (!request->home_server || !request->home_server->server) return 0;
1945 if (request->parent) {
1946 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1950 fake = request_alloc_fake(request);
1952 RDEBUG2("WARNING: Out of memory");
1956 fake->packet->vps = paircopy(request->proxy->vps);
1957 fake->server = request->home_server->server;
1959 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1960 fun = rad_authenticate;
1962 #ifdef WITH_ACCOUNTING
1963 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1964 fun = rad_accounting;
1968 RDEBUG2("Unknown packet type %d", request->proxy->code);
1969 ev_request_free(&fake);
1973 RDEBUG2(">>> Sending proxied request internally to virtual server.");
1974 radius_handle_request(fake, fun);
1975 RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1977 if (fake->reply->code != 0) {
1978 request->proxy_reply = fake->reply;
1982 * There was no response
1984 setup_post_proxy_fail(request);
1987 ev_request_free(&fake);
1989 process_proxy_reply(request);
1992 * Process it through the normal section again, but ONLY
1993 * if we received a proxy reply..
1995 if (request->proxy_reply) {
1996 if (request->server) RDEBUG("server %s {",
1997 request->server != NULL ?
1998 request->server : "");
2001 if (request->server) RDEBUG("} # server %s",
2002 request->server != NULL ?
2003 request->server : "");
2006 return 2; /* success, but NOT '1' !*/
2010 * Return 1 if we did proxy it, or the proxy attempt failed
2011 * completely. Either way, the caller doesn't touch the request
2012 * any more if we return 1.
2014 static int successfully_proxied_request(REQUEST *request)
2017 int pre_proxy_type = 0;
2018 VALUE_PAIR *realmpair;
2019 VALUE_PAIR *strippedname;
2021 char *realmname = NULL;
2023 REALM *realm = NULL;
2027 * If it was already proxied, do nothing.
2029 * FIXME: This should really be a serious error.
2031 if (request->in_proxy_hash ||
2032 (request->proxy_reply && (request->proxy_reply->code != 0))) {
2036 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
2037 if (!realmpair || (realmpair->length == 0)) {
2040 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
2043 switch (request->packet->code) {
2044 case PW_AUTHENTICATION_REQUEST:
2045 pool_type = HOME_TYPE_AUTH;
2048 #ifdef WITH_ACCOUNTING
2049 case PW_ACCOUNTING_REQUEST:
2050 pool_type = HOME_TYPE_ACCT;
2055 case PW_COA_REQUEST:
2056 case PW_DISCONNECT_REQUEST:
2057 pool_type = HOME_TYPE_COA;
2065 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2067 RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2072 realmname = NULL; /* no realms */
2077 realmname = (char *) realmpair->vp_strvalue;
2079 realm = realm_find2(realmname);
2081 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2086 * Figure out which pool to use.
2088 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2089 pool = realm->auth_pool;
2091 #ifdef WITH_ACCOUNTING
2092 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2093 pool = realm->acct_pool;
2097 } else if ((request->packet->code == PW_COA_REQUEST) ||
2098 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2099 pool = realm->acct_pool;
2103 rad_panic("Internal sanity check failed");
2107 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2113 home = home_server_ldb(realmname, pool, request);
2115 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2119 request->home_pool = pool;
2123 * Once we've decided to proxy a request, we cannot send
2124 * a CoA packet. So we free up any CoA packet here.
2126 ev_request_free(&request->coa);
2129 * Remember that we sent the request to a Realm.
2131 if (realmname) pairadd(&request->packet->vps,
2132 pairmake("Realm", realmname, T_OP_EQ));
2135 * Strip the name, if told to.
2137 * Doing it here catches the case of proxied tunneled
2140 if (realm && (realm->striprealm == TRUE) &&
2141 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2143 * If there's a Stripped-User-Name attribute in
2144 * the request, then use THAT as the User-Name
2145 * for the proxied request, instead of the
2148 * This is done by making a copy of the
2149 * Stripped-User-Name attribute, turning it into
2150 * a User-Name attribute, deleting the
2151 * Stripped-User-Name and User-Name attributes
2152 * from the vps list, and making the new
2153 * User-Name the head of the vps list.
2155 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2157 vp = radius_paircreate(request, NULL,
2158 PW_USER_NAME, PW_TYPE_STRING);
2159 rad_assert(vp != NULL); /* handled by above function */
2160 /* Insert at the START of the list */
2161 vp->next = request->proxy->vps;
2162 request->proxy->vps = vp;
2164 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2165 sizeof(vp->vp_strvalue));
2166 vp->length = strippedname->length;
2169 * Do NOT delete Stripped-User-Name.
2174 * If there is no PW_CHAP_CHALLENGE attribute but
2175 * there is a PW_CHAP_PASSWORD we need to add it
2176 * since we can't use the request authenticator
2177 * anymore - we changed it.
2179 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2180 pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2181 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2182 vp = radius_paircreate(request, &request->proxy->vps,
2183 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2184 vp->length = AUTH_VECTOR_LEN;
2185 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2189 * The RFC's say we have to do this, but FreeRADIUS
2192 vp = radius_paircreate(request, &request->proxy->vps,
2193 PW_PROXY_STATE, PW_TYPE_OCTETS);
2194 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2195 request->packet->id);
2196 vp->length = strlen(vp->vp_strvalue);
2199 * Should be done BEFORE inserting into proxy hash, as
2200 * pre-proxy may use this information, or change it.
2202 request->proxy->code = request->packet->code;
2205 * Call the pre-proxy routines.
2207 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2209 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2210 pre_proxy_type = vp->vp_integer;
2213 rad_assert(request->home_pool != NULL);
2215 if (request->home_pool->virtual_server) {
2216 const char *old_server = request->server;
2218 request->server = request->home_pool->virtual_server;
2219 RDEBUG2(" server %s {", request->server);
2220 rcode = module_pre_proxy(pre_proxy_type, request);
2222 request->server = old_server;
2224 rcode = module_pre_proxy(pre_proxy_type, request);
2227 case RLM_MODULE_FAIL:
2228 case RLM_MODULE_INVALID:
2229 case RLM_MODULE_NOTFOUND:
2230 case RLM_MODULE_USERLOCK:
2232 /* FIXME: debug print failed stuff */
2235 case RLM_MODULE_REJECT:
2236 case RLM_MODULE_HANDLED:
2240 * Only proxy the packet if the pre-proxy code succeeded.
2242 case RLM_MODULE_NOOP:
2244 case RLM_MODULE_UPDATED:
2249 * If it's a fake request, don't send the proxy
2250 * packet. The outer tunnel session will take
2251 * care of doing that.
2253 if (request->packet->dst_port == 0) {
2254 request->home_server = NULL;
2258 if (request->home_server->server) {
2259 return proxy_to_virtual_server(request);
2262 if (!proxy_request(request)) {
2263 RDEBUG("ERROR: Failed to proxy request %u", request->number);
2271 static void request_post_handler(REQUEST *request)
2273 int child_state = -1;
2274 struct timeval when;
2277 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2279 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2280 RDEBUG2("request %u was cancelled.", request->number);
2281 #ifdef HAVE_PTHREAD_H
2282 request->child_pid = NO_SUCH_CHILD_PID;
2284 child_state = REQUEST_DONE;
2288 if (request->child_state != REQUEST_RUNNING) {
2289 rad_panic("Internal sanity check failed");
2294 * If it's not in the request hash, it's a CoA request.
2297 if (!request->in_request_hash &&
2299 ((request->proxy->code == PW_COA_REQUEST) ||
2300 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2301 request->next_callback = NULL;
2302 child_state = REQUEST_DONE;
2308 * Catch Auth-Type := Reject BEFORE proxying the packet.
2310 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2311 (request->reply->code == 0) &&
2312 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2313 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2314 request->reply->code = PW_AUTHENTICATION_REJECT;
2318 if (request->root->proxy_requests &&
2319 !request->in_proxy_hash &&
2320 (request->reply->code == 0) &&
2321 (request->packet->dst_port != 0) &&
2322 (request->packet->code != PW_STATUS_SERVER)) {
2323 int rcode = successfully_proxied_request(request);
2325 if (rcode == 1) return; /* request is invalid */
2328 * Failed proxying it (dead home servers, etc.)
2329 * Run it through Post-Proxy-Type = Fail, and
2330 * respond to the request.
2332 * Note that we're in a child thread here, so we
2333 * do NOT re-schedule the request. Instead, we
2334 * do what we would have done, which is run the
2335 * pre-handler, a NULL request handler, and then
2338 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2339 request_pre_handler(request);
2343 * Else we weren't supposed to proxy it,
2344 * OR we proxied it internally to a virutal server.
2349 else if (request->proxy && request->coa) {
2350 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2351 ev_request_free(&request->coa);
2357 * Fake requests don't get encoded or signed. The caller
2358 * also requires the reply VP's, so we don't free them
2361 if (request->packet->dst_port == 0) {
2362 /* FIXME: RDEBUG going to the next request */
2363 #ifdef HAVE_PTHREAD_H
2364 request->child_pid = NO_SUCH_CHILD_PID;
2366 request->child_state = REQUEST_DONE;
2372 * Copy Proxy-State from the request to the reply.
2374 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2375 if (vp) pairadd(&request->reply->vps, vp);
2379 * Access-Requests get delayed or cached.
2381 switch (request->packet->code) {
2382 case PW_AUTHENTICATION_REQUEST:
2383 gettimeofday(&request->next_when, NULL);
2385 if (request->reply->code == 0) {
2387 * Check if the lack of response is intentional.
2389 vp = pairfind(request->config_items,
2390 PW_RESPONSE_PACKET_TYPE);
2392 RDEBUG2("There was no response configured: rejecting request %u",
2394 request->reply->code = PW_AUTHENTICATION_REJECT;
2396 } else if (vp->vp_integer == 256) {
2397 RDEBUG2("Not responding to request %u",
2401 * Force cleanup after a long
2402 * time, so that we don't
2403 * re-process the packet.
2405 request->next_when.tv_sec += request->root->max_request_time;
2406 request->next_callback = cleanup_delay;
2407 child_state = REQUEST_CLEANUP_DELAY;
2410 request->reply->code = vp->vp_integer;
2416 * Run rejected packets through
2418 * Post-Auth-Type = Reject
2420 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2421 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2422 vp = radius_pairmake(request, &request->config_items,
2423 "Post-Auth-Type", "Reject",
2425 if (vp) rad_postauth(request);
2428 * If configured, delay Access-Reject packets.
2430 * If request->root->reject_delay = 0, we discover
2431 * that we have to send the packet now.
2433 when = request->received;
2434 when.tv_sec += request->root->reject_delay;
2436 if (timercmp(&when, &request->next_when, >)) {
2437 RDEBUG2("Delaying reject of request %u for %d seconds",
2439 request->root->reject_delay);
2440 request->next_when = when;
2441 request->next_callback = reject_delay;
2442 #ifdef HAVE_PTHREAD_H
2443 request->child_pid = NO_SUCH_CHILD_PID;
2445 request->child_state = REQUEST_REJECT_DELAY;
2451 case PW_COA_REQUEST:
2452 case PW_DISCONNECT_REQUEST:
2454 request->next_when.tv_sec += request->root->cleanup_delay;
2455 request->next_callback = cleanup_delay;
2456 child_state = REQUEST_CLEANUP_DELAY;
2459 case PW_ACCOUNTING_REQUEST:
2460 request->next_callback = NULL; /* just to be safe */
2461 child_state = REQUEST_DONE;
2465 * FIXME: Status-Server should probably not be
2468 case PW_STATUS_SERVER:
2469 request->next_callback = NULL;
2470 child_state = REQUEST_DONE;
2477 request->next_callback = NULL;
2478 child_state = REQUEST_DONE;
2483 * Suppress "no reply" packets here, unless we're reading
2484 * from the "detail" file. In that case, we've got to
2485 * tell the detail file handler that the request is dead,
2486 * and it should re-send it.
2487 * If configured, encode, sign, and send.
2489 if ((request->reply->code != 0) ||
2490 (request->listener->type == RAD_LISTEN_DETAIL)) {
2491 DEBUG_PACKET(request, request->reply, 1);
2492 request->listener->send(request->listener, request);
2497 * Now that we've completely processed the request,
2498 * see if we need to originate a CoA request. But ONLY
2499 * if it wasn't proxied.
2501 if (!request->proxy &&
2502 (request->packet->code != PW_COA_REQUEST) &&
2503 (request->packet->code != PW_DISCONNECT_REQUEST) &&
2505 (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL))) {
2506 if (!originated_coa_request(request)) {
2507 RDEBUG2("Do CoA Fail handler here");
2509 /* request->coa is stil set, so we can update events */
2515 * Clean up. These are no longer needed.
2517 pairfree(&request->config_items);
2519 pairfree(&request->packet->vps);
2520 request->username = NULL;
2521 request->password = NULL;
2523 pairfree(&request->reply->vps);
2526 if (request->proxy) {
2527 pairfree(&request->proxy->vps);
2529 if (request->proxy_reply) {
2530 pairfree(&request->proxy_reply->vps);
2535 * We're not tracking responses from the home
2536 * server, we can therefore free this memory in
2539 if (!request->in_proxy_hash) {
2540 rad_free(&request->proxy);
2541 rad_free(&request->proxy_reply);
2542 request->home_server = NULL;
2548 RDEBUG2("Finished request %u.", request->number);
2549 rad_assert(child_state >= 0);
2550 request->child_state = child_state;
2553 * Single threaded mode: update timers now.
2555 if (!have_children) wait_a_bit(request);
2559 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2565 RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2566 RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2568 switch (request->child_state) {
2569 case REQUEST_QUEUED:
2570 case REQUEST_RUNNING:
2574 radlog(L_ERR, "Discarding duplicate request from "
2575 "client %s port %d - ID: %d due to unfinished request %u",
2577 request->packet->src_port,request->packet->id,
2582 case REQUEST_PROXIED:
2584 * We're not supposed to have duplicate
2585 * accounting packets. The other states handle
2586 * duplicates fine (discard, or send duplicate
2587 * reply). But we do NOT want to retransmit an
2588 * accounting request here, because that would
2589 * involve updating the Acct-Delay-Time, and
2590 * therefore changing the packet Id, etc.
2592 * Instead, we just discard the packet. We may
2593 * eventually respond, or the client will send a
2594 * new accounting packet.
2596 * The same comments go for Status-Server, and
2597 * other packet types.
2599 * FIXME: coa: when we proxy CoA && Disconnect
2600 * packets, this logic has to be fixed.
2602 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2606 check_for_zombie_home_server(request);
2609 * If we've just discovered that the home server is
2610 * dead, send the packet to another one.
2612 if ((request->packet->dst_port != 0) &&
2613 (request->home_server->state == HOME_STATE_IS_DEAD)) {
2616 remove_from_proxy_hash(request);
2618 home = home_server_ldb(NULL, request->home_pool, request);
2620 RDEBUG2("ERROR: Failed to find live home server for request %u", request->number);
2623 * Do post-request processing,
2624 * and any insertion of necessary
2627 post_proxy_fail_handler(request);
2631 request->proxy->code = request->packet->code;
2634 * Free the old packet, to force re-encoding
2636 free(request->proxy->data);
2637 request->proxy->data = NULL;
2638 request->proxy->data_len = 0;
2641 * This request failed over to a virtual
2642 * server. Push it back onto the queue
2645 if (request->home_server->server) {
2646 proxy_fallback_handler(request);
2651 * Try to proxy the request.
2653 if (!proxy_request(request)) {
2654 RDEBUG("ERROR: Failed to re-proxy request %u", request->number);
2655 goto no_home_servers;
2659 * This code executes in the main server
2660 * thread, so there's no need for locking.
2662 rad_assert(request->next_callback != NULL);
2663 INSERT_EVENT(request->next_callback, request);
2664 request->next_callback = NULL;
2666 } /* else the home server is still alive */
2668 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2669 inet_ntop(request->proxy->dst_ipaddr.af,
2670 &request->proxy->dst_ipaddr.ipaddr,
2671 buffer, sizeof(buffer)),
2672 request->proxy->dst_port,
2673 request->proxy->id);
2674 request->num_proxied_requests++;
2676 DEBUG_PACKET(request, request->proxy, 1);
2677 request->proxy_listener->send(request->proxy_listener,
2682 case REQUEST_REJECT_DELAY:
2683 RDEBUG2("Waiting to send Access-Reject "
2684 "to client %s port %d - ID: %d",
2686 request->packet->src_port, request->packet->id);
2689 case REQUEST_CLEANUP_DELAY:
2691 if (request->reply->code == 0) {
2692 RDEBUG2("Ignoring retransmit from client %s port %d "
2693 "- ID: %d, no reply was configured",
2695 request->packet->src_port, request->packet->id);
2700 * FIXME: This sends duplicate replies to
2701 * accounting requests, even if Acct-Delay-Time
2702 * or Event-Timestamp is in the packet. In those
2703 * cases, the Id should be changed, and the packet
2706 RDEBUG2("Sending duplicate reply "
2707 "to client %s port %d - ID: %d",
2709 request->packet->src_port, request->packet->id);
2710 DEBUG_PACKET(request, request->reply, 1);
2711 request->listener->send(request->listener, request);
2717 static void received_conflicting_request(REQUEST *request,
2718 const RADCLIENT *client)
2720 radlog(L_ERR, "Received conflicting packet from "
2721 "client %s port %d - ID: %d due to unfinished request %u. Giving up on old request.",
2723 request->packet->src_port, request->packet->id,
2727 * Nuke it from the request hash, so we can receive new
2730 remove_from_request_hash(request);
2732 switch (request->child_state) {
2733 #ifdef HAVE_PTHREAD_H
2735 * It's queued or running. Tell it to stop, and
2736 * wait for it to do so.
2738 case REQUEST_QUEUED:
2739 case REQUEST_RUNNING:
2740 request->master_state = REQUEST_STOP_PROCESSING;
2741 request->delay += request->delay >> 1;
2743 tv_add(&request->when, request->delay);
2745 INSERT_EVENT(wait_for_child_to_die, request);
2750 * Catch race conditions. It may have switched
2751 * from running to done while this code is being
2754 case REQUEST_REJECT_DELAY:
2755 case REQUEST_CLEANUP_DELAY:
2760 * It's in some other state, and therefore also
2761 * in the event queue. At some point, the
2762 * child will notice, and we can then delete it.
2764 case REQUEST_PROXIED:
2766 rad_assert(request->ev != NULL);
2772 static int can_handle_new_request(RADIUS_PACKET *packet,
2774 struct main_config_t *root)
2777 * Count the total number of requests, to see if
2778 * there are too many. If so, return with an
2781 if (root->max_requests) {
2782 int request_count = fr_packet_list_num_elements(pl);
2785 * This is a new request. Let's see if
2786 * it makes us go over our configured
2789 if (request_count > root->max_requests) {
2790 radlog(L_ERR, "Dropping request (%d is too many): "
2791 "from client %s port %d - ID: %d", request_count,
2793 packet->src_port, packet->id);
2794 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2795 "\tThe value for 'max_requests' is probably set too low.\n");
2797 } /* else there were a small number of requests */
2798 } /* else there was no configured limit for requests */
2801 * FIXME: Add per-client checks. If one client is sending
2802 * too many packets, start discarding them.
2804 * We increment the counters here, and decrement them
2805 * when the response is sent... somewhere in this file.
2809 * FUTURE: Add checks for system load. If the system is
2810 * busy, start dropping requests...
2812 * We can probably keep some statistics ourselves... if
2813 * there are more requests coming in than we can handle,
2814 * start dropping some.
2821 int received_request(rad_listen_t *listener,
2822 RADIUS_PACKET *packet, REQUEST **prequest,
2825 RADIUS_PACKET **packet_p;
2826 REQUEST *request = NULL;
2827 struct main_config_t *root = &mainconfig;
2829 packet_p = fr_packet_list_find(pl, packet);
2831 request = fr_packet2myptr(REQUEST, packet, packet_p);
2832 rad_assert(request->in_request_hash);
2834 if ((request->packet->data_len == packet->data_len) &&
2835 (memcmp(request->packet->vector, packet->vector,
2836 sizeof(packet->vector)) == 0)) {
2837 received_retransmit(request, client);
2842 * The new request is different from the old one,
2843 * but maybe the old is finished. If so, delete
2846 switch (request->child_state) {
2847 struct timeval when;
2851 * Special hacks for race conditions.
2852 * The reply is encoded, and therefore
2853 * likely sent. We received a *new*
2854 * packet from the client, likely before
2855 * the next line or two of code which
2856 * updated the child state. In this
2857 * case, just accept the new request.
2859 if ((request->reply->code != 0) &&
2860 request->reply->data) {
2861 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %u.",
2863 packet->src_port, packet->id,
2865 remove_from_request_hash(request);
2870 gettimeofday(&when, NULL);
2874 * If the cached request was received
2875 * within the last second, then we
2876 * discard the NEW request instead of the
2877 * old one. This will happen ONLY when
2878 * the client is severely broken, and is
2879 * sending conflicting packets very
2882 if (timercmp(&when, &request->received, <)) {
2883 radlog(L_ERR, "Discarding conflicting packet from "
2884 "client %s port %d - ID: %d due to recent request %u.",
2886 packet->src_port, packet->id,
2891 received_conflicting_request(request, client);
2895 case REQUEST_REJECT_DELAY:
2896 case REQUEST_CLEANUP_DELAY:
2897 request->child_state = REQUEST_DONE;
2899 cleanup_delay(request);
2906 * We may want to quench the new request.
2908 if ((listener->type != RAD_LISTEN_DETAIL) &&
2909 !can_handle_new_request(packet, client, root)) {
2914 * Create and initialize the new request.
2916 request = request_alloc(); /* never fails */
2918 if ((request->reply = rad_alloc(0)) == NULL) {
2919 radlog(L_ERR, "No memory");
2923 request->listener = listener;
2924 request->client = client;
2925 request->packet = packet;
2926 request->packet->timestamp = request->timestamp;
2927 request->number = request_num_counter++;
2928 request->priority = listener->type;
2929 #ifdef HAVE_PTHREAD_H
2930 request->child_pid = NO_SUCH_CHILD_PID;
2934 * Status-Server packets go to the head of the queue.
2936 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2939 * Set virtual server identity
2941 if (client->server) {
2942 request->server = client->server;
2943 } else if (listener->server) {
2944 request->server = listener->server;
2946 request->server = NULL;
2950 * Remember the request in the list.
2952 if (!fr_packet_list_insert(pl, &request->packet)) {
2953 radlog(L_ERR, "Failed to insert request %u in the list of live requests: discarding", request->number);
2954 ev_request_free(&request);
2958 request->in_request_hash = TRUE;
2959 request->root = root;
2963 * The request passes many of our sanity checks.
2964 * From here on in, if anything goes wrong, we
2965 * send a reject message, instead of dropping the
2970 * Build the reply template from the request.
2973 request->reply->sockfd = request->packet->sockfd;
2974 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2975 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2976 request->reply->dst_port = request->packet->src_port;
2977 request->reply->src_port = request->packet->dst_port;
2978 request->reply->id = request->packet->id;
2979 request->reply->code = 0; /* UNKNOWN code */
2980 memcpy(request->reply->vector, request->packet->vector,
2981 sizeof(request->reply->vector));
2982 request->reply->vps = NULL;
2983 request->reply->data = NULL;
2984 request->reply->data_len = 0;
2986 request->master_state = REQUEST_ACTIVE;
2987 request->child_state = REQUEST_QUEUED;
2988 request->next_callback = NULL;
2990 gettimeofday(&request->received, NULL);
2991 request->timestamp = request->received.tv_sec;
2992 request->when = request->received;
2994 request->delay = USEC;
2996 tv_add(&request->when, request->delay);
2998 INSERT_EVENT(wait_a_bit, request);
3000 *prequest = request;
3006 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
3012 * Also removes from the proxy hash if responses == requests
3014 request = lookup_in_proxy_hash(packet);
3017 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
3018 inet_ntop(packet->src_ipaddr.af,
3019 &packet->src_ipaddr.ipaddr,
3020 buffer, sizeof(buffer)),
3021 packet->src_port, packet->id);
3026 * We haven't replied to the NAS, but we have seen an
3027 * earlier reply from the home server. Ignore this packet,
3028 * as we're likely still processing the previous reply.
3030 if (request->proxy_reply) {
3031 if (memcmp(request->proxy_reply->vector,
3033 sizeof(request->proxy_reply->vector)) == 0) {
3034 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d for request %u",
3035 inet_ntop(packet->src_ipaddr.af,
3036 &packet->src_ipaddr.ipaddr,
3037 buffer, sizeof(buffer)),
3038 packet->src_port, packet->id,
3042 * ? The home server gave us a new proxy
3043 * reply which doesn't match the old
3046 RDEBUG2("Ignoring conflicting proxy reply");
3049 /* assert that there's an event queued for request? */
3054 * Verify the packet before doing ANYTHING with it. This
3055 * means we're doing more MD5 checks in the server core.
3056 * However, we can fix that by moving to multiple threads
3057 * listening on sockets.
3059 * We do this AFTER looking the request up in the hash,
3060 * and AFTER vhecking if we saw a previous request. This
3061 * helps minimize the DoS effect of people attacking us
3062 * with spoofed packets.
3064 if (rad_verify(packet, request->proxy,
3065 request->home_server->secret) != 0) {
3066 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
3070 gettimeofday(&now, NULL);
3073 * "ping" packets have a different algorithm for marking
3074 * a home server alive. They also skip all of the CoA,
3077 if (!request->packet) {
3078 request->proxy_reply = packet;
3079 received_response_to_ping(request);
3080 request->proxy_reply = NULL; /* caller will free it */
3081 ev_request_free(&request);
3086 * Maybe move this earlier in the decision process?
3087 * Having it here means that late or duplicate proxy
3088 * replies no longer get the home server marked as
3089 * "alive". This might be good for stability, though.
3091 * FIXME: Do we really want to do this whenever we
3092 * receive a packet? Setting this here means that we
3093 * mark it alive on *any* packet, even if it's lost all
3094 * of the *other* packets in the last 10s.
3096 * This behavior could be configurable.
3098 request->home_server->state = HOME_STATE_ALIVE;
3099 request->home_server->last_packet = now.tv_sec;
3103 * When originating CoA, the "proxy" reply is the reply
3104 * to the CoA request that we originated. At this point,
3105 * the original request is finished, and it has a reply.
3107 * However, if we haven't separated the two requests, do
3108 * so now. This is done so that cleaning up the original
3109 * request won't cause the CoA request to be free'd. See
3110 * util.c, request_free()
3112 if (request->parent && (request->parent->coa == request)) {
3113 request->parent->coa = NULL;
3114 request->parent = NULL;
3117 * The proxied packet was different from the
3118 * original packet, AND the proxied packet was
3121 } else if ((request->packet->code != request->proxy->code) &&
3122 ((request->proxy->code == PW_COA_REQUEST) ||
3123 (request->proxy->code == PW_DISCONNECT_REQUEST))) {
3125 * It's already divorced: do nothing.
3130 * Skip the next set of checks, as the original
3131 * reply is cached. We want to be able to still
3132 * process the CoA reply, AND to reference the
3133 * original request/reply.
3135 * This is getting to be really quite a bit of a
3141 * If there's a reply to the NAS, ignore everything
3142 * related to proxy responses
3144 if (request->reply && request->reply->code != 0) {
3145 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3151 * The average includes our time to receive packets and
3152 * look them up in the hashes, which should be the same
3155 * We update the response time only for the FIRST packet
3158 if (request->home_server->ema.window > 0) {
3159 radius_stats_ema(&request->home_server->ema,
3160 &now, &request->proxy_when);
3164 switch (request->child_state) {
3165 case REQUEST_QUEUED:
3166 case REQUEST_RUNNING:
3167 radlog(L_ERR, "Internal sanity check failed for child state");
3170 case REQUEST_REJECT_DELAY:
3171 case REQUEST_CLEANUP_DELAY:
3173 radlog(L_ERR, "Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
3174 inet_ntop(packet->src_ipaddr.af,
3175 &packet->src_ipaddr.ipaddr,
3176 buffer, sizeof(buffer)),
3177 packet->src_port, packet->id,
3179 /* assert that there's an event queued for request? */
3182 case REQUEST_PROXIED:
3186 request->proxy_reply = packet;
3190 * Perform RTT calculations, as per RFC 2988 (for TCP).
3191 * Note that we only do so on the first response.
3193 if ((request->num_proxied_responses == 1)
3195 home_server *home = request->home_server;
3197 rtt = now.tv_sec - request->proxy_when.tv_sec;
3200 rtt -= request->proxy_when.tv_usec;
3202 if (!home->has_rtt) {
3203 home->has_rtt = TRUE;
3206 home->rttvar = rtt / 2;
3209 home->rttvar -= home->rttvar >> 2;
3210 home->rttvar += (home->srtt - rtt);
3211 home->srtt -= home->srtt >> 3;
3212 home->srtt += rtt >> 3;
3215 home->rto = home->srtt;
3216 if (home->rttvar > (USEC / 4)) {
3217 home->rto += home->rttvar * 4;
3224 request->child_state = REQUEST_QUEUED;
3225 request->when = now;
3226 request->delay = USEC;
3227 request->priority = RAD_LISTEN_PROXY;
3228 tv_add(&request->when, request->delay);
3231 * Wait a bit will take care of max_request_time
3233 INSERT_EVENT(wait_a_bit, request);
3239 void event_new_fd(rad_listen_t *this)
3243 if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3245 this->print(this, buffer, sizeof(buffer));
3247 if (this->status == RAD_LISTEN_STATUS_INIT) {
3249 DEBUG("Listening on %s", buffer);
3251 radlog(L_INFO, " ... adding new socket %s", buffer);
3253 if (!fr_event_fd_insert(el, 0, this->fd,
3254 event_socket_handler, this)) {
3255 radlog(L_ERR, "Failed remembering handle for proxy socket!");
3259 this->status = RAD_LISTEN_STATUS_KNOWN;
3263 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3264 radlog(L_INFO, " ... closing socket %s", buffer);
3266 fr_event_fd_delete(el, 0, this->fd);
3267 this->status = RAD_LISTEN_STATUS_FINISH;
3270 * Close the fd AFTER fixing up the requests and
3271 * listeners, so that they don't send/recv on the
3272 * wrong socket (if someone manages to open
3280 static void handle_signal_self(int flag)
3282 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3283 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3284 fr_event_loop_exit(el, 1);
3286 fr_event_loop_exit(el, 2);
3290 } /* else exit/term flags weren't set */
3293 * Tell the even loop to stop processing.
3295 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3297 static time_t last_hup = 0;
3300 if ((int) (when - last_hup) < 5) {
3301 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3305 radlog(L_INFO, "Received HUP signal.");
3309 fr_event_loop_exit(el, 0x80);
3313 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3317 * FIXME: O(N) loops suck.
3319 for (this = mainconfig.listen;
3321 this = this->next) {
3322 if (this->type != RAD_LISTEN_DETAIL) continue;
3325 * This one didn't send the signal, skip
3328 if (!this->decode(this, NULL)) continue;
3331 * Go service the interrupt.
3333 event_poll_detail(this);
3338 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3341 for (this = mainconfig.listen;
3343 this = this->next) {
3349 #ifndef WITH_SELF_PIPE
3350 void radius_signal_self(int flag)
3352 handle_signal_self(flag);
3356 * Inform ourselves that we received a signal.
3358 void radius_signal_self(int flag)
3364 * The read MUST be non-blocking for this to work.
3366 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3370 for (i = 0; i < rcode; i++) {
3371 buffer[0] |= buffer[i];
3379 write(self_pipe[1], buffer, 1);
3383 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3384 UNUSED int fd, UNUSED void *ctx)
3389 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3390 if (rcode <= 0) return;
3393 * Merge pending signals.
3395 for (i = 0; i < rcode; i++) {
3396 buffer[0] |= buffer[i];
3399 handle_signal_self(buffer[0]);
3404 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3407 rad_listen_t *listener = ctx;
3408 RAD_REQUEST_FUNP fun;
3411 rad_assert(xel == el);
3415 if (listener->fd < 0) rad_panic("Socket was closed on us!");
3417 if (!listener->recv(listener, &fun, &request)) return;
3419 if (!thread_pool_addrequest(request, fun)) {
3420 request->child_state = REQUEST_DONE;
3426 * This function is called periodically to see if this detail
3427 * file is available for reading.
3429 static void event_poll_detail(void *ctx)
3432 RAD_REQUEST_FUNP fun;
3434 rad_listen_t *this = ctx;
3435 struct timeval when;
3436 listen_detail_t *detail = this->data;
3438 rad_assert(this->type == RAD_LISTEN_DETAIL);
3441 * Try to read something.
3443 * FIXME: This does poll AND receive.
3445 rcode = this->recv(this, &fun, &request);
3447 rad_assert(fun != NULL);
3448 rad_assert(request != NULL);
3450 if (!thread_pool_addrequest(request, fun)) {
3451 request->child_state = REQUEST_DONE;
3455 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3459 * Backdoor API to get the delay until the next poll
3462 delay = this->encode(this, NULL);
3463 tv_add(&when, delay);
3465 if (!fr_event_insert(el, event_poll_detail, this,
3466 &when, &detail->ev)) {
3467 radlog(L_ERR, "Failed creating handler");
3473 static void event_status(struct timeval *wake)
3475 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3479 if (debug_flag == 0) {
3481 radlog(L_INFO, "Ready to process requests.");
3482 just_started = FALSE;
3488 radlog(L_INFO, "Ready to process requests.");
3490 } else if ((wake->tv_sec != 0) ||
3491 (wake->tv_usec >= 100000)) {
3492 DEBUG("Waking up in %d.%01u seconds.",
3493 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3498 * FIXME: Put this somewhere else, where it isn't called
3499 * all of the time...
3502 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3504 * If there are no child threads, then there may
3505 * be child processes. In that case, wait for
3506 * their exit status, and throw that exit status
3507 * away. This helps get rid of zxombie children.
3509 while (waitpid(-1, &argval, WNOHANG) > 0) {
3517 * Externally-visibly functions.
3519 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3521 rad_listen_t *this, *head = NULL;
3525 time(&fr_start_time);
3527 el = fr_event_list_create(event_status);
3530 pl = fr_packet_list_create(0);
3531 if (!pl) return 0; /* leak el */
3533 request_num_counter = 0;
3536 if (mainconfig.proxy_requests) {
3538 * Create the tree for managing proxied requests and
3541 proxy_list = fr_packet_list_create(1);
3542 if (!proxy_list) return 0;
3544 #ifdef HAVE_PTHREAD_H
3545 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3546 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3554 #ifdef HAVE_PTHREAD_H
3556 NO_SUCH_CHILD_PID = (pthread_t ) (0);
3558 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3561 * Initialize the threads ONLY if we're spawning, AND
3562 * we're running normally.
3564 if (spawn_flag && !check_config &&
3565 (thread_pool_init(cs, &spawn_flag) < 0)) {
3571 * Move all of the thread calls to this file?
3573 * It may be best for the mutexes to be in this file...
3575 have_children = spawn_flag;
3578 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3580 if (listen_init(cs, &head) < 0) {
3587 #ifdef WITH_SELF_PIPE
3589 * Child threads need a pipe to signal us, as do the
3592 if (pipe(self_pipe) < 0) {
3593 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3597 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3598 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3602 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3603 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3608 if (!fr_event_fd_insert(el, 0, self_pipe[0],
3609 event_signal_handler, el)) {
3610 radlog(L_ERR, "Failed creating handler for signals");
3613 #endif /* WITH_SELF_PIPE */
3617 * Mark the proxy Fd's as unused.
3622 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3626 DEBUG("%s: #### Opening IP addresses and Ports ####",
3630 * The server temporarily switches to an unprivileged
3631 * user very early in the bootstrapping process.
3632 * However, some sockets MAY require privileged access
3633 * (bind to device, or to port < 1024, or to raw
3634 * sockets). Those sockets need to call suid up/down
3635 * themselves around the functions that need a privileged
3638 if (listen_init(cs, &head) < 0) {
3643 * At this point, no one has any business *ever* going
3646 fr_suid_down_permanent();
3649 * Add all of the sockets to the event loop.
3653 this = this->next) {
3656 this->print(this, buffer, sizeof(buffer));
3658 switch (this->type) {
3660 case RAD_LISTEN_DETAIL:
3661 DEBUG("Listening on %s", buffer);
3664 * Detail files are always known, and aren't
3665 * put into the socket event loop.
3667 this->status = RAD_LISTEN_STATUS_KNOWN;
3670 * Set up the first poll interval.
3672 event_poll_detail(this);
3677 case RAD_LISTEN_PROXY:
3678 if (proxy_add_fds(this) < 0) {
3679 radlog(L_ERR, "Failed creating new proxy socket");
3683 if (!fr_packet_list_socket_add(proxy_list,
3697 mainconfig.listen = head;
3703 static int request_hash_cb(UNUSED void *ctx, void *data)
3705 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3708 rad_assert(request->in_proxy_hash == FALSE);
3711 ev_request_free(&request);
3718 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3720 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3722 ev_request_free(&request);
3728 void radius_event_free(void)
3731 * FIXME: Stop all threads, or at least check that
3732 * they're all waiting on the semaphore, and the queues
3738 * There are requests in the proxy hash that aren't
3739 * referenced from anywhere else. Remove them first.
3742 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3743 fr_packet_list_free(proxy_list);
3748 fr_packet_list_walk(pl, NULL, request_hash_cb);
3750 fr_packet_list_free(pl);
3753 fr_event_list_free(el);
3756 int radius_event_process(void)
3760 return fr_event_loop(el);
3763 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3765 request->options = RAD_REQUEST_OPTION_DEBUG2;
3767 if (request_pre_handler(request)) {
3768 rad_assert(fun != NULL);
3769 rad_assert(request != NULL);
3771 if (request->server) RDEBUG("server %s {",
3772 request->server != NULL ?
3773 request->server : "");
3776 if (request->server) RDEBUG("} # server %s",
3777 request->server != NULL ?
3778 request->server : "");
3780 request_post_handler(request);
3783 DEBUG2("Going to the next request");