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>
31 #include <freeradius-devel/radius_snmp.h>
33 #include <freeradius-devel/rad_assert.h>
38 #ifdef HAVE_SYS_WAIT_H
39 # include <sys/wait.h>
42 #define USEC (1000000)
44 extern pid_t radius_pid;
46 extern int check_config;
47 extern void force_log_reopen(void);
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;
56 static time_t start_time;
57 static int have_children;
58 static int has_detail_listener = FALSE;
59 static int just_started = FALSE;
62 static int self_pipe[2];
66 static pthread_mutex_t proxy_mutex;
68 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
69 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
72 * This is easier than ifdef's throughout the code.
74 #define PTHREAD_MUTEX_LOCK(_x)
75 #define PTHREAD_MUTEX_UNLOCK(_x)
78 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
80 static fr_packet_list_t *proxy_list = NULL;
83 * We keep the proxy FD's here. The RADIUS Id's are marked
84 * "allocated" per Id, via a bit per proxy FD.
86 static int proxy_fds[32];
87 static rad_listen_t *proxy_listeners[32];
89 static void request_post_handler(REQUEST *request);
90 static void wait_a_bit(void *ctx);
91 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
93 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
96 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
100 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
103 static void tv_add(struct timeval *tv, int usec_delay)
105 if (usec_delay > USEC) {
106 tv->tv_sec += usec_delay / USEC;
109 tv->tv_usec += usec_delay;
111 if (tv->tv_usec > USEC) {
118 static void snmp_inc_counters(REQUEST *request)
120 if (!request->root->do_snmp) return;
122 if (request->master_state == REQUEST_COUNTED) return;
124 if ((request->listener->type != RAD_LISTEN_AUTH) &&
125 (request->listener->type != RAD_LISTEN_ACCT)) return;
128 * Update the SNMP statistics.
130 * Note that we do NOT do this in a child thread.
131 * Instead, we update the stats when a request is
132 * deleted, because only the main server thread calls
133 * this function, which makes it thread-safe.
135 switch (request->reply->code) {
136 case PW_AUTHENTICATION_ACK:
137 rad_snmp.auth.total_responses++;
138 rad_snmp.auth.total_access_accepts++;
139 if (request->client && request->client->auth) {
140 request->client->auth->accepts++;
144 case PW_AUTHENTICATION_REJECT:
145 rad_snmp.auth.total_responses++;
146 rad_snmp.auth.total_access_rejects++;
147 if (request->client && request->client->auth) {
148 request->client->auth->rejects++;
152 case PW_ACCESS_CHALLENGE:
153 rad_snmp.auth.total_responses++;
154 rad_snmp.auth.total_access_challenges++;
155 if (request->client && request->client->auth) {
156 request->client->auth->challenges++;
160 case PW_ACCOUNTING_RESPONSE:
161 rad_snmp.acct.total_responses++;
162 if (request->client && request->client->acct) {
163 request->client->acct->responses++;
168 * No response, it must have been a bad
172 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
173 rad_snmp.auth.total_bad_authenticators++;
174 if (request->client && request->client->auth) {
175 request->client->auth->bad_authenticators++;
184 request->master_state = REQUEST_COUNTED;
187 #define snmp_inc_counters(_x)
191 static void remove_from_request_hash(REQUEST *request)
193 if (!request->in_request_hash) return;
195 fr_packet_list_yank(pl, request->packet);
196 request->in_request_hash = FALSE;
198 snmp_inc_counters(request);
202 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
204 RADIUS_PACKET **proxy_p;
207 PTHREAD_MUTEX_LOCK(&proxy_mutex);
208 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
211 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
215 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
218 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
222 request->num_proxied_responses++;
225 * Catch the most common case of everything working
228 if (request->num_proxied_requests == request->num_proxied_responses) {
229 fr_packet_list_yank(proxy_list, request->proxy);
230 fr_packet_list_id_free(proxy_list, request->proxy);
231 request->in_proxy_hash = FALSE;
235 * On the FIRST reply, decrement the count of outstanding
236 * requests. Note that this is NOT the count of sent
237 * packets, but whether or not the home server has
240 if (!request->proxy_reply &&
241 request->home_server->currently_outstanding) {
242 request->home_server->currently_outstanding--;
245 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
251 static void remove_from_proxy_hash(REQUEST *request)
253 if (!request->in_proxy_hash) return;
255 PTHREAD_MUTEX_LOCK(&proxy_mutex);
256 fr_packet_list_yank(proxy_list, request->proxy);
257 fr_packet_list_id_free(proxy_list, request->proxy);
260 * The home server hasn't replied, but we've given up on
261 * this request. Don't count this request against the
264 if (!request->proxy_reply &&
265 request->home_server->currently_outstanding) {
266 request->home_server->currently_outstanding--;
269 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
271 request->in_proxy_hash = FALSE;
275 static int insert_into_proxy_hash(REQUEST *request)
280 rad_assert(request->proxy != NULL);
281 rad_assert(proxy_list != NULL);
283 request->proxy->sockfd = -1;
285 PTHREAD_MUTEX_LOCK(&proxy_mutex);
287 request->home_server->currently_outstanding++;
288 request->home_server->total_requests_sent++;
291 * On overflow, back up to ~0.
293 if (!request->home_server->total_requests_sent) {
294 request->home_server->total_requests_sent--;
297 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
299 rad_listen_t *proxy_listener;
302 * Allocate a new proxy fd. This function adds
303 * it to the tail of the list of listeners. With
304 * some care, this can be thread-safe.
306 proxy_listener = proxy_new_listener();
307 if (!proxy_listener) {
308 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
309 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
317 proxy = proxy_listener->fd;
318 for (i = 0; i < 32; i++) {
320 * Found a free entry. Save the socket,
321 * and remember where we saved it.
323 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
324 found = (proxy + i) & 0x1f;
325 proxy_fds[found] = proxy;
326 proxy_listeners[found] = proxy_listener;
330 rad_assert(found >= 0);
332 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
333 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
334 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
339 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
340 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
341 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
346 * Signal the main thread to add the new FD to the list
349 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
351 rad_assert(request->proxy->sockfd >= 0);
354 * FIXME: Hack until we get rid of rad_listen_t, and put
355 * the information into the packet_list.
358 for (i = 0; i < 32; i++) {
359 if (proxy_fds[i] == request->proxy->sockfd) {
366 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
367 DEBUG2("ERROR: All sockets are full.");
371 rad_assert(proxy_fds[proxy] != -1);
372 rad_assert(proxy_listeners[proxy] != NULL);
373 request->proxy_listener = proxy_listeners[proxy];
375 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
376 fr_packet_list_id_free(proxy_list, request->proxy);
377 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
378 DEBUG2("ERROR: Failed to insert entry into proxy list");
382 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
384 DEBUG3(" proxy: allocating destination %s port %d - Id %d",
385 inet_ntop(request->proxy->dst_ipaddr.af,
386 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
387 request->proxy->dst_port,
390 request->in_proxy_hash = TRUE;
397 * Called as BOTH an event, and in-line from other functions.
399 static void wait_for_proxy_id_to_expire(void *ctx)
401 REQUEST *request = ctx;
402 home_server *home = request->home_server;
404 rad_assert(request->magic == REQUEST_MAGIC);
405 rad_assert(request->proxy != NULL);
407 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
408 request->when = request->proxy_when;
409 request->when.tv_sec += home->response_window;
411 if ((request->num_proxied_requests == request->num_proxied_responses) ||
412 timercmp(&now, &request->when, >)) {
413 if (request->packet) {
414 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
415 request->number, request->packet->id,
416 (unsigned int) (request->timestamp - start_time));
418 DEBUG2("Cleaning up request %d with timestamp +%d",
420 (unsigned int) (request->timestamp - start_time));
422 fr_event_delete(el, &request->ev);
423 remove_from_proxy_hash(request);
424 remove_from_request_hash(request);
425 request_free(&request);
429 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
433 static void wait_for_child_to_die(void *ctx)
435 REQUEST *request = ctx;
437 rad_assert(request->magic == REQUEST_MAGIC);
439 if ((request->child_state == REQUEST_QUEUED) |
440 (request->child_state == REQUEST_RUNNING)) {
441 request->delay += (request->delay >> 1);
442 tv_add(&request->when, request->delay);
444 DEBUG2("Child is still stuck for request %d", request->number);
446 INSERT_EVENT(wait_for_child_to_die, request);
450 DEBUG2("Child is finally responsive for request %d", request->number);
451 remove_from_request_hash(request);
453 if (request->proxy) {
454 wait_for_proxy_id_to_expire(request);
458 request_free(&request);
462 static void cleanup_delay(void *ctx)
464 REQUEST *request = ctx;
466 rad_assert(request->magic == REQUEST_MAGIC);
467 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
468 (request->child_state == REQUEST_DONE));
470 remove_from_request_hash(request);
472 if (request->proxy && request->in_proxy_hash) {
473 wait_for_proxy_id_to_expire(request);
477 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
478 request->number, request->packet->id,
479 (unsigned int) (request->timestamp - start_time));
481 fr_event_delete(el, &request->ev);
482 request_free(&request);
486 static void reject_delay(void *ctx)
488 REQUEST *request = ctx;
490 rad_assert(request->magic == REQUEST_MAGIC);
491 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
493 DEBUG2("Sending delayed reject for request %d", request->number);
495 request->listener->send(request->listener, request);
497 request->when.tv_sec += request->root->cleanup_delay;
498 request->child_state = REQUEST_CLEANUP_DELAY;
500 INSERT_EVENT(cleanup_delay, request);
504 static void revive_home_server(void *ctx)
506 home_server *home = ctx;
508 home->state = HOME_STATE_ALIVE;
509 DEBUG2("Marking home server alive again... we have no idea if it really is alive or not.");
510 home->currently_outstanding = 0;
514 static void no_response_to_ping(void *ctx)
516 REQUEST *request = ctx;
517 home_server *home = request->home_server;
520 home->num_received_pings = 0;
522 DEBUG2("No response to status check %d from home server %s port %d",
524 inet_ntop(request->proxy->dst_ipaddr.af,
525 &request->proxy->dst_ipaddr.ipaddr,
526 buffer, sizeof(buffer)),
527 request->proxy->dst_port);
529 wait_for_proxy_id_to_expire(request);
533 static void received_response_to_ping(REQUEST *request)
535 home_server *home = request->home_server;
538 home->num_received_pings++;
540 DEBUG2("Received response to status check %d (%d in current sequence)",
541 request->number, home->num_received_pings);
543 if (home->num_received_pings < home->num_pings_to_alive) {
544 wait_for_proxy_id_to_expire(request);
548 DEBUG2("Marking home server %s port %d alive",
549 inet_ntop(request->proxy->dst_ipaddr.af,
550 &request->proxy->dst_ipaddr.ipaddr,
551 buffer, sizeof(buffer)),
552 request->proxy->dst_port);
554 if (!fr_event_delete(el, &home->ev)) {
555 DEBUG2("Hmm... no event for home server, WTF?");
558 if (!fr_event_delete(el, &request->ev)) {
559 DEBUG2("Hmm... no event for request, WTF?");
562 wait_for_proxy_id_to_expire(request);
564 home->state = HOME_STATE_ALIVE;
565 home->currently_outstanding = 0;
569 static void ping_home_server(void *ctx)
572 home_server *home = ctx;
576 if (home->state == HOME_STATE_ALIVE) {
577 radlog(L_INFO, "Suspicious proxy state... continuing");
581 request = request_alloc();
582 request->number = request_num_counter++;
584 request->proxy = rad_alloc(1);
585 rad_assert(request->proxy != NULL);
587 fr_event_now(el, &request->when);
588 home->when = request->when;
590 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
591 request->proxy->code = PW_STATUS_SERVER;
593 radius_pairmake(request, &request->proxy->vps,
594 "Message-Authenticator", "0x00", T_OP_SET);
596 } else if (home->type == HOME_TYPE_AUTH) {
597 request->proxy->code = PW_AUTHENTICATION_REQUEST;
599 radius_pairmake(request, &request->proxy->vps,
600 "User-Name", home->ping_user_name, T_OP_SET);
601 radius_pairmake(request, &request->proxy->vps,
602 "User-Password", home->ping_user_password, T_OP_SET);
603 radius_pairmake(request, &request->proxy->vps,
604 "Service-Type", "Authenticate-Only", T_OP_SET);
605 radius_pairmake(request, &request->proxy->vps,
606 "Message-Authenticator", "0x00", T_OP_SET);
609 request->proxy->code = PW_ACCOUNTING_REQUEST;
611 radius_pairmake(request, &request->proxy->vps,
612 "User-Name", home->ping_user_name, T_OP_SET);
613 radius_pairmake(request, &request->proxy->vps,
614 "Acct-Status-Type", "Stop", T_OP_SET);
615 radius_pairmake(request, &request->proxy->vps,
616 "Acct-Session-Id", "00000000", T_OP_SET);
617 vp = radius_pairmake(request, &request->proxy->vps,
618 "Event-Timestamp", "0", T_OP_SET);
619 vp->vp_date = now.tv_sec;
622 radius_pairmake(request, &request->proxy->vps,
623 "NAS-Identifier", "Status Check. Are you alive?",
626 request->proxy->dst_ipaddr = home->ipaddr;
627 request->proxy->dst_port = home->port;
628 request->home_server = home;
630 rad_assert(request->proxy_listener == NULL);
632 if (!insert_into_proxy_hash(request)) {
633 DEBUG2("ERROR: Failed inserting status check %d into proxy hash. Discarding it.",
635 request_free(&request);
638 rad_assert(request->proxy_listener != NULL);
639 request->proxy_listener->send(request->proxy_listener,
642 request->next_callback = NULL;
643 request->child_state = REQUEST_PROXIED;
644 request->when.tv_sec += home->ping_timeout;;
646 INSERT_EVENT(no_response_to_ping, request);
649 * Add +/- 2s of jitter, as suggested in RFC 3539
650 * and in the Issues and Fixes draft.
652 home->when.tv_sec += home->ping_interval - 2;
655 jitter ^= (jitter >> 10);
656 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
658 tv_add(&home->when, jitter);
661 INSERT_EVENT(ping_home_server, home);
665 static void check_for_zombie_home_server(REQUEST *request)
671 home = request->home_server;
673 if (home->state != HOME_STATE_ZOMBIE) return;
675 when = home->zombie_period_start;
676 when.tv_sec += home->zombie_period;
678 fr_event_now(el, &now);
679 if (timercmp(&now, &when, <)) {
684 * It's been a zombie for too long, mark it as
687 DEBUG2("FAILURE: Marking home server %s port %d as dead.",
688 inet_ntop(request->proxy->dst_ipaddr.af,
689 &request->proxy->dst_ipaddr.ipaddr,
690 buffer, sizeof(buffer)),
691 request->proxy->dst_port);
692 home->state = HOME_STATE_IS_DEAD;
693 home->num_received_pings = 0;
694 home->when = request->when;
696 if (home->ping_check != HOME_PING_CHECK_NONE) {
697 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
698 (home->ping_user_name != NULL));
699 home->when.tv_sec += home->ping_interval;
701 INSERT_EVENT(ping_home_server, home);
703 home->when.tv_sec += home->revive_interval;
705 INSERT_EVENT(revive_home_server, home);
710 static int setup_post_proxy_fail(REQUEST *request)
712 DICT_VALUE *dval = NULL;
715 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
716 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
718 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
719 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
725 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
728 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
732 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
733 if (!vp) vp = radius_paircreate(request, &request->config_items,
734 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
735 vp->vp_integer = dval->value;
737 rad_assert(request->proxy_reply == NULL);
743 static int null_handler(UNUSED REQUEST *request)
748 static void post_proxy_fail_handler(REQUEST *request)
751 * A proper time is required for wait_a_bit.
753 request->delay = USEC / 10;
754 gettimeofday(&now, NULL);
757 * Not set up to run Post-Proxy-Type = Fail.
759 * Mark the request as still running, and figure out what
762 if (!setup_post_proxy_fail(request)) {
763 request->child_state = REQUEST_RUNNING;
764 request_post_handler(request);
768 * Re-queue the request.
770 request->child_state = REQUEST_QUEUED;
773 * There is a post-proxy-type of fail. We run
774 * the request through the pre/post proxy
775 * handlers, just like it was a real proxied
776 * request. However, we set the per-request
777 * handler to NULL, as we don't want to do
780 * Note that when we're not threaded, this will
781 * process the request even if it's greater than
782 * max_request_time. That's not fatal.
784 request->priority = 0;
785 rad_assert(request->proxy != NULL);
786 thread_pool_addrequest(request, null_handler);
791 * MAY free the request if we're over max_request_time,
792 * AND we're not in threaded mode!
794 * Note that we call this ONLY if we're threaded, as
795 * if we're NOT threaded, request_post_handler() calls
796 * wait_a_bit(), which means that "request" may not
799 if (have_children) wait_a_bit(request);
803 /* maybe check this against wait_for_proxy_id_to_expire? */
804 static void no_response_to_proxied_request(void *ctx)
806 REQUEST *request = ctx;
810 rad_assert(request->magic == REQUEST_MAGIC);
811 rad_assert(request->child_state == REQUEST_PROXIED);
813 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
815 inet_ntop(request->proxy->dst_ipaddr.af,
816 &request->proxy->dst_ipaddr.ipaddr,
817 buffer, sizeof(buffer)),
818 request->proxy->dst_port);
820 check_for_zombie_home_server(request);
822 home = request->home_server;
824 post_proxy_fail_handler(request);
827 * Don't touch request due to race conditions
829 if (home->state == HOME_STATE_IS_DEAD) {
830 rad_assert(home->ev != NULL); /* or it will never wake up */
835 * Enable the zombie period when we notice that the home
836 * server hasn't responded. We also back-date the start
837 * of the zombie period to when the proxied request was
840 if (home->state == HOME_STATE_ALIVE) {
841 DEBUG2("WARNING: Marking home server %s port %d as zombie (it looks like it is dead).",
842 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
843 buffer, sizeof(buffer)),
845 home->state = HOME_STATE_ZOMBIE;
846 home->zombie_period_start = now;
847 home->zombie_period_start.tv_sec -= home->response_window;
853 static void wait_a_bit(void *ctx)
856 REQUEST *request = ctx;
857 fr_event_callback_t callback = NULL;
859 rad_assert(request->magic == REQUEST_MAGIC);
861 switch (request->child_state) {
863 case REQUEST_RUNNING:
864 when = request->received;
865 when.tv_sec += request->root->max_request_time;
868 * Normally called from the event loop with the
869 * proper event loop time. Otherwise, called from
870 * post proxy fail handler, which sets "now", and
871 * this call won't re-set it, because we're not
874 fr_event_now(el, &now);
877 * Request still has more time. Continue
880 if (timercmp(&now, &when, <) ||
881 ((request->listener->type == RAD_LISTEN_DETAIL) &&
882 (request->child_state == REQUEST_QUEUED))) {
883 if (request->delay < (USEC / 10)) {
884 request->delay = USEC / 10;
886 request->delay += request->delay >> 1;
889 * Cap wait at some sane value for detail
892 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
893 (request->delay > (request->root->max_request_time * USEC))) {
894 request->delay = request->root->max_request_time * USEC;
898 tv_add(&request->when, request->delay);
899 callback = wait_a_bit;
904 * A child thread MAY still be running on the
905 * request. Ask the thread to stop working on
909 /* FIXME: kill unresponsive children? */
912 * Print this error message ONLY if
913 * there's a child currently processing
914 * the request. As we don't have thread
915 * locks here, there may be race
916 * conditions on this check. But it's
917 * just an error message, so that's OK.
919 if (request->child_pid != NO_SUCH_CHILD_PID) {
920 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
921 (unsigned long)request->child_pid, request->number,
922 request->module ? request->module : "<server core>",
923 request->component ? request->component : "<server core>");
926 request->master_state = REQUEST_STOP_PROCESSING;
928 request->delay = USEC / 4;
929 tv_add(&request->when, request->delay);
930 callback = wait_for_child_to_die;
935 * Else there are no child threads. We probably
936 * should have just marked the request as 'done'
937 * elsewhere, like in the post-proxy-fail
938 * handler. But doing that would involve
939 * checking for max_request_time in multiple
940 * places, so this may be simplest.
942 request->child_state = REQUEST_DONE;
946 * Mark the request as no longer running,
950 request->child_pid = NO_SUCH_CHILD_PID;
951 snmp_inc_counters(request);
952 cleanup_delay(request);
955 case REQUEST_REJECT_DELAY:
956 case REQUEST_CLEANUP_DELAY:
957 request->child_pid = NO_SUCH_CHILD_PID;
958 snmp_inc_counters(request);
960 case REQUEST_PROXIED:
961 rad_assert(request->next_callback != NULL);
962 rad_assert(request->next_callback != wait_a_bit);
964 request->when = request->next_when;
965 callback = request->next_callback;
966 request->next_callback = NULL;
970 rad_panic("Internal sanity check failure");
975 * Something major went wrong. Discard the request, and
978 * FIXME: No idea why this happens or how to fix it...
979 * It seems to happen *only* when requests are proxied,
980 * and where the home server doesn't respond. So it looks
981 * like a race condition above, but it happens in debug
982 * mode, with no threads...
985 DEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
986 fr_event_delete(el, &request->ev);
987 remove_from_proxy_hash(request);
988 remove_from_request_hash(request);
989 request_free(&request);
993 INSERT_EVENT(callback, request);
997 static int request_pre_handler(REQUEST *request)
1001 rad_assert(request->magic == REQUEST_MAGIC);
1002 rad_assert(request->packet != NULL);
1004 request->child_state = REQUEST_RUNNING;
1007 * Don't decode the packet if it's an internal "fake"
1008 * request. Instead, just return so that the caller can
1011 if (request->packet->dst_port == 0) {
1012 request->username = pairfind(request->packet->vps,
1014 request->password = pairfind(request->packet->vps,
1020 * Put the decoded packet into it's proper place.
1022 if (request->proxy_reply != NULL) {
1023 rcode = request->proxy_listener->decode(request->proxy_listener,
1025 } else if (request->packet->vps == NULL) {
1026 rcode = request->listener->decode(request->listener, request);
1033 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
1034 request->child_state = REQUEST_DONE;
1038 if (!request->proxy) {
1039 request->username = pairfind(request->packet->vps,
1043 int post_proxy_type = 0;
1047 * Delete any reply we had accumulated until now.
1049 pairfree(&request->reply->vps);
1052 * Run the packet through the post-proxy stage,
1053 * BEFORE playing games with the attributes.
1055 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1057 DEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1058 post_proxy_type = vp->vp_integer;
1061 rad_assert(request->home_pool != NULL);
1063 if (request->home_pool->virtual_server) {
1064 const char *old_server = request->server;
1066 request->server = request->home_pool->virtual_server;
1067 DEBUG2(" server %s {", request->server);
1068 rcode = module_post_proxy(post_proxy_type, request);
1070 request->server = old_server;
1072 rcode = module_post_proxy(post_proxy_type, request);
1076 * There may NOT be a proxy reply, as we may be
1077 * running Post-Proxy-Type = Fail.
1079 if (request->proxy_reply) {
1081 * Delete the Proxy-State Attributes from
1082 * the reply. These include Proxy-State
1083 * attributes from us and remote server.
1085 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1088 * Add the attributes left in the proxy
1089 * reply to the reply list.
1091 pairadd(&request->reply->vps, request->proxy_reply->vps);
1092 request->proxy_reply->vps = NULL;
1095 * Free proxy request pairs.
1097 pairfree(&request->proxy->vps);
1101 default: /* Don't do anything */
1103 case RLM_MODULE_FAIL:
1104 /* FIXME: debug print stuff */
1105 request->child_state = REQUEST_DONE;
1108 case RLM_MODULE_HANDLED:
1109 /* FIXME: debug print stuff */
1110 request->child_state = REQUEST_DONE;
1120 * Do state handling when we proxy a request.
1122 static int proxy_request(REQUEST *request)
1124 struct timeval when;
1127 if (!insert_into_proxy_hash(request)) {
1128 DEBUG("ERROR: Failed inserting request into proxy hash.");
1132 request->proxy_listener->encode(request->proxy_listener, request);
1134 when = request->received;
1135 when.tv_sec += request->root->max_request_time;
1137 gettimeofday(&request->proxy_when, NULL);
1139 request->next_when = request->proxy_when;
1140 request->next_when.tv_sec += request->home_server->response_window;
1142 rad_assert(request->home_server->response_window > 0);
1144 if (timercmp(&when, &request->next_when, <)) {
1145 request->next_when = when;
1147 request->next_callback = no_response_to_proxied_request;
1149 DEBUG2("Proxying request %d to home server %s port %d",
1151 inet_ntop(request->proxy->dst_ipaddr.af,
1152 &request->proxy->dst_ipaddr.ipaddr,
1153 buffer, sizeof(buffer)),
1154 request->proxy->dst_port);
1157 * Note that we set proxied BEFORE sending the packet.
1159 * Once we send it, the request is tainted, as
1160 * another thread may have picked it up. Don't
1163 request->num_proxied_requests = 1;
1164 request->num_proxied_responses = 0;
1165 request->child_pid = NO_SUCH_CHILD_PID;
1166 request->child_state = REQUEST_PROXIED;
1167 request->proxy_listener->send(request->proxy_listener,
1174 * "Proxy" the request by sending it to a new virtual server.
1176 static int proxy_to_virtual_server(REQUEST *request)
1180 if (!request->home_server || !request->home_server->server) return 0;
1182 if (request->parent) {
1183 DEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1187 fake = request_alloc_fake(request);
1189 DEBUG2("WARNING: Out of memory");
1193 fake->packet->vps = paircopy(request->proxy->vps);
1194 fake->server = request->home_server->server;
1196 DEBUG2(">>> Sending proxied request internally to virtual server.");
1197 radius_handle_request(fake, rad_authenticate);
1198 DEBUG2("<<< Received proxied response from internal virtual server.");
1200 request->proxy_reply = fake->reply;
1204 * And run it through the post-proxy section...
1206 rad_authenticate(request);
1208 return 2; /* success, but NOT '1' !*/
1213 * Return 1 if we did proxy it, or the proxy attempt failed
1214 * completely. Either way, the caller doesn't touch the request
1215 * any more if we return 1.
1217 static int successfully_proxied_request(REQUEST *request)
1220 int pre_proxy_type = 0;
1221 VALUE_PAIR *realmpair;
1222 VALUE_PAIR *strippedname;
1226 REALM *realm = NULL;
1230 * If it was already proxied, do nothing.
1232 * FIXME: This should really be a serious error.
1234 if (request->in_proxy_hash) {
1238 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1239 if (!realmpair || (realmpair->length == 0)) {
1243 realmname = (char *) realmpair->vp_strvalue;
1245 realm = realm_find(realmname);
1247 DEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1252 * Figure out which pool to use.
1254 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1255 pool = realm->auth_pool;
1257 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1258 pool = realm->acct_pool;
1261 rad_panic("Internal sanity check failed");
1265 DEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1270 home = home_server_ldb(realmname, pool, request);
1272 DEBUG2("ERROR: Failed to find live home server for realm %s",
1276 request->home_pool = pool;
1279 * Remember that we sent the request to a Realm.
1281 pairadd(&request->packet->vps,
1282 pairmake("Realm", realmname, T_OP_EQ));
1285 * We read the packet from a detail file, AND it came from
1286 * the server we're about to send it to. Don't do that.
1288 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1289 (request->listener->type == RAD_LISTEN_DETAIL) &&
1290 (home->ipaddr.af == AF_INET) &&
1291 (request->packet->src_ipaddr.af == AF_INET) &&
1292 (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1293 DEBUG2(" rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1298 * Allocate the proxy packet, only if it wasn't already
1299 * allocated by a module. This check is mainly to support
1300 * the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1302 * In those cases, the EAP module creates a "fake"
1303 * request, and recursively passes it through the
1304 * authentication stage of the server. The module then
1305 * checks if the request was supposed to be proxied, and
1306 * if so, creates a proxy packet from the TUNNELED request,
1307 * and not from the EAP request outside of the tunnel.
1309 * The proxy then works like normal, except that the response
1310 * packet is "eaten" by the EAP module, and encapsulated into
1313 if (!request->proxy) {
1314 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1315 radlog(L_ERR|L_CONS, "no memory");
1320 * Copy the request, then look up name and
1321 * plain-text password in the copy.
1323 * Note that the User-Name attribute is the
1324 * *original* as sent over by the client. The
1325 * Stripped-User-Name attribute is the one hacked
1326 * through the 'hints' file.
1328 request->proxy->vps = paircopy(request->packet->vps);
1332 * Strip the name, if told to.
1334 * Doing it here catches the case of proxied tunneled
1337 if (realm->striprealm == TRUE &&
1338 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1340 * If there's a Stripped-User-Name attribute in
1341 * the request, then use THAT as the User-Name
1342 * for the proxied request, instead of the
1345 * This is done by making a copy of the
1346 * Stripped-User-Name attribute, turning it into
1347 * a User-Name attribute, deleting the
1348 * Stripped-User-Name and User-Name attributes
1349 * from the vps list, and making the new
1350 * User-Name the head of the vps list.
1352 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1354 vp = radius_paircreate(request, NULL,
1355 PW_USER_NAME, PW_TYPE_STRING);
1356 rad_assert(vp != NULL); /* handled by above function */
1357 /* Insert at the START of the list */
1358 vp->next = request->proxy->vps;
1359 request->proxy->vps = vp;
1361 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1362 sizeof(vp->vp_strvalue));
1363 vp->length = strippedname->length;
1366 * Do NOT delete Stripped-User-Name.
1371 * If there is no PW_CHAP_CHALLENGE attribute but
1372 * there is a PW_CHAP_PASSWORD we need to add it
1373 * since we can't use the request authenticator
1374 * anymore - we changed it.
1376 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1377 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1378 vp = radius_paircreate(request, &request->proxy->vps,
1379 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1380 vp->length = AUTH_VECTOR_LEN;
1381 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1385 * The RFC's say we have to do this, but FreeRADIUS
1388 vp = radius_paircreate(request, &request->proxy->vps,
1389 PW_PROXY_STATE, PW_TYPE_OCTETS);
1390 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
1391 request->packet->id);
1392 vp->length = strlen(vp->vp_strvalue);
1395 * Should be done BEFORE inserting into proxy hash, as
1396 * pre-proxy may use this information, or change it.
1398 request->proxy->code = request->packet->code;
1399 request->proxy->dst_ipaddr = home->ipaddr;
1400 request->proxy->dst_port = home->port;
1401 request->home_server = home;
1404 * Call the pre-proxy routines.
1406 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1408 DEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1409 pre_proxy_type = vp->vp_integer;
1412 rad_assert(request->home_pool != NULL);
1414 if (request->home_pool->virtual_server) {
1415 const char *old_server = request->server;
1417 request->server = request->home_pool->virtual_server;
1418 DEBUG2(" server %s {", request->server);
1419 rcode = module_pre_proxy(pre_proxy_type, request);
1421 request->server = old_server;
1423 rcode = module_pre_proxy(pre_proxy_type, request);
1426 case RLM_MODULE_FAIL:
1427 case RLM_MODULE_INVALID:
1428 case RLM_MODULE_NOTFOUND:
1429 case RLM_MODULE_USERLOCK:
1431 /* FIXME: debug print failed stuff */
1434 case RLM_MODULE_REJECT:
1435 case RLM_MODULE_HANDLED:
1439 * Only proxy the packet if the pre-proxy code succeeded.
1441 case RLM_MODULE_NOOP:
1443 case RLM_MODULE_UPDATED:
1448 * If it's a fake request, don't send the proxy
1449 * packet. The outer tunnel session will take
1450 * care of doing that.
1452 if (request->packet->dst_port == 0) {
1453 request->home_server = NULL;
1457 if (request->home_server->server) {
1458 return proxy_to_virtual_server(request);
1461 if (!proxy_request(request)) {
1462 DEBUG("ERROR: Failed to proxy request %d", request->number);
1470 static void request_post_handler(REQUEST *request)
1472 int child_state = -1;
1473 struct timeval when;
1476 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1478 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1479 DEBUG2("Request %d was cancelled.", request->number);
1480 request->child_pid = NO_SUCH_CHILD_PID;
1481 request->child_state = REQUEST_DONE;
1485 if (request->child_state != REQUEST_RUNNING) {
1486 rad_panic("Internal sanity check failed");
1489 if ((request->reply->code == 0) &&
1490 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1491 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1492 request->reply->code = PW_AUTHENTICATION_REJECT;
1495 if (request->root->proxy_requests &&
1496 !request->in_proxy_hash &&
1497 (request->reply->code == 0) &&
1498 (request->packet->dst_port != 0) &&
1499 (request->packet->code != PW_STATUS_SERVER)) {
1500 int rcode = successfully_proxied_request(request);
1502 if (rcode == 1) return;
1505 * Failed proxying it (dead home servers, etc.)
1506 * Run it through Post-Proxy-Type = Fail, and
1507 * respond to the request.
1509 * Note that we're in a child thread here, so we
1510 * do NOT re-schedule the request. Instead, we
1511 * do what we would have done, which is run the
1512 * pre-handler, a NULL request handler, and then
1515 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1516 request_pre_handler(request);
1520 * Else we weren't supposed to proxy it,
1521 * OR we proxied it internally to a virutal server.
1526 * Fake requests don't get encoded or signed. The caller
1527 * also requires the reply VP's, so we don't free them
1530 if (request->packet->dst_port == 0) {
1531 /* FIXME: DEBUG going to the next request */
1532 request->child_pid = NO_SUCH_CHILD_PID;
1533 request->child_state = REQUEST_DONE;
1538 * Copy Proxy-State from the request to the reply.
1540 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1541 if (vp) pairadd(&request->reply->vps, vp);
1544 * Access-Requests get delayed or cached.
1546 switch (request->packet->code) {
1547 case PW_AUTHENTICATION_REQUEST:
1548 gettimeofday(&request->next_when, NULL);
1550 if (request->reply->code == 0) {
1552 * Check if the lack of response is intentional.
1554 vp = pairfind(request->config_items,
1555 PW_RESPONSE_PACKET_TYPE);
1556 if (!vp || (vp->vp_integer != 256)) {
1557 DEBUG2("There was no response configured: rejecting request %d",
1559 request->reply->code = PW_AUTHENTICATION_REJECT;
1561 DEBUG2("Not responding to request %d",
1567 * Run rejected packets through
1569 * Post-Auth-Type = Reject
1571 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1572 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1573 vp = radius_pairmake(request, &request->config_items,
1574 "Post-Auth-Type", "Reject",
1576 if (vp) rad_postauth(request);
1579 * If configured, delay Access-Reject packets.
1581 * If request->root->reject_delay = 0, we discover
1582 * that we have to send the packet now.
1584 when = request->received;
1585 when.tv_sec += request->root->reject_delay;
1587 if (timercmp(&when, &request->next_when, >)) {
1588 DEBUG2("Delaying reject of request %d for %d seconds",
1590 request->root->reject_delay);
1591 request->next_when = when;
1592 request->next_callback = reject_delay;
1593 request->child_pid = NO_SUCH_CHILD_PID;
1594 request->child_state = REQUEST_REJECT_DELAY;
1599 request->next_when.tv_sec += request->root->cleanup_delay;
1600 request->next_callback = cleanup_delay;
1601 child_state = REQUEST_CLEANUP_DELAY;
1604 case PW_ACCOUNTING_REQUEST:
1605 request->next_callback = NULL; /* just to be safe */
1606 child_state = REQUEST_DONE;
1610 * FIXME: Status-Server should probably not be
1613 case PW_STATUS_SERVER:
1614 request->next_callback = NULL;
1615 child_state = REQUEST_DONE;
1619 rad_panic("Unknown packet type");
1624 * Suppress "no reply" packets here, unless we're reading
1625 * from the "detail" file. In that case, we've got to
1626 * tell the detail file handler that the request is dead,
1627 * and it should re-send it.
1628 * If configured, encode, sign, and send.
1630 if ((request->reply->code != 0) ||
1631 (request->listener->type == RAD_LISTEN_DETAIL)) {
1632 request->listener->send(request->listener, request);
1636 * Clean up. These are no longer needed.
1638 pairfree(&request->config_items);
1640 pairfree(&request->packet->vps);
1641 request->username = NULL;
1642 request->password = NULL;
1644 pairfree(&request->reply->vps);
1646 if (request->proxy) {
1647 pairfree(&request->proxy->vps);
1649 if (request->proxy_reply) {
1650 pairfree(&request->proxy_reply->vps);
1654 * We're not tracking responses from the home
1655 * server, we can therefore free this memory in
1658 if (!request->in_proxy_hash) {
1659 rad_free(&request->proxy);
1660 rad_free(&request->proxy_reply);
1661 request->home_server = NULL;
1665 DEBUG2("Finished request %d.", request->number);
1667 request->child_state = child_state;
1670 * Single threaded mode: update timers now.
1672 if (!have_children) wait_a_bit(request);
1676 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1680 RAD_SNMP_TYPE_INC(request->listener, total_dup_requests);
1681 RAD_SNMP_CLIENT_INC(request->listener, client, dup_requests);
1683 switch (request->child_state) {
1684 case REQUEST_QUEUED:
1685 case REQUEST_RUNNING:
1687 radlog(L_ERR, "Discarding duplicate request from "
1688 "client %s port %d - ID: %d due to unfinished request %d",
1690 request->packet->src_port,request->packet->id,
1694 case REQUEST_PROXIED:
1696 * We're not supposed to have duplicate
1697 * accounting packets. The other states handle
1698 * duplicates fine (discard, or send duplicate
1699 * reply). But we do NOT want to retransmit an
1700 * accounting request here, because that would
1701 * involve updating the Acct-Delay-Time, and
1702 * therefore changing the packet Id, etc.
1704 * Instead, we just discard the packet. We may
1705 * eventually respond, or the client will send a
1706 * new accounting packet.
1708 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1712 check_for_zombie_home_server(request);
1715 * If we've just discovered that the home server is
1716 * dead, send the packet to another one.
1718 if ((request->packet->dst_port != 0) &&
1719 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1722 remove_from_proxy_hash(request);
1724 home = home_server_ldb(NULL, request->home_pool, request);
1726 DEBUG2("Failed to find live home server for request %d", request->number);
1729 * Do post-request processing,
1730 * and any insertion of necessary
1733 post_proxy_fail_handler(request);
1737 request->proxy->code = request->packet->code;
1738 request->proxy->dst_ipaddr = home->ipaddr;
1739 request->proxy->dst_port = home->port;
1740 request->home_server = home;
1743 * Free the old packet, to force re-encoding
1745 free(request->proxy->data);
1746 request->proxy->data = NULL;
1747 request->proxy->data_len = 0;
1750 * Try to proxy the request.
1752 if (!proxy_request(request)) {
1753 DEBUG("ERROR: Failed to re-proxy request %d", request->number);
1754 goto no_home_servers;
1758 * This code executes in the main server
1759 * thread, so there's no need for locking.
1761 rad_assert(request->next_callback != NULL);
1762 INSERT_EVENT(request->next_callback, request);
1763 request->next_callback = NULL;
1765 } /* else the home server is still alive */
1767 DEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1768 inet_ntop(request->proxy->dst_ipaddr.af,
1769 &request->proxy->dst_ipaddr.ipaddr,
1770 buffer, sizeof(buffer)),
1771 request->proxy->dst_port,
1772 request->proxy->id);
1773 request->num_proxied_requests++;
1774 request->proxy_listener->send(request->proxy_listener,
1778 case REQUEST_REJECT_DELAY:
1779 DEBUG2("Waiting to send Access-Reject "
1780 "to client %s port %d - ID: %d",
1782 request->packet->src_port, request->packet->id);
1785 case REQUEST_CLEANUP_DELAY:
1787 DEBUG2("Sending duplicate reply "
1788 "to client %s port %d - ID: %d",
1790 request->packet->src_port, request->packet->id);
1791 request->listener->send(request->listener, request);
1797 static void received_conflicting_request(REQUEST *request,
1798 const RADCLIENT *client)
1800 radlog(L_ERR, "Received conflicting packet from "
1801 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
1803 request->packet->src_port, request->packet->id,
1807 * Nuke it from the request hash, so we can receive new
1810 remove_from_request_hash(request);
1812 switch (request->child_state) {
1814 * It's queued or running. Tell it to stop, and
1815 * wait for it to do so.
1817 case REQUEST_QUEUED:
1818 case REQUEST_RUNNING:
1819 request->master_state = REQUEST_STOP_PROCESSING;
1820 request->delay += request->delay >> 1;
1822 tv_add(&request->when, request->delay);
1824 INSERT_EVENT(wait_for_child_to_die, request);
1828 * It's in some other state, and therefore also
1829 * in the event queue. At some point, the
1830 * child will notice, and we can then delete it.
1833 rad_assert(request->ev != NULL);
1839 static int can_handle_new_request(RADIUS_PACKET *packet,
1841 struct main_config_t *root)
1844 * Count the total number of requests, to see if
1845 * there are too many. If so, return with an
1848 if (root->max_requests) {
1849 int request_count = fr_packet_list_num_elements(pl);
1852 * This is a new request. Let's see if
1853 * it makes us go over our configured
1856 if (request_count > root->max_requests) {
1857 radlog(L_ERR, "Dropping request (%d is too many): "
1858 "from client %s port %d - ID: %d", request_count,
1860 packet->src_port, packet->id);
1861 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
1862 "\tThe value for 'max_requests' is probably set too low.\n");
1864 } /* else there were a small number of requests */
1865 } /* else there was no configured limit for requests */
1868 * FIXME: Add per-client checks. If one client is sending
1869 * too many packets, start discarding them.
1871 * We increment the counters here, and decrement them
1872 * when the response is sent... somewhere in this file.
1876 * FUTURE: Add checks for system load. If the system is
1877 * busy, start dropping requests...
1879 * We can probably keep some statistics ourselves... if
1880 * there are more requests coming in than we can handle,
1881 * start dropping some.
1888 int received_request(rad_listen_t *listener,
1889 RADIUS_PACKET *packet, REQUEST **prequest,
1892 RADIUS_PACKET **packet_p;
1893 REQUEST *request = NULL;
1894 struct main_config_t *root = &mainconfig;
1896 packet_p = fr_packet_list_find(pl, packet);
1898 request = fr_packet2myptr(REQUEST, packet, packet_p);
1899 rad_assert(request->in_request_hash);
1901 if ((request->packet->data_len == packet->data_len) &&
1902 (memcmp(request->packet->vector, packet->vector,
1903 sizeof(packet->vector)) == 0)) {
1904 received_retransmit(request, client);
1909 * The new request is different from the old one,
1910 * but maybe the old is finished. If so, delete
1913 switch (request->child_state) {
1914 struct timeval when;
1917 gettimeofday(&when, NULL);
1921 * If the cached request was received
1922 * within the last second, then we
1923 * discard the NEW request instead of the
1924 * old one. This will happen ONLY when
1925 * the client is severely broken, and is
1926 * sending conflicting packets very
1929 if (timercmp(&when, &request->received, <)) {
1930 radlog(L_ERR, "Discarding conflicting packet from "
1931 "client %s port %d - ID: %d due to recent request %d.",
1933 packet->src_port, packet->id,
1938 received_conflicting_request(request, client);
1942 case REQUEST_REJECT_DELAY:
1943 case REQUEST_CLEANUP_DELAY:
1944 request->child_state = REQUEST_DONE;
1946 cleanup_delay(request);
1953 * We may want to quench the new request.
1955 if ((listener->type != RAD_LISTEN_DETAIL) &&
1956 !can_handle_new_request(packet, client, root)) {
1961 * Create and initialize the new request.
1963 request = request_alloc(); /* never fails */
1965 if ((request->reply = rad_alloc(0)) == NULL) {
1966 radlog(L_ERR, "No memory");
1970 request->listener = listener;
1971 request->client = client;
1972 request->packet = packet;
1973 request->packet->timestamp = request->timestamp;
1974 request->number = request_num_counter++;
1975 request->priority = listener->type;
1978 * Set virtual server identity
1980 if (client->server) {
1981 request->server = client->server;
1982 } else if (listener->server) {
1983 request->server = listener->server;
1985 request->server = NULL;
1989 * Remember the request in the list.
1991 if (!fr_packet_list_insert(pl, &request->packet)) {
1992 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
1993 request_free(&request);
1997 request->in_request_hash = TRUE;
1998 request->root = root;
2002 * The request passes many of our sanity checks.
2003 * From here on in, if anything goes wrong, we
2004 * send a reject message, instead of dropping the
2009 * Build the reply template from the request.
2012 request->reply->sockfd = request->packet->sockfd;
2013 request->reply->dst_ipaddr = request->packet->src_ipaddr;
2014 request->reply->src_ipaddr = request->packet->dst_ipaddr;
2015 request->reply->dst_port = request->packet->src_port;
2016 request->reply->src_port = request->packet->dst_port;
2017 request->reply->id = request->packet->id;
2018 request->reply->code = 0; /* UNKNOWN code */
2019 memcpy(request->reply->vector, request->packet->vector,
2020 sizeof(request->reply->vector));
2021 request->reply->vps = NULL;
2022 request->reply->data = NULL;
2023 request->reply->data_len = 0;
2025 request->master_state = REQUEST_ACTIVE;
2026 request->child_state = REQUEST_QUEUED;
2027 request->next_callback = NULL;
2029 gettimeofday(&request->received, NULL);
2030 request->timestamp = request->received.tv_sec;
2031 request->when = request->received;
2033 request->delay = USEC;
2035 tv_add(&request->when, request->delay);
2037 INSERT_EVENT(wait_a_bit, request);
2039 *prequest = request;
2044 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2050 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
2051 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
2052 inet_ntop(packet->src_ipaddr.af,
2053 &packet->src_ipaddr.ipaddr,
2054 buffer, sizeof(buffer)),
2061 * Also removes from the proxy hash if responses == requests
2063 request = lookup_in_proxy_hash(packet);
2066 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
2067 inet_ntop(packet->src_ipaddr.af,
2068 &packet->src_ipaddr.ipaddr,
2069 buffer, sizeof(buffer)),
2070 packet->src_port, packet->id);
2075 home = request->home_server;
2077 gettimeofday(&now, NULL);
2078 home->state = HOME_STATE_ALIVE;
2080 if (request->reply && request->reply->code != 0) {
2081 DEBUG2("We already replied to this request. Discarding response from home server.");
2087 * We had previously received a reply, so we don't need
2088 * to do anything here.
2090 if (request->proxy_reply) {
2091 if (memcmp(request->proxy_reply->vector,
2093 sizeof(request->proxy_reply->vector)) == 0) {
2094 DEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
2095 inet_ntop(packet->src_ipaddr.af,
2096 &packet->src_ipaddr.ipaddr,
2097 buffer, sizeof(buffer)),
2098 packet->src_port, packet->id,
2102 * ? The home server gave us a new proxy
2103 * reply, which doesn't match the old
2106 DEBUG2("Ignoring conflicting proxy reply");
2109 /* assert that there's an event queued for request? */
2114 switch (request->child_state) {
2115 case REQUEST_QUEUED:
2116 case REQUEST_RUNNING:
2117 rad_panic("Internal sanity check failed for child state");
2120 case REQUEST_REJECT_DELAY:
2121 case REQUEST_CLEANUP_DELAY:
2123 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'",
2124 inet_ntop(packet->src_ipaddr.af,
2125 &packet->src_ipaddr.ipaddr,
2126 buffer, sizeof(buffer)),
2127 packet->src_port, packet->id,
2129 /* assert that there's an event queued for request? */
2133 case REQUEST_PROXIED:
2137 request->proxy_reply = packet;
2141 * Perform RTT calculations, as per RFC 2988 (for TCP).
2142 * Note that we do so only if we sent one request, and
2143 * received one response. If we sent two requests, we
2144 * have no idea if the response is for the first, or for
2145 * the second request/
2147 if (request->num_proxied_requests == 1) {
2149 home_server *home = request->home_server;
2151 rtt = now.tv_sec - request->proxy_when.tv_sec;
2154 rtt -= request->proxy_when.tv_usec;
2156 if (!home->has_rtt) {
2157 home->has_rtt = TRUE;
2160 home->rttvar = rtt / 2;
2163 home->rttvar -= home->rttvar >> 2;
2164 home->rttvar += (home->srtt - rtt);
2165 home->srtt -= home->srtt >> 3;
2166 home->srtt += rtt >> 3;
2169 home->rto = home->srtt;
2170 if (home->rttvar > (USEC / 4)) {
2171 home->rto += home->rttvar * 4;
2179 * There's no incoming request, so it's a proxied packet
2182 if (!request->packet) {
2183 received_response_to_ping(request);
2187 request->child_state = REQUEST_QUEUED;
2188 request->when = now;
2189 request->delay = USEC;
2190 request->priority = RAD_LISTEN_PROXY;
2191 tv_add(&request->when, request->delay);
2194 * Wait a bit will take care of max_request_time
2196 INSERT_EVENT(wait_a_bit, request);
2202 static void event_detail_timer(void *ctx)
2204 rad_listen_t *listener = ctx;
2205 RAD_REQUEST_FUNP fun;
2208 if (listener->recv(listener, &fun, &request)) {
2209 if (!thread_pool_addrequest(request, fun)) {
2210 request->child_state = REQUEST_DONE;
2215 static void handle_signal_self(int flag)
2217 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2218 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2219 fr_event_loop_exit(el, 1);
2221 fr_event_loop_exit(el, 2);
2225 } /* else exit/term flags weren't set */
2228 * Tell the even loop to stop processing.
2230 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2232 static time_t last_hup = 0;
2234 DEBUG("Received HUP signal.");
2237 if ((int) (when - last_hup) < 5) {
2238 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2243 fr_event_loop_exit(el, 0x80);
2246 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2249 for (this = mainconfig.listen;
2251 this = this->next) {
2253 struct timeval when;
2255 if (this->type != RAD_LISTEN_DETAIL) continue;
2257 delay = detail_delay(this);
2258 if (!delay) continue;
2260 fr_event_now(el, &now);
2262 tv_add(&when, delay);
2264 if (delay > 100000) {
2265 DEBUG2("Delaying next detail event for %d.%01u seconds.",
2266 delay / USEC, (delay % USEC) / 100000);
2269 if (!fr_event_insert(el, event_detail_timer, this,
2271 radlog(L_ERR, "Failed remembering timer");
2277 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2280 for (this = mainconfig.listen;
2282 this = this->next) {
2283 if (this->type != RAD_LISTEN_PROXY) continue;
2285 if (!fr_event_fd_insert(el, 0, this->fd,
2286 event_socket_handler, this)) {
2287 radlog(L_ERR, "Failed remembering handle for proxy socket!");
2295 void radius_signal_self(int flag)
2297 handle_signal_self(flag);
2301 * Inform ourselves that we received a signal.
2303 void radius_signal_self(int flag)
2309 * The read MUST be non-blocking for this to work.
2311 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2315 for (i = 0; i < rcode; i++) {
2316 buffer[0] |= buffer[i];
2324 write(self_pipe[1], buffer, 1);
2328 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2329 UNUSED int fd, UNUSED void *ctx)
2334 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2335 if (rcode <= 0) return;
2338 * Merge pending signals.
2340 for (i = 0; i < rcode; i++) {
2341 buffer[0] |= buffer[i];
2344 handle_signal_self(buffer[0]);
2349 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
2352 rad_listen_t *listener = ctx;
2353 RAD_REQUEST_FUNP fun;
2356 rad_assert(xel == el);
2360 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2362 if (!listener->recv(listener, &fun, &request)) return;
2364 if (!thread_pool_addrequest(request, fun)) {
2365 request->child_state = REQUEST_DONE;
2371 * This function is called periodically to see if any FD's are
2372 * available for reading.
2374 static void event_poll_fds(UNUSED void *ctx)
2377 RAD_REQUEST_FUNP fun;
2380 struct timeval when;
2382 fr_event_now(el, &now);
2386 for (this = mainconfig.listen; this != NULL; this = this->next) {
2387 if (this->fd >= 0) continue;
2390 * Try to read something.
2392 * FIXME: This does poll AND receive.
2394 rcode = this->recv(this, &fun, &request);
2395 if (!rcode) continue;
2397 rad_assert(fun != NULL);
2398 rad_assert(request != NULL);
2400 if (!thread_pool_addrequest(request, fun)) {
2401 request->child_state = REQUEST_DONE;
2405 * We have an FD. Start watching it.
2407 if (this->fd >= 0) {
2409 * ... unless it's a detail file. In
2410 * that case, we rely on the signal to
2411 * self to know when to continue
2412 * processing the detail file.
2414 if (this->type == RAD_LISTEN_DETAIL) continue;
2417 * FIXME: this should be SNMP handler,
2418 * and we should do SOMETHING when the
2421 if (!fr_event_fd_insert(el, 0, this->fd,
2422 event_socket_handler, this)) {
2425 this->print(this, buffer, sizeof(buffer));
2426 rad_panic("Failed creating handler for snmp");
2434 if (!fr_event_insert(el, event_poll_fds, NULL,
2436 radlog(L_ERR, "Failed creating handler");
2442 static void event_status(struct timeval *wake)
2444 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2448 if (debug_flag == 0) {
2450 radlog(L_INFO, "Ready to process requests.");
2451 just_started = FALSE;
2457 DEBUG("Ready to process requests.");
2459 } else if ((wake->tv_sec != 0) ||
2460 (wake->tv_usec >= 100000)) {
2461 DEBUG("Waking up in %d.%01u seconds.",
2462 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2467 * FIXME: Put this somewhere else, where it isn't called
2468 * all of the time...
2471 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2473 * If there are no child threads, then there may
2474 * be child processes. In that case, wait for
2475 * their exit status, and throw that exit status
2476 * away. This helps get rid of zxombie children.
2478 while (waitpid(-1, &argval, WNOHANG) > 0) {
2487 * Externally-visibly functions.
2489 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2492 int has_snmp_listener = FALSE;
2493 rad_listen_t *this, *head = NULL;
2499 el = fr_event_list_create(event_status);
2502 pl = fr_packet_list_create(0);
2505 request_num_counter = 0;
2508 * Move all of the thread calls to this file?
2510 * It may be best for the mutexes to be in this file...
2512 have_children = spawn_flag;
2514 if (mainconfig.proxy_requests) {
2516 * Create the tree for managing proxied requests and
2519 proxy_list = fr_packet_list_create(1);
2520 if (!proxy_list) return 0;
2522 #ifdef HAVE_PTHREAD_H
2523 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2524 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2532 * Just before we spawn the child threads, force the log
2533 * subsystem to re-open the log file for every write.
2535 if (spawn_flag) force_log_reopen();
2537 #ifdef HAVE_PTHREAD_H
2538 if (thread_pool_init(cs, spawn_flag) < 0) {
2544 DEBUG2("%s: #### Skipping IP addresses and Ports ####",
2551 * Child threads need a pipe to signal us, as do the
2554 if (pipe(self_pipe) < 0) {
2555 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2559 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2560 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2564 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2565 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2570 if (!fr_event_fd_insert(el, 0, self_pipe[0],
2571 event_signal_handler, el)) {
2572 radlog(L_ERR, "Failed creating handler for signals");
2578 * Mark the proxy Fd's as unused.
2580 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2582 DEBUG2("%s: #### Opening IP addresses and Ports ####",
2585 if (listen_init(cs, &head) < 0) {
2590 * Add all of the sockets to the event loop.
2594 this = this->next) {
2597 this->print(this, buffer, sizeof(buffer));
2599 switch (this->type) {
2600 case RAD_LISTEN_DETAIL:
2601 DEBUG("Listening on %s", buffer);
2602 has_detail_listener = TRUE;
2605 case RAD_LISTEN_SNMP:
2606 DEBUG("Listening on SNMP %s", buffer);
2607 has_snmp_listener = TRUE;
2610 case RAD_LISTEN_PROXY:
2611 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2612 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2614 proxy_fds[this->fd & 0x1f] = this->fd;
2615 proxy_listeners[this->fd & 0x1f] = this;
2616 if (!fr_packet_list_socket_add(proxy_list,
2623 DEBUG("Listening on %s", buffer);
2628 * The file descriptor isn't ready. Poll for
2629 * when it will become ready. This is for SNMP
2630 * and detail file fd's.
2637 * The socket is open. It MUST be a socket,
2638 * as we don't pre-open the detail files (yet).
2640 * FIXME: if we DO open the detail files automatically,
2641 * then much of this code becomes simpler.
2643 if (!fr_event_fd_insert(el, 0, this->fd,
2644 event_socket_handler, this)) {
2645 this->print(this, buffer, sizeof(buffer));
2646 radlog(L_ERR, "Failed creating handler for socket %s",
2652 if (has_detail_listener || has_snmp_listener) {
2653 struct timeval when;
2655 gettimeofday(&when, NULL);
2658 if (!fr_event_insert(el, event_poll_fds, NULL,
2660 radlog(L_ERR, "Failed creating handler");
2665 mainconfig.listen = head;
2671 static int request_hash_cb(UNUSED void *ctx, void *data)
2673 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2675 rad_assert(request->in_proxy_hash == FALSE);
2677 fr_event_delete(el, &request->ev);
2678 remove_from_request_hash(request);
2679 request_free(&request);
2685 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2687 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2689 fr_packet_list_yank(proxy_list, request->proxy);
2690 request->in_proxy_hash = FALSE;
2692 if (!request->in_request_hash) {
2693 fr_event_delete(el, &request->ev);
2694 request_free(&request);
2701 void radius_event_free(void)
2704 * FIXME: Stop all threads, or at least check that
2705 * they're all waiting on the semaphore, and the queues
2710 * There are requests in the proxy hash that aren't
2711 * referenced from anywhere else. Remove them first.
2714 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2715 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2716 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2717 fr_packet_list_free(proxy_list);
2721 fr_packet_list_walk(pl, NULL, request_hash_cb);
2723 fr_packet_list_free(pl);
2726 fr_event_list_free(el);
2729 int radius_event_process(void)
2733 just_started = TRUE;
2735 return fr_event_loop(el);
2738 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
2740 if (request_pre_handler(request)) {
2741 rad_assert(fun != NULL);
2742 rad_assert(request != NULL);
2744 if (request->server) DEBUG("server %s {",
2748 if (request->server) DEBUG("} # server %s",
2751 request_post_handler(request);
2754 DEBUG2("Going to the next request");