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;
48 * Ridiculous amounts of local state.
50 static lrad_event_list_t *el = NULL;
51 static lrad_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;
59 static int self_pipe[2];
62 static pthread_mutex_t proxy_mutex;
64 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
65 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
68 * This is easier than ifdef's throughout the code.
70 #define PTHREAD_MUTEX_LOCK(_x)
71 #define PTHREAD_MUTEX_UNLOCK(_x)
74 #define INSERT_EVENT(_function, _ctx) if (!lrad_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
76 static lrad_packet_list_t *proxy_list = NULL;
79 * We keep the proxy FD's here. The RADIUS Id's are marked
80 * "allocated" per Id, via a bit per proxy FD.
82 static int proxy_fds[32];
83 static rad_listen_t *proxy_listeners[32];
85 static void request_post_handler(REQUEST *request);
86 static void wait_a_bit(void *ctx);
87 static void event_poll_fd(void *ctx);
89 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
92 radlog(L_ERR, "]%s:%d] %s", file, line, msg);
96 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
99 static void tv_add(struct timeval *tv, int usec_delay)
101 if (usec_delay > USEC) {
102 tv->tv_sec += usec_delay / USEC;
105 tv->tv_usec += usec_delay;
107 if (tv->tv_usec > USEC) {
113 static VALUE_PAIR * radius_pairmake(REQUEST *request, VALUE_PAIR **vps,
114 const char *attribute, const char *value)
118 request = request; /* -Wunused */
120 vp = pairmake(attribute, value, T_OP_SET);
122 radlog(L_ERR, "No memory!");
123 rad_assert("No memory" == NULL);
133 static void snmp_inc_counters(REQUEST *request)
135 if (!request->root->do_snmp) return;
137 if (request->master_state == REQUEST_COUNTED) return;
139 if ((request->listener->type != RAD_LISTEN_AUTH) &&
140 (request->listener->type != RAD_LISTEN_ACCT)) return;
143 * Update the SNMP statistics.
145 * Note that we do NOT do this in a child thread.
146 * Instead, we update the stats when a request is
147 * deleted, because only the main server thread calls
148 * this function, which makes it thread-safe.
150 switch (request->reply->code) {
151 case PW_AUTHENTICATION_ACK:
152 rad_snmp.auth.total_responses++;
153 rad_snmp.auth.total_access_accepts++;
154 if (request->client) request->client->auth->accepts++;
157 case PW_AUTHENTICATION_REJECT:
158 rad_snmp.auth.total_responses++;
159 rad_snmp.auth.total_access_rejects++;
160 if (request->client) request->client->auth->rejects++;
163 case PW_ACCESS_CHALLENGE:
164 rad_snmp.auth.total_responses++;
165 rad_snmp.auth.total_access_challenges++;
166 if (request->client) request->client->auth->challenges++;
169 case PW_ACCOUNTING_RESPONSE:
170 rad_snmp.acct.total_responses++;
171 if (request->client) request->client->auth->responses++;
175 * No response, it must have been a bad
179 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
180 rad_snmp.auth.total_bad_authenticators++;
181 if (request->client) request->client->auth->bad_authenticators++;
189 request->master_state = REQUEST_COUNTED;
192 #define snmp_inc_counters(_x)
196 static void remove_from_request_hash(REQUEST *request)
198 if (!request->in_request_hash) return;
200 lrad_packet_list_yank(pl, request->packet);
201 request->in_request_hash = FALSE;
203 snmp_inc_counters(request);
207 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
209 RADIUS_PACKET **proxy_p;
212 PTHREAD_MUTEX_LOCK(&proxy_mutex);
213 proxy_p = lrad_packet_list_find_byreply(proxy_list, reply);
216 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
220 request = lrad_packet2myptr(REQUEST, proxy, proxy_p);
223 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
227 request->num_proxied_responses++;
230 * Catch the most common case of everything working
233 if (request->num_proxied_requests == request->num_proxied_responses) {
234 lrad_packet_list_yank(proxy_list, request->proxy);
235 lrad_packet_list_id_free(proxy_list, request->proxy);
236 request->in_proxy_hash = FALSE;
240 * On the FIRST reply, decrement the count of outstanding
241 * requests. Note that this is NOT the count of sent
242 * packets, but whether or not the home server has
245 if (!request->proxy_reply &&
246 request->home_server->currently_outstanding) {
247 request->home_server->currently_outstanding--;
250 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
256 static void remove_from_proxy_hash(REQUEST *request)
258 if (!request->in_proxy_hash) return;
260 PTHREAD_MUTEX_LOCK(&proxy_mutex);
261 lrad_packet_list_yank(proxy_list, request->proxy);
262 lrad_packet_list_id_free(proxy_list, request->proxy);
265 * The home server hasn't replied, but we've given up on
266 * this request. Don't count this request against the
269 if (!request->proxy_reply &&
270 request->home_server->currently_outstanding) {
271 request->home_server->currently_outstanding--;
274 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
276 request->in_proxy_hash = FALSE;
280 static int insert_into_proxy_hash(REQUEST *request)
285 rad_assert(request->proxy != NULL);
286 rad_assert(proxy_list != NULL);
288 request->proxy->sockfd = -1;
290 PTHREAD_MUTEX_LOCK(&proxy_mutex);
292 request->home_server->currently_outstanding++;
293 request->home_server->total_requests_sent++;
296 * On overflow, back up to ~0.
298 if (!request->home_server->total_requests_sent) {
299 request->home_server->total_requests_sent--;
302 if (!lrad_packet_list_id_alloc(proxy_list, request->proxy)) {
304 rad_listen_t *proxy_listener;
307 * Allocate a new proxy fd. This function adds it
308 * into the list of listeners.
310 * FIXME!: Call event_fd_insert()! Otherwise this
311 * FD will never be used in select()!
313 * We probably want to add RADIUS_SIGNAL_SELF_FD,
314 * which tells us to walk over the listeners,
317 * Hmm... maybe do this for the detail file, too.
318 * that will simplify some of the rest of the code.
320 proxy_listener = proxy_new_listener();
321 if (!proxy_listener) {
322 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
323 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
331 proxy = proxy_listener->fd;
332 for (i = 0; i < 32; i++) {
333 DEBUG2("PROXY %d %d", i, proxy_fds[(proxy + i) & 0x1f]);
336 * Found a free entry. Save the socket,
337 * and remember where we saved it.
339 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
340 found = (proxy + i) & 0x1f;
341 proxy_fds[found] = proxy;
342 proxy_listeners[found] = proxy_listener;
346 rad_assert(found >= 0);
348 if (!lrad_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
349 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
350 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
351 return 0; /* leak proxy_listener */
355 if (!lrad_packet_list_id_alloc(proxy_list, request->proxy)) {
356 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
357 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
361 rad_assert(request->proxy->sockfd >= 0);
364 * FIXME: Hack until we get rid of rad_listen_t, and put
365 * the information into the packet_list.
368 for (i = 0; i < 32; i++) {
369 if (proxy_fds[i] == request->proxy->sockfd) {
376 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
377 DEBUG2("ERROR: All sockets are full.");
381 rad_assert(proxy_fds[proxy] != -1);
382 rad_assert(proxy_listeners[proxy] != NULL);
383 request->proxy_listener = proxy_listeners[proxy];
385 if (!lrad_packet_list_insert(proxy_list, &request->proxy)) {
386 lrad_packet_list_id_free(proxy_list, request->proxy);
387 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
388 DEBUG2("ERROR: Failed to insert entry into proxy list");
392 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
394 DEBUG3(" proxy: allocating destination %s port %d - Id %d",
395 inet_ntop(request->proxy->dst_ipaddr.af,
396 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
397 request->proxy->dst_port,
400 request->in_proxy_hash = TRUE;
407 * Called as BOTH an event, and in-line from other functions.
409 static void wait_for_proxy_id_to_expire(void *ctx)
411 REQUEST *request = ctx;
412 home_server *home = request->home_server;
414 rad_assert(request->magic == REQUEST_MAGIC);
415 rad_assert(request->proxy != NULL);
417 request->when = request->proxy_when;
418 request->when.tv_sec += home->response_window;
420 if ((request->num_proxied_requests == request->num_proxied_responses) ||
421 timercmp(&now, &request->when, >)) {
422 if (request->packet) {
423 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
424 request->number, request->packet->id,
425 (unsigned int) (request->timestamp - start_time));
427 DEBUG2("Cleaning up request %d with timestamp +%d",
429 (unsigned int) (request->timestamp - start_time));
431 lrad_event_delete(el, &request->ev);
432 remove_from_proxy_hash(request);
433 remove_from_request_hash(request);
434 request_free(&request);
438 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
442 static void wait_for_child_to_die(void *ctx)
444 REQUEST *request = ctx;
446 rad_assert(request->magic == REQUEST_MAGIC);
448 if ((request->child_state == REQUEST_QUEUED) |
449 (request->child_state == REQUEST_RUNNING)) {
450 request->delay += (request->delay >> 1);
451 tv_add(&request->when, request->delay);
453 DEBUG2("Child is still stuck for request %d", request->number);
455 INSERT_EVENT(wait_for_child_to_die, request);
459 DEBUG2("Child is finally responsive for request %d", request->number);
460 remove_from_request_hash(request);
462 if (request->proxy) {
463 wait_for_proxy_id_to_expire(request);
467 request_free(&request);
471 static void cleanup_delay(void *ctx)
473 REQUEST *request = ctx;
475 rad_assert(request->magic == REQUEST_MAGIC);
476 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
477 (request->child_state == REQUEST_DONE));
479 remove_from_request_hash(request);
481 if (request->proxy && request->in_proxy_hash) {
482 wait_for_proxy_id_to_expire(request);
486 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
487 request->number, request->packet->id,
488 (unsigned int) (request->timestamp - start_time));
490 lrad_event_delete(el, &request->ev);
491 request_free(&request);
495 static void reject_delay(void *ctx)
497 REQUEST *request = ctx;
499 rad_assert(request->magic == REQUEST_MAGIC);
500 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
502 DEBUG2("Sending delayed reject for request %d", request->number);
504 request->listener->send(request->listener, request);
506 request->when.tv_sec += request->root->cleanup_delay;
507 request->child_state = REQUEST_CLEANUP_DELAY;
509 INSERT_EVENT(cleanup_delay, request);
513 static void revive_home_server(void *ctx)
515 home_server *home = ctx;
517 home->state = HOME_STATE_ALIVE;
518 DEBUG2("Marking home server alive again... we have no idea if it really is alive or not.");
519 home->currently_outstanding = 0;
523 static void no_response_to_ping(void *ctx)
525 REQUEST *request = ctx;
526 home_server *home = request->home_server;
529 home->num_received_pings = 0;
531 DEBUG2("No response to status check %d from home server %s port %d",
533 inet_ntop(request->proxy->dst_ipaddr.af,
534 &request->proxy->dst_ipaddr.ipaddr,
535 buffer, sizeof(buffer)),
536 request->proxy->dst_port);
538 wait_for_proxy_id_to_expire(request);
542 static void received_response_to_ping(REQUEST *request)
544 home_server *home = request->home_server;
547 home->num_received_pings++;
549 DEBUG2("Received response to status check %d (%d in current sequence)",
550 request->number, home->num_received_pings);
552 if (home->num_received_pings < home->num_pings_to_alive) {
553 wait_for_proxy_id_to_expire(request);
557 DEBUG2("Marking home server %s port %d alive",
558 inet_ntop(request->proxy->dst_ipaddr.af,
559 &request->proxy->dst_ipaddr.ipaddr,
560 buffer, sizeof(buffer)),
561 request->proxy->dst_port);
563 if (!lrad_event_delete(el, &home->ev)) {
564 DEBUG2("Hmm... no event for home server, WTF?");
567 if (!lrad_event_delete(el, &request->ev)) {
568 DEBUG2("Hmm... no event for request, WTF?");
571 wait_for_proxy_id_to_expire(request);
573 home->state = HOME_STATE_ALIVE;
574 home->currently_outstanding = 0;
578 static void ping_home_server(void *ctx)
581 home_server *home = ctx;
585 if (home->state == HOME_STATE_ALIVE) {
586 radlog(L_INFO, "Suspicious proxy state... continuing");
590 request = request_alloc();
591 request->number = request_num_counter++;
593 request->proxy = rad_alloc(1);
594 rad_assert(request->proxy != NULL);
596 gettimeofday(&request->when, NULL);
597 home->when = request->when;
599 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
600 request->proxy->code = PW_STATUS_SERVER;
602 radius_pairmake(request, &request->proxy->vps,
603 "Message-Authenticator", "0x00");
605 } else if (home->type == HOME_TYPE_AUTH) {
606 request->proxy->code = PW_AUTHENTICATION_REQUEST;
608 radius_pairmake(request, &request->proxy->vps,
609 "User-Name", home->ping_user_name);
610 radius_pairmake(request, &request->proxy->vps,
611 "User-Password", home->ping_user_password);
612 radius_pairmake(request, &request->proxy->vps,
613 "Service-Type", "Authenticate-Only");
614 radius_pairmake(request, &request->proxy->vps,
615 "Message-Authenticator", "0x00");
618 request->proxy->code = PW_ACCOUNTING_REQUEST;
620 radius_pairmake(request, &request->proxy->vps,
621 "User-Name", home->ping_user_name);
622 radius_pairmake(request, &request->proxy->vps,
623 "Acct-Status-Type", "Stop");
624 radius_pairmake(request, &request->proxy->vps,
625 "Acct-Session-Id", "00000000");
626 vp = radius_pairmake(request, &request->proxy->vps,
627 "Event-Timestamp", "0");
628 vp->vp_date = now.tv_sec;
631 radius_pairmake(request, &request->proxy->vps,
632 "NAS-Identifier", "Status Check. Are you alive?");
634 request->proxy->dst_ipaddr = home->ipaddr;
635 request->proxy->dst_port = home->port;
636 request->home_server = home;
638 rad_assert(request->proxy_listener == NULL);
640 if (!insert_into_proxy_hash(request)) {
641 DEBUG2("Failed inserting status check %d into proxy hash. Discarding it.",
643 request_free(&request);
646 rad_assert(request->proxy_listener != NULL);
647 request->proxy_listener->send(request->proxy_listener,
650 request->next_callback = NULL;
651 request->child_state = REQUEST_PROXIED;
652 request->when.tv_sec += home->ping_timeout;;
654 INSERT_EVENT(no_response_to_ping, request);
657 * Add +/- 2s of jitter, as suggested in RFC 3539
658 * and in the Issues and Fixes draft.
660 home->when.tv_sec += home->ping_interval - 2;
662 jitter = lrad_rand();
663 jitter ^= (jitter >> 10);
664 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
666 tv_add(&home->when, jitter);
669 INSERT_EVENT(ping_home_server, home);
673 static void check_for_zombie_home_server(REQUEST *request)
679 home = request->home_server;
681 if (home->state != HOME_STATE_ZOMBIE) return;
683 when = home->zombie_period_start;
684 when.tv_sec += home->zombie_period;
686 if (timercmp(&now, &when, <)) {
691 * It's been a zombie for too long, mark it as
694 DEBUG2("FAILURE: Marking home server %s port %d as dead.",
695 inet_ntop(request->proxy->dst_ipaddr.af,
696 &request->proxy->dst_ipaddr.ipaddr,
697 buffer, sizeof(buffer)),
698 request->proxy->dst_port);
699 home->state = HOME_STATE_IS_DEAD;
700 home->num_received_pings = 0;
701 home->when = request->when;
703 if (home->ping_check != HOME_PING_CHECK_NONE) {
704 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
705 (home->ping_user_name != NULL));
706 home->when.tv_sec += home->ping_interval;
708 INSERT_EVENT(ping_home_server, home);
710 home->when.tv_sec += home->revive_interval;
712 INSERT_EVENT(revive_home_server, home);
717 static int setup_post_proxy_fail(REQUEST *request)
719 DICT_VALUE *dval = NULL;
722 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
723 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
725 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
726 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
732 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
735 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
739 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
740 if (!vp) vp = radius_paircreate(request, &request->config_items,
741 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
742 vp->vp_integer = dval->value;
744 rad_assert(request->proxy_reply == NULL);
750 static int null_handler(UNUSED REQUEST *request)
755 static void post_proxy_fail_handler(REQUEST *request)
758 * Not set up to run Post-Proxy-Type = Fail.
760 * Mark the request as still running, and figure out what
763 if (!setup_post_proxy_fail(request)) {
764 request->child_state = REQUEST_RUNNING;
765 request_post_handler(request);
770 * Re-queue the request.
772 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 lrad_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;
855 if (timercmp(&now, &when, <)) {
856 callback = wait_a_bit;
858 /* FIXME: kill unresponsive children? */
859 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
860 (unsigned long)request->child_pid, request->number,
861 request->module ? request->module : "<server core>",
862 request->component ? request->component : "<server core>");
864 request->master_state = REQUEST_STOP_PROCESSING;
866 request->delay = USEC / 2;
867 tv_add(&request->when, request->delay);
868 callback = wait_for_child_to_die;
870 request->delay += request->delay >> 1;
873 case REQUEST_REJECT_DELAY:
874 case REQUEST_CLEANUP_DELAY:
875 request->child_pid = NO_SUCH_CHILD_PID;
876 snmp_inc_counters(request);
878 case REQUEST_PROXIED:
879 rad_assert(request->next_callback != NULL);
880 rad_assert(request->next_callback != wait_a_bit);
882 request->when = request->next_when;
883 callback = request->next_callback;
884 request->next_callback = NULL;
888 * Mark the request as no longer running,
892 request->child_pid = NO_SUCH_CHILD_PID;
893 snmp_inc_counters(request);
894 cleanup_delay(request);
898 rad_panic("Internal sanity check failure");
902 INSERT_EVENT(callback, request);
906 static int request_pre_handler(REQUEST *request)
910 rad_assert(request->magic == REQUEST_MAGIC);
911 rad_assert(request->packet != NULL);
912 rad_assert(request->packet->dst_port != 0);
914 request->child_state = REQUEST_RUNNING;
917 * Don't decode the packet if it's an internal "fake"
918 * request. Instead, just return so that the caller can
921 if (request->packet->dst_port == 0) {
922 request->username = pairfind(request->packet->vps,
924 request->password = pairfind(request->packet->vps,
930 * Put the decoded packet into it's proper place.
932 if (request->proxy_reply != NULL) {
933 rcode = request->proxy_listener->decode(request->proxy_listener,
935 } else if (request->packet->vps == NULL) {
936 rcode = request->listener->decode(request->listener, request);
943 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
944 request->child_state = REQUEST_DONE;
948 if (!request->proxy) {
949 request->username = pairfind(request->packet->vps,
953 int post_proxy_type = 0;
957 * Delete any reply we had accumulated until now.
959 pairfree(&request->reply->vps);
962 * Run the packet through the post-proxy stage,
963 * BEFORE playing games with the attributes.
965 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
967 DEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
968 post_proxy_type = vp->vp_integer;
971 rad_assert(request->home_pool != NULL);
973 if (request->home_pool->virtual_server) {
974 const char *old_server = request->server;
976 request->server = request->home_pool->virtual_server;
977 DEBUG2(" server %s {", request->server);
978 rcode = module_post_proxy(post_proxy_type, request);
980 request->server = old_server;
982 rcode = module_post_proxy(post_proxy_type, request);
986 * There may NOT be a proxy reply, as we may be
987 * running Post-Proxy-Type = Fail.
989 if (request->proxy_reply) {
991 * Delete the Proxy-State Attributes from
992 * the reply. These include Proxy-State
993 * attributes from us and remote server.
995 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
998 * Add the attributes left in the proxy
999 * reply to the reply list.
1001 pairadd(&request->reply->vps, request->proxy_reply->vps);
1002 request->proxy_reply->vps = NULL;
1005 * Free proxy request pairs.
1007 pairfree(&request->proxy->vps);
1011 default: /* Don't do anything */
1013 case RLM_MODULE_FAIL:
1014 /* FIXME: debug print stuff */
1015 request->child_state = REQUEST_DONE;
1018 case RLM_MODULE_HANDLED:
1019 /* FIXME: debug print stuff */
1020 request->child_state = REQUEST_DONE;
1030 * Do state handling when we proxy a request.
1032 static int proxy_request(REQUEST *request)
1034 struct timeval when;
1037 if (!insert_into_proxy_hash(request)) {
1038 DEBUG("Error: Failed inserting request into proxy hash.");
1042 request->proxy_listener->encode(request->proxy_listener, request);
1044 when = request->received;
1045 when.tv_sec += request->root->max_request_time;
1047 gettimeofday(&request->proxy_when, NULL);
1049 request->next_when = request->proxy_when;
1050 request->next_when.tv_sec += request->home_server->response_window;
1052 rad_assert(request->home_server->response_window > 0);
1054 if (timercmp(&when, &request->next_when, <)) {
1055 request->next_when = when;
1057 request->next_callback = no_response_to_proxied_request;
1059 DEBUG2("Proxying request %d to home server %s port %d",
1061 inet_ntop(request->proxy->dst_ipaddr.af,
1062 &request->proxy->dst_ipaddr.ipaddr,
1063 buffer, sizeof(buffer)),
1064 request->proxy->dst_port);
1067 * Note that we set proxied BEFORE sending the packet.
1069 * Once we send it, the request is tainted, as
1070 * another thread may have picked it up. Don't
1073 request->num_proxied_requests = 1;
1074 request->num_proxied_responses = 0;
1075 request->child_pid = NO_SUCH_CHILD_PID;
1076 request->child_state = REQUEST_PROXIED;
1077 request->proxy_listener->send(request->proxy_listener,
1083 * Return 1 if we did proxy it, or the proxy attempt failed
1084 * completely. Either way, the caller doesn't touch the request
1085 * any more if we return 1.
1087 static int successfully_proxied_request(REQUEST *request)
1090 int pre_proxy_type = 0;
1091 VALUE_PAIR *realmpair;
1092 VALUE_PAIR *strippedname;
1096 REALM *realm = NULL;
1099 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1100 if (!realmpair || (realmpair->length == 0)) {
1104 realmname = (char *) realmpair->vp_strvalue;
1106 realm = realm_find(realmname);
1108 DEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1113 * Figure out which pool to use.
1115 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1116 pool = realm->auth_pool;
1118 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1119 pool = realm->acct_pool;
1122 rad_panic("Internal sanity check failed");
1126 DEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1131 home = home_server_ldb(realmname, pool, request);
1133 DEBUG2("ERROR: Failed to find live home server for realm %s",
1137 request->home_pool = pool;
1140 * Remember that we sent the request to a Realm.
1142 pairadd(&request->packet->vps,
1143 pairmake("Realm", realmname, T_OP_EQ));
1146 * We read the packet from a detail file, AND it came from
1147 * the server we're about to send it to. Don't do that.
1149 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1150 (request->listener->type == RAD_LISTEN_DETAIL) &&
1151 (home->ipaddr.af == AF_INET) &&
1152 (request->packet->src_ipaddr.af == AF_INET) &&
1153 (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1154 DEBUG2(" rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1159 * Allocate the proxy packet, only if it wasn't already
1160 * allocated by a module. This check is mainly to support
1161 * the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1163 * In those cases, the EAP module creates a "fake"
1164 * request, and recursively passes it through the
1165 * authentication stage of the server. The module then
1166 * checks if the request was supposed to be proxied, and
1167 * if so, creates a proxy packet from the TUNNELED request,
1168 * and not from the EAP request outside of the tunnel.
1170 * The proxy then works like normal, except that the response
1171 * packet is "eaten" by the EAP module, and encapsulated into
1174 if (!request->proxy) {
1175 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1176 radlog(L_ERR|L_CONS, "no memory");
1181 * Copy the request, then look up name and
1182 * plain-text password in the copy.
1184 * Note that the User-Name attribute is the
1185 * *original* as sent over by the client. The
1186 * Stripped-User-Name attribute is the one hacked
1187 * through the 'hints' file.
1189 request->proxy->vps = paircopy(request->packet->vps);
1193 * Strip the name, if told to.
1195 * Doing it here catches the case of proxied tunneled
1198 if (realm->striprealm == TRUE &&
1199 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1201 * If there's a Stripped-User-Name attribute in
1202 * the request, then use THAT as the User-Name
1203 * for the proxied request, instead of the
1206 * This is done by making a copy of the
1207 * Stripped-User-Name attribute, turning it into
1208 * a User-Name attribute, deleting the
1209 * Stripped-User-Name and User-Name attributes
1210 * from the vps list, and making the new
1211 * User-Name the head of the vps list.
1213 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1215 vp = paircreate(PW_USER_NAME, PW_TYPE_STRING);
1217 radlog(L_ERR|L_CONS, "no memory");
1220 /* Insert at the START of the list */
1221 vp->next = request->proxy->vps;
1222 request->proxy->vps = vp;
1224 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1225 sizeof(vp->vp_strvalue));
1226 vp->length = strippedname->length;
1229 * Do NOT delete Stripped-User-Name.
1234 * If there is no PW_CHAP_CHALLENGE attribute but
1235 * there is a PW_CHAP_PASSWORD we need to add it
1236 * since we can't use the request authenticator
1237 * anymore - we changed it.
1239 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1240 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1241 vp = radius_paircreate(request, &request->proxy->vps,
1242 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1243 vp->length = AUTH_VECTOR_LEN;
1244 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1248 * The RFC's say we have to do this, but FreeRADIUS
1251 vp = radius_paircreate(request, &request->proxy->vps,
1252 PW_PROXY_STATE, PW_TYPE_OCTETS);
1253 sprintf(vp->vp_strvalue, "%d", request->packet->id);
1254 vp->length = strlen(vp->vp_strvalue);
1257 * Should be done BEFORE inserting into proxy hash, as
1258 * pre-proxy may use this information, or change it.
1260 request->proxy->code = request->packet->code;
1261 request->proxy->dst_ipaddr = home->ipaddr;
1262 request->proxy->dst_port = home->port;
1263 request->home_server = home;
1266 * Call the pre-proxy routines.
1268 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1270 DEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1271 pre_proxy_type = vp->vp_integer;
1274 rad_assert(request->home_pool != NULL);
1276 if (request->home_pool->virtual_server) {
1277 const char *old_server = request->server;
1279 request->server = request->home_pool->virtual_server;
1280 DEBUG2(" server %s {", request->server);
1281 rcode = module_pre_proxy(pre_proxy_type, request);
1283 request->server = old_server;
1285 rcode = module_pre_proxy(pre_proxy_type, request);
1288 case RLM_MODULE_FAIL:
1289 case RLM_MODULE_INVALID:
1290 case RLM_MODULE_NOTFOUND:
1291 case RLM_MODULE_USERLOCK:
1293 /* FIXME: debug print failed stuff */
1296 case RLM_MODULE_REJECT:
1297 case RLM_MODULE_HANDLED:
1301 * Only proxy the packet if the pre-proxy code succeeded.
1303 case RLM_MODULE_NOOP:
1305 case RLM_MODULE_UPDATED:
1310 * If it's a fake request, don't send the proxy
1311 * packet. The outer tunnel session will take
1312 * care of doing that.
1314 if (request->packet->dst_port == 0) {
1315 request->home_server = NULL;
1319 if (!proxy_request(request)) {
1320 DEBUG("ERROR: Failed to proxy request %d", request->number);
1328 static void request_post_handler(REQUEST *request)
1330 int child_state = -1;
1331 struct timeval when;
1334 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1336 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1337 DEBUG2("Request %d was cancelled.", request->number);
1338 request->child_pid = NO_SUCH_CHILD_PID;
1339 request->child_state = REQUEST_DONE;
1343 if (request->child_state != REQUEST_RUNNING) {
1344 rad_panic("Internal sanity check failed");
1347 if ((request->reply->code == 0) &&
1348 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1349 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1350 request->reply->code = PW_AUTHENTICATION_REJECT;
1353 if (request->root->proxy_requests &&
1355 (request->reply->code == 0) &&
1356 (request->packet->code != PW_STATUS_SERVER)) {
1357 int rcode = successfully_proxied_request(request);
1359 if (rcode == 1) return;
1362 * Failed proxying it (dead home servers, etc.)
1363 * Run it through Post-Proxy-Type = Fail, and
1364 * respond to the request.
1366 * Note that we're in a child thread here, so we
1367 * do NOT re-schedule the request. Instead, we
1368 * do what we would have done, which is run the
1369 * pre-handler, a NULL request handler, and then
1372 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1373 request_pre_handler(request);
1377 * Else we weren't supposed to proxy it.
1382 * Fake requests don't get encoded or signed. The caller
1383 * also requires the reply VP's, so we don't free them
1386 if (request->packet->dst_port == 0) {
1387 /* FIXME: DEBUG going to the next request */
1388 request->child_pid = NO_SUCH_CHILD_PID;
1389 request->child_state = REQUEST_DONE;
1394 * Copy Proxy-State from the request to the reply.
1396 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1397 if (vp) pairadd(&request->reply->vps, vp);
1400 * Access-Requests get delayed or cached.
1402 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1403 gettimeofday(&request->next_when, NULL);
1405 if (request->reply->code == 0) {
1407 * Check if the lack of response is intentional.
1409 vp = pairfind(request->config_items,
1410 PW_RESPONSE_PACKET_TYPE);
1411 if (!vp || (vp->vp_integer != 256)) {
1412 DEBUG2("There was no response configured: rejecting request %d",
1414 request->reply->code = PW_AUTHENTICATION_REJECT;
1416 DEBUG2("Not responding to request %d",
1422 * Run rejected packets through
1424 * Post-Auth-Type = Reject
1426 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1427 vp = pairmake("Post-Auth-Type", "Reject", T_OP_SET);
1429 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1430 pairadd(&request->config_items, vp);
1431 rad_postauth(request);
1432 } /* else no Reject section defined */
1435 * If configured, delay Access-Reject packets.
1437 * If request->root->reject_delay = 0, we discover
1438 * that we have to send the packet now.
1440 when = request->received;
1441 when.tv_sec += request->root->reject_delay;
1443 if (timercmp(&when, &request->next_when, >)) {
1444 DEBUG2("Delaying reject of request %d for %d seconds",
1446 request->root->reject_delay);
1447 request->next_when = when;
1448 request->next_callback = reject_delay;
1449 request->child_pid = NO_SUCH_CHILD_PID;
1450 request->child_state = REQUEST_REJECT_DELAY;
1455 request->next_when.tv_sec += request->root->cleanup_delay;
1456 request->next_callback = cleanup_delay;
1457 child_state = REQUEST_CLEANUP_DELAY;
1459 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1460 request->next_callback = NULL; /* just to be safe */
1461 child_state = REQUEST_DONE;
1464 * FIXME: Status-Server should probably not be
1467 } else if (request->packet->code == PW_STATUS_SERVER) {
1468 request->next_callback = NULL;
1469 child_state = REQUEST_DONE;
1472 rad_panic("Unknown packet type");
1476 * Suppress "no reply" packets here, unless we're reading
1477 * from the "detail" file. In that case, we've got to
1478 * tell the detail file handler that the request is dead,
1479 * and it should re-send it.
1480 * If configured, encode, sign, and send.
1482 if ((request->reply->code != 0) ||
1483 (request->listener->type == RAD_LISTEN_DETAIL)) {
1484 request->listener->send(request->listener, request);
1488 * Clean up. These are no longer needed.
1490 pairfree(&request->config_items);
1492 pairfree(&request->packet->vps);
1493 request->username = NULL;
1494 request->password = NULL;
1496 pairfree(&request->reply->vps);
1498 if (request->proxy) {
1499 pairfree(&request->proxy->vps);
1501 if (request->proxy_reply) {
1502 pairfree(&request->proxy_reply->vps);
1506 * We're not tracking responses from the home
1507 * server, we can therefore free this memory in
1510 if (!request->in_proxy_hash) {
1511 rad_free(&request->proxy);
1512 rad_free(&request->proxy_reply);
1513 request->home_server = NULL;
1517 DEBUG2("Finished request %d.", request->number);
1519 request->child_state = child_state;
1523 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1527 RAD_SNMP_TYPE_INC(request->listener, total_dup_requests);
1528 RAD_SNMP_CLIENT_INC(request->listener, client, dup_requests);
1530 switch (request->child_state) {
1531 case REQUEST_QUEUED:
1532 case REQUEST_RUNNING:
1534 radlog(L_ERR, "Discarding duplicate request from "
1535 "client %s port %d - ID: %d due to unfinished request %d",
1537 request->packet->src_port,request->packet->id,
1541 case REQUEST_PROXIED:
1543 * We're not supposed to have duplicate
1544 * accounting packets. The other states handle
1545 * duplicates fine (discard, or send duplicate
1546 * reply). But we do NOT want to retransmit an
1547 * accounting request here, because that would
1548 * involve updating the Acct-Delay-Time, and
1549 * therefore changing the packet Id, etc.
1551 * Instead, we just discard the packet. We may
1552 * eventually respond, or the client will send a
1553 * new accounting packet.
1555 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1559 check_for_zombie_home_server(request);
1562 * If we've just discovered that the home server is
1563 * dead, send the packet to another one.
1565 if ((request->packet->dst_port != 0) &&
1566 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1569 remove_from_proxy_hash(request);
1571 home = home_server_ldb(NULL, request->home_pool, request);
1573 DEBUG2("Failed to find live home server for request %d", request->number);
1576 * Do post-request processing,
1577 * and any insertion of necessary
1580 post_proxy_fail_handler(request);
1584 request->proxy->code = request->packet->code;
1585 request->proxy->dst_ipaddr = home->ipaddr;
1586 request->proxy->dst_port = home->port;
1587 request->home_server = home;
1590 * Free the old packet, to force re-encoding
1592 free(request->proxy->data);
1593 request->proxy->data = NULL;
1594 request->proxy->data_len = 0;
1597 * Try to proxy the request.
1599 if (!proxy_request(request)) {
1600 DEBUG("ERROR: Failed to re-proxy request %d", request->number);
1601 goto no_home_servers;
1605 * This code executes in the main server
1606 * thread, so there's no need for locking.
1608 rad_assert(request->next_callback != NULL);
1609 INSERT_EVENT(request->next_callback, request);
1610 request->next_callback = NULL;
1612 } /* else the home server is still alive */
1614 DEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1615 inet_ntop(request->proxy->dst_ipaddr.af,
1616 &request->proxy->dst_ipaddr.ipaddr,
1617 buffer, sizeof(buffer)),
1618 request->proxy->dst_port,
1619 request->proxy->id);
1620 request->num_proxied_requests++;
1621 request->proxy_listener->send(request->proxy_listener,
1625 case REQUEST_REJECT_DELAY:
1626 DEBUG2("Waiting to send Access-Reject "
1627 "to client %s port %d - ID: %d",
1629 request->packet->src_port, request->packet->id);
1632 case REQUEST_CLEANUP_DELAY:
1634 DEBUG2("Sending duplicate reply "
1635 "to client %s port %d - ID: %d",
1637 request->packet->src_port, request->packet->id);
1638 request->listener->send(request->listener, request);
1644 static void received_conflicting_request(REQUEST *request,
1645 const RADCLIENT *client)
1647 radlog(L_ERR, "Received conflicting packet from "
1648 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
1650 request->packet->src_port, request->packet->id,
1654 * Nuke it from the request hash, so we can receive new
1657 remove_from_request_hash(request);
1659 switch (request->child_state) {
1661 * It's queued or running. Tell it to stop, and
1662 * wait for it to do so.
1664 case REQUEST_QUEUED:
1665 case REQUEST_RUNNING:
1666 request->master_state = REQUEST_STOP_PROCESSING;
1667 request->delay += request->delay >> 1;
1669 tv_add(&request->when, request->delay);
1671 INSERT_EVENT(wait_for_child_to_die, request);
1675 * It's in some other state, and therefore also
1676 * in the event queue. At some point, the
1677 * child will notice, and we can then delete it.
1680 rad_assert(request->ev != NULL);
1686 static int can_handle_new_request(RADIUS_PACKET *packet,
1688 struct main_config_t *root)
1691 * Count the total number of requests, to see if
1692 * there are too many. If so, return with an
1695 if (root->max_requests) {
1696 int request_count = lrad_packet_list_num_elements(pl);
1699 * This is a new request. Let's see if
1700 * it makes us go over our configured
1703 if (request_count > root->max_requests) {
1704 radlog(L_ERR, "Dropping request (%d is too many): "
1705 "from client %s port %d - ID: %d", request_count,
1707 packet->src_port, packet->id);
1708 radlog(L_INFO, "WARNING: Please check the %s file.\n"
1709 "\tThe value for 'max_requests' is probably set too low.\n", root->radiusd_conf);
1711 } /* else there were a small number of requests */
1712 } /* else there was no configured limit for requests */
1715 * FIXME: Add per-client checks. If one client is sending
1716 * too many packets, start discarding them.
1718 * We increment the counters here, and decrement them
1719 * when the response is sent... somewhere in this file.
1723 * FUTURE: Add checks for system load. If the system is
1724 * busy, start dropping requests...
1726 * We can probably keep some statistics ourselves... if
1727 * there are more requests coming in than we can handle,
1728 * start dropping some.
1735 int received_request(rad_listen_t *listener,
1736 RADIUS_PACKET *packet, REQUEST **prequest,
1739 RADIUS_PACKET **packet_p;
1740 REQUEST *request = NULL;
1741 struct main_config_t *root = &mainconfig;
1743 packet_p = lrad_packet_list_find(pl, packet);
1745 request = lrad_packet2myptr(REQUEST, packet, packet_p);
1746 rad_assert(request->in_request_hash);
1748 if ((request->packet->data_len == packet->data_len) &&
1749 (memcmp(request->packet->vector, packet->vector,
1750 sizeof(packet->vector)) == 0)) {
1751 received_retransmit(request, client);
1756 * The new request is different from the old one,
1757 * but maybe the old is finished. If so, delete
1760 switch (request->child_state) {
1761 struct timeval when;
1764 gettimeofday(&when, NULL);
1768 * If the cached request was received
1769 * within the last second, then we
1770 * discard the NEW request instead of the
1771 * old one. This will happen ONLY when
1772 * the client is severely broken, and is
1773 * sending conflicting packets very
1776 if (timercmp(&when, &request->received, <)) {
1777 radlog(L_ERR, "Discarding conflicting packet from "
1778 "client %s port %d - ID: %d due to recent request %d.",
1780 packet->src_port, packet->id,
1785 received_conflicting_request(request, client);
1789 case REQUEST_REJECT_DELAY:
1790 case REQUEST_CLEANUP_DELAY:
1791 request->child_state = REQUEST_DONE;
1793 cleanup_delay(request);
1802 * We may want to quench the new request.
1804 if (!can_handle_new_request(packet, client, root)) {
1809 * Create and initialize the new request.
1811 request = request_alloc(); /* never fails */
1813 if ((request->reply = rad_alloc(0)) == NULL) {
1814 radlog(L_ERR, "No memory");
1818 request->listener = listener;
1819 request->client = client;
1820 request->packet = packet;
1821 request->packet->timestamp = request->timestamp;
1822 request->number = request_num_counter++;
1823 request->priority = listener->type;
1824 request->root = root;
1827 * Set virtual server identity
1829 if (client->server) {
1830 request->server = client->server;
1831 } else if (listener->server) {
1832 request->server = listener->server;
1834 request->server = NULL;
1838 * Remember the request in the list.
1840 if (!lrad_packet_list_insert(pl, &request->packet)) {
1841 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
1842 request_free(&request);
1845 request->in_request_hash = TRUE;
1848 * The request passes many of our sanity checks.
1849 * From here on in, if anything goes wrong, we
1850 * send a reject message, instead of dropping the
1855 * Build the reply template from the request.
1858 request->reply->sockfd = request->packet->sockfd;
1859 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1860 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1861 request->reply->dst_port = request->packet->src_port;
1862 request->reply->src_port = request->packet->dst_port;
1863 request->reply->id = request->packet->id;
1864 request->reply->code = 0; /* UNKNOWN code */
1865 memcpy(request->reply->vector, request->packet->vector,
1866 sizeof(request->reply->vector));
1867 request->reply->vps = NULL;
1868 request->reply->data = NULL;
1869 request->reply->data_len = 0;
1871 request->master_state = REQUEST_ACTIVE;
1872 request->child_state = REQUEST_QUEUED;
1873 request->next_callback = NULL;
1875 gettimeofday(&request->received, NULL);
1876 request->timestamp = request->received.tv_sec;
1877 request->when = request->received;
1879 request->delay = USEC / 10;
1881 tv_add(&request->when, request->delay);
1883 INSERT_EVENT(wait_a_bit, request);
1885 *prequest = request;
1890 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
1896 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
1897 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
1898 inet_ntop(packet->src_ipaddr.af,
1899 &packet->src_ipaddr.ipaddr,
1900 buffer, sizeof(buffer)),
1907 * Also removes from the proxy hash if responses == requests
1909 request = lookup_in_proxy_hash(packet);
1912 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
1913 inet_ntop(packet->src_ipaddr.af,
1914 &packet->src_ipaddr.ipaddr,
1915 buffer, sizeof(buffer)),
1916 packet->src_port, packet->id);
1921 home = request->home_server;
1923 gettimeofday(&now, NULL);
1924 home->state = HOME_STATE_ALIVE;
1926 if (request->reply && request->reply->code != 0) {
1927 DEBUG2("We already replied to this request. Discarding response from home server.");
1933 * We had previously received a reply, so we don't need
1934 * to do anything here.
1936 if (request->proxy_reply) {
1937 if (memcmp(request->proxy_reply->vector,
1939 sizeof(request->proxy_reply->vector)) == 0) {
1940 DEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
1941 inet_ntop(packet->src_ipaddr.af,
1942 &packet->src_ipaddr.ipaddr,
1943 buffer, sizeof(buffer)),
1944 packet->src_port, packet->id,
1948 * ? The home server gave us a new proxy
1949 * reply, which doesn't match the old
1952 DEBUG2("Ignoring conflicting proxy reply");
1955 /* assert that there's an event queued for request? */
1960 switch (request->child_state) {
1961 case REQUEST_QUEUED:
1962 case REQUEST_RUNNING:
1963 rad_panic("Internal sanity check failed for child state");
1966 case REQUEST_REJECT_DELAY:
1967 case REQUEST_CLEANUP_DELAY:
1969 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'",
1970 inet_ntop(packet->src_ipaddr.af,
1971 &packet->src_ipaddr.ipaddr,
1972 buffer, sizeof(buffer)),
1973 packet->src_port, packet->id,
1975 /* assert that there's an event queued for request? */
1979 case REQUEST_PROXIED:
1983 request->proxy_reply = packet;
1987 * Perform RTT calculations, as per RFC 2988 (for TCP).
1988 * Note that we do so only if we sent one request, and
1989 * received one response. If we sent two requests, we
1990 * have no idea if the response is for the first, or for
1991 * the second request/
1993 if (request->num_proxied_requests == 1) {
1995 home_server *home = request->home_server;
1997 rtt = now.tv_sec - request->proxy_when.tv_sec;
2000 rtt -= request->proxy_when.tv_usec;
2002 if (!home->has_rtt) {
2003 home->has_rtt = TRUE;
2006 home->rttvar = rtt / 2;
2009 home->rttvar -= home->rttvar >> 2;
2010 home->rttvar += (home->srtt - rtt);
2011 home->srtt -= home->srtt >> 3;
2012 home->srtt += rtt >> 3;
2015 home->rto = home->srtt;
2016 if (home->rttvar > (USEC / 4)) {
2017 home->rto += home->rttvar * 4;
2025 * There's no incoming request, so it's a proxied packet
2028 if (!request->packet) {
2029 received_response_to_ping(request);
2033 request->child_state = REQUEST_QUEUED;
2034 request->when = now;
2035 request->delay = USEC / 10;
2036 request->priority = RAD_LISTEN_PROXY;
2037 tv_add(&request->when, request->delay);
2040 * Wait a bit will take care of max_request_time
2042 INSERT_EVENT(wait_a_bit, request);
2049 * Inform ourselves that we received a signal.
2051 void radius_signal_self(int flag)
2057 * The caller is telling us it's OK to read from the
2058 * detail files. However, we're not even listening on
2059 * the detail files. Therefore, suppress the flag to
2060 * avoid bothering the main worker thread.
2062 if ((flag == RADIUS_SIGNAL_SELF_DETAIL) &&
2063 !has_detail_listener) {
2068 * The read MUST be non-blocking for this to work.
2070 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2074 for (i = 1; i < rcode; i++) {
2075 buffer[0] |= buffer[i];
2080 memset(buffer + 1, 0, sizeof(buffer) - 1);
2085 write(self_pipe[1], buffer, 1);
2089 static void event_signal_handler(lrad_event_list_t *xel, int fd, void *ctx)
2098 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2099 if (rcode <= 0) return;
2102 * Merge pending signals.
2104 for (i = 1; i < rcode; i++) {
2105 buffer[0] |= buffer[i];
2109 * The thread pool has nothing more to do. Start reading
2110 * from the detail file.
2112 if ((buffer[0] & (RADIUS_SIGNAL_SELF_DETAIL)) != 0) {
2113 read_from_detail = TRUE;
2116 if ((buffer[0] & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2117 if ((buffer[0] & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2118 lrad_event_loop_exit(el, 1);
2120 lrad_event_loop_exit(el, 2);
2124 } /* else exit/term flags weren't set */
2127 * Tell the even loop to stop processing.
2129 if ((buffer[0] & RADIUS_SIGNAL_SELF_HUP) != 0) {
2130 DEBUG("Received HUP signal.");
2132 lrad_event_loop_exit(el, 0x80);
2138 * The given FD is closed. Delete it from the list of FD's to poll,
2139 * and set a timer to periodically look for an FD again.
2141 static void event_reset_fd(rad_listen_t *listener, int fd, int usec)
2143 struct timeval when;
2144 gettimeofday(&when, NULL);
2146 tv_add(&when, usec);
2148 if (!lrad_event_fd_delete(el, 0, fd)) {
2149 rad_panic("Failed deleting fd");
2152 if (!lrad_event_insert(el, event_poll_fd, listener,
2154 rad_panic("Failed inserting event");
2160 * Reads from the detail file if possible, OR sets up a timeout
2161 * to see if the detail file is ready for reading.
2163 * FIXME: On Linux, use inotify to watch the detail file. This
2166 static void event_detail_handler(lrad_event_list_t *xel, int fd, void *ctx)
2168 rad_listen_t *listener = ctx;
2169 RAD_REQUEST_FUNP fun;
2172 rad_assert(xel == el);
2173 rad_assert(fd == listener->fd);
2178 * We're too busy to read from the detail file. Stop
2179 * watching the file, and instead go back to polling.
2181 if (!read_from_detail) {
2182 event_reset_fd(listener, fd, USEC);
2187 * FIXME: Put this somewhere else, where it isn't called
2188 * all of the time...
2190 #ifndef HAVE_PTHREAD_H
2192 * If there are no child threads, then there may
2193 * be child processes. In that case, wait for
2194 * their exit status, and throw that exit status
2195 * away. This helps get rid of zxombie children.
2197 while (waitpid(-1, &argval, WNOHANG) > 0) {
2203 * Didn't read anything from the detail file.
2204 * Wake up in one second to check it again.
2206 if (!listener->recv(listener, &fun, &request)) {
2207 event_reset_fd(listener, fd, USEC);
2212 * Drop the request into the thread pool,
2213 * and let the thread pool take care of
2214 * doing something with it.
2216 if (!thread_pool_addrequest(request, fun)) {
2217 request->child_state = REQUEST_DONE;
2221 * Reset based on the fd we were given, as detail_recv()
2222 * may have read all of the file, and closed it. It then
2223 * sets listener->fd = -1.
2225 event_reset_fd(listener, fd, *(int *) listener->data);
2229 static void event_socket_handler(lrad_event_list_t *xel, int fd, void *ctx)
2231 rad_listen_t *listener = ctx;
2232 RAD_REQUEST_FUNP fun;
2235 rad_assert(xel == el);
2240 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2243 * FIXME: Put this somewhere else, where it isn't called
2244 * all of the time...
2246 #ifndef HAVE_PTHREAD_H
2248 * If there are no child threads, then there may
2249 * be child processes. In that case, wait for
2250 * their exit status, and throw that exit status
2251 * away. This helps get rid of zxombie children.
2253 while (waitpid(-1, &argval, WNOHANG) > 0) {
2258 if (!listener->recv(listener, &fun, &request)) return;
2260 if (!thread_pool_addrequest(request, fun)) {
2261 request->child_state = REQUEST_DONE;
2265 * If we've read a packet from a socket OTHER than the
2266 * detail file, we start ignoring the detail file.
2268 * When the child thread pulls the request off of the
2269 * queues, it will check if the queues are empty. Once
2270 * all queues are empty, it will signal us to read the
2271 * detail file again.
2273 read_from_detail = FALSE;
2278 * This function is called periodically to see if a file
2279 * descriptor is available for reading.
2281 static void event_poll_fd(void *ctx)
2284 RAD_REQUEST_FUNP fun;
2286 rad_listen_t *listener = ctx;
2287 lrad_event_fd_handler_t handler;
2290 * Ignore the detail file if we're busy with other work.
2292 if ((listener->type == RAD_LISTEN_DETAIL) && !read_from_detail) {
2297 * Try to read a RADIUS packet. This also opens the FD.
2299 * FIXME: This does poll AND receive.
2301 rcode = listener->recv(listener, &fun, &request);
2304 * We read a request. Add it to the list for processing.
2307 rad_assert(fun != NULL);
2308 rad_assert(request != NULL);
2310 if (!thread_pool_addrequest(request, fun)) {
2311 request->child_state = REQUEST_DONE;
2316 * Still no FD, OR the fd was read completely, and then
2317 * closed. Re-set the polling timer and return.
2319 if (listener->fd < 0) {
2320 struct timeval when;
2323 gettimeofday(&when, NULL);
2326 if (!lrad_event_insert(el, event_poll_fd, listener,
2328 rad_panic("Failed inserting event");
2334 if (listener->type == RAD_LISTEN_DETAIL) {
2335 handler = event_detail_handler;
2337 handler = event_socket_handler;
2341 * We have an FD. Start watching it.
2343 if (!lrad_event_fd_insert(el, 0, listener->fd,
2344 handler, listener)) {
2347 listener->print(listener, buffer, sizeof(buffer));
2348 rad_panic("Failed creating handler for socket");
2353 static void event_status(struct timeval *wake)
2355 if (debug_flag == 0) return;
2358 DEBUG("Waiting for the next request.");
2359 } else if ((wake->tv_sec != 0) ||
2360 (wake->tv_usec >= 100000)) {
2361 DEBUG("Waking up in %d.%01d seconds.\n",
2362 (int) wake->tv_sec, (int) wake->tv_usec / 100000);
2368 * Externally-visibly functions.
2370 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2373 rad_listen_t *this, *head = NULL;
2379 el = lrad_event_list_create(event_status);
2382 pl = lrad_packet_list_create(0);
2385 request_num_counter = 0;
2388 * Move all of the thread calls to this file?
2390 * It may be best for the mutexes to be in this file...
2392 have_children = spawn_flag;
2394 if (mainconfig.proxy_requests) {
2396 * Create the tree for managing proxied requests and
2399 proxy_list = lrad_packet_list_create(1);
2400 if (!proxy_list) return 0;
2402 #ifdef HAVE_PTHREAD_H
2403 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2404 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2411 if (thread_pool_init(cs, spawn_flag) < 0) {
2416 * Child threads need a pipe to signal us, as do the
2419 if (pipe(self_pipe) < 0) {
2420 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2424 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2425 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2429 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2430 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2435 if (!lrad_event_fd_insert(el, 0, self_pipe[0],
2436 event_signal_handler, el)) {
2437 radlog(L_ERR, "Failed creating handler for signals");
2443 * Mark the proxy Fd's as unused.
2445 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2447 DEBUG2("radiusd: #### Opening IP addresses and Ports ####");
2449 if (listen_init(cs, &head) < 0) {
2454 * Add all of the sockets to the event loop.
2456 * FIXME: New proxy sockets aren't currently added to the
2457 * event loop. They're allocated in a child thread, and
2458 * we don't have (or want) a mutex around the event
2463 this = this->next) {
2466 this->print(this, buffer, sizeof(buffer));
2468 switch (this->type) {
2469 case RAD_LISTEN_DETAIL:
2470 DEBUG("Listening on %s", buffer);
2471 has_detail_listener = TRUE;
2474 case RAD_LISTEN_PROXY:
2475 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2476 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2478 proxy_fds[this->fd & 0x1f] = this->fd;
2479 proxy_listeners[this->fd & 0x1f] = this;
2480 if (!lrad_packet_list_socket_add(proxy_list,
2486 case RAD_LISTEN_SNMP:
2487 DEBUG("Listening on SNMP %s", buffer);
2491 DEBUG("Listening on %s", buffer);
2496 * The file descriptor isn't ready. Poll for
2497 * when it will become ready. This is for SNMP
2498 * and detail file fd's.
2501 struct timeval when;
2503 gettimeofday(&when, NULL);
2506 if (!lrad_event_insert(el, event_poll_fd, this,
2508 radlog(L_ERR, "Failed creating handler");
2515 * The socket is open. It MUST be a socket,
2516 * as we don't pre-open the detail files (yet).
2518 * FIXME: if we DO open the detail files automatically,
2519 * then much of this code becomes simpler.
2521 if (!lrad_event_fd_insert(el, 0, this->fd,
2522 event_socket_handler, this)) {
2523 this->print(this, buffer, sizeof(buffer));
2524 radlog(L_ERR, "Failed creating handler for socket %s",
2534 static int request_hash_cb(void *ctx, void *data)
2536 ctx = ctx; /* -Wunused */
2537 REQUEST *request = lrad_packet2myptr(REQUEST, packet, data);
2539 rad_assert(request->in_proxy_hash == FALSE);
2541 lrad_event_delete(el, &request->ev);
2542 remove_from_request_hash(request);
2543 request_free(&request);
2549 static int proxy_hash_cb(void *ctx, void *data)
2551 ctx = ctx; /* -Wunused */
2552 REQUEST *request = lrad_packet2myptr(REQUEST, proxy, data);
2554 lrad_packet_list_yank(proxy_list, request->proxy);
2555 request->in_proxy_hash = FALSE;
2557 if (!request->in_request_hash) {
2558 lrad_event_delete(el, &request->ev);
2559 request_free(&request);
2566 void radius_event_free(void)
2569 * FIXME: Stop all threads, or at least check that
2570 * they're all waiting on the semaphore, and the queues
2575 * There are requests in the proxy hash that aren't
2576 * referenced from anywhere else. Remove them first.
2579 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2580 lrad_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2581 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2582 lrad_packet_list_free(proxy_list);
2586 lrad_packet_list_walk(pl, NULL, request_hash_cb);
2588 lrad_packet_list_free(pl);
2591 lrad_event_list_free(el);
2594 int radius_event_process(void)
2598 radlog(L_INFO, "Ready to process requests.");
2600 return lrad_event_loop(el);
2603 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
2605 if (request_pre_handler(request)) {
2606 rad_assert(fun != NULL);
2607 rad_assert(request != NULL);
2609 if (request->server) DEBUG("server %s {",
2613 if (request->server) DEBUG("} # server %s",
2616 request_post_handler(request);
2619 DEBUG2("Going to the next request");