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/radius_snmp.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;
48 * Ridiculous amounts of local state.
50 static fr_event_list_t *el = NULL;
51 static fr_packet_list_t *pl = NULL;
52 static int request_num_counter = 0;
53 static struct timeval now;
54 static time_t start_time;
55 static int have_children;
56 static int has_detail_listener = FALSE;
57 static int read_from_detail = TRUE;
58 static int just_started = FALSE;
61 static int self_pipe[2];
65 static pthread_mutex_t proxy_mutex;
67 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
68 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
71 * This is easier than ifdef's throughout the code.
73 #define PTHREAD_MUTEX_LOCK(_x)
74 #define PTHREAD_MUTEX_UNLOCK(_x)
77 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
79 static fr_packet_list_t *proxy_list = NULL;
82 * We keep the proxy FD's here. The RADIUS Id's are marked
83 * "allocated" per Id, via a bit per proxy FD.
85 static int proxy_fds[32];
86 static rad_listen_t *proxy_listeners[32];
88 static void request_post_handler(REQUEST *request);
89 static void wait_a_bit(void *ctx);
90 static void event_poll_fd(void *ctx);
92 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
95 radlog(L_ERR, "]%s:%d] %s", file, line, msg);
99 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
102 static void tv_add(struct timeval *tv, int usec_delay)
104 if (usec_delay > USEC) {
105 tv->tv_sec += usec_delay / USEC;
108 tv->tv_usec += usec_delay;
110 if (tv->tv_usec > USEC) {
117 static void snmp_inc_counters(REQUEST *request)
119 if (!request->root->do_snmp) return;
121 if (request->master_state == REQUEST_COUNTED) return;
123 if ((request->listener->type != RAD_LISTEN_AUTH) &&
124 (request->listener->type != RAD_LISTEN_ACCT)) return;
127 * Update the SNMP statistics.
129 * Note that we do NOT do this in a child thread.
130 * Instead, we update the stats when a request is
131 * deleted, because only the main server thread calls
132 * this function, which makes it thread-safe.
134 switch (request->reply->code) {
135 case PW_AUTHENTICATION_ACK:
136 rad_snmp.auth.total_responses++;
137 rad_snmp.auth.total_access_accepts++;
138 if (request->client && request->client->auth) {
139 request->client->auth->accepts++;
143 case PW_AUTHENTICATION_REJECT:
144 rad_snmp.auth.total_responses++;
145 rad_snmp.auth.total_access_rejects++;
146 if (request->client && request->client->auth) {
147 request->client->auth->rejects++;
151 case PW_ACCESS_CHALLENGE:
152 rad_snmp.auth.total_responses++;
153 rad_snmp.auth.total_access_challenges++;
154 if (request->client && request->client->auth) {
155 request->client->auth->challenges++;
159 case PW_ACCOUNTING_RESPONSE:
160 rad_snmp.acct.total_responses++;
161 if (request->client && request->client->acct) {
162 request->client->acct->responses++;
167 * No response, it must have been a bad
171 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
172 rad_snmp.auth.total_bad_authenticators++;
173 if (request->client && request->client->auth) {
174 request->client->auth->bad_authenticators++;
183 request->master_state = REQUEST_COUNTED;
186 #define snmp_inc_counters(_x)
190 static void remove_from_request_hash(REQUEST *request)
192 if (!request->in_request_hash) return;
194 fr_packet_list_yank(pl, request->packet);
195 request->in_request_hash = FALSE;
197 snmp_inc_counters(request);
201 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
203 RADIUS_PACKET **proxy_p;
206 PTHREAD_MUTEX_LOCK(&proxy_mutex);
207 proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
210 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
214 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
217 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
221 request->num_proxied_responses++;
224 * Catch the most common case of everything working
227 if (request->num_proxied_requests == request->num_proxied_responses) {
228 fr_packet_list_yank(proxy_list, request->proxy);
229 fr_packet_list_id_free(proxy_list, request->proxy);
230 request->in_proxy_hash = FALSE;
234 * On the FIRST reply, decrement the count of outstanding
235 * requests. Note that this is NOT the count of sent
236 * packets, but whether or not the home server has
239 if (!request->proxy_reply &&
240 request->home_server->currently_outstanding) {
241 request->home_server->currently_outstanding--;
244 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
250 static void remove_from_proxy_hash(REQUEST *request)
252 if (!request->in_proxy_hash) return;
254 PTHREAD_MUTEX_LOCK(&proxy_mutex);
255 fr_packet_list_yank(proxy_list, request->proxy);
256 fr_packet_list_id_free(proxy_list, request->proxy);
259 * The home server hasn't replied, but we've given up on
260 * this request. Don't count this request against the
263 if (!request->proxy_reply &&
264 request->home_server->currently_outstanding) {
265 request->home_server->currently_outstanding--;
268 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
270 request->in_proxy_hash = FALSE;
274 static int insert_into_proxy_hash(REQUEST *request)
279 rad_assert(request->proxy != NULL);
280 rad_assert(proxy_list != NULL);
282 request->proxy->sockfd = -1;
284 PTHREAD_MUTEX_LOCK(&proxy_mutex);
286 request->home_server->currently_outstanding++;
287 request->home_server->total_requests_sent++;
290 * On overflow, back up to ~0.
292 if (!request->home_server->total_requests_sent) {
293 request->home_server->total_requests_sent--;
296 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
298 rad_listen_t *proxy_listener;
301 * Allocate a new proxy fd. This function adds it
302 * into the list of listeners.
304 * FIXME!: Call event_fd_insert()! Otherwise this
305 * FD will never be used in select()!
307 * We probably want to add RADIUS_SIGNAL_SELF_FD,
308 * which tells us to walk over the listeners,
311 * Hmm... maybe do this for the detail file, too.
312 * that will simplify some of the rest of the code.
314 proxy_listener = proxy_new_listener();
315 if (!proxy_listener) {
316 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
317 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
325 proxy = proxy_listener->fd;
326 for (i = 0; i < 32; i++) {
327 DEBUG2("PROXY %d %d", i, proxy_fds[(proxy + i) & 0x1f]);
330 * Found a free entry. Save the socket,
331 * and remember where we saved it.
333 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
334 found = (proxy + i) & 0x1f;
335 proxy_fds[found] = proxy;
336 proxy_listeners[found] = proxy_listener;
340 rad_assert(found >= 0);
342 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
343 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
344 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
345 return 0; /* leak proxy_listener */
349 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
350 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
351 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
355 rad_assert(request->proxy->sockfd >= 0);
358 * FIXME: Hack until we get rid of rad_listen_t, and put
359 * the information into the packet_list.
362 for (i = 0; i < 32; i++) {
363 if (proxy_fds[i] == request->proxy->sockfd) {
370 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
371 DEBUG2("ERROR: All sockets are full.");
375 rad_assert(proxy_fds[proxy] != -1);
376 rad_assert(proxy_listeners[proxy] != NULL);
377 request->proxy_listener = proxy_listeners[proxy];
379 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
380 fr_packet_list_id_free(proxy_list, request->proxy);
381 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
382 DEBUG2("ERROR: Failed to insert entry into proxy list");
386 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
388 DEBUG3(" proxy: allocating destination %s port %d - Id %d",
389 inet_ntop(request->proxy->dst_ipaddr.af,
390 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
391 request->proxy->dst_port,
394 request->in_proxy_hash = TRUE;
401 * Called as BOTH an event, and in-line from other functions.
403 static void wait_for_proxy_id_to_expire(void *ctx)
405 REQUEST *request = ctx;
406 home_server *home = request->home_server;
408 rad_assert(request->magic == REQUEST_MAGIC);
409 rad_assert(request->proxy != NULL);
411 request->when = request->proxy_when;
412 request->when.tv_sec += home->response_window;
414 if ((request->num_proxied_requests == request->num_proxied_responses) ||
415 timercmp(&now, &request->when, >)) {
416 if (request->packet) {
417 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
418 request->number, request->packet->id,
419 (unsigned int) (request->timestamp - start_time));
421 DEBUG2("Cleaning up request %d with timestamp +%d",
423 (unsigned int) (request->timestamp - start_time));
425 fr_event_delete(el, &request->ev);
426 remove_from_proxy_hash(request);
427 remove_from_request_hash(request);
428 request_free(&request);
432 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
436 static void wait_for_child_to_die(void *ctx)
438 REQUEST *request = ctx;
440 rad_assert(request->magic == REQUEST_MAGIC);
442 if ((request->child_state == REQUEST_QUEUED) |
443 (request->child_state == REQUEST_RUNNING)) {
444 request->delay += (request->delay >> 1);
445 tv_add(&request->when, request->delay);
447 DEBUG2("Child is still stuck for request %d", request->number);
449 INSERT_EVENT(wait_for_child_to_die, request);
453 DEBUG2("Child is finally responsive for request %d", request->number);
454 remove_from_request_hash(request);
456 if (request->proxy) {
457 wait_for_proxy_id_to_expire(request);
461 request_free(&request);
465 static void cleanup_delay(void *ctx)
467 REQUEST *request = ctx;
469 rad_assert(request->magic == REQUEST_MAGIC);
470 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
471 (request->child_state == REQUEST_DONE));
473 remove_from_request_hash(request);
475 if (request->proxy && request->in_proxy_hash) {
476 wait_for_proxy_id_to_expire(request);
480 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
481 request->number, request->packet->id,
482 (unsigned int) (request->timestamp - start_time));
484 fr_event_delete(el, &request->ev);
485 request_free(&request);
489 static void reject_delay(void *ctx)
491 REQUEST *request = ctx;
493 rad_assert(request->magic == REQUEST_MAGIC);
494 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
496 DEBUG2("Sending delayed reject for request %d", request->number);
498 request->listener->send(request->listener, request);
500 request->when.tv_sec += request->root->cleanup_delay;
501 request->child_state = REQUEST_CLEANUP_DELAY;
503 INSERT_EVENT(cleanup_delay, request);
507 static void revive_home_server(void *ctx)
509 home_server *home = ctx;
511 home->state = HOME_STATE_ALIVE;
512 DEBUG2("Marking home server alive again... we have no idea if it really is alive or not.");
513 home->currently_outstanding = 0;
517 static void no_response_to_ping(void *ctx)
519 REQUEST *request = ctx;
520 home_server *home = request->home_server;
523 home->num_received_pings = 0;
525 DEBUG2("No response to status check %d from home server %s port %d",
527 inet_ntop(request->proxy->dst_ipaddr.af,
528 &request->proxy->dst_ipaddr.ipaddr,
529 buffer, sizeof(buffer)),
530 request->proxy->dst_port);
532 wait_for_proxy_id_to_expire(request);
536 static void received_response_to_ping(REQUEST *request)
538 home_server *home = request->home_server;
541 home->num_received_pings++;
543 DEBUG2("Received response to status check %d (%d in current sequence)",
544 request->number, home->num_received_pings);
546 if (home->num_received_pings < home->num_pings_to_alive) {
547 wait_for_proxy_id_to_expire(request);
551 DEBUG2("Marking home server %s port %d alive",
552 inet_ntop(request->proxy->dst_ipaddr.af,
553 &request->proxy->dst_ipaddr.ipaddr,
554 buffer, sizeof(buffer)),
555 request->proxy->dst_port);
557 if (!fr_event_delete(el, &home->ev)) {
558 DEBUG2("Hmm... no event for home server, WTF?");
561 if (!fr_event_delete(el, &request->ev)) {
562 DEBUG2("Hmm... no event for request, WTF?");
565 wait_for_proxy_id_to_expire(request);
567 home->state = HOME_STATE_ALIVE;
568 home->currently_outstanding = 0;
572 static void ping_home_server(void *ctx)
575 home_server *home = ctx;
579 if (home->state == HOME_STATE_ALIVE) {
580 radlog(L_INFO, "Suspicious proxy state... continuing");
584 request = request_alloc();
585 request->number = request_num_counter++;
587 request->proxy = rad_alloc(1);
588 rad_assert(request->proxy != NULL);
590 fr_event_now(el, &request->when);
591 home->when = request->when;
593 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
594 request->proxy->code = PW_STATUS_SERVER;
596 radius_pairmake(request, &request->proxy->vps,
597 "Message-Authenticator", "0x00", T_OP_SET);
599 } else if (home->type == HOME_TYPE_AUTH) {
600 request->proxy->code = PW_AUTHENTICATION_REQUEST;
602 radius_pairmake(request, &request->proxy->vps,
603 "User-Name", home->ping_user_name, T_OP_SET);
604 radius_pairmake(request, &request->proxy->vps,
605 "User-Password", home->ping_user_password, T_OP_SET);
606 radius_pairmake(request, &request->proxy->vps,
607 "Service-Type", "Authenticate-Only", T_OP_SET);
608 radius_pairmake(request, &request->proxy->vps,
609 "Message-Authenticator", "0x00", T_OP_SET);
612 request->proxy->code = PW_ACCOUNTING_REQUEST;
614 radius_pairmake(request, &request->proxy->vps,
615 "User-Name", home->ping_user_name, T_OP_SET);
616 radius_pairmake(request, &request->proxy->vps,
617 "Acct-Status-Type", "Stop", T_OP_SET);
618 radius_pairmake(request, &request->proxy->vps,
619 "Acct-Session-Id", "00000000", T_OP_SET);
620 vp = radius_pairmake(request, &request->proxy->vps,
621 "Event-Timestamp", "0", T_OP_SET);
622 vp->vp_date = now.tv_sec;
625 radius_pairmake(request, &request->proxy->vps,
626 "NAS-Identifier", "Status Check. Are you alive?",
629 request->proxy->dst_ipaddr = home->ipaddr;
630 request->proxy->dst_port = home->port;
631 request->home_server = home;
633 rad_assert(request->proxy_listener == NULL);
635 if (!insert_into_proxy_hash(request)) {
636 DEBUG2("Failed inserting status check %d into proxy hash. Discarding it.",
638 request_free(&request);
641 rad_assert(request->proxy_listener != NULL);
642 request->proxy_listener->send(request->proxy_listener,
645 request->next_callback = NULL;
646 request->child_state = REQUEST_PROXIED;
647 request->when.tv_sec += home->ping_timeout;;
649 INSERT_EVENT(no_response_to_ping, request);
652 * Add +/- 2s of jitter, as suggested in RFC 3539
653 * and in the Issues and Fixes draft.
655 home->when.tv_sec += home->ping_interval - 2;
658 jitter ^= (jitter >> 10);
659 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
661 tv_add(&home->when, jitter);
664 INSERT_EVENT(ping_home_server, home);
668 static void check_for_zombie_home_server(REQUEST *request)
674 home = request->home_server;
676 if (home->state != HOME_STATE_ZOMBIE) return;
678 when = home->zombie_period_start;
679 when.tv_sec += home->zombie_period;
681 if (timercmp(&now, &when, <)) {
686 * It's been a zombie for too long, mark it as
689 DEBUG2("FAILURE: Marking home server %s port %d as dead.",
690 inet_ntop(request->proxy->dst_ipaddr.af,
691 &request->proxy->dst_ipaddr.ipaddr,
692 buffer, sizeof(buffer)),
693 request->proxy->dst_port);
694 home->state = HOME_STATE_IS_DEAD;
695 home->num_received_pings = 0;
696 home->when = request->when;
698 if (home->ping_check != HOME_PING_CHECK_NONE) {
699 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
700 (home->ping_user_name != NULL));
701 home->when.tv_sec += home->ping_interval;
703 INSERT_EVENT(ping_home_server, home);
705 home->when.tv_sec += home->revive_interval;
707 INSERT_EVENT(revive_home_server, home);
712 static int setup_post_proxy_fail(REQUEST *request)
714 DICT_VALUE *dval = NULL;
717 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
718 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
720 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
721 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
727 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
730 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
734 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
735 if (!vp) vp = radius_paircreate(request, &request->config_items,
736 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
737 vp->vp_integer = dval->value;
739 rad_assert(request->proxy_reply == NULL);
745 static int null_handler(UNUSED REQUEST *request)
750 static void post_proxy_fail_handler(REQUEST *request)
753 * A proper time is required for wait_a_bit.
755 request->delay = USEC / 10;
756 gettimeofday(&now, NULL);
759 * Not set up to run Post-Proxy-Type = Fail.
761 * Mark the request as still running, and figure out what
764 if (!setup_post_proxy_fail(request)) {
765 request->child_state = REQUEST_RUNNING;
766 request_post_handler(request);
771 * Re-queue the request.
773 request->child_state = REQUEST_QUEUED;
777 * There is a post-proxy-type of fail. We run
778 * the request through the pre/post proxy
779 * handlers, just like it was a real proxied
780 * request. However, we set the per-request
781 * handler to NULL, as we don't want to do
784 request->priority = 0;
785 rad_assert(request->proxy != NULL);
786 thread_pool_addrequest(request, null_handler);
791 /* maybe check this against wait_for_proxy_id_to_expire? */
792 static void no_response_to_proxied_request(void *ctx)
794 REQUEST *request = ctx;
798 rad_assert(request->magic == REQUEST_MAGIC);
799 rad_assert(request->child_state == REQUEST_PROXIED);
801 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
803 inet_ntop(request->proxy->dst_ipaddr.af,
804 &request->proxy->dst_ipaddr.ipaddr,
805 buffer, sizeof(buffer)),
806 request->proxy->dst_port);
808 check_for_zombie_home_server(request);
810 home = request->home_server;
812 post_proxy_fail_handler(request);
815 * Don't touch request due to race conditions
817 if (home->state == HOME_STATE_IS_DEAD) {
818 rad_assert(home->ev != NULL); /* or it will never wake up */
823 * Enable the zombie period when we notice that the home
824 * server hasn't responded. We also back-date the start
825 * of the zombie period to when the proxied request was
828 if (home->state == HOME_STATE_ALIVE) {
829 DEBUG2("WARNING: Marking home server %s port %d as zombie (it looks like it is dead).",
830 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
831 buffer, sizeof(buffer)),
833 home->state = HOME_STATE_ZOMBIE;
834 home->zombie_period_start = now;
835 home->zombie_period_start.tv_sec -= home->response_window;
841 static void wait_a_bit(void *ctx)
844 REQUEST *request = ctx;
845 fr_event_callback_t callback = NULL;
847 rad_assert(request->magic == REQUEST_MAGIC);
849 switch (request->child_state) {
851 case REQUEST_RUNNING:
852 when = request->received;
853 when.tv_sec += request->root->max_request_time;
856 * Normally called from the event loop with the
857 * proper event loop time. Otherwise, called from
858 * post proxy fail handler, which sets "now", and
859 * this call won't re-set it, because we're not
862 fr_event_now(el, &now);
864 if (timercmp(&now, &when, <)) {
865 if (request->delay < (USEC / 10)) {
866 request->delay = USEC / 10;
868 request->delay += request->delay >> 1;
870 tv_add(&request->when, request->delay);
871 callback = wait_a_bit;
874 /* FIXME: kill unresponsive children? */
875 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
876 (unsigned long)request->child_pid, request->number,
877 request->module ? request->module : "<server core>",
878 request->component ? request->component : "<server core>");
880 request->master_state = REQUEST_STOP_PROCESSING;
882 request->delay = USEC / 4;
883 tv_add(&request->when, request->delay);
884 callback = wait_for_child_to_die;
888 case REQUEST_REJECT_DELAY:
889 case REQUEST_CLEANUP_DELAY:
890 request->child_pid = NO_SUCH_CHILD_PID;
891 snmp_inc_counters(request);
893 case REQUEST_PROXIED:
894 rad_assert(request->next_callback != NULL);
895 rad_assert(request->next_callback != wait_a_bit);
897 request->when = request->next_when;
898 callback = request->next_callback;
899 request->next_callback = NULL;
903 * Mark the request as no longer running,
907 request->child_pid = NO_SUCH_CHILD_PID;
908 snmp_inc_counters(request);
909 cleanup_delay(request);
913 rad_panic("Internal sanity check failure");
917 INSERT_EVENT(callback, request);
921 static int request_pre_handler(REQUEST *request)
925 rad_assert(request->magic == REQUEST_MAGIC);
926 rad_assert(request->packet != NULL);
927 rad_assert(request->packet->dst_port != 0);
929 request->child_state = REQUEST_RUNNING;
932 * Don't decode the packet if it's an internal "fake"
933 * request. Instead, just return so that the caller can
936 if (request->packet->dst_port == 0) {
937 request->username = pairfind(request->packet->vps,
939 request->password = pairfind(request->packet->vps,
945 * Put the decoded packet into it's proper place.
947 if (request->proxy_reply != NULL) {
948 rcode = request->proxy_listener->decode(request->proxy_listener,
950 } else if (request->packet->vps == NULL) {
951 rcode = request->listener->decode(request->listener, request);
958 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
959 request->child_state = REQUEST_DONE;
963 if (!request->proxy) {
964 request->username = pairfind(request->packet->vps,
968 int post_proxy_type = 0;
972 * Delete any reply we had accumulated until now.
974 pairfree(&request->reply->vps);
977 * Run the packet through the post-proxy stage,
978 * BEFORE playing games with the attributes.
980 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
982 DEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
983 post_proxy_type = vp->vp_integer;
986 rad_assert(request->home_pool != NULL);
988 if (request->home_pool->virtual_server) {
989 const char *old_server = request->server;
991 request->server = request->home_pool->virtual_server;
992 DEBUG2(" server %s {", request->server);
993 rcode = module_post_proxy(post_proxy_type, request);
995 request->server = old_server;
997 rcode = module_post_proxy(post_proxy_type, request);
1001 * There may NOT be a proxy reply, as we may be
1002 * running Post-Proxy-Type = Fail.
1004 if (request->proxy_reply) {
1006 * Delete the Proxy-State Attributes from
1007 * the reply. These include Proxy-State
1008 * attributes from us and remote server.
1010 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1013 * Add the attributes left in the proxy
1014 * reply to the reply list.
1016 pairadd(&request->reply->vps, request->proxy_reply->vps);
1017 request->proxy_reply->vps = NULL;
1020 * Free proxy request pairs.
1022 pairfree(&request->proxy->vps);
1026 default: /* Don't do anything */
1028 case RLM_MODULE_FAIL:
1029 /* FIXME: debug print stuff */
1030 request->child_state = REQUEST_DONE;
1033 case RLM_MODULE_HANDLED:
1034 /* FIXME: debug print stuff */
1035 request->child_state = REQUEST_DONE;
1045 * Do state handling when we proxy a request.
1047 static int proxy_request(REQUEST *request)
1049 struct timeval when;
1052 if (!insert_into_proxy_hash(request)) {
1053 DEBUG("Error: Failed inserting request into proxy hash.");
1057 request->proxy_listener->encode(request->proxy_listener, request);
1059 when = request->received;
1060 when.tv_sec += request->root->max_request_time;
1062 gettimeofday(&request->proxy_when, NULL);
1064 request->next_when = request->proxy_when;
1065 request->next_when.tv_sec += request->home_server->response_window;
1067 rad_assert(request->home_server->response_window > 0);
1069 if (timercmp(&when, &request->next_when, <)) {
1070 request->next_when = when;
1072 request->next_callback = no_response_to_proxied_request;
1074 DEBUG2("Proxying request %d to home server %s port %d",
1076 inet_ntop(request->proxy->dst_ipaddr.af,
1077 &request->proxy->dst_ipaddr.ipaddr,
1078 buffer, sizeof(buffer)),
1079 request->proxy->dst_port);
1082 * Note that we set proxied BEFORE sending the packet.
1084 * Once we send it, the request is tainted, as
1085 * another thread may have picked it up. Don't
1088 request->num_proxied_requests = 1;
1089 request->num_proxied_responses = 0;
1090 request->child_pid = NO_SUCH_CHILD_PID;
1091 request->child_state = REQUEST_PROXIED;
1092 request->proxy_listener->send(request->proxy_listener,
1098 * Return 1 if we did proxy it, or the proxy attempt failed
1099 * completely. Either way, the caller doesn't touch the request
1100 * any more if we return 1.
1102 static int successfully_proxied_request(REQUEST *request)
1105 int pre_proxy_type = 0;
1106 VALUE_PAIR *realmpair;
1107 VALUE_PAIR *strippedname;
1111 REALM *realm = NULL;
1114 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1115 if (!realmpair || (realmpair->length == 0)) {
1119 realmname = (char *) realmpair->vp_strvalue;
1121 realm = realm_find(realmname);
1123 DEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1128 * Figure out which pool to use.
1130 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1131 pool = realm->auth_pool;
1133 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1134 pool = realm->acct_pool;
1137 rad_panic("Internal sanity check failed");
1141 DEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1146 home = home_server_ldb(realmname, pool, request);
1148 DEBUG2("ERROR: Failed to find live home server for realm %s",
1152 request->home_pool = pool;
1155 * Remember that we sent the request to a Realm.
1157 pairadd(&request->packet->vps,
1158 pairmake("Realm", realmname, T_OP_EQ));
1161 * We read the packet from a detail file, AND it came from
1162 * the server we're about to send it to. Don't do that.
1164 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1165 (request->listener->type == RAD_LISTEN_DETAIL) &&
1166 (home->ipaddr.af == AF_INET) &&
1167 (request->packet->src_ipaddr.af == AF_INET) &&
1168 (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1169 DEBUG2(" rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1174 * Allocate the proxy packet, only if it wasn't already
1175 * allocated by a module. This check is mainly to support
1176 * the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1178 * In those cases, the EAP module creates a "fake"
1179 * request, and recursively passes it through the
1180 * authentication stage of the server. The module then
1181 * checks if the request was supposed to be proxied, and
1182 * if so, creates a proxy packet from the TUNNELED request,
1183 * and not from the EAP request outside of the tunnel.
1185 * The proxy then works like normal, except that the response
1186 * packet is "eaten" by the EAP module, and encapsulated into
1189 if (!request->proxy) {
1190 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1191 radlog(L_ERR|L_CONS, "no memory");
1196 * Copy the request, then look up name and
1197 * plain-text password in the copy.
1199 * Note that the User-Name attribute is the
1200 * *original* as sent over by the client. The
1201 * Stripped-User-Name attribute is the one hacked
1202 * through the 'hints' file.
1204 request->proxy->vps = paircopy(request->packet->vps);
1208 * Strip the name, if told to.
1210 * Doing it here catches the case of proxied tunneled
1213 if (realm->striprealm == TRUE &&
1214 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1216 * If there's a Stripped-User-Name attribute in
1217 * the request, then use THAT as the User-Name
1218 * for the proxied request, instead of the
1221 * This is done by making a copy of the
1222 * Stripped-User-Name attribute, turning it into
1223 * a User-Name attribute, deleting the
1224 * Stripped-User-Name and User-Name attributes
1225 * from the vps list, and making the new
1226 * User-Name the head of the vps list.
1228 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1230 vp = radius_paircreate(request, NULL,
1231 PW_USER_NAME, PW_TYPE_STRING);
1232 rad_assert(vp != NULL); /* handled by above function */
1233 /* Insert at the START of the list */
1234 vp->next = request->proxy->vps;
1235 request->proxy->vps = vp;
1237 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1238 sizeof(vp->vp_strvalue));
1239 vp->length = strippedname->length;
1242 * Do NOT delete Stripped-User-Name.
1247 * If there is no PW_CHAP_CHALLENGE attribute but
1248 * there is a PW_CHAP_PASSWORD we need to add it
1249 * since we can't use the request authenticator
1250 * anymore - we changed it.
1252 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1253 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1254 vp = radius_paircreate(request, &request->proxy->vps,
1255 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1256 vp->length = AUTH_VECTOR_LEN;
1257 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1261 * The RFC's say we have to do this, but FreeRADIUS
1264 vp = radius_paircreate(request, &request->proxy->vps,
1265 PW_PROXY_STATE, PW_TYPE_OCTETS);
1266 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
1267 request->packet->id);
1268 vp->length = strlen(vp->vp_strvalue);
1271 * Should be done BEFORE inserting into proxy hash, as
1272 * pre-proxy may use this information, or change it.
1274 request->proxy->code = request->packet->code;
1275 request->proxy->dst_ipaddr = home->ipaddr;
1276 request->proxy->dst_port = home->port;
1277 request->home_server = home;
1280 * Call the pre-proxy routines.
1282 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1284 DEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1285 pre_proxy_type = vp->vp_integer;
1288 rad_assert(request->home_pool != NULL);
1290 if (request->home_pool->virtual_server) {
1291 const char *old_server = request->server;
1293 request->server = request->home_pool->virtual_server;
1294 DEBUG2(" server %s {", request->server);
1295 rcode = module_pre_proxy(pre_proxy_type, request);
1297 request->server = old_server;
1299 rcode = module_pre_proxy(pre_proxy_type, request);
1302 case RLM_MODULE_FAIL:
1303 case RLM_MODULE_INVALID:
1304 case RLM_MODULE_NOTFOUND:
1305 case RLM_MODULE_USERLOCK:
1307 /* FIXME: debug print failed stuff */
1310 case RLM_MODULE_REJECT:
1311 case RLM_MODULE_HANDLED:
1315 * Only proxy the packet if the pre-proxy code succeeded.
1317 case RLM_MODULE_NOOP:
1319 case RLM_MODULE_UPDATED:
1324 * If it's a fake request, don't send the proxy
1325 * packet. The outer tunnel session will take
1326 * care of doing that.
1328 if (request->packet->dst_port == 0) {
1329 request->home_server = NULL;
1333 if (!proxy_request(request)) {
1334 DEBUG("ERROR: Failed to proxy request %d", request->number);
1342 static void request_post_handler(REQUEST *request)
1344 int child_state = -1;
1345 struct timeval when;
1348 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1350 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1351 DEBUG2("Request %d was cancelled.", request->number);
1352 request->child_pid = NO_SUCH_CHILD_PID;
1353 request->child_state = REQUEST_DONE;
1357 if (request->child_state != REQUEST_RUNNING) {
1358 rad_panic("Internal sanity check failed");
1361 if ((request->reply->code == 0) &&
1362 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1363 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1364 request->reply->code = PW_AUTHENTICATION_REJECT;
1367 if (request->root->proxy_requests &&
1368 (request->reply->code == 0) &&
1369 (request->packet->dst_port != 0) &&
1370 (request->packet->code != PW_STATUS_SERVER)) {
1371 int rcode = successfully_proxied_request(request);
1373 if (rcode == 1) return;
1376 * Failed proxying it (dead home servers, etc.)
1377 * Run it through Post-Proxy-Type = Fail, and
1378 * respond to the request.
1380 * Note that we're in a child thread here, so we
1381 * do NOT re-schedule the request. Instead, we
1382 * do what we would have done, which is run the
1383 * pre-handler, a NULL request handler, and then
1386 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1387 request_pre_handler(request);
1391 * Else we weren't supposed to proxy it.
1396 * Fake requests don't get encoded or signed. The caller
1397 * also requires the reply VP's, so we don't free them
1400 if (request->packet->dst_port == 0) {
1401 /* FIXME: DEBUG going to the next request */
1402 request->child_pid = NO_SUCH_CHILD_PID;
1403 request->child_state = REQUEST_DONE;
1408 * Copy Proxy-State from the request to the reply.
1410 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1411 if (vp) pairadd(&request->reply->vps, vp);
1414 * Access-Requests get delayed or cached.
1416 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1417 gettimeofday(&request->next_when, NULL);
1419 if (request->reply->code == 0) {
1421 * Check if the lack of response is intentional.
1423 vp = pairfind(request->config_items,
1424 PW_RESPONSE_PACKET_TYPE);
1425 if (!vp || (vp->vp_integer != 256)) {
1426 DEBUG2("There was no response configured: rejecting request %d",
1428 request->reply->code = PW_AUTHENTICATION_REJECT;
1430 DEBUG2("Not responding to request %d",
1436 * Run rejected packets through
1438 * Post-Auth-Type = Reject
1440 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1441 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1442 vp = radius_pairmake(request, &request->config_items,
1443 "Post-Auth-Type", "Reject",
1445 if (vp) rad_postauth(request);
1448 * If configured, delay Access-Reject packets.
1450 * If request->root->reject_delay = 0, we discover
1451 * that we have to send the packet now.
1453 when = request->received;
1454 when.tv_sec += request->root->reject_delay;
1456 if (timercmp(&when, &request->next_when, >)) {
1457 DEBUG2("Delaying reject of request %d for %d seconds",
1459 request->root->reject_delay);
1460 request->next_when = when;
1461 request->next_callback = reject_delay;
1462 request->child_pid = NO_SUCH_CHILD_PID;
1463 request->child_state = REQUEST_REJECT_DELAY;
1468 request->next_when.tv_sec += request->root->cleanup_delay;
1469 request->next_callback = cleanup_delay;
1470 child_state = REQUEST_CLEANUP_DELAY;
1472 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1473 request->next_callback = NULL; /* just to be safe */
1474 child_state = REQUEST_DONE;
1477 * FIXME: Status-Server should probably not be
1480 } else if (request->packet->code == PW_STATUS_SERVER) {
1481 request->next_callback = NULL;
1482 child_state = REQUEST_DONE;
1485 rad_panic("Unknown packet type");
1489 * Suppress "no reply" packets here, unless we're reading
1490 * from the "detail" file. In that case, we've got to
1491 * tell the detail file handler that the request is dead,
1492 * and it should re-send it.
1493 * If configured, encode, sign, and send.
1495 if ((request->reply->code != 0) ||
1496 (request->listener->type == RAD_LISTEN_DETAIL)) {
1497 request->listener->send(request->listener, request);
1501 * Clean up. These are no longer needed.
1503 pairfree(&request->config_items);
1505 pairfree(&request->packet->vps);
1506 request->username = NULL;
1507 request->password = NULL;
1509 pairfree(&request->reply->vps);
1511 if (request->proxy) {
1512 pairfree(&request->proxy->vps);
1514 if (request->proxy_reply) {
1515 pairfree(&request->proxy_reply->vps);
1519 * We're not tracking responses from the home
1520 * server, we can therefore free this memory in
1523 if (!request->in_proxy_hash) {
1524 rad_free(&request->proxy);
1525 rad_free(&request->proxy_reply);
1526 request->home_server = NULL;
1530 DEBUG2("Finished request %d.", request->number);
1532 request->child_state = child_state;
1536 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1540 RAD_SNMP_TYPE_INC(request->listener, total_dup_requests);
1541 RAD_SNMP_CLIENT_INC(request->listener, client, dup_requests);
1543 switch (request->child_state) {
1544 case REQUEST_QUEUED:
1545 case REQUEST_RUNNING:
1547 radlog(L_ERR, "Discarding duplicate request from "
1548 "client %s port %d - ID: %d due to unfinished request %d",
1550 request->packet->src_port,request->packet->id,
1554 case REQUEST_PROXIED:
1556 * We're not supposed to have duplicate
1557 * accounting packets. The other states handle
1558 * duplicates fine (discard, or send duplicate
1559 * reply). But we do NOT want to retransmit an
1560 * accounting request here, because that would
1561 * involve updating the Acct-Delay-Time, and
1562 * therefore changing the packet Id, etc.
1564 * Instead, we just discard the packet. We may
1565 * eventually respond, or the client will send a
1566 * new accounting packet.
1568 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1572 check_for_zombie_home_server(request);
1575 * If we've just discovered that the home server is
1576 * dead, send the packet to another one.
1578 if ((request->packet->dst_port != 0) &&
1579 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1582 remove_from_proxy_hash(request);
1584 home = home_server_ldb(NULL, request->home_pool, request);
1586 DEBUG2("Failed to find live home server for request %d", request->number);
1589 * Do post-request processing,
1590 * and any insertion of necessary
1593 post_proxy_fail_handler(request);
1597 request->proxy->code = request->packet->code;
1598 request->proxy->dst_ipaddr = home->ipaddr;
1599 request->proxy->dst_port = home->port;
1600 request->home_server = home;
1603 * Free the old packet, to force re-encoding
1605 free(request->proxy->data);
1606 request->proxy->data = NULL;
1607 request->proxy->data_len = 0;
1610 * Try to proxy the request.
1612 if (!proxy_request(request)) {
1613 DEBUG("ERROR: Failed to re-proxy request %d", request->number);
1614 goto no_home_servers;
1618 * This code executes in the main server
1619 * thread, so there's no need for locking.
1621 rad_assert(request->next_callback != NULL);
1622 INSERT_EVENT(request->next_callback, request);
1623 request->next_callback = NULL;
1625 } /* else the home server is still alive */
1627 DEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1628 inet_ntop(request->proxy->dst_ipaddr.af,
1629 &request->proxy->dst_ipaddr.ipaddr,
1630 buffer, sizeof(buffer)),
1631 request->proxy->dst_port,
1632 request->proxy->id);
1633 request->num_proxied_requests++;
1634 request->proxy_listener->send(request->proxy_listener,
1638 case REQUEST_REJECT_DELAY:
1639 DEBUG2("Waiting to send Access-Reject "
1640 "to client %s port %d - ID: %d",
1642 request->packet->src_port, request->packet->id);
1645 case REQUEST_CLEANUP_DELAY:
1647 DEBUG2("Sending duplicate reply "
1648 "to client %s port %d - ID: %d",
1650 request->packet->src_port, request->packet->id);
1651 request->listener->send(request->listener, request);
1657 static void received_conflicting_request(REQUEST *request,
1658 const RADCLIENT *client)
1660 radlog(L_ERR, "Received conflicting packet from "
1661 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
1663 request->packet->src_port, request->packet->id,
1667 * Nuke it from the request hash, so we can receive new
1670 remove_from_request_hash(request);
1672 switch (request->child_state) {
1674 * It's queued or running. Tell it to stop, and
1675 * wait for it to do so.
1677 case REQUEST_QUEUED:
1678 case REQUEST_RUNNING:
1679 request->master_state = REQUEST_STOP_PROCESSING;
1680 request->delay += request->delay >> 1;
1682 tv_add(&request->when, request->delay);
1684 INSERT_EVENT(wait_for_child_to_die, request);
1688 * It's in some other state, and therefore also
1689 * in the event queue. At some point, the
1690 * child will notice, and we can then delete it.
1693 rad_assert(request->ev != NULL);
1699 static int can_handle_new_request(RADIUS_PACKET *packet,
1701 struct main_config_t *root)
1704 * Count the total number of requests, to see if
1705 * there are too many. If so, return with an
1708 if (root->max_requests) {
1709 int request_count = fr_packet_list_num_elements(pl);
1712 * This is a new request. Let's see if
1713 * it makes us go over our configured
1716 if (request_count > root->max_requests) {
1717 radlog(L_ERR, "Dropping request (%d is too many): "
1718 "from client %s port %d - ID: %d", request_count,
1720 packet->src_port, packet->id);
1721 radlog(L_INFO, "WARNING: Please check the %s file.\n"
1722 "\tThe value for 'max_requests' is probably set too low.\n", root->radiusd_conf);
1724 } /* else there were a small number of requests */
1725 } /* else there was no configured limit for requests */
1728 * FIXME: Add per-client checks. If one client is sending
1729 * too many packets, start discarding them.
1731 * We increment the counters here, and decrement them
1732 * when the response is sent... somewhere in this file.
1736 * FUTURE: Add checks for system load. If the system is
1737 * busy, start dropping requests...
1739 * We can probably keep some statistics ourselves... if
1740 * there are more requests coming in than we can handle,
1741 * start dropping some.
1748 int received_request(rad_listen_t *listener,
1749 RADIUS_PACKET *packet, REQUEST **prequest,
1752 RADIUS_PACKET **packet_p;
1753 REQUEST *request = NULL;
1754 struct main_config_t *root = &mainconfig;
1756 packet_p = fr_packet_list_find(pl, packet);
1758 request = fr_packet2myptr(REQUEST, packet, packet_p);
1759 rad_assert(request->in_request_hash);
1761 if ((request->packet->data_len == packet->data_len) &&
1762 (memcmp(request->packet->vector, packet->vector,
1763 sizeof(packet->vector)) == 0)) {
1764 received_retransmit(request, client);
1769 * The new request is different from the old one,
1770 * but maybe the old is finished. If so, delete
1773 switch (request->child_state) {
1774 struct timeval when;
1777 gettimeofday(&when, NULL);
1781 * If the cached request was received
1782 * within the last second, then we
1783 * discard the NEW request instead of the
1784 * old one. This will happen ONLY when
1785 * the client is severely broken, and is
1786 * sending conflicting packets very
1789 if (timercmp(&when, &request->received, <)) {
1790 radlog(L_ERR, "Discarding conflicting packet from "
1791 "client %s port %d - ID: %d due to recent request %d.",
1793 packet->src_port, packet->id,
1798 received_conflicting_request(request, client);
1802 case REQUEST_REJECT_DELAY:
1803 case REQUEST_CLEANUP_DELAY:
1804 request->child_state = REQUEST_DONE;
1806 cleanup_delay(request);
1813 * We may want to quench the new request.
1815 if (!can_handle_new_request(packet, client, root)) {
1820 * Create and initialize the new request.
1822 request = request_alloc(); /* never fails */
1824 if ((request->reply = rad_alloc(0)) == NULL) {
1825 radlog(L_ERR, "No memory");
1829 request->listener = listener;
1830 request->client = client;
1831 request->packet = packet;
1832 request->packet->timestamp = request->timestamp;
1833 request->number = request_num_counter++;
1834 request->priority = listener->type;
1837 * Set virtual server identity
1839 if (client->server) {
1840 request->server = client->server;
1841 } else if (listener->server) {
1842 request->server = listener->server;
1844 request->server = NULL;
1848 * Remember the request in the list.
1850 if (!fr_packet_list_insert(pl, &request->packet)) {
1851 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
1852 request_free(&request);
1856 request->in_request_hash = TRUE;
1857 request->root = root;
1861 * The request passes many of our sanity checks.
1862 * From here on in, if anything goes wrong, we
1863 * send a reject message, instead of dropping the
1868 * Build the reply template from the request.
1871 request->reply->sockfd = request->packet->sockfd;
1872 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1873 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1874 request->reply->dst_port = request->packet->src_port;
1875 request->reply->src_port = request->packet->dst_port;
1876 request->reply->id = request->packet->id;
1877 request->reply->code = 0; /* UNKNOWN code */
1878 memcpy(request->reply->vector, request->packet->vector,
1879 sizeof(request->reply->vector));
1880 request->reply->vps = NULL;
1881 request->reply->data = NULL;
1882 request->reply->data_len = 0;
1884 request->master_state = REQUEST_ACTIVE;
1885 request->child_state = REQUEST_QUEUED;
1886 request->next_callback = NULL;
1888 gettimeofday(&request->received, NULL);
1889 request->timestamp = request->received.tv_sec;
1890 request->when = request->received;
1892 request->delay = USEC / 10;
1894 tv_add(&request->when, request->delay);
1896 INSERT_EVENT(wait_a_bit, request);
1898 *prequest = request;
1903 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
1909 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
1910 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
1911 inet_ntop(packet->src_ipaddr.af,
1912 &packet->src_ipaddr.ipaddr,
1913 buffer, sizeof(buffer)),
1920 * Also removes from the proxy hash if responses == requests
1922 request = lookup_in_proxy_hash(packet);
1925 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
1926 inet_ntop(packet->src_ipaddr.af,
1927 &packet->src_ipaddr.ipaddr,
1928 buffer, sizeof(buffer)),
1929 packet->src_port, packet->id);
1934 home = request->home_server;
1936 gettimeofday(&now, NULL);
1937 home->state = HOME_STATE_ALIVE;
1939 if (request->reply && request->reply->code != 0) {
1940 DEBUG2("We already replied to this request. Discarding response from home server.");
1946 * We had previously received a reply, so we don't need
1947 * to do anything here.
1949 if (request->proxy_reply) {
1950 if (memcmp(request->proxy_reply->vector,
1952 sizeof(request->proxy_reply->vector)) == 0) {
1953 DEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
1954 inet_ntop(packet->src_ipaddr.af,
1955 &packet->src_ipaddr.ipaddr,
1956 buffer, sizeof(buffer)),
1957 packet->src_port, packet->id,
1961 * ? The home server gave us a new proxy
1962 * reply, which doesn't match the old
1965 DEBUG2("Ignoring conflicting proxy reply");
1968 /* assert that there's an event queued for request? */
1973 switch (request->child_state) {
1974 case REQUEST_QUEUED:
1975 case REQUEST_RUNNING:
1976 rad_panic("Internal sanity check failed for child state");
1979 case REQUEST_REJECT_DELAY:
1980 case REQUEST_CLEANUP_DELAY:
1982 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'",
1983 inet_ntop(packet->src_ipaddr.af,
1984 &packet->src_ipaddr.ipaddr,
1985 buffer, sizeof(buffer)),
1986 packet->src_port, packet->id,
1988 /* assert that there's an event queued for request? */
1992 case REQUEST_PROXIED:
1996 request->proxy_reply = packet;
2000 * Perform RTT calculations, as per RFC 2988 (for TCP).
2001 * Note that we do so only if we sent one request, and
2002 * received one response. If we sent two requests, we
2003 * have no idea if the response is for the first, or for
2004 * the second request/
2006 if (request->num_proxied_requests == 1) {
2008 home_server *home = request->home_server;
2010 rtt = now.tv_sec - request->proxy_when.tv_sec;
2013 rtt -= request->proxy_when.tv_usec;
2015 if (!home->has_rtt) {
2016 home->has_rtt = TRUE;
2019 home->rttvar = rtt / 2;
2022 home->rttvar -= home->rttvar >> 2;
2023 home->rttvar += (home->srtt - rtt);
2024 home->srtt -= home->srtt >> 3;
2025 home->srtt += rtt >> 3;
2028 home->rto = home->srtt;
2029 if (home->rttvar > (USEC / 4)) {
2030 home->rto += home->rttvar * 4;
2038 * There's no incoming request, so it's a proxied packet
2041 if (!request->packet) {
2042 received_response_to_ping(request);
2046 request->child_state = REQUEST_QUEUED;
2047 request->when = now;
2048 request->delay = USEC / 10;
2049 request->priority = RAD_LISTEN_PROXY;
2050 tv_add(&request->when, request->delay);
2053 * Wait a bit will take care of max_request_time
2055 INSERT_EVENT(wait_a_bit, request);
2061 static void handle_signal_self(int flag)
2063 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2064 read_from_detail = TRUE;
2067 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2068 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2069 fr_event_loop_exit(el, 1);
2071 fr_event_loop_exit(el, 2);
2075 } /* else exit/term flags weren't set */
2078 * Tell the even loop to stop processing.
2080 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2082 static time_t last_hup = 0;
2084 DEBUG("Received HUP signal.");
2087 if ((int) (when - last_hup) < 5) {
2088 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2093 fr_event_loop_exit(el, 0x80);
2098 void radius_signal_self(int flag)
2100 handle_signal_self(flag);
2104 * Inform ourselves that we received a signal.
2106 void radius_signal_self(int flag)
2112 * The caller is telling us it's OK to read from the
2113 * detail files. However, we're not even listening on
2114 * the detail files. Therefore, suppress the flag to
2115 * avoid bothering the main worker thread.
2117 if ((flag == RADIUS_SIGNAL_SELF_DETAIL) &&
2118 !has_detail_listener) {
2123 * The read MUST be non-blocking for this to work.
2125 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2129 for (i = 1; i < rcode; i++) {
2130 buffer[0] |= buffer[i];
2135 memset(buffer + 1, 0, sizeof(buffer) - 1);
2140 write(self_pipe[1], buffer, 1);
2144 static void event_signal_handler(fr_event_list_t *xel, int fd, void *ctx)
2153 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2154 if (rcode <= 0) return;
2157 * Merge pending signals.
2159 for (i = 1; i < rcode; i++) {
2160 buffer[0] |= buffer[i];
2163 handle_signal_self(buffer[0]);
2168 * The given FD is closed. Delete it from the list of FD's to poll,
2169 * and set a timer to periodically look for an FD again.
2171 static void event_reset_fd(rad_listen_t *listener, int fd, int usec)
2173 struct timeval when;
2174 gettimeofday(&when, NULL);
2176 tv_add(&when, usec);
2178 if (!fr_event_fd_delete(el, 0, fd)) {
2179 rad_panic("Failed deleting fd");
2182 if (!fr_event_insert(el, event_poll_fd, listener,
2184 rad_panic("Failed inserting event");
2190 * Reads from the detail file if possible, OR sets up a timeout
2191 * to see if the detail file is ready for reading.
2193 * FIXME: On Linux, use inotify to watch the detail file. This
2196 static void event_detail_handler(fr_event_list_t *xel, int fd, void *ctx)
2198 rad_listen_t *listener = ctx;
2199 RAD_REQUEST_FUNP fun;
2202 rad_assert(xel == el);
2203 rad_assert(fd == listener->fd);
2208 * We're too busy to read from the detail file. Stop
2209 * watching the file, and instead go back to polling.
2211 if (!read_from_detail) {
2212 event_reset_fd(listener, fd, USEC);
2217 * FIXME: Put this somewhere else, where it isn't called
2218 * all of the time...
2220 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2222 * If there are no child threads, then there may
2223 * be child processes. In that case, wait for
2224 * their exit status, and throw that exit status
2225 * away. This helps get rid of zxombie children.
2227 while (waitpid(-1, &argval, WNOHANG) > 0) {
2233 * Didn't read anything from the detail file.
2234 * Wake up in one second to check it again.
2236 if (!listener->recv(listener, &fun, &request)) {
2237 event_reset_fd(listener, fd, USEC);
2242 * Drop the request into the thread pool,
2243 * and let the thread pool take care of
2244 * doing something with it.
2246 if (!thread_pool_addrequest(request, fun)) {
2247 request->child_state = REQUEST_DONE;
2251 * Reset based on the fd we were given, as detail_recv()
2252 * may have read all of the file, and closed it. It then
2253 * sets listener->fd = -1.
2255 event_reset_fd(listener, fd, *(int *) listener->data);
2259 static void event_socket_handler(fr_event_list_t *xel, int fd, void *ctx)
2261 rad_listen_t *listener = ctx;
2262 RAD_REQUEST_FUNP fun;
2265 rad_assert(xel == el);
2270 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2273 * FIXME: Put this somewhere else, where it isn't called
2274 * all of the time...
2276 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2278 * If there are no child threads, then there may
2279 * be child processes. In that case, wait for
2280 * their exit status, and throw that exit status
2281 * away. This helps get rid of zxombie children.
2283 while (waitpid(-1, &argval, WNOHANG) > 0) {
2288 if (!listener->recv(listener, &fun, &request)) return;
2290 if (!thread_pool_addrequest(request, fun)) {
2291 request->child_state = REQUEST_DONE;
2295 * If we've read a packet from a socket OTHER than the
2296 * detail file, we start ignoring the detail file.
2298 * When the child thread pulls the request off of the
2299 * queues, it will check if the queues are empty. Once
2300 * all queues are empty, it will signal us to read the
2301 * detail file again.
2303 read_from_detail = FALSE;
2308 * This function is called periodically to see if a file
2309 * descriptor is available for reading.
2311 static void event_poll_fd(void *ctx)
2314 RAD_REQUEST_FUNP fun;
2316 rad_listen_t *listener = ctx;
2317 fr_event_fd_handler_t handler;
2320 * Ignore the detail file if we're busy with other work.
2322 if ((listener->type == RAD_LISTEN_DETAIL) && !read_from_detail) {
2327 * Try to read a RADIUS packet. This also opens the FD.
2329 * FIXME: This does poll AND receive.
2331 rcode = listener->recv(listener, &fun, &request);
2334 * We read a request. Add it to the list for processing.
2337 rad_assert(fun != NULL);
2338 rad_assert(request != NULL);
2340 if (!thread_pool_addrequest(request, fun)) {
2341 request->child_state = REQUEST_DONE;
2346 * Still no FD, OR the fd was read completely, and then
2347 * closed. Re-set the polling timer and return.
2349 if (listener->fd < 0) {
2350 struct timeval when;
2353 gettimeofday(&when, NULL);
2356 if (!fr_event_insert(el, event_poll_fd, listener,
2358 rad_panic("Failed inserting event");
2364 if (listener->type == RAD_LISTEN_DETAIL) {
2365 handler = event_detail_handler;
2367 handler = event_socket_handler;
2371 * We have an FD. Start watching it.
2373 if (!fr_event_fd_insert(el, 0, listener->fd,
2374 handler, listener)) {
2377 listener->print(listener, buffer, sizeof(buffer));
2378 rad_panic("Failed creating handler for socket");
2383 static void event_status(struct timeval *wake)
2385 if (debug_flag == 0) {
2387 radlog(L_INFO, "Ready to process requests.");
2388 just_started = FALSE;
2394 DEBUG("Ready to process requests.");
2395 } else if ((wake->tv_sec != 0) ||
2396 (wake->tv_usec >= 100000)) {
2397 DEBUG("Waking up in %d.%01d seconds.\n",
2398 (int) wake->tv_sec, (int) wake->tv_usec / 100000);
2404 * Externally-visibly functions.
2406 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2409 rad_listen_t *this, *head = NULL;
2415 el = fr_event_list_create(event_status);
2418 pl = fr_packet_list_create(0);
2421 request_num_counter = 0;
2424 * Move all of the thread calls to this file?
2426 * It may be best for the mutexes to be in this file...
2428 have_children = spawn_flag;
2430 if (mainconfig.proxy_requests) {
2432 * Create the tree for managing proxied requests and
2435 proxy_list = fr_packet_list_create(1);
2436 if (!proxy_list) return 0;
2438 #ifdef HAVE_PTHREAD_H
2439 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2440 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2447 #ifdef HAVE_PTHREAD_H
2448 if (thread_pool_init(cs, spawn_flag) < 0) {
2454 DEBUG2("radiusd: #### Skipping IP addresses and Ports ####");
2460 * Child threads need a pipe to signal us, as do the
2463 if (pipe(self_pipe) < 0) {
2464 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2468 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2469 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2473 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2474 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2479 if (!fr_event_fd_insert(el, 0, self_pipe[0],
2480 event_signal_handler, el)) {
2481 radlog(L_ERR, "Failed creating handler for signals");
2487 * Mark the proxy Fd's as unused.
2489 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2491 DEBUG2("radiusd: #### Opening IP addresses and Ports ####");
2493 if (listen_init(cs, &head) < 0) {
2498 * Add all of the sockets to the event loop.
2500 * FIXME: New proxy sockets aren't currently added to the
2501 * event loop. They're allocated in a child thread, and
2502 * we don't have (or want) a mutex around the event
2507 this = this->next) {
2510 this->print(this, buffer, sizeof(buffer));
2512 switch (this->type) {
2513 case RAD_LISTEN_DETAIL:
2514 DEBUG("Listening on %s", buffer);
2515 has_detail_listener = TRUE;
2518 case RAD_LISTEN_PROXY:
2519 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2520 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2522 proxy_fds[this->fd & 0x1f] = this->fd;
2523 proxy_listeners[this->fd & 0x1f] = this;
2524 if (!fr_packet_list_socket_add(proxy_list,
2530 case RAD_LISTEN_SNMP:
2531 DEBUG("Listening on SNMP %s", buffer);
2535 DEBUG("Listening on %s", buffer);
2540 * The file descriptor isn't ready. Poll for
2541 * when it will become ready. This is for SNMP
2542 * and detail file fd's.
2545 struct timeval when;
2547 gettimeofday(&when, NULL);
2550 if (!fr_event_insert(el, event_poll_fd, this,
2552 radlog(L_ERR, "Failed creating handler");
2559 * The socket is open. It MUST be a socket,
2560 * as we don't pre-open the detail files (yet).
2562 * FIXME: if we DO open the detail files automatically,
2563 * then much of this code becomes simpler.
2565 if (!fr_event_fd_insert(el, 0, this->fd,
2566 event_socket_handler, this)) {
2567 this->print(this, buffer, sizeof(buffer));
2568 radlog(L_ERR, "Failed creating handler for socket %s",
2578 static int request_hash_cb(void *ctx, void *data)
2580 ctx = ctx; /* -Wunused */
2581 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2583 rad_assert(request->in_proxy_hash == FALSE);
2585 fr_event_delete(el, &request->ev);
2586 remove_from_request_hash(request);
2587 request_free(&request);
2593 static int proxy_hash_cb(void *ctx, void *data)
2595 ctx = ctx; /* -Wunused */
2596 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2598 fr_packet_list_yank(proxy_list, request->proxy);
2599 request->in_proxy_hash = FALSE;
2601 if (!request->in_request_hash) {
2602 fr_event_delete(el, &request->ev);
2603 request_free(&request);
2610 void radius_event_free(void)
2613 * FIXME: Stop all threads, or at least check that
2614 * they're all waiting on the semaphore, and the queues
2619 * There are requests in the proxy hash that aren't
2620 * referenced from anywhere else. Remove them first.
2623 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2624 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2625 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2626 fr_packet_list_free(proxy_list);
2630 fr_packet_list_walk(pl, NULL, request_hash_cb);
2632 fr_packet_list_free(pl);
2635 fr_event_list_free(el);
2638 int radius_event_process(void)
2642 just_started = TRUE;
2644 return fr_event_loop(el);
2647 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
2649 if (request_pre_handler(request)) {
2650 rad_assert(fun != NULL);
2651 rad_assert(request != NULL);
2653 if (request->server) DEBUG("server %s {",
2657 if (request->server) DEBUG("} # server %s",
2660 request_post_handler(request);
2663 DEBUG2("Going to the next request");