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;
58 static int just_started = FALSE;
60 static int self_pipe[2];
63 static pthread_mutex_t proxy_mutex;
65 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
66 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
69 * This is easier than ifdef's throughout the code.
71 #define PTHREAD_MUTEX_LOCK(_x)
72 #define PTHREAD_MUTEX_UNLOCK(_x)
73 #define thread_addrequest radius_handle_request
76 #define INSERT_EVENT(_function, _ctx) if (!lrad_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
78 static lrad_packet_list_t *proxy_list = NULL;
81 * We keep the proxy FD's here. The RADIUS Id's are marked
82 * "allocated" per Id, via a bit per proxy FD.
84 static int proxy_fds[32];
85 static rad_listen_t *proxy_listeners[32];
87 static void request_post_handler(REQUEST *request);
88 static void wait_a_bit(void *ctx);
89 static void event_poll_fd(void *ctx);
91 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
94 radlog(L_ERR, "]%s:%d] %s", file, line, msg);
98 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
101 static void tv_add(struct timeval *tv, int usec_delay)
103 if (usec_delay > USEC) {
104 tv->tv_sec += usec_delay / USEC;
107 tv->tv_usec += usec_delay;
109 if (tv->tv_usec > USEC) {
115 static VALUE_PAIR * radius_pairmake(REQUEST *request, VALUE_PAIR **vps,
116 const char *attribute, const char *value)
120 request = request; /* -Wunused */
122 vp = pairmake(attribute, value, T_OP_SET);
124 radlog(L_ERR, "No memory!");
125 rad_assert("No memory" == NULL);
135 static void snmp_inc_counters(REQUEST *request)
137 if (!request->root->do_snmp) return;
139 if (request->master_state == REQUEST_COUNTED) return;
141 if ((request->listener->type != RAD_LISTEN_AUTH) &&
142 (request->listener->type != RAD_LISTEN_ACCT)) return;
145 * Update the SNMP statistics.
147 * Note that we do NOT do this in a child thread.
148 * Instead, we update the stats when a request is
149 * deleted, because only the main server thread calls
150 * this function, which makes it thread-safe.
152 switch (request->reply->code) {
153 case PW_AUTHENTICATION_ACK:
154 rad_snmp.auth.total_responses++;
155 rad_snmp.auth.total_access_accepts++;
156 if (request->client) request->client->auth->accepts++;
159 case PW_AUTHENTICATION_REJECT:
160 rad_snmp.auth.total_responses++;
161 rad_snmp.auth.total_access_rejects++;
162 if (request->client) request->client->auth->rejects++;
165 case PW_ACCESS_CHALLENGE:
166 rad_snmp.auth.total_responses++;
167 rad_snmp.auth.total_access_challenges++;
168 if (request->client) request->client->auth->challenges++;
171 case PW_ACCOUNTING_RESPONSE:
172 rad_snmp.acct.total_responses++;
173 if (request->client) request->client->auth->responses++;
177 * No response, it must have been a bad
181 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
182 rad_snmp.auth.total_bad_authenticators++;
183 if (request->client) request->client->auth->bad_authenticators++;
191 request->master_state = REQUEST_COUNTED;
194 #define snmp_inc_counters(_x)
198 static void remove_from_request_hash(REQUEST *request)
200 if (!request->in_request_hash) return;
202 lrad_packet_list_yank(pl, request->packet);
203 request->in_request_hash = FALSE;
205 snmp_inc_counters(request);
209 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
211 RADIUS_PACKET **proxy_p;
214 PTHREAD_MUTEX_LOCK(&proxy_mutex);
215 proxy_p = lrad_packet_list_find_byreply(proxy_list, reply);
218 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
222 request = lrad_packet2myptr(REQUEST, proxy, proxy_p);
225 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
229 request->num_proxied_responses++;
232 * Catch the most common case of everything working
235 if (request->num_proxied_requests == request->num_proxied_responses) {
236 lrad_packet_list_yank(proxy_list, request->proxy);
237 lrad_packet_list_id_free(proxy_list, request->proxy);
238 request->in_proxy_hash = FALSE;
242 * On the FIRST reply, decrement the count of outstanding
243 * requests. Note that this is NOT the count of sent
244 * packets, but whether or not the home server has
247 if (!request->proxy_reply &&
248 request->home_server->currently_outstanding) {
249 request->home_server->currently_outstanding--;
252 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
258 static void remove_from_proxy_hash(REQUEST *request)
260 if (!request->in_proxy_hash) return;
262 PTHREAD_MUTEX_LOCK(&proxy_mutex);
263 lrad_packet_list_yank(proxy_list, request->proxy);
264 lrad_packet_list_id_free(proxy_list, request->proxy);
267 * The home server hasn't replied, but we've given up on
268 * this request. Don't count this request against the
271 if (!request->proxy_reply &&
272 request->home_server->currently_outstanding) {
273 request->home_server->currently_outstanding--;
276 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
278 request->in_proxy_hash = FALSE;
282 static int insert_into_proxy_hash(REQUEST *request)
287 rad_assert(request->proxy != NULL);
288 rad_assert(proxy_list != NULL);
290 request->proxy->sockfd = -1;
292 PTHREAD_MUTEX_LOCK(&proxy_mutex);
294 request->home_server->currently_outstanding++;
295 request->home_server->total_requests_sent++;
298 * On overflow, back up to ~0.
300 if (!request->home_server->total_requests_sent) {
301 request->home_server->total_requests_sent--;
304 if (!lrad_packet_list_id_alloc(proxy_list, request->proxy)) {
306 rad_listen_t *proxy_listener;
309 * Allocate a new proxy fd. This function adds it
310 * into the list of listeners.
312 * FIXME!: Call event_fd_insert()! Otherwise this
313 * FD will never be used in select()!
315 * We probably want to add RADIUS_SIGNAL_SELF_FD,
316 * which tells us to walk over the listeners,
319 * Hmm... maybe do this for the detail file, too.
320 * that will simplify some of the rest of the code.
322 proxy_listener = proxy_new_listener();
323 if (!proxy_listener) {
324 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
325 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
333 proxy = proxy_listener->fd;
334 for (i = 0; i < 32; i++) {
335 DEBUG2("PROXY %d %d", i, proxy_fds[(proxy + i) & 0x1f]);
338 * Found a free entry. Save the socket,
339 * and remember where we saved it.
341 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
342 found = (proxy + i) & 0x1f;
343 proxy_fds[found] = proxy;
344 proxy_listeners[found] = proxy_listener;
348 rad_assert(found >= 0);
350 if (!lrad_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
351 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
352 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
353 return 0; /* leak proxy_listener */
357 if (!lrad_packet_list_id_alloc(proxy_list, request->proxy)) {
358 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
359 DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
363 rad_assert(request->proxy->sockfd >= 0);
366 * FIXME: Hack until we get rid of rad_listen_t, and put
367 * the information into the packet_list.
370 for (i = 0; i < 32; i++) {
371 if (proxy_fds[i] == request->proxy->sockfd) {
378 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
379 DEBUG2("ERROR: All sockets are full.");
383 rad_assert(proxy_fds[proxy] != -1);
384 rad_assert(proxy_listeners[proxy] != NULL);
385 request->proxy_listener = proxy_listeners[proxy];
387 if (!lrad_packet_list_insert(proxy_list, &request->proxy)) {
388 lrad_packet_list_id_free(proxy_list, request->proxy);
389 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
390 DEBUG2("ERROR: Failed to insert entry into proxy list");
394 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
396 DEBUG3(" proxy: allocating destination %s port %d - Id %d",
397 inet_ntop(request->proxy->dst_ipaddr.af,
398 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
399 request->proxy->dst_port,
402 request->in_proxy_hash = TRUE;
409 * Called as BOTH an event, and in-line from other functions.
411 static void wait_for_proxy_id_to_expire(void *ctx)
413 REQUEST *request = ctx;
414 home_server *home = request->home_server;
416 rad_assert(request->magic == REQUEST_MAGIC);
417 rad_assert(request->proxy != NULL);
419 request->when = request->proxy_when;
420 request->when.tv_sec += home->response_window;
422 if ((request->num_proxied_requests == request->num_proxied_responses) ||
423 timercmp(&now, &request->when, >)) {
424 if (request->packet) {
425 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
426 request->number, request->packet->id,
427 (unsigned int) (request->timestamp - start_time));
429 DEBUG2("Cleaning up request %d with timestamp +%d",
431 (unsigned int) (request->timestamp - start_time));
433 lrad_event_delete(el, &request->ev);
434 remove_from_proxy_hash(request);
435 remove_from_request_hash(request);
436 request_free(&request);
440 INSERT_EVENT(wait_for_proxy_id_to_expire, request);
444 static void wait_for_child_to_die(void *ctx)
446 REQUEST *request = ctx;
448 rad_assert(request->magic == REQUEST_MAGIC);
450 if ((request->child_state == REQUEST_QUEUED) |
451 (request->child_state == REQUEST_RUNNING)) {
452 request->delay += (request->delay >> 1);
453 tv_add(&request->when, request->delay);
455 DEBUG2("Child is still stuck for request %d", request->number);
457 INSERT_EVENT(wait_for_child_to_die, request);
461 DEBUG2("Child is finally responsive for request %d", request->number);
462 remove_from_request_hash(request);
464 if (request->proxy) {
465 wait_for_proxy_id_to_expire(request);
469 request_free(&request);
473 static void cleanup_delay(void *ctx)
475 REQUEST *request = ctx;
477 rad_assert(request->magic == REQUEST_MAGIC);
478 rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
479 (request->child_state == REQUEST_DONE));
481 remove_from_request_hash(request);
483 if (request->proxy && request->in_proxy_hash) {
484 wait_for_proxy_id_to_expire(request);
488 DEBUG2("Cleaning up request %d ID %d with timestamp +%d",
489 request->number, request->packet->id,
490 (unsigned int) (request->timestamp - start_time));
492 lrad_event_delete(el, &request->ev);
493 request_free(&request);
497 static void reject_delay(void *ctx)
499 REQUEST *request = ctx;
501 rad_assert(request->magic == REQUEST_MAGIC);
502 rad_assert(request->child_state == REQUEST_REJECT_DELAY);
504 DEBUG2("Sending delayed reject for request %d", request->number);
506 request->listener->send(request->listener, request);
508 request->when.tv_sec += request->root->cleanup_delay;
509 request->child_state = REQUEST_CLEANUP_DELAY;
511 INSERT_EVENT(cleanup_delay, request);
515 static void revive_home_server(void *ctx)
517 home_server *home = ctx;
519 home->state = HOME_STATE_ALIVE;
520 DEBUG2("Marking home server alive again... we have no idea if it really is alive or not.");
521 home->currently_outstanding = 0;
525 static void no_response_to_ping(void *ctx)
527 REQUEST *request = ctx;
528 home_server *home = request->home_server;
531 home->num_received_pings = 0;
533 DEBUG2("No response to status check %d from home server %s port %d",
535 inet_ntop(request->proxy->dst_ipaddr.af,
536 &request->proxy->dst_ipaddr.ipaddr,
537 buffer, sizeof(buffer)),
538 request->proxy->dst_port);
540 wait_for_proxy_id_to_expire(request);
544 static void received_response_to_ping(REQUEST *request)
546 home_server *home = request->home_server;
549 home->num_received_pings++;
551 DEBUG2("Received response to status check %d (%d in current sequence)",
552 request->number, home->num_received_pings);
554 if (home->num_received_pings < home->num_pings_to_alive) {
555 wait_for_proxy_id_to_expire(request);
559 DEBUG2("Marking home server %s port %d alive",
560 inet_ntop(request->proxy->dst_ipaddr.af,
561 &request->proxy->dst_ipaddr.ipaddr,
562 buffer, sizeof(buffer)),
563 request->proxy->dst_port);
565 if (!lrad_event_delete(el, &home->ev)) {
566 DEBUG2("Hmm... no event for home server, WTF?");
569 if (!lrad_event_delete(el, &request->ev)) {
570 DEBUG2("Hmm... no event for request, WTF?");
573 wait_for_proxy_id_to_expire(request);
575 home->state = HOME_STATE_ALIVE;
576 home->currently_outstanding = 0;
580 static void ping_home_server(void *ctx)
583 home_server *home = ctx;
587 if (home->state == HOME_STATE_ALIVE) {
588 radlog(L_INFO, "Suspicious proxy state... continuing");
592 request = request_alloc();
593 request->number = request_num_counter++;
595 request->proxy = rad_alloc(1);
596 rad_assert(request->proxy != NULL);
598 gettimeofday(&request->when, NULL);
599 home->when = request->when;
601 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
602 request->proxy->code = PW_STATUS_SERVER;
604 radius_pairmake(request, &request->proxy->vps,
605 "Message-Authenticator", "0x00");
607 } else if (home->type == HOME_TYPE_AUTH) {
608 request->proxy->code = PW_AUTHENTICATION_REQUEST;
610 radius_pairmake(request, &request->proxy->vps,
611 "User-Name", home->ping_user_name);
612 radius_pairmake(request, &request->proxy->vps,
613 "User-Password", home->ping_user_password);
614 radius_pairmake(request, &request->proxy->vps,
615 "Service-Type", "Authenticate-Only");
616 radius_pairmake(request, &request->proxy->vps,
617 "Message-Authenticator", "0x00");
620 request->proxy->code = PW_ACCOUNTING_REQUEST;
622 radius_pairmake(request, &request->proxy->vps,
623 "User-Name", home->ping_user_name);
624 radius_pairmake(request, &request->proxy->vps,
625 "Acct-Status-Type", "Stop");
626 radius_pairmake(request, &request->proxy->vps,
627 "Acct-Session-Id", "00000000");
628 vp = radius_pairmake(request, &request->proxy->vps,
629 "Event-Timestamp", "0");
630 vp->vp_date = now.tv_sec;
633 radius_pairmake(request, &request->proxy->vps,
634 "NAS-Identifier", "Status Check. Are you alive?");
636 request->proxy->dst_ipaddr = home->ipaddr;
637 request->proxy->dst_port = home->port;
638 request->home_server = home;
640 rad_assert(request->proxy_listener == NULL);
642 if (!insert_into_proxy_hash(request)) {
643 DEBUG2("Failed inserting status check %d into proxy hash. Discarding it.",
645 request_free(&request);
648 rad_assert(request->proxy_listener != NULL);
649 request->proxy_listener->send(request->proxy_listener,
652 request->next_callback = NULL;
653 request->child_state = REQUEST_PROXIED;
654 request->when.tv_sec += home->ping_timeout;;
656 INSERT_EVENT(no_response_to_ping, request);
659 * Add +/- 2s of jitter, as suggested in RFC 3539
660 * and in the Issues and Fixes draft.
662 home->when.tv_sec += home->ping_interval - 2;
664 jitter = lrad_rand();
665 jitter ^= (jitter >> 10);
666 jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
668 tv_add(&home->when, jitter);
671 INSERT_EVENT(ping_home_server, home);
675 static void check_for_zombie_home_server(REQUEST *request)
681 home = request->home_server;
683 if (home->state != HOME_STATE_ZOMBIE) return;
685 when = home->zombie_period_start;
686 when.tv_sec += home->zombie_period;
688 if (timercmp(&now, &when, <)) {
693 * It's been a zombie for too long, mark it as
696 DEBUG2("FAILURE: Marking home server %s port %d as dead.",
697 inet_ntop(request->proxy->dst_ipaddr.af,
698 &request->proxy->dst_ipaddr.ipaddr,
699 buffer, sizeof(buffer)),
700 request->proxy->dst_port);
701 home->state = HOME_STATE_IS_DEAD;
702 home->num_received_pings = 0;
703 home->when = request->when;
705 if (home->ping_check != HOME_PING_CHECK_NONE) {
706 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
707 (home->ping_user_name != NULL));
708 home->when.tv_sec += home->ping_interval;
710 INSERT_EVENT(ping_home_server, home);
712 home->when.tv_sec += home->revive_interval;
714 INSERT_EVENT(revive_home_server, home);
719 static int setup_post_proxy_fail(REQUEST *request)
721 DICT_VALUE *dval = NULL;
724 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
725 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
727 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
728 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
734 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
737 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
741 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
742 if (!vp) vp = radius_paircreate(request, &request->config_items,
743 PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
744 vp->vp_integer = dval->value;
746 rad_assert(request->proxy_reply == NULL);
752 static int null_handler(UNUSED REQUEST *request)
757 static void post_proxy_fail_handler(REQUEST *request)
760 * Not set up to run Post-Proxy-Type = Fail.
762 * Mark the request as still running, and figure out what
765 if (!setup_post_proxy_fail(request)) {
766 request->child_state = REQUEST_RUNNING;
767 request_post_handler(request);
772 * Re-queue the request.
774 request->child_state = REQUEST_QUEUED;
779 * There is a post-proxy-type of fail. We run
780 * the request through the pre/post proxy
781 * handlers, just like it was a real proxied
782 * request. However, we set the per-request
783 * handler to NULL, as we don't want to do
786 request->priority = 0;
787 rad_assert(request->proxy != NULL);
788 thread_pool_addrequest(request, null_handler);
793 /* maybe check this against wait_for_proxy_id_to_expire? */
794 static void no_response_to_proxied_request(void *ctx)
796 REQUEST *request = ctx;
800 rad_assert(request->magic == REQUEST_MAGIC);
801 rad_assert(request->child_state == REQUEST_PROXIED);
803 radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
805 inet_ntop(request->proxy->dst_ipaddr.af,
806 &request->proxy->dst_ipaddr.ipaddr,
807 buffer, sizeof(buffer)),
808 request->proxy->dst_port);
810 check_for_zombie_home_server(request);
812 home = request->home_server;
814 post_proxy_fail_handler(request);
817 * Don't touch request due to race conditions
819 if (home->state == HOME_STATE_IS_DEAD) {
820 rad_assert(home->ev != NULL); /* or it will never wake up */
825 * Enable the zombie period when we notice that the home
826 * server hasn't responded. We also back-date the start
827 * of the zombie period to when the proxied request was
830 if (home->state == HOME_STATE_ALIVE) {
831 DEBUG2("WARNING: Marking home server %s port %d as zombie (it looks like it is dead).",
832 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
833 buffer, sizeof(buffer)),
835 home->state = HOME_STATE_ZOMBIE;
836 home->zombie_period_start = now;
837 home->zombie_period_start.tv_sec -= home->response_window;
843 static void wait_a_bit(void *ctx)
846 REQUEST *request = ctx;
847 lrad_event_callback_t callback = NULL;
849 rad_assert(request->magic == REQUEST_MAGIC);
851 switch (request->child_state) {
853 case REQUEST_RUNNING:
854 when = request->received;
855 when.tv_sec += request->root->max_request_time;
857 if (timercmp(&now, &when, <)) {
858 callback = wait_a_bit;
860 /* FIXME: kill unresponsive children? */
861 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
862 (unsigned long)request->child_pid, request->number,
863 request->module ? request->module : "<server core>",
864 request->component ? request->component : "<server core>");
866 request->master_state = REQUEST_STOP_PROCESSING;
868 request->delay = USEC / 2;
869 tv_add(&request->when, request->delay);
870 callback = wait_for_child_to_die;
872 request->delay += request->delay >> 1;
875 case REQUEST_REJECT_DELAY:
876 case REQUEST_CLEANUP_DELAY:
877 request->child_pid = NO_SUCH_CHILD_PID;
878 snmp_inc_counters(request);
880 case REQUEST_PROXIED:
881 rad_assert(request->next_callback != NULL);
882 rad_assert(request->next_callback != wait_a_bit);
884 request->when = request->next_when;
885 callback = request->next_callback;
886 request->next_callback = NULL;
890 * Mark the request as no longer running,
894 request->child_pid = NO_SUCH_CHILD_PID;
895 snmp_inc_counters(request);
896 cleanup_delay(request);
900 rad_panic("Internal sanity check failure");
904 INSERT_EVENT(callback, request);
908 static int request_pre_handler(REQUEST *request)
912 rad_assert(request->magic == REQUEST_MAGIC);
913 rad_assert(request->packet != NULL);
914 rad_assert(request->packet->dst_port != 0);
916 request->child_state = REQUEST_RUNNING;
919 * Don't decode the packet if it's an internal "fake"
920 * request. Instead, just return so that the caller can
923 if (request->packet->dst_port == 0) {
924 request->username = pairfind(request->packet->vps,
926 request->password = pairfind(request->packet->vps,
932 * Put the decoded packet into it's proper place.
934 if (request->proxy_reply != NULL) {
935 rcode = request->proxy_listener->decode(request->proxy_listener,
937 } else if (request->packet->vps == NULL) {
938 rcode = request->listener->decode(request->listener, request);
945 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
946 request->child_state = REQUEST_DONE;
950 if (!request->proxy) {
951 request->username = pairfind(request->packet->vps,
955 int post_proxy_type = 0;
959 * Delete any reply we had accumulated until now.
961 pairfree(&request->reply->vps);
964 * Run the packet through the post-proxy stage,
965 * BEFORE playing games with the attributes.
967 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
969 DEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
970 post_proxy_type = vp->vp_integer;
973 rad_assert(request->home_pool != NULL);
975 if (request->home_pool->virtual_server) {
976 const char *old_server = request->server;
978 request->server = request->home_pool->virtual_server;
979 DEBUG2(" server %s {", request->server);
980 rcode = module_post_proxy(post_proxy_type, request);
982 request->server = old_server;
984 rcode = module_post_proxy(post_proxy_type, request);
988 * There may NOT be a proxy reply, as we may be
989 * running Post-Proxy-Type = Fail.
991 if (request->proxy_reply) {
993 * Delete the Proxy-State Attributes from
994 * the reply. These include Proxy-State
995 * attributes from us and remote server.
997 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1000 * Add the attributes left in the proxy
1001 * reply to the reply list.
1003 pairadd(&request->reply->vps, request->proxy_reply->vps);
1004 request->proxy_reply->vps = NULL;
1007 * Free proxy request pairs.
1009 pairfree(&request->proxy->vps);
1013 default: /* Don't do anything */
1015 case RLM_MODULE_FAIL:
1016 /* FIXME: debug print stuff */
1017 request->child_state = REQUEST_DONE;
1020 case RLM_MODULE_HANDLED:
1021 /* FIXME: debug print stuff */
1022 request->child_state = REQUEST_DONE;
1032 * Do state handling when we proxy a request.
1034 static int proxy_request(REQUEST *request)
1036 struct timeval when;
1039 if (!insert_into_proxy_hash(request)) {
1040 DEBUG("Error: Failed inserting request into proxy hash.");
1044 request->proxy_listener->encode(request->proxy_listener, request);
1046 when = request->received;
1047 when.tv_sec += request->root->max_request_time;
1049 gettimeofday(&request->proxy_when, NULL);
1051 request->next_when = request->proxy_when;
1052 request->next_when.tv_sec += request->home_server->response_window;
1054 rad_assert(request->home_server->response_window > 0);
1056 if (timercmp(&when, &request->next_when, <)) {
1057 request->next_when = when;
1059 request->next_callback = no_response_to_proxied_request;
1061 DEBUG2("Proxying request %d to home server %s port %d",
1063 inet_ntop(request->proxy->dst_ipaddr.af,
1064 &request->proxy->dst_ipaddr.ipaddr,
1065 buffer, sizeof(buffer)),
1066 request->proxy->dst_port);
1069 * Note that we set proxied BEFORE sending the packet.
1071 * Once we send it, the request is tainted, as
1072 * another thread may have picked it up. Don't
1075 request->num_proxied_requests = 1;
1076 request->num_proxied_responses = 0;
1077 request->child_pid = NO_SUCH_CHILD_PID;
1078 request->child_state = REQUEST_PROXIED;
1079 request->proxy_listener->send(request->proxy_listener,
1085 * Return 1 if we did proxy it, or the proxy attempt failed
1086 * completely. Either way, the caller doesn't touch the request
1087 * any more if we return 1.
1089 static int successfully_proxied_request(REQUEST *request)
1092 int pre_proxy_type = 0;
1093 VALUE_PAIR *realmpair;
1094 VALUE_PAIR *strippedname;
1098 REALM *realm = NULL;
1101 realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1102 if (!realmpair || (realmpair->length == 0)) {
1106 realmname = (char *) realmpair->vp_strvalue;
1108 realm = realm_find(realmname);
1110 DEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1115 * Figure out which pool to use.
1117 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1118 pool = realm->auth_pool;
1120 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1121 pool = realm->acct_pool;
1124 rad_panic("Internal sanity check failed");
1128 DEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1133 home = home_server_ldb(realmname, pool, request);
1135 DEBUG2("ERROR: Failed to find live home server for realm %s",
1139 request->home_pool = pool;
1142 * Remember that we sent the request to a Realm.
1144 pairadd(&request->packet->vps,
1145 pairmake("Realm", realmname, T_OP_EQ));
1148 * We read the packet from a detail file, AND it came from
1149 * the server we're about to send it to. Don't do that.
1151 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1152 (request->listener->type == RAD_LISTEN_DETAIL) &&
1153 (home->ipaddr.af == AF_INET) &&
1154 (request->packet->src_ipaddr.af == AF_INET) &&
1155 (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1156 DEBUG2(" rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1161 * Allocate the proxy packet, only if it wasn't already
1162 * allocated by a module. This check is mainly to support
1163 * the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1165 * In those cases, the EAP module creates a "fake"
1166 * request, and recursively passes it through the
1167 * authentication stage of the server. The module then
1168 * checks if the request was supposed to be proxied, and
1169 * if so, creates a proxy packet from the TUNNELED request,
1170 * and not from the EAP request outside of the tunnel.
1172 * The proxy then works like normal, except that the response
1173 * packet is "eaten" by the EAP module, and encapsulated into
1176 if (!request->proxy) {
1177 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1178 radlog(L_ERR|L_CONS, "no memory");
1183 * Copy the request, then look up name and
1184 * plain-text password in the copy.
1186 * Note that the User-Name attribute is the
1187 * *original* as sent over by the client. The
1188 * Stripped-User-Name attribute is the one hacked
1189 * through the 'hints' file.
1191 request->proxy->vps = paircopy(request->packet->vps);
1195 * Strip the name, if told to.
1197 * Doing it here catches the case of proxied tunneled
1200 if (realm->striprealm == TRUE &&
1201 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1203 * If there's a Stripped-User-Name attribute in
1204 * the request, then use THAT as the User-Name
1205 * for the proxied request, instead of the
1208 * This is done by making a copy of the
1209 * Stripped-User-Name attribute, turning it into
1210 * a User-Name attribute, deleting the
1211 * Stripped-User-Name and User-Name attributes
1212 * from the vps list, and making the new
1213 * User-Name the head of the vps list.
1215 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1217 vp = paircreate(PW_USER_NAME, PW_TYPE_STRING);
1219 radlog(L_ERR|L_CONS, "no memory");
1222 /* Insert at the START of the list */
1223 vp->next = request->proxy->vps;
1224 request->proxy->vps = vp;
1226 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1227 sizeof(vp->vp_strvalue));
1228 vp->length = strippedname->length;
1231 * Do NOT delete Stripped-User-Name.
1236 * If there is no PW_CHAP_CHALLENGE attribute but
1237 * there is a PW_CHAP_PASSWORD we need to add it
1238 * since we can't use the request authenticator
1239 * anymore - we changed it.
1241 if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1242 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1243 vp = radius_paircreate(request, &request->proxy->vps,
1244 PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1245 vp->length = AUTH_VECTOR_LEN;
1246 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1250 * The RFC's say we have to do this, but FreeRADIUS
1253 vp = radius_paircreate(request, &request->proxy->vps,
1254 PW_PROXY_STATE, PW_TYPE_OCTETS);
1255 sprintf(vp->vp_strvalue, "%d", request->packet->id);
1256 vp->length = strlen(vp->vp_strvalue);
1259 * Should be done BEFORE inserting into proxy hash, as
1260 * pre-proxy may use this information, or change it.
1262 request->proxy->code = request->packet->code;
1263 request->proxy->dst_ipaddr = home->ipaddr;
1264 request->proxy->dst_port = home->port;
1265 request->home_server = home;
1268 * Call the pre-proxy routines.
1270 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1272 DEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
1273 pre_proxy_type = vp->vp_integer;
1276 rad_assert(request->home_pool != NULL);
1278 if (request->home_pool->virtual_server) {
1279 const char *old_server = request->server;
1281 request->server = request->home_pool->virtual_server;
1282 DEBUG2(" server %s {", request->server);
1283 rcode = module_pre_proxy(pre_proxy_type, request);
1285 request->server = old_server;
1287 rcode = module_pre_proxy(pre_proxy_type, request);
1290 case RLM_MODULE_FAIL:
1291 case RLM_MODULE_INVALID:
1292 case RLM_MODULE_NOTFOUND:
1293 case RLM_MODULE_USERLOCK:
1295 /* FIXME: debug print failed stuff */
1298 case RLM_MODULE_REJECT:
1299 case RLM_MODULE_HANDLED:
1303 * Only proxy the packet if the pre-proxy code succeeded.
1305 case RLM_MODULE_NOOP:
1307 case RLM_MODULE_UPDATED:
1312 * If it's a fake request, don't send the proxy
1313 * packet. The outer tunnel session will take
1314 * care of doing that.
1316 if (request->packet->dst_port == 0) {
1317 request->home_server = NULL;
1321 if (!proxy_request(request)) {
1322 DEBUG("ERROR: Failed to proxy request %d", request->number);
1330 static void request_post_handler(REQUEST *request)
1332 int child_state = -1;
1333 struct timeval when;
1336 if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1338 (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1339 DEBUG2("Request %d was cancelled.", request->number);
1340 request->child_pid = NO_SUCH_CHILD_PID;
1341 request->child_state = REQUEST_DONE;
1345 if (request->child_state != REQUEST_RUNNING) {
1346 rad_panic("Internal sanity check failed");
1349 if ((request->reply->code == 0) &&
1350 ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1351 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1352 request->reply->code = PW_AUTHENTICATION_REJECT;
1355 if (request->root->proxy_requests &&
1356 (request->reply->code == 0) &&
1357 (request->packet->dst_port != 0) &&
1358 (request->packet->code != PW_STATUS_SERVER)) {
1359 int rcode = successfully_proxied_request(request);
1361 if (rcode == 1) return;
1364 * Failed proxying it (dead home servers, etc.)
1365 * Run it through Post-Proxy-Type = Fail, and
1366 * respond to the request.
1368 * Note that we're in a child thread here, so we
1369 * do NOT re-schedule the request. Instead, we
1370 * do what we would have done, which is run the
1371 * pre-handler, a NULL request handler, and then
1374 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1375 request_pre_handler(request);
1379 * Else we weren't supposed to proxy it.
1384 * Fake requests don't get encoded or signed. The caller
1385 * also requires the reply VP's, so we don't free them
1388 if (request->packet->dst_port == 0) {
1389 /* FIXME: DEBUG going to the next request */
1390 request->child_pid = NO_SUCH_CHILD_PID;
1391 request->child_state = REQUEST_DONE;
1396 * Copy Proxy-State from the request to the reply.
1398 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1399 if (vp) pairadd(&request->reply->vps, vp);
1402 * Access-Requests get delayed or cached.
1404 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1405 gettimeofday(&request->next_when, NULL);
1407 if (request->reply->code == 0) {
1409 * Check if the lack of response is intentional.
1411 vp = pairfind(request->config_items,
1412 PW_RESPONSE_PACKET_TYPE);
1413 if (!vp || (vp->vp_integer != 256)) {
1414 DEBUG2("There was no response configured: rejecting request %d",
1416 request->reply->code = PW_AUTHENTICATION_REJECT;
1418 DEBUG2("Not responding to request %d",
1424 * Run rejected packets through
1426 * Post-Auth-Type = Reject
1428 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1429 vp = pairmake("Post-Auth-Type", "Reject", T_OP_SET);
1431 pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1432 pairadd(&request->config_items, vp);
1433 rad_postauth(request);
1434 } /* else no Reject section defined */
1437 * If configured, delay Access-Reject packets.
1439 * If request->root->reject_delay = 0, we discover
1440 * that we have to send the packet now.
1442 when = request->received;
1443 when.tv_sec += request->root->reject_delay;
1445 if (timercmp(&when, &request->next_when, >)) {
1446 DEBUG2("Delaying reject of request %d for %d seconds",
1448 request->root->reject_delay);
1449 request->next_when = when;
1450 request->next_callback = reject_delay;
1451 request->child_pid = NO_SUCH_CHILD_PID;
1452 request->child_state = REQUEST_REJECT_DELAY;
1457 request->next_when.tv_sec += request->root->cleanup_delay;
1458 request->next_callback = cleanup_delay;
1459 child_state = REQUEST_CLEANUP_DELAY;
1461 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1462 request->next_callback = NULL; /* just to be safe */
1463 child_state = REQUEST_DONE;
1466 * FIXME: Status-Server should probably not be
1469 } else if (request->packet->code == PW_STATUS_SERVER) {
1470 request->next_callback = NULL;
1471 child_state = REQUEST_DONE;
1474 rad_panic("Unknown packet type");
1478 * Suppress "no reply" packets here, unless we're reading
1479 * from the "detail" file. In that case, we've got to
1480 * tell the detail file handler that the request is dead,
1481 * and it should re-send it.
1482 * If configured, encode, sign, and send.
1484 if ((request->reply->code != 0) ||
1485 (request->listener->type == RAD_LISTEN_DETAIL)) {
1486 request->listener->send(request->listener, request);
1490 * Clean up. These are no longer needed.
1492 pairfree(&request->config_items);
1494 pairfree(&request->packet->vps);
1495 request->username = NULL;
1496 request->password = NULL;
1498 pairfree(&request->reply->vps);
1500 if (request->proxy) {
1501 pairfree(&request->proxy->vps);
1503 if (request->proxy_reply) {
1504 pairfree(&request->proxy_reply->vps);
1508 * We're not tracking responses from the home
1509 * server, we can therefore free this memory in
1512 if (!request->in_proxy_hash) {
1513 rad_free(&request->proxy);
1514 rad_free(&request->proxy_reply);
1515 request->home_server = NULL;
1519 DEBUG2("Finished request %d.", request->number);
1521 request->child_state = child_state;
1525 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1529 RAD_SNMP_TYPE_INC(request->listener, total_dup_requests);
1530 RAD_SNMP_CLIENT_INC(request->listener, client, dup_requests);
1532 switch (request->child_state) {
1533 case REQUEST_QUEUED:
1534 case REQUEST_RUNNING:
1536 radlog(L_ERR, "Discarding duplicate request from "
1537 "client %s port %d - ID: %d due to unfinished request %d",
1539 request->packet->src_port,request->packet->id,
1543 case REQUEST_PROXIED:
1545 * We're not supposed to have duplicate
1546 * accounting packets. The other states handle
1547 * duplicates fine (discard, or send duplicate
1548 * reply). But we do NOT want to retransmit an
1549 * accounting request here, because that would
1550 * involve updating the Acct-Delay-Time, and
1551 * therefore changing the packet Id, etc.
1553 * Instead, we just discard the packet. We may
1554 * eventually respond, or the client will send a
1555 * new accounting packet.
1557 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1561 check_for_zombie_home_server(request);
1564 * If we've just discovered that the home server is
1565 * dead, send the packet to another one.
1567 if ((request->packet->dst_port != 0) &&
1568 (request->home_server->state == HOME_STATE_IS_DEAD)) {
1571 remove_from_proxy_hash(request);
1573 home = home_server_ldb(NULL, request->home_pool, request);
1575 DEBUG2("Failed to find live home server for request %d", request->number);
1578 * Do post-request processing,
1579 * and any insertion of necessary
1582 post_proxy_fail_handler(request);
1586 request->proxy->code = request->packet->code;
1587 request->proxy->dst_ipaddr = home->ipaddr;
1588 request->proxy->dst_port = home->port;
1589 request->home_server = home;
1592 * Free the old packet, to force re-encoding
1594 free(request->proxy->data);
1595 request->proxy->data = NULL;
1596 request->proxy->data_len = 0;
1599 * Try to proxy the request.
1601 if (!proxy_request(request)) {
1602 DEBUG("ERROR: Failed to re-proxy request %d", request->number);
1603 goto no_home_servers;
1607 * This code executes in the main server
1608 * thread, so there's no need for locking.
1610 rad_assert(request->next_callback != NULL);
1611 INSERT_EVENT(request->next_callback, request);
1612 request->next_callback = NULL;
1614 } /* else the home server is still alive */
1616 DEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1617 inet_ntop(request->proxy->dst_ipaddr.af,
1618 &request->proxy->dst_ipaddr.ipaddr,
1619 buffer, sizeof(buffer)),
1620 request->proxy->dst_port,
1621 request->proxy->id);
1622 request->num_proxied_requests++;
1623 request->proxy_listener->send(request->proxy_listener,
1627 case REQUEST_REJECT_DELAY:
1628 DEBUG2("Waiting to send Access-Reject "
1629 "to client %s port %d - ID: %d",
1631 request->packet->src_port, request->packet->id);
1634 case REQUEST_CLEANUP_DELAY:
1636 DEBUG2("Sending duplicate reply "
1637 "to client %s port %d - ID: %d",
1639 request->packet->src_port, request->packet->id);
1640 request->listener->send(request->listener, request);
1646 static void received_conflicting_request(REQUEST *request,
1647 const RADCLIENT *client)
1649 radlog(L_ERR, "Received conflicting packet from "
1650 "client %s port %d - ID: %d due to unfinished request %d. Giving up on old request.",
1652 request->packet->src_port, request->packet->id,
1656 * Nuke it from the request hash, so we can receive new
1659 remove_from_request_hash(request);
1661 switch (request->child_state) {
1663 * It's queued or running. Tell it to stop, and
1664 * wait for it to do so.
1666 case REQUEST_QUEUED:
1667 case REQUEST_RUNNING:
1668 request->master_state = REQUEST_STOP_PROCESSING;
1669 request->delay += request->delay >> 1;
1671 tv_add(&request->when, request->delay);
1673 INSERT_EVENT(wait_for_child_to_die, request);
1677 * It's in some other state, and therefore also
1678 * in the event queue. At some point, the
1679 * child will notice, and we can then delete it.
1682 rad_assert(request->ev != NULL);
1688 static int can_handle_new_request(RADIUS_PACKET *packet,
1690 struct main_config_t *root)
1693 * Count the total number of requests, to see if
1694 * there are too many. If so, return with an
1697 if (root->max_requests) {
1698 int request_count = lrad_packet_list_num_elements(pl);
1701 * This is a new request. Let's see if
1702 * it makes us go over our configured
1705 if (request_count > root->max_requests) {
1706 radlog(L_ERR, "Dropping request (%d is too many): "
1707 "from client %s port %d - ID: %d", request_count,
1709 packet->src_port, packet->id);
1710 radlog(L_INFO, "WARNING: Please check the %s file.\n"
1711 "\tThe value for 'max_requests' is probably set too low.\n", root->radiusd_conf);
1713 } /* else there were a small number of requests */
1714 } /* else there was no configured limit for requests */
1717 * FIXME: Add per-client checks. If one client is sending
1718 * too many packets, start discarding them.
1720 * We increment the counters here, and decrement them
1721 * when the response is sent... somewhere in this file.
1725 * FUTURE: Add checks for system load. If the system is
1726 * busy, start dropping requests...
1728 * We can probably keep some statistics ourselves... if
1729 * there are more requests coming in than we can handle,
1730 * start dropping some.
1737 int received_request(rad_listen_t *listener,
1738 RADIUS_PACKET *packet, REQUEST **prequest,
1741 RADIUS_PACKET **packet_p;
1742 REQUEST *request = NULL;
1743 struct main_config_t *root = &mainconfig;
1745 packet_p = lrad_packet_list_find(pl, packet);
1747 request = lrad_packet2myptr(REQUEST, packet, packet_p);
1748 rad_assert(request->in_request_hash);
1750 if ((request->packet->data_len == packet->data_len) &&
1751 (memcmp(request->packet->vector, packet->vector,
1752 sizeof(packet->vector)) == 0)) {
1753 received_retransmit(request, client);
1758 * The new request is different from the old one,
1759 * but maybe the old is finished. If so, delete
1762 switch (request->child_state) {
1763 struct timeval when;
1766 gettimeofday(&when, NULL);
1770 * If the cached request was received
1771 * within the last second, then we
1772 * discard the NEW request instead of the
1773 * old one. This will happen ONLY when
1774 * the client is severely broken, and is
1775 * sending conflicting packets very
1778 if (timercmp(&when, &request->received, <)) {
1779 radlog(L_ERR, "Discarding conflicting packet from "
1780 "client %s port %d - ID: %d due to recent request %d.",
1782 packet->src_port, packet->id,
1787 received_conflicting_request(request, client);
1791 case REQUEST_REJECT_DELAY:
1792 case REQUEST_CLEANUP_DELAY:
1793 request->child_state = REQUEST_DONE;
1795 cleanup_delay(request);
1804 * We may want to quench the new request.
1806 if (!can_handle_new_request(packet, client, root)) {
1811 * Create and initialize the new request.
1813 request = request_alloc(); /* never fails */
1815 if ((request->reply = rad_alloc(0)) == NULL) {
1816 radlog(L_ERR, "No memory");
1820 request->listener = listener;
1821 request->client = client;
1822 request->packet = packet;
1823 request->packet->timestamp = request->timestamp;
1824 request->number = request_num_counter++;
1825 request->priority = listener->type;
1828 * Set virtual server identity
1830 if (client->server) {
1831 request->server = client->server;
1832 } else if (listener->server) {
1833 request->server = listener->server;
1835 request->server = NULL;
1839 * Remember the request in the list.
1841 if (!lrad_packet_list_insert(pl, &request->packet)) {
1842 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
1843 request_free(&request);
1847 request->in_request_hash = TRUE;
1848 request->root = root;
1852 * The request passes many of our sanity checks.
1853 * From here on in, if anything goes wrong, we
1854 * send a reject message, instead of dropping the
1859 * Build the reply template from the request.
1862 request->reply->sockfd = request->packet->sockfd;
1863 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1864 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1865 request->reply->dst_port = request->packet->src_port;
1866 request->reply->src_port = request->packet->dst_port;
1867 request->reply->id = request->packet->id;
1868 request->reply->code = 0; /* UNKNOWN code */
1869 memcpy(request->reply->vector, request->packet->vector,
1870 sizeof(request->reply->vector));
1871 request->reply->vps = NULL;
1872 request->reply->data = NULL;
1873 request->reply->data_len = 0;
1875 request->master_state = REQUEST_ACTIVE;
1876 request->child_state = REQUEST_QUEUED;
1877 request->next_callback = NULL;
1879 gettimeofday(&request->received, NULL);
1880 request->timestamp = request->received.tv_sec;
1881 request->when = request->received;
1883 request->delay = USEC / 10;
1885 tv_add(&request->when, request->delay);
1887 INSERT_EVENT(wait_a_bit, request);
1889 *prequest = request;
1894 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
1900 if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
1901 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
1902 inet_ntop(packet->src_ipaddr.af,
1903 &packet->src_ipaddr.ipaddr,
1904 buffer, sizeof(buffer)),
1911 * Also removes from the proxy hash if responses == requests
1913 request = lookup_in_proxy_hash(packet);
1916 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
1917 inet_ntop(packet->src_ipaddr.af,
1918 &packet->src_ipaddr.ipaddr,
1919 buffer, sizeof(buffer)),
1920 packet->src_port, packet->id);
1925 home = request->home_server;
1927 gettimeofday(&now, NULL);
1928 home->state = HOME_STATE_ALIVE;
1930 if (request->reply && request->reply->code != 0) {
1931 DEBUG2("We already replied to this request. Discarding response from home server.");
1937 * We had previously received a reply, so we don't need
1938 * to do anything here.
1940 if (request->proxy_reply) {
1941 if (memcmp(request->proxy_reply->vector,
1943 sizeof(request->proxy_reply->vector)) == 0) {
1944 DEBUG2("Discarding duplicate reply from home server %s port %d - ID: %d for request %d",
1945 inet_ntop(packet->src_ipaddr.af,
1946 &packet->src_ipaddr.ipaddr,
1947 buffer, sizeof(buffer)),
1948 packet->src_port, packet->id,
1952 * ? The home server gave us a new proxy
1953 * reply, which doesn't match the old
1956 DEBUG2("Ignoring conflicting proxy reply");
1959 /* assert that there's an event queued for request? */
1964 switch (request->child_state) {
1965 case REQUEST_QUEUED:
1966 case REQUEST_RUNNING:
1967 rad_panic("Internal sanity check failed for child state");
1970 case REQUEST_REJECT_DELAY:
1971 case REQUEST_CLEANUP_DELAY:
1973 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'",
1974 inet_ntop(packet->src_ipaddr.af,
1975 &packet->src_ipaddr.ipaddr,
1976 buffer, sizeof(buffer)),
1977 packet->src_port, packet->id,
1979 /* assert that there's an event queued for request? */
1983 case REQUEST_PROXIED:
1987 request->proxy_reply = packet;
1991 * Perform RTT calculations, as per RFC 2988 (for TCP).
1992 * Note that we do so only if we sent one request, and
1993 * received one response. If we sent two requests, we
1994 * have no idea if the response is for the first, or for
1995 * the second request/
1997 if (request->num_proxied_requests == 1) {
1999 home_server *home = request->home_server;
2001 rtt = now.tv_sec - request->proxy_when.tv_sec;
2004 rtt -= request->proxy_when.tv_usec;
2006 if (!home->has_rtt) {
2007 home->has_rtt = TRUE;
2010 home->rttvar = rtt / 2;
2013 home->rttvar -= home->rttvar >> 2;
2014 home->rttvar += (home->srtt - rtt);
2015 home->srtt -= home->srtt >> 3;
2016 home->srtt += rtt >> 3;
2019 home->rto = home->srtt;
2020 if (home->rttvar > (USEC / 4)) {
2021 home->rto += home->rttvar * 4;
2029 * There's no incoming request, so it's a proxied packet
2032 if (!request->packet) {
2033 received_response_to_ping(request);
2037 request->child_state = REQUEST_QUEUED;
2038 request->when = now;
2039 request->delay = USEC / 10;
2040 request->priority = RAD_LISTEN_PROXY;
2041 tv_add(&request->when, request->delay);
2044 * Wait a bit will take care of max_request_time
2046 INSERT_EVENT(wait_a_bit, request);
2053 * Inform ourselves that we received a signal.
2055 void radius_signal_self(int flag)
2061 * The caller is telling us it's OK to read from the
2062 * detail files. However, we're not even listening on
2063 * the detail files. Therefore, suppress the flag to
2064 * avoid bothering the main worker thread.
2066 if ((flag == RADIUS_SIGNAL_SELF_DETAIL) &&
2067 !has_detail_listener) {
2072 * The read MUST be non-blocking for this to work.
2074 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2078 for (i = 1; i < rcode; i++) {
2079 buffer[0] |= buffer[i];
2084 memset(buffer + 1, 0, sizeof(buffer) - 1);
2089 write(self_pipe[1], buffer, 1);
2093 static void event_signal_handler(lrad_event_list_t *xel, int fd, void *ctx)
2102 rcode = read(self_pipe[0], buffer, sizeof(buffer));
2103 if (rcode <= 0) return;
2106 * Merge pending signals.
2108 for (i = 1; i < rcode; i++) {
2109 buffer[0] |= buffer[i];
2113 * The thread pool has nothing more to do. Start reading
2114 * from the detail file.
2116 if ((buffer[0] & (RADIUS_SIGNAL_SELF_DETAIL)) != 0) {
2117 read_from_detail = TRUE;
2120 if ((buffer[0] & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2121 if ((buffer[0] & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2122 lrad_event_loop_exit(el, 1);
2124 lrad_event_loop_exit(el, 2);
2128 } /* else exit/term flags weren't set */
2131 * Tell the even loop to stop processing.
2133 if ((buffer[0] & RADIUS_SIGNAL_SELF_HUP) != 0) {
2134 DEBUG("Received HUP signal.");
2136 lrad_event_loop_exit(el, 0x80);
2142 * The given FD is closed. Delete it from the list of FD's to poll,
2143 * and set a timer to periodically look for an FD again.
2145 static void event_reset_fd(rad_listen_t *listener, int fd, int usec)
2147 struct timeval when;
2148 gettimeofday(&when, NULL);
2150 tv_add(&when, usec);
2152 if (!lrad_event_fd_delete(el, 0, fd)) {
2153 rad_panic("Failed deleting fd");
2156 if (!lrad_event_insert(el, event_poll_fd, listener,
2158 rad_panic("Failed inserting event");
2164 * Reads from the detail file if possible, OR sets up a timeout
2165 * to see if the detail file is ready for reading.
2167 * FIXME: On Linux, use inotify to watch the detail file. This
2170 static void event_detail_handler(lrad_event_list_t *xel, int fd, void *ctx)
2172 rad_listen_t *listener = ctx;
2173 RAD_REQUEST_FUNP fun;
2176 rad_assert(xel == el);
2177 rad_assert(fd == listener->fd);
2182 * We're too busy to read from the detail file. Stop
2183 * watching the file, and instead go back to polling.
2185 if (!read_from_detail) {
2186 event_reset_fd(listener, fd, USEC);
2191 * FIXME: Put this somewhere else, where it isn't called
2192 * all of the time...
2194 #ifndef HAVE_PTHREAD_H
2196 * If there are no child threads, then there may
2197 * be child processes. In that case, wait for
2198 * their exit status, and throw that exit status
2199 * away. This helps get rid of zxombie children.
2201 while (waitpid(-1, &argval, WNOHANG) > 0) {
2207 * Didn't read anything from the detail file.
2208 * Wake up in one second to check it again.
2210 if (!listener->recv(listener, &fun, &request)) {
2211 event_reset_fd(listener, fd, USEC);
2216 * Drop the request into the thread pool,
2217 * and let the thread pool take care of
2218 * doing something with it.
2220 if (!thread_pool_addrequest(request, fun)) {
2221 request->child_state = REQUEST_DONE;
2225 * Reset based on the fd we were given, as detail_recv()
2226 * may have read all of the file, and closed it. It then
2227 * sets listener->fd = -1.
2229 event_reset_fd(listener, fd, *(int *) listener->data);
2233 static void event_socket_handler(lrad_event_list_t *xel, int fd, void *ctx)
2235 rad_listen_t *listener = ctx;
2236 RAD_REQUEST_FUNP fun;
2239 rad_assert(xel == el);
2244 if (listener->fd < 0) rad_panic("Socket was closed on us!");
2247 * FIXME: Put this somewhere else, where it isn't called
2248 * all of the time...
2250 #ifndef HAVE_PTHREAD_H
2252 * If there are no child threads, then there may
2253 * be child processes. In that case, wait for
2254 * their exit status, and throw that exit status
2255 * away. This helps get rid of zxombie children.
2257 while (waitpid(-1, &argval, WNOHANG) > 0) {
2262 if (!listener->recv(listener, &fun, &request)) return;
2264 if (!thread_pool_addrequest(request, fun)) {
2265 request->child_state = REQUEST_DONE;
2269 * If we've read a packet from a socket OTHER than the
2270 * detail file, we start ignoring the detail file.
2272 * When the child thread pulls the request off of the
2273 * queues, it will check if the queues are empty. Once
2274 * all queues are empty, it will signal us to read the
2275 * detail file again.
2277 read_from_detail = FALSE;
2282 * This function is called periodically to see if a file
2283 * descriptor is available for reading.
2285 static void event_poll_fd(void *ctx)
2288 RAD_REQUEST_FUNP fun;
2290 rad_listen_t *listener = ctx;
2291 lrad_event_fd_handler_t handler;
2294 * Ignore the detail file if we're busy with other work.
2296 if ((listener->type == RAD_LISTEN_DETAIL) && !read_from_detail) {
2301 * Try to read a RADIUS packet. This also opens the FD.
2303 * FIXME: This does poll AND receive.
2305 rcode = listener->recv(listener, &fun, &request);
2308 * We read a request. Add it to the list for processing.
2311 rad_assert(fun != NULL);
2312 rad_assert(request != NULL);
2314 if (!thread_pool_addrequest(request, fun)) {
2315 request->child_state = REQUEST_DONE;
2320 * Still no FD, OR the fd was read completely, and then
2321 * closed. Re-set the polling timer and return.
2323 if (listener->fd < 0) {
2324 struct timeval when;
2327 gettimeofday(&when, NULL);
2330 if (!lrad_event_insert(el, event_poll_fd, listener,
2332 rad_panic("Failed inserting event");
2338 if (listener->type == RAD_LISTEN_DETAIL) {
2339 handler = event_detail_handler;
2341 handler = event_socket_handler;
2345 * We have an FD. Start watching it.
2347 if (!lrad_event_fd_insert(el, 0, listener->fd,
2348 handler, listener)) {
2351 listener->print(listener, buffer, sizeof(buffer));
2352 rad_panic("Failed creating handler for socket");
2357 static void event_status(struct timeval *wake)
2359 if (debug_flag == 0) {
2361 radlog(L_INFO, "Ready to process requests.");
2362 just_started = FALSE;
2368 DEBUG("Ready to process requests.");
2369 } else if ((wake->tv_sec != 0) ||
2370 (wake->tv_usec >= 100000)) {
2371 DEBUG("Waking up in %d.%01d seconds.\n",
2372 (int) wake->tv_sec, (int) wake->tv_usec / 100000);
2378 * Externally-visibly functions.
2380 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2383 rad_listen_t *this, *head = NULL;
2389 el = lrad_event_list_create(event_status);
2392 pl = lrad_packet_list_create(0);
2395 request_num_counter = 0;
2398 * Move all of the thread calls to this file?
2400 * It may be best for the mutexes to be in this file...
2402 have_children = spawn_flag;
2404 if (mainconfig.proxy_requests) {
2406 * Create the tree for managing proxied requests and
2409 proxy_list = lrad_packet_list_create(1);
2410 if (!proxy_list) return 0;
2412 #ifdef HAVE_PTHREAD_H
2413 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2414 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2421 #ifdef HAVE_PTHREAD_H
2422 if (thread_pool_init(cs, spawn_flag) < 0) {
2428 * Child threads need a pipe to signal us, as do the
2431 if (pipe(self_pipe) < 0) {
2432 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2436 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2437 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2441 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2442 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2447 if (!lrad_event_fd_insert(el, 0, self_pipe[0],
2448 event_signal_handler, el)) {
2449 radlog(L_ERR, "Failed creating handler for signals");
2455 * Mark the proxy Fd's as unused.
2457 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2459 DEBUG2("radiusd: #### Opening IP addresses and Ports ####");
2461 if (listen_init(cs, &head) < 0) {
2466 * Add all of the sockets to the event loop.
2468 * FIXME: New proxy sockets aren't currently added to the
2469 * event loop. They're allocated in a child thread, and
2470 * we don't have (or want) a mutex around the event
2475 this = this->next) {
2478 this->print(this, buffer, sizeof(buffer));
2480 switch (this->type) {
2481 case RAD_LISTEN_DETAIL:
2482 DEBUG("Listening on %s", buffer);
2483 has_detail_listener = TRUE;
2486 case RAD_LISTEN_PROXY:
2487 rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2488 rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2490 proxy_fds[this->fd & 0x1f] = this->fd;
2491 proxy_listeners[this->fd & 0x1f] = this;
2492 if (!lrad_packet_list_socket_add(proxy_list,
2498 case RAD_LISTEN_SNMP:
2499 DEBUG("Listening on SNMP %s", buffer);
2503 DEBUG("Listening on %s", buffer);
2508 * The file descriptor isn't ready. Poll for
2509 * when it will become ready. This is for SNMP
2510 * and detail file fd's.
2513 struct timeval when;
2515 gettimeofday(&when, NULL);
2518 if (!lrad_event_insert(el, event_poll_fd, this,
2520 radlog(L_ERR, "Failed creating handler");
2527 * The socket is open. It MUST be a socket,
2528 * as we don't pre-open the detail files (yet).
2530 * FIXME: if we DO open the detail files automatically,
2531 * then much of this code becomes simpler.
2533 if (!lrad_event_fd_insert(el, 0, this->fd,
2534 event_socket_handler, this)) {
2535 this->print(this, buffer, sizeof(buffer));
2536 radlog(L_ERR, "Failed creating handler for socket %s",
2546 static int request_hash_cb(void *ctx, void *data)
2548 ctx = ctx; /* -Wunused */
2549 REQUEST *request = lrad_packet2myptr(REQUEST, packet, data);
2551 rad_assert(request->in_proxy_hash == FALSE);
2553 lrad_event_delete(el, &request->ev);
2554 remove_from_request_hash(request);
2555 request_free(&request);
2561 static int proxy_hash_cb(void *ctx, void *data)
2563 ctx = ctx; /* -Wunused */
2564 REQUEST *request = lrad_packet2myptr(REQUEST, proxy, data);
2566 lrad_packet_list_yank(proxy_list, request->proxy);
2567 request->in_proxy_hash = FALSE;
2569 if (!request->in_request_hash) {
2570 lrad_event_delete(el, &request->ev);
2571 request_free(&request);
2578 void radius_event_free(void)
2581 * FIXME: Stop all threads, or at least check that
2582 * they're all waiting on the semaphore, and the queues
2587 * There are requests in the proxy hash that aren't
2588 * referenced from anywhere else. Remove them first.
2591 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2592 lrad_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2593 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2594 lrad_packet_list_free(proxy_list);
2598 lrad_packet_list_walk(pl, NULL, request_hash_cb);
2600 lrad_packet_list_free(pl);
2603 lrad_event_list_free(el);
2606 int radius_event_process(void)
2610 just_started = TRUE;
2612 return lrad_event_loop(el);
2615 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
2617 if (request_pre_handler(request)) {
2618 rad_assert(fun != NULL);
2619 rad_assert(request != NULL);
2621 if (request->server) DEBUG("server %s {",
2625 if (request->server) DEBUG("} # server %s",
2628 request_post_handler(request);
2631 DEBUG2("Going to the next request");