2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Defines the state machines that control how requests are processed.
23 * @copyright 2012 The FreeRADIUS server project
24 * @copyright 2012 Alan DeKok <aland@deployingradius.com>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
33 #include <freeradius-devel/rad_assert.h>
36 #include <freeradius-devel/detail.h>
42 #ifdef HAVE_SYS_WAIT_H
43 # include <sys/wait.h>
46 extern pid_t radius_pid;
47 extern bool check_config;
48 extern fr_cond_t *debug_condition;
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static fr_packet_list_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57 /* Currently we do not run a second event loop for modules. */
61 static char const *action_codes[] = {
73 #ifdef DEBUG_STATE_MACHINE
74 #define TRACE_STATE_MACHINE if (debug_flag) printf("(%u) ********\tSTATE %s action %s live M-%s C-%s\t********\n", request->number, __FUNCTION__, action_codes[action], master_state_names[request->master_state], child_state_names[request->child_state])
76 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
83 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
94 #define TRACE_STATE_MACHINE {}
98 * Declare a state in the state machine.
101 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
103 #define STATE_MACHINE_TIMER(_x) request->timer_action = _x; \
104 fr_event_insert(el, request_timer, request, \
105 &when, &request->ev);
110 * @section request_timeline
112 * Time sequence of a request
115 * RQ-----------------P=============================Y-J-C
116 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
119 * - R: received. Duplicate detection is done, and request is
122 * - Q: Request is placed onto a queue for child threads to pick up.
123 * If there are no child threads, the request goes immediately
126 * - P: Processing the request through the modules.
128 * - Y: Reply is ready. Rejects MAY be delayed here. All other
129 * replies are sent immediately.
131 * - J: Reject is sent "reject_delay" after the reply is ready.
133 * - C: For Access-Requests, After "cleanup_delay", the request is
134 * deleted. Accounting-Request packets go directly from Y to C.
136 * - M: Max request time. If the request hits this timer, it is
139 * Other considerations include duplicate and conflicting
140 * packets. When a dupicate packet is received, it is ignored
141 * until we've reached Y, as no response is ready. If the reply
142 * is a reject, duplicates are ignored until J, when we're ready
143 * to send the reply. In between the reply being sent (Y or J),
144 * and C, the server responds to duplicates by sending the cached
147 * Conflicting packets are sent in 2 situations.
149 * The first is in between R and Y. In that case, we consider
150 * it as a hint that we're taking too long, and the NAS has given
151 * up on the request. We then behave just as if the M timer was
152 * reached, and we discard the current request. This allows us
153 * to process the new one.
155 * The second case is when we're at Y, but we haven't yet
156 * finished processing the request. This is a race condition in
157 * the threading code (avoiding locks is faster). It means that
158 * a thread has actually encoded and sent the reply, and that the
159 * NAS has responded with a new packet. The server can then
160 * safely mark the current request as "OK to delete", and behaves
161 * just as if the M timer was reached. This usually happens only
162 * in high-load situations.
164 * Duplicate packets are sent when the NAS thinks we're taking
165 * too long, and wants a reply. From R-Y, duplicates are
166 * ignored. From Y-J (for Access-Rejects), duplicates are also
167 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
168 * they cause the "cleanup_delay" time to be extended. This
169 * extension means that we're more likely to send a duplicate
170 * reply (if we have one), or to suppress processing the packet
171 * twice if we didn't reply to it.
173 * All functions in this file should be thread-safe, and should
174 * assume thet the REQUEST structure is being accessed
175 * simultaneously by the main thread, and by the child worker
176 * threads. This means that timers, etc. cannot be updated in
179 * Instead, the master thread periodically calls request->process
180 * with action TIMER. It's up to the individual functions to
181 * determine how to handle that. They need to check if they're
182 * being called from a child thread or the master, and then do
183 * different things based on that.
188 static fr_packet_list_t *proxy_list = NULL;
191 #ifdef HAVE_PTHREAD_H
193 static pthread_mutex_t proxy_mutex;
194 static rad_listen_t *proxy_listener_list = NULL;
195 static bool proxy_no_new_sockets = false;
198 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
199 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
201 static pthread_t NO_SUCH_CHILD_PID;
202 #define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
206 * This is easier than ifdef's throughout the code.
208 #define PTHREAD_MUTEX_LOCK(_x)
209 #define PTHREAD_MUTEX_UNLOCK(_x)
210 #define NO_CHILD_THREAD
214 * We need mutexes around the event FD list *only* in certain
217 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
218 static pthread_mutex_t fd_mutex;
219 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
220 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
223 * This is easier than ifdef's throughout the code.
225 #define FD_MUTEX_LOCK(_x)
226 #define FD_MUTEX_UNLOCK(_x)
229 static int request_num_counter = 0;
231 static int request_will_proxy(REQUEST *request);
232 static int request_proxy(REQUEST *request, int retransmit);
233 STATE_MACHINE_DECL(proxy_wait_for_reply);
234 STATE_MACHINE_DECL(proxy_running);
235 static int process_proxy_reply(REQUEST *request);
236 static void remove_from_proxy_hash(REQUEST *request);
237 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank);
238 static int insert_into_proxy_hash(REQUEST *request);
241 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
242 RADCLIENT *client, RAD_REQUEST_FUNP fun);
244 STATE_MACHINE_DECL(request_common);
246 #if defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
247 static bool we_are_master(void)
250 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
256 #define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
259 #define we_are_master(_x) (1)
260 #define ASSERT_MASTER
263 STATE_MACHINE_DECL(request_reject_delay);
264 STATE_MACHINE_DECL(request_cleanup_delay);
265 STATE_MACHINE_DECL(request_running);
267 static void request_coa_originate(REQUEST *request);
268 STATE_MACHINE_DECL(coa_running);
269 STATE_MACHINE_DECL(coa_wait_for_reply);
270 static void request_coa_separate(REQUEST *coa);
274 #define USEC (1000000)
276 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
278 static void _rad_panic(char const *file, unsigned int line, char const *msg)
280 ERROR("[%s:%d] %s", file, line, msg);
287 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
289 static void tv_add(struct timeval *tv, int usec_delay)
291 if (usec_delay >= USEC) {
292 tv->tv_sec += usec_delay / USEC;
295 tv->tv_usec += usec_delay;
297 if (tv->tv_usec >= USEC) {
298 tv->tv_sec += tv->tv_usec / USEC;
304 * In daemon mode, AND this request has debug flags set.
306 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
308 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
313 char const *received, *from;
314 fr_ipaddr_t const *ip;
319 rad_assert(request->radlog != NULL);
321 if (direction == 0) {
322 received = "Received";
323 from = "from"; /* what else? */
324 ip = &packet->src_ipaddr;
325 port = packet->src_port;
328 received = "Sending";
329 from = "to"; /* hah! */
330 ip = &packet->dst_ipaddr;
331 port = packet->dst_port;
335 * Client-specific debugging re-prints the input
336 * packet into the client log.
338 * This really belongs in a utility library
340 if (is_radius_code(packet->code)) {
341 RDEBUG("%s %s packet %s host %s port %i, id=%i, length=%zu",
342 received, fr_packet_codes[packet->code], from,
343 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
344 port, packet->id, packet->data_len);
346 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%zu",
348 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
350 packet->code, packet->id, packet->data_len);
353 for (vp = fr_cursor_init(&cursor, &packet->vps);
355 vp = fr_cursor_next(&cursor)) {
356 vp_prints(buffer, sizeof(buffer), vp);
357 RDEBUG("\t%s", buffer);
362 /***********************************************************************
364 * Start of RADIUS server state machine.
366 ***********************************************************************/
369 * Callback for ALL timer events related to the request.
371 static void request_timer(void *ctx)
373 REQUEST *request = ctx;
374 int action = request->timer_action;
378 request->process(request, action);
381 #define USEC (1000000)
384 * Only ever called from the master thread.
386 STATE_MACHINE_DECL(request_done)
388 struct timeval now, when;
397 * CoA requests can be cleaned up in the child thread,
398 * but ONLY if they aren't tied into anything.
400 if (request->parent && (request->parent->coa == request)) {
401 rad_assert(!request->in_request_hash);
402 rad_assert(!request->in_proxy_hash);
403 rad_assert(action == FR_ACTION_DONE);
404 rad_assert(request->ev == NULL);
408 #ifdef HAVE_PTHREAD_H
410 * If called from a child thread, mark ourselves as done,
411 * and wait for the master thread timer to clean us up.
413 if (!we_are_master()) {
414 request->child_state = REQUEST_DONE;
422 * Move the CoA request to its own handler.
424 if (request->coa) request_coa_separate(request->coa);
427 * If we're the CoA request, make the parent forget about
430 if (request->parent && (request->parent->coa == request)) {
431 request->parent->coa = NULL;
437 * It doesn't hurt to send duplicate replies. All other
438 * signals are ignored, as the request will be cleaned up
443 if (request->reply->code != 0) {
444 request->listener->send(request->listener, request);
450 * This is only called from the master thread
451 * when there is a child thread processing the
454 case FR_ACTION_CONFLICTING:
455 if (request->child_state == REQUEST_DONE) break;
458 * If there's a reply packet, then we presume
459 * that the child has sent the reply, and we get
460 * pinged here before the child has a chance to
463 if (request->reply->data) break;
465 RERROR("Received conflicting packet from "
466 "client %s port %d - ID: %u due to "
467 "unfinished request. Giving up on old request.",
468 request->client->shortname,
469 request->packet->src_port, request->packet->id);
473 * Called only when there's an error remembering
474 * the packet, or when the socket gets closed from
478 #ifdef HAVE_PTHREAD_H
480 * Do NOT set child_state to DONE if it's still in the queue.
482 if (we_are_master() && (request->child_state == REQUEST_QUEUED)) {
487 * If we have child threads and we're NOT the
488 * thread handling the request, don't do anything.
491 !pthread_equal(pthread_self(), request->child_pid)) {
495 #ifdef DEBUG_STATE_MACHINE
496 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
497 request->number, __FUNCTION__,
498 child_state_names[request->child_state],
499 child_state_names[REQUEST_DONE]);
501 request->child_state = REQUEST_DONE;
505 * Called when the child is taking too long to
506 * finish. We've already marked it "please
507 * stop", so we don't complain any more.
509 case FR_ACTION_TIMER:
514 * Child is still alive, and we're receiving more
515 * packets from the home server.
517 case FR_ACTION_PROXY_REPLY:
518 DEBUG2("Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
519 inet_ntop(request->proxy->src_ipaddr.af,
520 &request->proxy->src_ipaddr.ipaddr,
521 buffer, sizeof(buffer)),
522 request->proxy->dst_port, request->proxy->id,
528 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
533 * Remove it from the request hash.
535 if (request->in_request_hash) {
537 if (!fr_packet_list_yank(pl, request->packet)) {
540 request->in_request_hash = false;
545 * Wait for the proxy ID to expire. This allows us to
546 * avoid re-use of proxy IDs for a while.
548 if (request->in_proxy_hash) {
549 rad_assert(request->proxy != NULL);
551 fr_event_now(el, &now);
552 when = request->proxy->timestamp;
555 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
556 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
557 (request->packet->code != request->proxy->code)) {
558 when.tv_sec += request->home_server->coa_mrd;
561 when.tv_sec += request->home_server->response_window;
564 * We haven't received all responses, AND there's still
565 * time to wait. Do so.
567 if ((request->num_proxied_requests > request->num_proxied_responses) &&
569 (request->home_server->proto != IPPROTO_TCP) &&
571 timercmp(&now, &when, <)) {
572 RDEBUG("Waiting for more responses from the home server");
579 remove_from_proxy_hash(request);
583 #ifdef HAVE_PTHREAD_H
585 * If there's no children, we can mark the request as done.
588 request->child_state = REQUEST_DONE;
592 if (request->child_state != REQUEST_DONE) {
593 gettimeofday(&now, NULL);
598 #ifdef HAVE_PTHREAD_H
600 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
601 RDEBUG("Waiting for child thread to stop");
606 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
607 tv_add(&when, request->delay);
608 request->delay += request->delay >> 1;
609 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
611 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
615 #ifdef HAVE_PTHREAD_H
616 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
620 * @todo: do final states for TCP sockets, too?
622 request_stats_final(request);
624 if (request->listener) request->listener->count--;
627 if (request->packet) {
628 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
630 (unsigned int) (request->timestamp - fr_start_time));
631 } /* else don't print anything */
633 if (request->ev) fr_event_delete(el, &request->ev);
635 request_free(&request);
639 static void request_cleanup_delay_init(REQUEST *request, struct timeval const *pnow)
641 struct timeval now, when;
643 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
645 if (!request->root->cleanup_delay) goto done;
650 gettimeofday(&now, NULL);
653 rad_assert(request->reply->timestamp.tv_sec != 0);
654 when = request->reply->timestamp;
656 request->delay = request->root->cleanup_delay;
657 when.tv_sec += request->delay;
660 * Set timer for when we need to clean it up.
662 if (timercmp(&when, &now, >)) {
663 #ifdef DEBUG_STATE_MACHINE
664 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
666 request->process = request_cleanup_delay;
667 request->child_state = REQUEST_DONE;
668 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
673 * Otherwise just clean it up.
676 request_done(request, FR_ACTION_DONE);
681 * Function to do all time-related events.
683 static void request_process_timer(REQUEST *request)
685 struct timeval now, when;
686 rad_assert(request->magic == REQUEST_MAGIC);
687 #ifdef DEBUG_STATE_MACHINE
688 int action = FR_ACTION_TIMER;
696 * If we originated a CoA request, divorce it from the
697 * parent. Then, set up the timers so that we can clean
698 * it up as appropriate.
700 if (request->coa) request_coa_separate(request->coa);
703 * If we're the request, OR it isn't originating a CoA
704 * request, check more things.
706 if (!request->proxy || (request->packet->code == request->proxy->code))
709 rad_assert(request->listener != NULL);
712 * The socket was closed. Tell the request that
713 * there is no point in continuing.
715 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
716 if ((request->master_state == REQUEST_ACTIVE) &&
717 (request->child_state < REQUEST_REJECT_DELAY)) {
718 WDEBUG("Socket was closed while processing request %u: Stopping it.", request->number);
719 request->master_state = REQUEST_STOP_PROCESSING;
724 gettimeofday(&now, NULL);
727 * The request was forcibly stopped.
729 if (request->master_state == REQUEST_STOP_PROCESSING) {
730 switch (request->child_state) {
732 case REQUEST_RUNNING:
733 #ifdef HAVE_PTHREAD_H
734 rad_assert(spawn_flag == true);
739 * Sleep for some more. We HOPE that the
740 * child will become responsive at some
741 * point in the future.
744 tv_add(&when, request->delay);
745 request->delay += request->delay >> 1;
746 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
750 * These should all be managed by the master thread
753 case REQUEST_PROXIED:
755 case REQUEST_REJECT_DELAY:
756 case REQUEST_CLEANUP_DELAY:
759 request_done(request, FR_ACTION_DONE);
764 rad_assert(request->master_state == REQUEST_ACTIVE);
767 * It's still supposed to be running.
769 switch (request->child_state) {
771 case REQUEST_RUNNING:
773 case REQUEST_PROXIED:
775 when = request->packet->timestamp;
776 when.tv_sec += request->root->max_request_time;
779 * Taking too long: tell it to die.
781 if (timercmp(&now, &when, >=)) {
782 #ifdef HAVE_PTHREAD_H
784 * If there's a child thread processing it,
788 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
789 ERROR("Unresponsive child for request %u, in component %s module %s",
791 request->component ? request->component : "<core>",
792 request->module ? request->module : "<core>");
793 exec_trigger(request, NULL, "server.thread.unresponsive", true);
796 request->master_state = REQUEST_STOP_PROCESSING;
801 * We should wait for the proxy reply.
803 if (request->child_state == REQUEST_PROXIED) {
804 if (request->proxy_reply) {
805 request->process = proxy_running;
807 request->process = proxy_wait_for_reply;
813 * If the request has been told to die, we wait.
814 * Otherwise, we wait for the child thread to
819 case REQUEST_REJECT_DELAY:
820 rad_assert(request->root->reject_delay > 0);
822 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
825 request->process = request_reject_delay;
827 when = request->reply->timestamp;
828 when.tv_sec += request->root->reject_delay;
830 if (timercmp(&when, &now, >)) {
831 #ifdef DEBUG_STATE_MACHINE
832 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_reject_delay");
834 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
836 } /* else it's time to send the reject */
838 RDEBUG2("Sending delayed reject");
839 DEBUG_PACKET(request, request->reply, 1);
840 request->listener->send(request->listener, request);
841 request->child_state = REQUEST_CLEANUP_DELAY;
844 case REQUEST_CLEANUP_DELAY:
845 rad_assert(request->root->cleanup_delay > 0);
848 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
851 request->process = request_cleanup_delay;
853 when = request->reply->timestamp;
854 when.tv_sec += request->root->cleanup_delay;
856 if (timercmp(&when, &now, >)) {
857 #ifdef DEBUG_STATE_MACHINE
858 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
860 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
862 } /* else it's time to clean up */
871 static void request_queue_or_run(UNUSED REQUEST *request,
872 fr_request_process_t process)
874 #ifdef DEBUG_STATE_MACHINE
875 int action = FR_ACTION_TIMER;
881 * Do this here so that fewer other functions need to do
884 if (request->master_state == REQUEST_STOP_PROCESSING) {
885 #ifdef DEBUG_STATE_MACHINE
886 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
887 request->number, __FUNCTION__,
888 master_state_names[request->master_state],
889 child_state_names[request->child_state],
890 child_state_names[REQUEST_DONE]);
892 request_done(request, FR_ACTION_DONE);
896 request->process = process;
898 if (we_are_master()) {
902 * (re) set the initial delay.
904 request->delay = USEC / 3;
905 gettimeofday(&when, NULL);
906 tv_add(&when, request->delay);
907 request->delay += request->delay >> 1;
909 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
911 #ifdef HAVE_PTHREAD_H
914 * A child thread will eventually pick it up.
916 if (request_enqueue(request)) return;
919 * Otherwise we're not going to do anything with
922 request_done(request, FR_ACTION_DONE);
928 request->child_state = REQUEST_RUNNING;
929 request->process(request, FR_ACTION_RUN);
933 * Requests that care about child process exit
934 * codes have already either called
935 * rad_waitpid(), or they've given up.
937 while (waitpid(-1, NULL, WNOHANG) > 0);
941 STATE_MACHINE_DECL(request_common)
951 * Bail out as early as possible.
953 if (request->master_state == REQUEST_STOP_PROCESSING) {
954 request_done(request, REQUEST_DONE);
962 * We're still waiting for a proxy reply.
964 if (request->child_state == REQUEST_PROXIED) {
965 proxy_wait_for_reply(request, action);
970 ERROR("(%u) Discarding duplicate request from "
971 "client %s port %d - ID: %u due to unfinished request",
972 request->number, request->client->shortname,
973 request->packet->src_port,request->packet->id);
976 case FR_ACTION_CONFLICTING:
978 * We're in the master thread, ask the child to
979 * stop processing the request.
981 request_done(request, action);
984 case FR_ACTION_TIMER:
985 request_process_timer(request);
989 case FR_ACTION_PROXY_REPLY:
990 DEBUG2("Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
991 inet_ntop(request->proxy->src_ipaddr.af,
992 &request->proxy->src_ipaddr.ipaddr,
993 buffer, sizeof(buffer)),
994 request->proxy->dst_port, request->proxy->id,
1000 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1005 STATE_MACHINE_DECL(request_cleanup_delay)
1007 struct timeval when;
1009 TRACE_STATE_MACHINE;
1014 if (request->reply->code != 0) {
1015 request->listener->send(request->listener, request);
1017 RDEBUG("No reply. Ignoring retransmit.");
1021 * Double the cleanup_delay to catch retransmits.
1023 when = request->reply->timestamp;
1024 request->delay += request->delay ;
1025 when.tv_sec += request->delay;
1027 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1031 case FR_ACTION_PROXY_REPLY:
1033 case FR_ACTION_CONFLICTING:
1034 case FR_ACTION_TIMER:
1035 request_common(request, action);
1039 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1044 STATE_MACHINE_DECL(request_reject_delay)
1046 TRACE_STATE_MACHINE;
1051 ERROR("(%u) Discarding duplicate request from "
1052 "client %s port %d - ID: %u due to delayed reject",
1053 request->number, request->client->shortname,
1054 request->packet->src_port,request->packet->id);
1058 case FR_ACTION_PROXY_REPLY:
1060 case FR_ACTION_CONFLICTING:
1061 case FR_ACTION_TIMER:
1062 request_common(request, action);
1066 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1072 static int request_pre_handler(REQUEST *request, UNUSED int action)
1074 TRACE_STATE_MACHINE;
1078 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1081 * Don't decode the packet if it's an internal "fake"
1082 * request. Instead, just return so that the caller can
1085 if (request->packet->dst_port == 0) {
1086 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1087 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1093 * Put the decoded packet into it's proper place.
1095 if (request->proxy_reply != NULL) {
1097 * There may be a proxy reply, but it may be too late.
1099 if (!request->proxy_listener) return 0;
1101 rcode = request->proxy_listener->decode(request->proxy_listener, request);
1102 DEBUG_PACKET(request, request->proxy_reply, 0);
1105 * Pro-actively remove it from the proxy hash.
1106 * This is later than in 2.1.x, but it means that
1107 * the replies are authenticated before being
1108 * removed from the hash.
1111 (request->num_proxied_requests <= request->num_proxied_responses)) {
1112 remove_from_proxy_hash(request);
1117 if (request->packet->vps == NULL) {
1118 rcode = request->listener->decode(request->listener, request);
1121 if (debug_condition) {
1123 * Ignore parse errors.
1125 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1126 request->options = 2;
1127 request->radlog = vradlog_request;
1132 DEBUG_PACKET(request, request->packet, 0);
1138 RDEBUG("Dropping packet without response because of error: %s", fr_strerror());
1139 request->reply->offset = -2; /* bad authenticator */
1143 if (!request->username) {
1144 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1148 if (action == FR_ACTION_PROXY_REPLY) {
1149 return process_proxy_reply(request);
1156 STATE_MACHINE_DECL(request_finish)
1160 TRACE_STATE_MACHINE;
1162 (void) action; /* -Wunused */
1164 if (request->master_state == REQUEST_STOP_PROCESSING) return;
1167 * Don't send replies if there are none to send.
1169 if (!request->in_request_hash) {
1171 if ((request->listener->type == RAD_LISTEN_AUTH)
1172 #ifdef WITH_ACCOUNTING
1173 || (request->listener->type == RAD_LISTEN_ACCT)
1176 listen_socket_t *sock = request->listener->data;
1178 if (sock->proto == IPPROTO_UDP) return;
1181 * TCP packets aren't in the request
1191 * Override the response code if a control:Response-Packet-Type attribute is present.
1193 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1195 if (vp->vp_integer == 256) {
1196 RDEBUG2("Not responding to request");
1197 request->reply->code = 0;
1199 request->reply->code = vp->vp_integer;
1203 * Catch Auth-Type := Reject BEFORE proxying the packet.
1205 else if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1206 if (request->reply->code == 0) {
1207 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1209 if (!vp || (vp->vp_integer != PW_CODE_AUTHENTICATION_REJECT)) {
1210 RDEBUG2("There was no response configured: "
1211 "rejecting request");
1214 request->reply->code = PW_CODE_AUTHENTICATION_REJECT;
1219 * Copy Proxy-State from the request to the reply.
1221 vp = paircopy2(request->reply, request->packet->vps,
1222 PW_PROXY_STATE, 0, TAG_ANY);
1223 if (vp) pairadd(&request->reply->vps, vp);
1225 switch (request->reply->code) {
1226 case PW_CODE_AUTHENTICATION_ACK:
1227 rad_postauth(request);
1229 case PW_CODE_ACCESS_CHALLENGE:
1230 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1232 vp = pairmake_config("Post-Auth-Type", "Challenge", T_OP_SET);
1233 if (vp) rad_postauth(request);
1240 * Run rejected packets through
1242 * Post-Auth-Type = Reject
1244 * We do this separately so ACK and challenge can change the code
1245 * to reject if a module returns reject.
1247 if (request->reply->code == PW_CODE_AUTHENTICATION_REJECT) {
1248 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1249 vp = pairmake_config("Post-Auth-Type", "Reject", T_OP_SET);
1250 if (vp) rad_postauth(request);
1254 * Clean up. These are no longer needed.
1256 pairfree(&request->config_items);
1258 pairfree(&request->packet->vps);
1259 request->username = NULL;
1260 request->password = NULL;
1263 if (request->proxy) {
1264 pairfree(&request->proxy->vps);
1266 if (request->proxy_reply) {
1267 pairfree(&request->proxy_reply->vps);
1271 gettimeofday(&request->reply->timestamp, NULL);
1276 if ((request->reply->code != PW_CODE_AUTHENTICATION_REJECT) ||
1277 (request->root->reject_delay == 0)) {
1278 DEBUG_PACKET(request, request->reply, 1);
1279 request->listener->send(request->listener,
1281 pairfree(&request->reply->vps);
1283 RDEBUG2("Finished request %u.", request->number);
1284 #ifdef WITH_ACCOUNTING
1285 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1287 request->child_state = REQUEST_DONE;
1291 if (request->root->cleanup_delay == 0) {
1293 request->child_state = REQUEST_DONE;
1296 request->child_state = REQUEST_CLEANUP_DELAY;
1299 RDEBUG2("Delaying reject of request %u for %d seconds",
1301 request->root->reject_delay);
1303 request->child_state = REQUEST_REJECT_DELAY;
1307 STATE_MACHINE_DECL(request_running)
1309 TRACE_STATE_MACHINE;
1312 case FR_ACTION_TIMER:
1313 request_process_timer(request);
1316 case FR_ACTION_CONFLICTING:
1318 request_common(request, action);
1323 * This can happen due to a race condition where
1324 * we send a proxied request, and immediately get
1325 * another reply, before the timer has a chance
1326 * to update the various states.
1328 case FR_ACTION_PROXY_REPLY:
1329 request->child_state = REQUEST_RUNNING;
1330 request->process = proxy_running;
1335 if (!request_pre_handler(request, action)) {
1336 #ifdef DEBUG_STATE_MACHINE
1337 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1338 request->number, __FUNCTION__,
1339 child_state_names[request->child_state],
1340 child_state_names[REQUEST_DONE]);
1344 request->child_state = REQUEST_DONE;
1348 rad_assert(request->handle != NULL);
1349 request->handle(request);
1353 * We may need to send a proxied request.
1355 if ((action == FR_ACTION_RUN) &&
1356 request_will_proxy(request)) {
1357 #ifdef DEBUG_STATE_MACHINE
1358 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1362 * takes care of setting
1363 * up the post proxy fail
1366 if (request_proxy(request, 0) < 0) goto finished;
1370 #ifdef DEBUG_STATE_MACHINE
1371 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1376 * Maybe originate a CoA request.
1378 if ((action == FR_ACTION_RUN) && request->coa) {
1379 request_coa_originate(request);
1386 request_finish(request, action);
1391 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1396 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1397 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1400 RADIUS_PACKET **packet_p;
1401 REQUEST *request = NULL;
1403 listen_socket_t *sock = NULL;
1406 * Set the last packet received.
1408 gettimeofday(&now, NULL);
1410 #ifdef WITH_ACCOUNTING
1411 if (listener->type != RAD_LISTEN_DETAIL)
1414 sock = listener->data;
1415 sock->last_packet = now.tv_sec;
1417 packet->timestamp = now;
1420 * Skip everything if required.
1422 if (listener->nodup) goto skip_dup;
1424 packet_p = fr_packet_list_find(pl, packet);
1426 request = fr_packet2myptr(REQUEST, packet, packet_p);
1427 rad_assert(request->in_request_hash);
1430 * Same src/dst ip/port, length, and
1431 * authentication vector: must be a duplicate.
1433 if ((request->packet->data_len == packet->data_len) &&
1434 (memcmp(request->packet->vector, packet->vector,
1435 sizeof(packet->vector)) == 0)) {
1438 switch (packet->code) {
1439 case PW_CODE_AUTHENTICATION_REQUEST:
1440 FR_STATS_INC(auth, total_dup_requests);
1443 #ifdef WITH_ACCOUNTING
1444 case PW_CODE_ACCOUNTING_REQUEST:
1445 FR_STATS_INC(acct, total_dup_requests);
1449 case PW_CODE_COA_REQUEST:
1450 FR_STATS_INC(coa, total_dup_requests);
1453 case PW_CODE_DISCONNECT_REQUEST:
1454 FR_STATS_INC(dsc, total_dup_requests);
1461 #endif /* WITH_STATS */
1463 request->process(request, FR_ACTION_DUP);
1468 * Say we're ignoring the old one, and continue
1469 * to process the new one.
1471 request->process(request, FR_ACTION_CONFLICTING);
1476 * Quench maximum number of outstanding requests.
1478 if (mainconfig.max_requests &&
1479 ((count = fr_packet_list_num_elements(pl)) > mainconfig.max_requests)) {
1480 static time_t last_complained = 0;
1482 if (last_complained == now.tv_sec) return 0;
1484 last_complained = now.tv_sec;
1486 ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1488 packet->src_port, packet->id);
1489 WARN("Please check the configuration file.\n"
1490 "\tThe value for 'max_requests' is probably set too low.\n");
1492 exec_trigger(NULL, NULL, "server.max_requests", true);
1498 * Rate-limit the incoming packets
1500 if (sock && sock->max_rate) {
1503 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now,
1504 &sock->rate_time, &now);
1506 if (pps > sock->max_rate) {
1507 DEBUG("Dropping request due to rate limiting");
1510 sock->rate_pps_now++;
1513 request = request_setup(listener, packet, client, fun);
1514 if (!request) return 1;
1517 * Remember the request in the list.
1519 if (!listener->nodup) {
1520 if (!fr_packet_list_insert(pl, &request->packet)) {
1521 RERROR("Failed to insert request in the list of live requests: discarding it");
1522 request_done(request, FR_ACTION_DONE);
1526 request->in_request_hash = true;
1530 * Process it. Send a response, and free it.
1532 if (listener->synchronous) {
1533 request->listener->decode(request->listener, request);
1534 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1535 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1538 request->listener->send(request->listener, request);
1539 request_free(&request);
1544 * Otherwise, insert it into the state machine.
1545 * The child threads will take care of processing it.
1547 request_queue_or_run(request, request_running);
1553 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
1554 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1559 * Create and initialize the new request.
1561 request = request_alloc(NULL);
1562 request->reply = rad_alloc(request, 0);
1563 if (!request->reply) {
1565 request_free(&request);
1569 request->listener = listener;
1570 request->client = client;
1571 request->packet = talloc_steal(request, packet);
1572 request->number = request_num_counter++;
1573 request->priority = listener->type;
1574 request->master_state = REQUEST_ACTIVE;
1575 #ifdef DEBUG_STATE_MACHINE
1576 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1577 request->number, __FUNCTION__,
1578 child_state_names[request->child_state],
1579 child_state_names[REQUEST_RUNNING]);
1581 request->child_state = REQUEST_RUNNING;
1582 request->handle = fun;
1586 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1587 if (packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1588 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1589 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1590 #ifdef WITH_ACCOUNTING
1591 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1592 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1593 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1596 #endif /* WITH_STATS */
1599 * Status-Server packets go to the head of the queue.
1601 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1604 * Set virtual server identity
1606 if (client->server) {
1607 request->server = client->server;
1608 } else if (listener->server) {
1609 request->server = listener->server;
1611 request->server = NULL;
1614 request->root = &mainconfig;
1616 request->listener->count++;
1620 * The request passes many of our sanity checks.
1621 * From here on in, if anything goes wrong, we
1622 * send a reject message, instead of dropping the
1627 * Build the reply template from the request.
1630 request->reply->sockfd = request->packet->sockfd;
1631 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1632 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1633 request->reply->dst_port = request->packet->src_port;
1634 request->reply->src_port = request->packet->dst_port;
1635 request->reply->id = request->packet->id;
1636 request->reply->code = 0; /* UNKNOWN code */
1637 memcpy(request->reply->vector, request->packet->vector,
1638 sizeof(request->reply->vector));
1639 request->reply->vps = NULL;
1640 request->reply->data = NULL;
1641 request->reply->data_len = 0;
1647 /***********************************************************************
1651 ***********************************************************************/
1654 * Timer function for all TCP sockets.
1656 static void tcp_socket_timer(void *ctx)
1658 rad_listen_t *listener = ctx;
1659 listen_socket_t *sock = listener->data;
1660 struct timeval end, now;
1662 fr_socket_limit_t *limit;
1664 fr_event_now(el, &now);
1666 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1668 switch (listener->type) {
1670 case RAD_LISTEN_PROXY:
1671 limit = &sock->home->limit;
1675 case RAD_LISTEN_AUTH:
1676 #ifdef WITH_ACCOUNTING
1677 case RAD_LISTEN_ACCT:
1679 limit = &sock->limit;
1687 * If we enforce a lifetime, do it now.
1689 if (limit->lifetime > 0) {
1690 end.tv_sec = sock->opened + limit->lifetime;
1693 if (timercmp(&end, &now, <=)) {
1694 listener->print(listener, buffer, sizeof(buffer));
1695 DEBUG("Reached maximum lifetime on socket %s", buffer);
1699 listener->status = RAD_LISTEN_STATUS_EOL;
1700 event_new_fd(listener);
1709 * Enforce an idle timeout.
1711 if (limit->idle_timeout > 0) {
1712 struct timeval idle;
1714 rad_assert(sock->last_packet != 0);
1715 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1718 if (timercmp(&idle, &now, <=)) {
1719 listener->print(listener, buffer, sizeof(buffer));
1720 DEBUG("Reached idle timeout on socket %s", buffer);
1725 * Enforce the minimum of idle timeout or lifetime.
1727 if (timercmp(&idle, &end, <)) {
1733 * Wake up at t + 0.5s. The code above checks if the timers
1734 * are <= t. This addition gives us a bit of leeway.
1736 end.tv_usec = USEC / 2;
1738 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1739 rad_panic("Failed to insert event");
1746 * Add +/- 2s of jitter, as suggested in RFC 3539
1749 static void add_jitter(struct timeval *when)
1756 jitter ^= (jitter >> 10);
1757 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1760 * Add in ~ (4 * USEC) of jitter.
1762 tv_add(when, jitter);
1766 * Called by socket_del to remove requests with this socket
1768 static int eol_proxy_listener(void *ctx, void *data)
1770 rad_listen_t *this = ctx;
1771 RADIUS_PACKET **proxy_p = data;
1774 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1775 if (request->proxy_listener != this) return 0;
1778 * The normal "remove_from_proxy_hash" tries to grab the
1779 * proxy mutex. We already have it held, so grabbing it
1780 * again will cause a deadlock. Instead, call the "no
1781 * lock" version of the function.
1783 rad_assert(request->in_proxy_hash == true);
1784 remove_from_proxy_hash_nl(request, false);
1787 * Don't mark it as DONE. The client can retransmit, and
1788 * the packet SHOULD be re-proxied somewhere else.
1790 * Return "2" means that the rbtree code will remove it
1791 * from the tree, and we don't need to do it ourselves.
1795 #endif /* WITH_PROXY */
1797 static int eol_listener(void *ctx, void *data)
1799 rad_listen_t *this = ctx;
1800 RADIUS_PACKET **packet_p = data;
1803 request = fr_packet2myptr(REQUEST, packet, packet_p);
1804 if (request->listener != this) return 0;
1806 request->master_state = REQUEST_STOP_PROCESSING;
1810 #endif /* WITH_TCP */
1813 /***********************************************************************
1815 * Proxy handlers for the state machine.
1817 ***********************************************************************/
1820 * Called with the proxy mutex held
1822 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1824 if (!request->in_proxy_hash) return;
1826 fr_packet_list_id_free(proxy_list, request->proxy, yank);
1827 request->in_proxy_hash = false;
1830 * On the FIRST reply, decrement the count of outstanding
1831 * requests. Note that this is NOT the count of sent
1832 * packets, but whether or not the home server has
1835 if (request->home_server &&
1836 request->home_server->currently_outstanding) {
1837 request->home_server->currently_outstanding--;
1840 * If we're NOT sending it packets, then we don't know
1841 * if it's alive or dead.
1843 if ((request->home_server->currently_outstanding == 0) &&
1844 (request->home_server->state == HOME_STATE_ALIVE)) {
1845 request->home_server->state = HOME_STATE_UNKNOWN;
1846 request->home_server->last_packet_sent = 0;
1847 request->home_server->last_packet_recv = 0;
1852 rad_assert(request->proxy_listener != NULL);
1853 request->proxy_listener->count--;
1855 request->proxy_listener = NULL;
1858 * Got from YES in hash, to NO, not in hash while we hold
1859 * the mutex. This guarantees that when another thread
1860 * grabs the mutex, the "not in hash" flag is correct.
1862 RDEBUG3("proxy: request is no longer in proxy hash");
1865 static void remove_from_proxy_hash(REQUEST *request)
1868 * Check this without grabbing the mutex because it's a
1869 * lot faster that way.
1871 if (!request->in_proxy_hash) return;
1874 * The "not in hash" flag is definitive. However, if the
1875 * flag says that it IS in the hash, there might still be
1876 * a race condition where it isn't.
1878 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1880 if (!request->in_proxy_hash) {
1881 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1885 remove_from_proxy_hash_nl(request, true);
1887 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1890 static int insert_into_proxy_hash(REQUEST *request)
1894 void *proxy_listener;
1896 rad_assert(request->proxy != NULL);
1897 rad_assert(request->home_server != NULL);
1898 rad_assert(proxy_list != NULL);
1901 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1902 proxy_listener = NULL;
1903 request->num_proxied_requests = 1;
1904 request->num_proxied_responses = 0;
1906 for (tries = 0; tries < 2; tries++) {
1909 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
1910 rcode = fr_packet_list_id_alloc(proxy_list,
1911 request->home_server->proto,
1912 &request->proxy, &proxy_listener);
1913 if ((debug_flag > 2) && (rcode == 0)) {
1914 RDEBUG("proxy: Failed allocating ID: %s", fr_strerror());
1916 if (rcode > 0) break;
1917 if (tries > 0) continue; /* try opening new socket only once */
1919 #ifdef HAVE_PTHREAD_H
1920 if (proxy_no_new_sockets) break;
1923 RDEBUG3("proxy: Trying to open a new listener to the home server");
1924 this = proxy_new_listener(request->home_server, 0);
1926 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1930 request->proxy->src_port = 0; /* Use any new socket */
1931 proxy_listener = this;
1934 * Add it to the event loop (and to the packet list)
1935 * before we try to grab another Id.
1937 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1938 if (!event_new_fd(this)) {
1939 RDEBUG3("proxy: Failed inserting new socket into event loop");
1943 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1946 if (!proxy_listener || (rcode == 0)) {
1947 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1948 REDEBUG2("proxy: Failed allocating Id for proxied request");
1950 request->proxy_listener = NULL;
1951 request->in_proxy_hash = false;
1955 rad_assert(request->proxy->id >= 0);
1957 request->proxy_listener = proxy_listener;
1958 request->in_proxy_hash = true;
1959 RDEBUG3("proxy: request is now in proxy hash");
1962 * Keep track of maximum outstanding requests to a
1963 * particular home server. 'max_outstanding' is
1964 * enforced in home_server_ldb(), in realms.c.
1966 request->home_server->currently_outstanding++;
1969 request->proxy_listener->count++;
1972 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1974 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
1975 inet_ntop(request->proxy->dst_ipaddr.af,
1976 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
1977 request->proxy->dst_port,
1978 request->proxy->id);
1983 static int process_proxy_reply(REQUEST *request)
1986 int post_proxy_type = 0;
1990 * Delete any reply we had accumulated until now.
1992 pairfree(&request->reply->vps);
1995 * Run the packet through the post-proxy stage,
1996 * BEFORE playing games with the attributes.
1998 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2001 * If we have a proxy_reply, and it was a reject, setup
2002 * post-proxy-type Reject
2004 if (!vp && request->proxy_reply &&
2005 request->proxy_reply->code == PW_CODE_AUTHENTICATION_REJECT) {
2008 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2010 vp = radius_paircreate(request, &request->config_items,
2011 PW_POST_PROXY_TYPE, 0);
2013 vp->vp_integer = dval->value;
2018 post_proxy_type = vp->vp_integer;
2020 RDEBUG2(" Found Post-Proxy-Type %s",
2021 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0,
2025 if (request->home_pool && request->home_pool->virtual_server) {
2026 char const *old_server = request->server;
2028 request->server = request->home_pool->virtual_server;
2029 RDEBUG2(" server %s {", request->server);
2030 rcode = process_post_proxy(post_proxy_type, request);
2032 request->server = old_server;
2034 rcode = process_post_proxy(post_proxy_type, request);
2038 if (request->packet->code == request->proxy->code)
2040 * Don't run the next bit if we originated a CoA
2041 * packet, after receiving an Access-Request or
2042 * Accounting-Request.
2047 * There may NOT be a proxy reply, as we may be
2048 * running Post-Proxy-Type = Fail.
2050 if (request->proxy_reply) {
2052 * Delete the Proxy-State Attributes from
2053 * the reply. These include Proxy-State
2054 * attributes from us and remote server.
2056 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2059 * Add the attributes left in the proxy
2060 * reply to the reply list.
2062 pairfilter(request->reply, &request->reply->vps,
2063 &request->proxy_reply->vps, 0, 0, TAG_ANY);
2066 * Free proxy request pairs.
2068 pairfree(&request->proxy->vps);
2072 default: /* Don't do anything */
2074 case RLM_MODULE_FAIL:
2077 case RLM_MODULE_HANDLED:
2084 int request_proxy_reply(RADIUS_PACKET *packet)
2086 RADIUS_PACKET **proxy_p;
2091 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2092 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2095 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2096 PROXY( "No outstanding request was found for reply from host %s port %d - ID %u",
2097 inet_ntop(packet->src_ipaddr.af,
2098 &packet->src_ipaddr.ipaddr,
2099 buffer, sizeof(buffer)),
2100 packet->src_port, packet->id);
2104 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2105 request->num_proxied_responses++; /* needs to be protected by lock */
2107 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2110 * No reply, BUT the current packet fails verification:
2111 * ignore it. This does the MD5 calculations in the
2112 * server core, but I guess we can fix that later.
2114 if (!request->proxy_reply &&
2115 (rad_verify(packet, request->proxy,
2116 request->home_server->secret) != 0)) {
2117 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2122 * The home server sent us a packet which doesn't match
2123 * something we have: ignore it. This is done only to
2124 * catch the case of broken systems.
2126 if (request->proxy_reply &&
2127 (memcmp(request->proxy_reply->vector,
2129 sizeof(request->proxy_reply->vector)) != 0)) {
2130 RDEBUG2("Ignoring conflicting proxy reply");
2134 gettimeofday(&now, NULL);
2137 * Status-Server packets don't count as real packets.
2139 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2140 listen_socket_t *sock = request->proxy_listener->data;
2142 request->home_server->last_packet_recv = now.tv_sec;
2143 sock->last_packet = now.tv_sec;
2147 * If we have previously seen a reply, ignore the
2150 if (request->proxy_reply) {
2151 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2152 inet_ntop(packet->src_ipaddr.af,
2153 &packet->src_ipaddr.ipaddr,
2154 buffer, sizeof(buffer)),
2155 packet->src_port, packet->id);
2160 * Call the state machine to do something useful with the
2163 request->proxy_reply = packet;
2164 packet->timestamp = now;
2165 request->priority = RAD_LISTEN_PROXY;
2168 * We've received a reply. If we hadn't been sending it
2169 * packets for a while, just mark it alive.
2171 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2172 request->home_server->state = HOME_STATE_ALIVE;
2176 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2177 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2179 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2180 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2181 #ifdef WITH_ACCOUNTING
2182 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2183 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2186 #endif /* WITH_STATS */
2190 * When we originate CoA requests, we patch them in here
2191 * so that they don't affect the rest of the state
2194 if (request->parent) {
2195 rad_assert(request->parent->coa == request);
2196 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
2197 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
2198 rad_assert(request->process != NULL);
2199 request_coa_separate(request);
2203 request->process(request, FR_ACTION_PROXY_REPLY);
2209 static int setup_post_proxy_fail(REQUEST *request)
2211 DICT_VALUE const *dval = NULL;
2214 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2215 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2216 "Fail-Authentication");
2218 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2219 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2222 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2223 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2225 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2226 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2229 WDEBUG("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2233 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2236 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2240 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2241 if (!vp) vp = radius_paircreate(request, &request->config_items,
2242 PW_POST_PROXY_TYPE, 0);
2243 vp->vp_integer = dval->value;
2248 STATE_MACHINE_DECL(proxy_running)
2250 TRACE_STATE_MACHINE;
2253 case FR_ACTION_CONFLICTING:
2255 case FR_ACTION_TIMER:
2256 case FR_ACTION_PROXY_REPLY:
2257 request_common(request, action);
2261 request_running(request, action);
2265 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2270 STATE_MACHINE_DECL(request_virtual_server)
2274 TRACE_STATE_MACHINE;
2277 case FR_ACTION_CONFLICTING:
2279 case FR_ACTION_TIMER:
2280 case FR_ACTION_PROXY_REPLY:
2281 request_common(request, action);
2285 old = request->server;
2286 request->server = request->home_server->server;
2287 request_running(request, action);
2288 request->server = old;
2292 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2298 static int request_will_proxy(REQUEST *request)
2300 int rcode, pre_proxy_type = 0;
2301 char const *realmname = NULL;
2302 VALUE_PAIR *vp, *strippedname;
2303 home_server_t *home;
2304 REALM *realm = NULL;
2305 home_pool_t *pool = NULL;
2307 if (!request->root->proxy_requests) return 0;
2308 if (request->packet->dst_port == 0) return 0;
2309 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2310 if (request->in_proxy_hash) return 0;
2313 * FIXME: for 3.0, allow this only for rejects?
2315 if (request->reply->code != 0) return 0;
2317 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2319 realm = realm_find2(vp->vp_strvalue);
2321 REDEBUG2("Cannot proxy to unknown realm %s",
2326 realmname = vp->vp_strvalue;
2329 * Figure out which pool to use.
2331 if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
2332 pool = realm->auth_pool;
2334 #ifdef WITH_ACCOUNTING
2335 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2336 pool = realm->acct_pool;
2340 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2341 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2342 pool = realm->coa_pool;
2352 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2355 switch (request->packet->code) {
2356 case PW_CODE_AUTHENTICATION_REQUEST:
2357 pool_type = HOME_TYPE_AUTH;
2360 #ifdef WITH_ACCOUNTING
2361 case PW_CODE_ACCOUNTING_REQUEST:
2362 pool_type = HOME_TYPE_ACCT;
2367 case PW_CODE_COA_REQUEST:
2368 case PW_CODE_DISCONNECT_REQUEST:
2369 pool_type = HOME_TYPE_COA;
2377 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2381 RWDEBUG2("Cancelling proxy as no home pool exists");
2385 if (request->listener->synchronous) {
2386 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2390 request->home_pool = pool;
2392 home = home_server_ldb(realmname, pool, request);
2394 REDEBUG2("Failed to find live home server: Cancelling proxy");
2397 home_server_update_request(home, request);
2401 * Once we've decided to proxy a request, we cannot send
2402 * a CoA packet. So we free up any CoA packet here.
2404 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2408 * Remember that we sent the request to a Realm.
2410 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2413 * Strip the name, if told to.
2415 * Doing it here catches the case of proxied tunneled
2418 if (realm && (realm->striprealm == true) &&
2419 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2421 * If there's a Stripped-User-Name attribute in
2422 * the request, then use THAT as the User-Name
2423 * for the proxied request, instead of the
2426 * This is done by making a copy of the
2427 * Stripped-User-Name attribute, turning it into
2428 * a User-Name attribute, deleting the
2429 * Stripped-User-Name and User-Name attributes
2430 * from the vps list, and making the new
2431 * User-Name the head of the vps list.
2433 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2436 vp = radius_paircreate(request, NULL,
2438 rad_assert(vp != NULL); /* handled by above function */
2439 /* Insert at the START of the list */
2440 /* FIXME: Can't make assumptions about ordering */
2441 fr_cursor_init(&cursor, &vp);
2442 fr_cursor_insert(&cursor, request->proxy->vps);
2443 request->proxy->vps = vp;
2445 pairstrcpy(vp, strippedname->vp_strvalue);
2448 * Do NOT delete Stripped-User-Name.
2453 * If there is no PW_CHAP_CHALLENGE attribute but
2454 * there is a PW_CHAP_PASSWORD we need to add it
2455 * since we can't use the request authenticator
2456 * anymore - we changed it.
2458 if ((request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) &&
2459 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2460 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2461 vp = radius_paircreate(request, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2462 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2466 * The RFC's say we have to do this, but FreeRADIUS
2469 vp = radius_paircreate(request, &request->proxy->vps, PW_PROXY_STATE, 0);
2470 pairsprintf(vp, "%u", request->packet->id);
2473 * Should be done BEFORE inserting into proxy hash, as
2474 * pre-proxy may use this information, or change it.
2476 request->proxy->code = request->packet->code;
2479 * Call the pre-proxy routines.
2481 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2483 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2484 /* Must be a validation issue */
2486 RDEBUG2(" Found Pre-Proxy-Type %s", dval->name);
2487 pre_proxy_type = vp->vp_integer;
2490 rad_assert(request->home_pool != NULL);
2492 if (request->home_pool->virtual_server) {
2493 char const *old_server = request->server;
2495 request->server = request->home_pool->virtual_server;
2496 RDEBUG2(" server %s {", request->server);
2497 rcode = process_pre_proxy(pre_proxy_type, request);
2499 request->server = old_server;
2501 rcode = process_pre_proxy(pre_proxy_type, request);
2504 case RLM_MODULE_FAIL:
2505 case RLM_MODULE_INVALID:
2506 case RLM_MODULE_NOTFOUND:
2507 case RLM_MODULE_USERLOCK:
2509 /* FIXME: debug print failed stuff */
2512 case RLM_MODULE_REJECT:
2513 case RLM_MODULE_HANDLED:
2517 * Only proxy the packet if the pre-proxy code succeeded.
2519 case RLM_MODULE_NOOP:
2521 case RLM_MODULE_UPDATED:
2528 static int request_proxy(REQUEST *request, int retransmit)
2532 rad_assert(request->parent == NULL);
2533 rad_assert(request->home_server != NULL);
2535 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2539 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2540 request_done(request->coa, FR_ACTION_DONE);
2545 * The request may be sent to a virtual server. If we're
2546 * in a child thread, just process it here. If we're the
2547 * master, push it back onto the queue for later
2550 if (request->home_server->server) {
2551 DEBUG("Proxying to virtual server %s",
2552 request->home_server->server);
2554 if (!we_are_master()) {
2555 request_virtual_server(request, FR_ACTION_RUN);
2560 request_queue_or_run(request, request_virtual_server);
2565 * We're actually sending a proxied packet. Do that now.
2567 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2568 EDEBUG("Failed to insert request into the proxy list.");
2572 rad_assert(request->proxy->id >= 0);
2575 if (request->home_server->tls) {
2576 RDEBUG2("Proxying request to home server %s port %d (TLS)",
2577 inet_ntop(request->proxy->dst_ipaddr.af,
2578 &request->proxy->dst_ipaddr.ipaddr,
2579 buffer, sizeof(buffer)),
2580 request->proxy->dst_port);
2583 RDEBUG2("Proxying request to home server %s port %d",
2584 inet_ntop(request->proxy->dst_ipaddr.af,
2585 &request->proxy->dst_ipaddr.ipaddr,
2586 buffer, sizeof(buffer)),
2587 request->proxy->dst_port);
2589 DEBUG_PACKET(request, request->proxy, 1);
2591 gettimeofday(&request->proxy_retransmit, NULL);
2593 request->proxy->timestamp = request->proxy_retransmit;
2594 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2597 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2599 request->child_state = REQUEST_PROXIED;
2600 request->proxy_listener->send(request->proxy_listener,
2606 * Proxy the packet as if it was new.
2608 static int request_proxy_anew(REQUEST *request)
2610 home_server_t *home;
2613 * Delete the request from the proxy list.
2615 * The packet list code takes care of ensuring that IDs
2616 * aren't reused until all 256 IDs have been used. So
2617 * there's a 1/256 chance of re-using the same ID when
2618 * we're sending to the same home server. Which is
2621 remove_from_proxy_hash(request);
2624 * Find a live home server for the request.
2626 home = home_server_ldb(NULL, request->home_pool, request);
2628 REDEBUG2("Failed to find live home server for request");
2630 if (setup_post_proxy_fail(request)) {
2631 request_queue_or_run(request, proxy_running);
2633 gettimeofday(&request->reply->timestamp, NULL);
2634 request_cleanup_delay_init(request, NULL);
2638 home_server_update_request(home, request);
2640 if (!insert_into_proxy_hash(request)) {
2641 RPROXY("Failed to insert retransmission into the proxy list.");
2642 goto post_proxy_fail;
2646 * Free the old packet, to force re-encoding
2648 talloc_free(request->proxy->data);
2649 request->proxy->data = NULL;
2650 request->proxy->data_len = 0;
2652 #ifdef WITH_ACCOUNTING
2654 * Update the Acct-Delay-Time attribute.
2656 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2659 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2660 if (!vp) vp = radius_paircreate(request,
2661 &request->proxy->vps,
2662 PW_ACCT_DELAY_TIME, 0);
2666 gettimeofday(&now, NULL);
2667 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2672 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2677 STATE_MACHINE_DECL(request_ping)
2679 home_server_t *home = request->home_server;
2682 TRACE_STATE_MACHINE;
2686 case FR_ACTION_TIMER:
2687 ERROR("No response to status check %d for home server %s port %d",
2689 inet_ntop(request->proxy->dst_ipaddr.af,
2690 &request->proxy->dst_ipaddr.ipaddr,
2691 buffer, sizeof(buffer)),
2692 request->proxy->dst_port);
2695 case FR_ACTION_PROXY_REPLY:
2696 rad_assert(request->in_proxy_hash);
2698 request->home_server->num_received_pings++;
2699 RPROXY("Received response to status check %d (%d in current sequence)",
2700 request->number, home->num_received_pings);
2703 * Remove the request from any hashes
2705 fr_event_delete(el, &request->ev);
2706 remove_from_proxy_hash(request);
2709 * The control socket may have marked the home server as
2710 * alive. OR, it may have suddenly started responding to
2711 * requests again. If so, don't re-do the "make alive"
2714 if (home->state == HOME_STATE_ALIVE) break;
2717 * It's dead, and we haven't received enough ping
2718 * responses to mark it "alive". Wait a bit.
2720 * If it's zombie, we mark it alive immediately.
2722 if ((home->state == HOME_STATE_IS_DEAD) &&
2723 (home->num_received_pings < home->num_pings_to_alive)) {
2728 * Mark it alive and delete any outstanding
2731 home->state = HOME_STATE_ALIVE;
2732 exec_trigger(request, home->cs, "home_server.alive", false);
2733 home->currently_outstanding = 0;
2734 home->num_sent_pings = 0;
2735 home->num_received_pings = 0;
2736 gettimeofday(&home->revive_time, NULL);
2738 fr_event_delete(el, &home->ev);
2740 RPROXY("Marking home server %s port %d alive",
2741 inet_ntop(request->proxy->dst_ipaddr.af,
2742 &request->proxy->dst_ipaddr.ipaddr,
2743 buffer, sizeof(buffer)),
2744 request->proxy->dst_port);
2748 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2752 rad_assert(!request->in_request_hash);
2753 rad_assert(request->ev == NULL);
2754 request_done(request, FR_ACTION_DONE);
2758 * Called from start of zombie period, OR after control socket
2759 * marks the home server dead.
2761 static void ping_home_server(void *ctx)
2763 home_server_t *home = ctx;
2766 struct timeval when, now;
2768 if ((home->state == HOME_STATE_ALIVE) ||
2769 (home->ping_check == HOME_PING_CHECK_NONE) ||
2771 (home->proto == IPPROTO_TCP) ||
2773 (home->ev != NULL)) {
2777 gettimeofday(&now, NULL);
2779 if (home->state == HOME_STATE_ZOMBIE) {
2780 when = home->zombie_period_start;
2781 when.tv_sec += home->zombie_period;
2783 if (timercmp(&when, &now, <)) {
2784 DEBUG("PING: Zombie period is over for home server %s",
2786 mark_home_server_dead(home, &now);
2790 request = request_alloc(NULL);
2791 request->number = request_num_counter++;
2794 request->proxy = rad_alloc(request, 1);
2795 rad_assert(request->proxy != NULL);
2797 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2798 request->proxy->code = PW_CODE_STATUS_SERVER;
2800 pairmake(request->proxy, &request->proxy->vps,
2801 "Message-Authenticator", "0x00", T_OP_SET);
2803 } else if (home->type == HOME_TYPE_AUTH) {
2804 request->proxy->code = PW_CODE_AUTHENTICATION_REQUEST;
2806 pairmake(request->proxy, &request->proxy->vps,
2807 "User-Name", home->ping_user_name, T_OP_SET);
2808 pairmake(request->proxy, &request->proxy->vps,
2809 "User-Password", home->ping_user_password, T_OP_SET);
2810 pairmake(request->proxy, &request->proxy->vps,
2811 "Service-Type", "Authenticate-Only", T_OP_SET);
2812 pairmake(request->proxy, &request->proxy->vps,
2813 "Message-Authenticator", "0x00", T_OP_SET);
2816 #ifdef WITH_ACCOUNTING
2817 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
2819 pairmake(request->proxy, &request->proxy->vps,
2820 "User-Name", home->ping_user_name, T_OP_SET);
2821 pairmake(request->proxy, &request->proxy->vps,
2822 "Acct-Status-Type", "Stop", T_OP_SET);
2823 pairmake(request->proxy, &request->proxy->vps,
2824 "Acct-Session-Id", "00000000", T_OP_SET);
2825 vp = pairmake(request->proxy, &request->proxy->vps,
2826 "Event-Timestamp", "0", T_OP_SET);
2827 vp->vp_date = now.tv_sec;
2829 rad_assert("Internal sanity check failed");
2833 vp = pairmake(request->proxy, &request->proxy->vps,
2834 "NAS-Identifier", "", T_OP_SET);
2836 pairsprintf(vp, "Status Check %u. Are you alive?",
2837 home->num_sent_pings);
2840 request->proxy->src_ipaddr = home->src_ipaddr;
2841 request->proxy->dst_ipaddr = home->ipaddr;
2842 request->proxy->dst_port = home->port;
2843 request->home_server = home;
2844 #ifdef DEBUG_STATE_MACHINE
2845 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
2846 child_state_names[request->child_state],
2847 child_state_names[REQUEST_DONE]);
2848 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2850 #ifdef HAVE_PTHREAD_H
2851 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2853 request->child_state = REQUEST_DONE;
2854 request->process = request_ping;
2856 rad_assert(request->proxy_listener == NULL);
2858 if (!insert_into_proxy_hash(request)) {
2859 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
2862 rad_assert(!request->in_request_hash);
2863 rad_assert(!request->in_proxy_hash);
2864 rad_assert(request->ev == NULL);
2865 request_free(&request);
2870 * Set up the timer callback.
2873 when.tv_sec += home->ping_timeout;
2875 DEBUG("PING: Waiting %u seconds for response to ping",
2876 home->ping_timeout);
2878 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2879 home->num_sent_pings++;
2881 rad_assert(request->proxy_listener != NULL);
2882 request->proxy_listener->send(request->proxy_listener,
2886 * Add +/- 2s of jitter, as suggested in RFC 3539
2887 * and in the Issues and Fixes draft.
2890 home->when.tv_sec += home->ping_interval;
2892 add_jitter(&home->when);
2894 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
2895 INSERT_EVENT(ping_home_server, home);
2898 static void home_trigger(home_server_t *home, char const *trigger)
2901 RADIUS_PACKET my_packet;
2903 memset(&my_request, 0, sizeof(my_request));
2904 memset(&my_packet, 0, sizeof(my_packet));
2905 my_request.proxy = &my_packet;
2906 my_packet.dst_ipaddr = home->ipaddr;
2907 my_packet.src_ipaddr = home->src_ipaddr;
2909 exec_trigger(&my_request, home->cs, trigger, false);
2912 static void mark_home_server_zombie(home_server_t *home, struct timeval *now)
2919 rad_assert((home->state == HOME_STATE_ALIVE) ||
2920 (home->state == HOME_STATE_UNKNOWN));
2923 if (home->proto == IPPROTO_TCP) {
2924 WDEBUG("Not marking TCP server %s zombie", home->name);
2930 * We've received a real packet recently. Don't mark the
2931 * server as zombie until we've received NO packets for a
2932 * while. The "1/4" of zombie period was chosen rather
2933 * arbitrarily. It's a balance between too short, which
2934 * gives quick fail-over and fail-back, or too long,
2935 * where the proxy still sends packets to an unresponsive
2938 start = now->tv_sec - ((home->zombie_period + 3) / 4);
2939 if (home->last_packet_recv >= start) {
2940 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
2941 (int) (now->tv_sec - home->last_packet_recv));
2945 home->state = HOME_STATE_ZOMBIE;
2946 home_trigger(home, "home_server.zombie");
2949 * Set the home server to "zombie", as of the time
2952 home->zombie_period_start.tv_sec = start;
2953 home->zombie_period_start.tv_usec = USEC / 2;
2955 fr_event_delete(el, &home->ev);
2956 home->num_sent_pings = 0;
2957 home->num_received_pings = 0;
2959 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d seconds).",
2960 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2961 buffer, sizeof(buffer)),
2962 home->port, home->response_window);
2964 ping_home_server(home);
2968 void revive_home_server(void *ctx)
2970 home_server_t *home = ctx;
2974 rad_assert(home->proto != IPPROTO_TCP);
2977 home->state = HOME_STATE_ALIVE;
2978 home_trigger(home, "home_server.alive");
2979 home->currently_outstanding = 0;
2980 gettimeofday(&home->revive_time, NULL);
2983 * Delete any outstanding events.
2985 if (home->ev) fr_event_delete(el, &home->ev);
2987 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
2988 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2989 buffer, sizeof(buffer)),
2993 void mark_home_server_dead(home_server_t *home, struct timeval *when)
2995 int previous_state = home->state;
2999 if (home->proto == IPPROTO_TCP) {
3000 WDEBUG("Not marking TCP server dead");
3005 PROXY( "Marking home server %s port %d as dead.",
3006 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3007 buffer, sizeof(buffer)),
3010 home->state = HOME_STATE_IS_DEAD;
3011 home_trigger(home, "home_server.dead");
3013 if (home->ping_check != HOME_PING_CHECK_NONE) {
3015 * If the control socket marks us dead, start
3016 * pinging. Otherwise, we already started
3017 * pinging when it was marked "zombie".
3019 if (previous_state == HOME_STATE_ALIVE) {
3020 ping_home_server(home);
3022 DEBUG("PING: Already pinging home server %s",
3028 * Revive it after a fixed period of time. This
3029 * is very, very, bad.
3032 home->when.tv_sec += home->revive_interval;
3034 DEBUG("PING: Reviving home server %s in %u seconds",
3035 home->name, home->revive_interval);
3036 INSERT_EVENT(revive_home_server, home);
3040 STATE_MACHINE_DECL(proxy_wait_for_reply)
3042 struct timeval now, when;
3043 home_server_t *home = request->home_server;
3046 TRACE_STATE_MACHINE;
3048 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3049 rad_assert(request->home_server != NULL);
3051 if (request->master_state == REQUEST_STOP_PROCESSING) {
3052 request->child_state = REQUEST_DONE;
3056 gettimeofday(&now, NULL);
3060 if (request->proxy_reply) return;
3062 if ((home->state == HOME_STATE_IS_DEAD) ||
3063 !request->proxy_listener ||
3064 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3065 request_proxy_anew(request);
3070 if (home->proto == IPPROTO_TCP) {
3071 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3072 inet_ntop(request->proxy->dst_ipaddr.af,
3073 &request->proxy->dst_ipaddr.ipaddr,
3074 buffer, sizeof(buffer)),
3075 request->proxy->dst_port,
3076 request->proxy->id);
3082 * More than one retransmit a second is stupid,
3083 * and should be suppressed by the proxy.
3085 when = request->proxy_retransmit;
3088 if (timercmp(&now, &when, <)) {
3089 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3090 inet_ntop(request->proxy->dst_ipaddr.af,
3091 &request->proxy->dst_ipaddr.ipaddr,
3092 buffer, sizeof(buffer)),
3093 request->proxy->dst_port,
3094 request->proxy->id);
3098 #ifdef WITH_ACCOUNTING
3100 * If we update the Acct-Delay-Time, we need to
3103 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3104 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3105 request_proxy_anew(request);
3110 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3111 inet_ntop(request->proxy->dst_ipaddr.af,
3112 &request->proxy->dst_ipaddr.ipaddr,
3113 buffer, sizeof(buffer)),
3114 request->proxy->dst_port,
3115 request->proxy->id);
3116 request->num_proxied_requests++;
3118 rad_assert(request->proxy_listener != NULL);;
3119 DEBUG_PACKET(request, request->proxy, 1);
3120 FR_STATS_TYPE_INC(home->stats.total_requests);
3121 home->last_packet_sent = now.tv_sec;
3122 request->proxy_retransmit = now;
3123 request->proxy_listener->send(request->proxy_listener,
3127 case FR_ACTION_TIMER:
3129 if (!request->proxy_listener ||
3130 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3131 remove_from_proxy_hash(request);
3133 when = request->packet->timestamp;
3134 when.tv_sec += request->root->max_request_time;
3136 if (timercmp(&when, &now, >)) {
3137 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3138 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3145 * Wake up "response_window" time in the future.
3146 * i.e. when MY packet hasn't received a response.
3148 * Note that we DO NOT mark the home server as
3149 * zombie if it doesn't respond to us. It may be
3150 * responding to other (better looking) packets.
3152 when = request->proxy->timestamp;
3153 when.tv_sec += home->response_window;
3156 * Not at the response window. Set the timer for
3159 if (timercmp(&when, &now, >)) {
3160 RDEBUG("Expecting proxy response no later than %d seconds from now", home->response_window);
3161 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3166 RDEBUG("No proxy response, giving up on request and marking it done");
3169 * If we haven't received any packets for
3170 * "response_window", then mark the home server
3173 * If the connection is TCP, then another
3174 * "watchdog timer" function takes care of pings,
3175 * etc. So we don't need to do it here.
3177 * This check should really be part of a home
3178 * server state machine.
3180 if (((home->state == HOME_STATE_ALIVE) ||
3181 (home->state == HOME_STATE_UNKNOWN))
3183 && (home->proto != IPPROTO_TCP)
3186 mark_home_server_zombie(home, &now);
3189 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3190 if (home->type == HOME_TYPE_AUTH) {
3191 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3192 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3195 else if (home->type == HOME_TYPE_ACCT) {
3196 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3197 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3202 * There was no response within the window. Stop
3203 * the request. If the client retransmitted, it
3204 * may have failed over to another home server.
3205 * But that one may be dead, too.
3207 RERROR("Failing request - proxy ID %u, due to lack of any response from home server %s port %d",
3209 inet_ntop(request->proxy->dst_ipaddr.af,
3210 &request->proxy->dst_ipaddr.ipaddr,
3211 buffer, sizeof(buffer)),
3212 request->proxy->dst_port);
3214 if (!setup_post_proxy_fail(request)) {
3215 gettimeofday(&request->reply->timestamp, NULL);
3216 request_cleanup_delay_init(request, NULL);
3222 * Duplicate proxy replies have been quenched by
3223 * now. This state is only called ONCE, when we
3224 * receive a new reply from the home server.
3226 case FR_ACTION_PROXY_REPLY:
3227 request_queue_or_run(request, proxy_running);
3230 case FR_ACTION_CONFLICTING:
3231 request_done(request, action);
3235 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3239 #endif /* WITH_PROXY */
3241 /***********************************************************************
3245 ***********************************************************************/
3247 static int null_handler(UNUSED REQUEST *request)
3253 * See if we need to originate a CoA request.
3255 static void request_coa_originate(REQUEST *request)
3257 int rcode, pre_proxy_type = 0;
3263 rad_assert(request != NULL);
3264 rad_assert(request->coa != NULL);
3265 rad_assert(request->proxy == NULL);
3266 rad_assert(!request->in_proxy_hash);
3267 rad_assert(request->proxy_reply == NULL);
3270 * Check whether we want to originate one, or cancel one.
3272 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3274 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3278 if (vp->vp_integer == 0) {
3280 request_free(&request->coa);
3288 * src_ipaddr will be set up in proxy_encode.
3290 memset(&ipaddr, 0, sizeof(ipaddr));
3291 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3293 ipaddr.af = AF_INET;
3294 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3296 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3297 ipaddr.af = AF_INET6;
3298 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3300 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3301 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3303 if (!coa->home_pool) {
3304 RWDEBUG2("No such home_server_pool %s",
3310 * Prefer the pool to one server
3312 } else if (request->client->coa_pool) {
3313 coa->home_pool = request->client->coa_pool;
3315 } else if (request->client->coa_server) {
3316 coa->home_server = request->client->coa_server;
3320 * If all else fails, send it to the client that
3321 * originated this request.
3323 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3327 * Use the pool, if it exists.
3329 if (coa->home_pool) {
3330 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3331 if (!coa->home_server) {
3332 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3335 home_server_update_request(coa->home_server, coa);
3337 } else if (!coa->home_server) {
3338 int port = PW_COA_UDP_PORT;
3340 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3341 if (vp) port = vp->vp_integer;
3343 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3344 if (!coa->home_server) {
3345 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3346 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3347 buffer, sizeof(buffer)), port);
3352 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3354 switch (vp->vp_integer) {
3355 case PW_CODE_COA_REQUEST:
3356 case PW_CODE_DISCONNECT_REQUEST:
3357 coa->proxy->code = vp->vp_integer;
3361 DEBUG("Cannot set CoA Packet-Type to code %d",
3367 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3370 * The rest of the server code assumes that
3371 * request->packet && request->reply exist. Copy them
3372 * from the original request.
3374 rad_assert(coa->packet != NULL);
3375 rad_assert(coa->packet->vps == NULL);
3376 memcpy(coa->packet, request->packet, sizeof(*request->packet));
3377 coa->packet->vps = paircopy(coa->packet, request->packet->vps);
3378 coa->packet->data = NULL;
3379 rad_assert(coa->reply != NULL);
3380 rad_assert(coa->reply->vps == NULL);
3381 memcpy(coa->reply, request->reply, sizeof(*request->reply));
3382 coa->reply->vps = paircopy(coa->reply, request->reply->vps);
3383 coa->reply->data = NULL;
3384 coa->config_items = paircopy(coa, request->config_items);
3385 coa->num_coa_requests = 0;
3386 coa->handle = null_handler;
3387 coa->number = request->number ^ (1 << 24);
3390 * Call the pre-proxy routines.
3392 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3394 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3395 /* Must be a validation issue */
3397 RDEBUG2(" Found Pre-Proxy-Type %s", dval->name);
3398 pre_proxy_type = vp->vp_integer;
3401 if (coa->home_pool && coa->home_pool->virtual_server) {
3402 char const *old_server = coa->server;
3404 coa->server = coa->home_pool->virtual_server;
3405 RDEBUG2(" server %s {", coa->server);
3406 rcode = process_pre_proxy(pre_proxy_type, coa);
3408 coa->server = old_server;
3410 rcode = process_pre_proxy(pre_proxy_type, coa);
3417 * Only send the CoA packet if the pre-proxy code succeeded.
3419 case RLM_MODULE_NOOP:
3421 case RLM_MODULE_UPDATED:
3426 * Source IP / port is set when the proxy socket
3429 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3430 coa->proxy->dst_port = coa->home_server->port;
3432 if (!insert_into_proxy_hash(coa)) {
3433 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list.");
3438 * We CANNOT divorce the CoA request from the parent
3439 * request. This function is running in a child thread,
3440 * and we need access to the main event loop in order to
3441 * to add the timers for the CoA packet.
3443 * Instead, we wait for the timer on the parent request
3446 gettimeofday(&coa->proxy->timestamp, NULL);
3447 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3448 coa->delay = 0; /* need to calculate a new delay */
3450 DEBUG_PACKET(coa, coa->proxy, 1);
3452 coa->process = coa_wait_for_reply;
3453 #ifdef DEBUG_STATE_MACHINE
3454 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3455 child_state_names[request->child_state],
3456 child_state_names[REQUEST_RUNNING]);
3458 coa->child_state = REQUEST_PROXIED;
3459 rad_assert(coa->proxy_reply == NULL);
3460 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3461 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3462 coa->proxy_listener->send(coa->proxy_listener, coa);
3466 static void coa_timer(REQUEST *request)
3469 struct timeval now, when, mrd;
3471 rad_assert(request->parent == NULL);
3473 if (request->proxy_reply) return request_process_timer(request);
3475 gettimeofday(&now, NULL);
3477 if (request->delay == 0) {
3479 * Implement re-transmit algorithm as per RFC 5080
3482 * We want IRT + RAND*IRT
3483 * or 0.9 IRT + rand(0,.2) IRT
3485 * 2^20 ~ USEC, and we want 2.
3486 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3488 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3489 request->delay = delay * request->home_server->coa_irt;
3490 delay = request->home_server->coa_irt * USEC;
3491 delay -= delay / 10;
3492 delay += request->delay;
3493 request->delay = delay;
3495 when = request->proxy->timestamp;
3496 tv_add(&when, delay);
3498 if (timercmp(&when, &now, >)) {
3499 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3505 * Retransmit CoA request.
3509 * Cap count at MRC, if it is non-zero.
3511 if (request->home_server->coa_mrc &&
3512 (request->num_coa_requests >= request->home_server->coa_mrc)) {
3513 if (!setup_post_proxy_fail(request)) {
3517 request_queue_or_run(request, coa_running);
3522 * RFC 5080 Section 2.2.1
3524 * RT = 2*RTprev + RAND*RTprev
3525 * = 1.9 * RTprev + rand(0,.2) * RTprev
3526 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3529 delay ^= (delay >> 16);
3531 frac = request->delay / 5;
3532 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3534 delay += (2 * request->delay) - (request->delay / 10);
3537 * Cap delay at MRT, if MRT is non-zero.
3539 if (request->home_server->coa_mrt &&
3540 (delay > (request->home_server->coa_mrt * USEC))) {
3541 int mrt_usec = request->home_server->coa_mrt * USEC;
3544 * delay = MRT + RAND * MRT
3545 * = 0.9 MRT + rand(0,.2) * MRT
3548 delay ^= (delay >> 15);
3550 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3551 delay += mrt_usec - (mrt_usec / 10);
3554 request->delay = delay;
3556 tv_add(&when, request->delay);
3557 mrd = request->proxy->timestamp;
3558 mrd.tv_sec += request->home_server->coa_mrd;
3561 * Cap duration at MRD.
3563 if (timercmp(&mrd, &when, <)) {
3566 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3568 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3570 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3573 * Status servers don't count as real packets sent.
3575 request->proxy_listener->send(request->proxy_listener,
3579 STATE_MACHINE_DECL(coa_wait_for_reply)
3581 rad_assert(request->parent == NULL);
3583 TRACE_STATE_MACHINE;
3586 case FR_ACTION_TIMER:
3588 * This is big enough to be in it's own function.
3593 case FR_ACTION_PROXY_REPLY:
3594 rad_assert(request->parent == NULL);
3595 #ifdef HAVE_PTHREAD_H
3597 * Catch the case of a proxy reply when called
3598 * from the main worker thread.
3600 if (we_are_master()) {
3601 request_queue_or_run(request, coa_running);
3607 request_running(request, action);
3611 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3616 static void request_coa_separate(REQUEST *request)
3618 #ifdef DEBUG_STATE_MACHINE
3619 int action = FR_ACTION_TIMER;
3621 TRACE_STATE_MACHINE;
3623 rad_assert(request->parent != NULL);
3624 rad_assert(request->parent->coa == request);
3625 rad_assert(request->ev == NULL);
3626 rad_assert(!request->in_request_hash);
3628 rad_assert(request->proxy_listener != NULL);
3629 /* don't talloc_steal request, it will be cleaned up elsewhere */
3630 request->parent->coa = NULL;
3631 request->parent = NULL;
3634 * Should be coa_wait_for_reply()
3636 request->process(request, FR_ACTION_TIMER);
3639 STATE_MACHINE_DECL(coa_running)
3641 TRACE_STATE_MACHINE;
3644 case FR_ACTION_TIMER:
3645 request_process_timer(request);
3648 case FR_ACTION_PROXY_REPLY:
3649 request_common(request, action);
3653 request_running(request, FR_ACTION_PROXY_REPLY);
3657 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3661 #endif /* WITH_COA */
3663 /***********************************************************************
3665 * End of the State machine. Start of additional helper code.
3667 ***********************************************************************/
3669 /***********************************************************************
3673 ***********************************************************************/
3674 static void event_socket_handler(UNUSED fr_event_list_t *xel, UNUSED int fd, void *ctx)
3676 rad_listen_t *listener = ctx;
3678 rad_assert(xel == el);
3682 (listener->type != RAD_LISTEN_DETAIL) &&
3684 (listener->fd < 0)) {
3687 listener->print(listener, buffer, sizeof(buffer));
3688 ERROR("FATAL: Asked to read from closed socket: %s",
3691 rad_panic("Socket was closed on us!");
3695 listener->recv(listener);
3700 * This function is called periodically to see if this detail
3701 * file is available for reading.
3703 static void event_poll_detail(void *ctx)
3706 rad_listen_t *this = ctx;
3707 struct timeval when, now;
3708 listen_detail_t *detail = this->data;
3710 rad_assert(this->type == RAD_LISTEN_DETAIL);
3713 event_socket_handler(el, this->fd, this);
3715 fr_event_now(el, &now);
3719 * Backdoor API to get the delay until the next poll
3722 delay = this->encode(this, NULL);
3723 if (delay == 0) goto redo;
3725 tv_add(&when, delay);
3727 if (!fr_event_insert(el, event_poll_detail, this,
3728 &when, &detail->ev)) {
3729 ERROR("Failed creating handler");
3735 static void event_status(struct timeval *wake)
3737 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3741 if (debug_flag == 0) {
3743 INFO("Ready to process requests.");
3744 just_started = false;
3750 INFO("Ready to process requests.");
3752 } else if ((wake->tv_sec != 0) ||
3753 (wake->tv_usec >= 100000)) {
3754 DEBUG("Waking up in %d.%01u seconds.",
3755 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3760 * FIXME: Put this somewhere else, where it isn't called
3761 * all of the time...
3764 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3766 * If there are no child threads, then there may
3767 * be child processes. In that case, wait for
3768 * their exit status, and throw that exit status
3769 * away. This helps get rid of zxombie children.
3771 while (waitpid(-1, &argval, WNOHANG) > 0) {
3779 static void listener_free_cb(void *ctx)
3781 rad_listen_t *this = ctx;
3784 if (this->count > 0) {
3785 struct timeval when;
3786 listen_socket_t *sock = this->data;
3788 fr_event_now(el, &when);
3791 if (!fr_event_insert(el, listener_free_cb, this, &when,
3793 rad_panic("Failed to insert event");
3800 * It's all free, close the socket.
3803 this->print(this, buffer, sizeof(buffer));
3804 DEBUG("... cleaning up socket %s", buffer);
3810 static int proxy_eol_cb(void *ctx, void *data)
3812 struct timeval when;
3813 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3815 if (request->proxy_listener != ctx) return 0;
3818 * We don't care if it's being processed in a child thread.
3821 #ifdef WITH_ACCOUNTING
3823 * Accounting packets should be deleted immediately.
3824 * They will never be retransmitted by the client.
3826 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
3827 RDEBUG("Stopping request due to failed connection to home server");
3828 request->master_state = REQUEST_STOP_PROCESSING;
3833 * Reset the timer to be now, so that the request is
3834 * quickly updated. But spread the requests randomly
3835 * over the next second, so that we don't overload the
3838 fr_event_now(el, &when);
3839 tv_add(&when, fr_rand() % USEC);
3840 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3843 * Don't delete it from the list.
3849 int event_new_fd(rad_listen_t *this)
3853 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
3855 this->print(this, buffer, sizeof(buffer));
3857 if (this->status == RAD_LISTEN_STATUS_INIT) {
3858 listen_socket_t *sock = this->data;
3861 DEBUG("Listening on %s", buffer);
3863 INFO(" ... adding new socket %s", buffer);
3868 * Add it to the list of sockets we can use.
3869 * Server sockets (i.e. auth/acct) are never
3870 * added to the packet list.
3872 if (this->type == RAD_LISTEN_PROXY) {
3873 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3874 if (!fr_packet_list_socket_add(proxy_list, this->fd,
3876 &sock->other_ipaddr, sock->other_port,
3879 #ifdef HAVE_PTHREAD_H
3880 proxy_no_new_sockets = true;
3882 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3885 * This is bad. However, the
3886 * packet list now supports 256
3887 * open sockets, which should
3888 * minimize this problem.
3890 ERROR("Failed adding proxy socket: %s",
3896 sock->home->limit.num_connections++;
3898 #ifdef HAVE_PTHREAD_H
3900 * If necessary, add it to the list of
3901 * new proxy listeners.
3903 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3904 this->next = proxy_listener_list;
3905 proxy_listener_list = this;
3909 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3912 * Tell the main thread that we've added
3913 * a proxy listener, but only if we need
3914 * to update the event list. Do this
3915 * with the mutex unlocked, to reduce
3919 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3920 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3928 * Detail files are always known, and aren't
3929 * put into the socket event loop.
3931 if (this->type == RAD_LISTEN_DETAIL) {
3932 this->status = RAD_LISTEN_STATUS_KNOWN;
3935 * Set up the first poll interval.
3937 event_poll_detail(this);
3944 * Add timers to child sockets, if necessary.
3946 if (sock->proto == IPPROTO_TCP && sock->opened &&
3947 (sock->limit.lifetime || sock->limit.idle_timeout)) {
3948 struct timeval when;
3952 when.tv_sec = sock->opened + 1;
3955 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3957 rad_panic("Failed to insert event");
3962 FD_MUTEX_LOCK(&fd_mutex);
3963 if (!fr_event_fd_insert(el, 0, this->fd,
3964 event_socket_handler, this)) {
3965 ERROR("Failed adding event handler for socket!");
3968 FD_MUTEX_UNLOCK(&fd_mutex);
3970 this->status = RAD_LISTEN_STATUS_KNOWN;
3976 * Stop using this socket, if at all possible.
3978 if (this->status == RAD_LISTEN_STATUS_EOL) {
3980 * Remove it from the list of live FD's.
3982 FD_MUTEX_LOCK(&fd_mutex);
3983 fr_event_fd_delete(el, 0, this->fd);
3984 FD_MUTEX_UNLOCK(&fd_mutex);
3988 * Proxy sockets get frozen, so that we don't use
3989 * them for new requests. But we do keep them
3990 * open to listen for replies to requests we had
3993 if (this->type == RAD_LISTEN_PROXY) {
3994 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3995 if (!fr_packet_list_socket_freeze(proxy_list,
3997 ERROR("Fatal error freezing socket: %s", fr_strerror());
4001 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4002 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4007 * Requests are still using the socket. Wait for
4010 if (this->count > 0) {
4011 struct timeval when;
4012 listen_socket_t *sock = this->data;
4015 * Try again to clean up the socket in 30
4018 gettimeofday(&when, NULL);
4021 if (!fr_event_insert(el,
4022 (fr_event_callback_t) event_new_fd,
4023 this, &when, &sock->ev)) {
4024 rad_panic("Failed to insert event");
4031 * No one is using the socket. We can remove it now.
4033 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4034 } /* socket is at EOL */
4040 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4043 listen_socket_t *sock = this->data;
4045 struct timeval when;
4048 * Re-open the socket, pointing it to /dev/null.
4049 * This means that all writes proceed without
4050 * blocking, and all reads return "no data".
4052 * This leaves the socket active, so any child
4053 * threads won't go insane. But it means that
4054 * they cannot send or receive any packets.
4056 * This is EXTRA work in the normal case, when
4057 * sockets are closed without error. But it lets
4058 * us have one simple processing method for all
4061 devnull = open("/dev/null", O_RDWR);
4063 ERROR("FATAL failure opening /dev/null: %s",
4064 fr_syserror(errno));
4067 if (dup2(devnull, this->fd) < 0) {
4068 ERROR("FATAL failure closing socket: %s",
4069 fr_syserror(errno));
4075 rad_assert(this->type != RAD_LISTEN_DETAIL);
4079 INFO(" ... shutting down socket %s", buffer);
4083 * The socket is dead. Force all proxied packets
4084 * to stop using it. And then remove it from the
4085 * list of outgoing sockets.
4087 if (this->type == RAD_LISTEN_PROXY) {
4088 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4089 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4091 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4092 ERROR("Fatal error removing socket %s: %s",
4093 buffer, fr_strerror());
4096 if (sock->home && sock->home->limit.num_connections) {
4097 sock->home->limit.num_connections--;
4099 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4104 * EOL all requests using this socket.
4106 fr_packet_list_walk(pl, this, eol_listener);
4110 * No child threads, clean it up now.
4113 if (sock->ev) fr_event_delete(el, &sock->ev);
4119 * Wait until all requests using this socket are done.
4121 gettimeofday(&when, NULL);
4124 if (!fr_event_insert(el, listener_free_cb, this, &when,
4126 rad_panic("Failed to insert event");
4129 #endif /* WITH_TCP */
4134 /***********************************************************************
4138 ***********************************************************************/
4140 static void handle_signal_self(int flag)
4142 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4143 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4144 INFO("Signalled to exit");
4145 fr_event_loop_exit(el, 1);
4147 INFO("Signalled to terminate");
4148 exec_trigger(NULL, NULL, "server.signal.term", true);
4149 fr_event_loop_exit(el, 2);
4153 } /* else exit/term flags weren't set */
4156 * Tell the even loop to stop processing.
4158 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4160 static time_t last_hup = 0;
4163 if ((int) (when - last_hup) < 5) {
4164 INFO("Ignoring HUP (less than 5s since last one)");
4168 INFO("Received HUP signal.");
4172 exec_trigger(NULL, NULL, "server.signal.hup", true);
4173 fr_event_loop_exit(el, 0x80);
4177 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4181 * FIXME: O(N) loops suck.
4183 for (this = mainconfig.listen;
4185 this = this->next) {
4186 if (this->type != RAD_LISTEN_DETAIL) continue;
4189 * This one didn't send the signal, skip
4192 if (!this->decode(this, NULL)) continue;
4195 * Go service the interrupt.
4197 event_poll_detail(this);
4204 #ifdef HAVE_PTHREAD_H
4206 * Add event handlers for idle timeouts && maximum lifetime.
4208 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4209 struct timeval when, now;
4211 fr_event_now(el, &now);
4213 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4215 while (proxy_listener_list) {
4216 rad_listen_t *this = proxy_listener_list;
4217 listen_socket_t *sock = this->data;
4219 rad_assert(sock->proto == IPPROTO_TCP);
4220 proxy_listener_list = this->next;
4223 if (!sock->home) continue; /* skip UDP sockets */
4228 * Sockets should only be added to the
4229 * proxy_listener_list if they have limits.
4232 rad_assert(sock->home->limit.lifetime || sock->home->limit.idle_timeout);
4234 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4236 rad_panic("Failed to insert event");
4240 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4242 #endif /* HAVE_PTHREAD_H */
4243 #endif /* WITH_PROXY */
4244 #endif /* WITH_TCP */
4247 #ifndef WITH_SELF_PIPE
4248 void radius_signal_self(int flag)
4250 handle_signal_self(flag);
4254 * Inform ourselves that we received a signal.
4256 void radius_signal_self(int flag)
4262 * The read MUST be non-blocking for this to work.
4264 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4268 for (i = 0; i < rcode; i++) {
4269 buffer[0] |= buffer[i];
4277 write(self_pipe[1], buffer, 1);
4281 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4282 UNUSED int fd, UNUSED void *ctx)
4287 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4288 if (rcode <= 0) return;
4291 * Merge pending signals.
4293 for (i = 0; i < rcode; i++) {
4294 buffer[0] |= buffer[i];
4297 handle_signal_self(buffer[0]);
4301 /***********************************************************************
4303 * Bootstrapping code.
4305 ***********************************************************************/
4308 * Externally-visibly functions.
4310 int radius_event_init(TALLOC_CTX *ctx) {
4311 el = fr_event_list_create(ctx, event_status);
4317 int radius_event_start(CONF_SECTION *cs, bool have_children)
4319 rad_listen_t *head = NULL;
4321 if (fr_start_time != (time_t)-1) return 0;
4323 time(&fr_start_time);
4326 * radius_event_init() must be called first
4329 if (fr_start_time == (time_t)-1) return 0;
4331 pl = fr_packet_list_create(0);
4332 if (!pl) return 0; /* leak el */
4334 request_num_counter = 0;
4337 if (mainconfig.proxy_requests) {
4339 * Create the tree for managing proxied requests and
4342 proxy_list = fr_packet_list_create(1);
4343 if (!proxy_list) return 0;
4345 #ifdef HAVE_PTHREAD_H
4346 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4347 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4348 fr_syserror(errno));
4356 * Move all of the thread calls to this file?
4358 * It may be best for the mutexes to be in this file...
4360 spawn_flag = have_children;
4362 #ifdef HAVE_PTHREAD_H
4363 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4366 * Initialize the threads ONLY if we're spawning, AND
4367 * we're running normally.
4369 if (have_children && !check_config &&
4370 (thread_pool_init(cs, &spawn_flag) < 0)) {
4376 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4378 if (listen_init(cs, &head, spawn_flag) < 0) {
4385 #ifdef WITH_SELF_PIPE
4387 * Child threads need a pipe to signal us, as do the
4390 if (pipe(self_pipe) < 0) {
4391 ERROR("radiusd: Error opening internal pipe: %s",
4392 fr_syserror(errno));
4395 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4396 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4397 ERROR("radiusd: Error setting internal flags: %s",
4398 fr_syserror(errno));
4401 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4402 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4403 ERROR("radiusd: Error setting internal flags: %s",
4404 fr_syserror(errno));
4408 if (!fr_event_fd_insert(el, 0, self_pipe[0],
4409 event_signal_handler, el)) {
4410 ERROR("Failed creating handler for signals");
4413 #endif /* WITH_SELF_PIPE */
4415 DEBUG("%s: #### Opening IP addresses and Ports ####",
4419 * The server temporarily switches to an unprivileged
4420 * user very early in the bootstrapping process.
4421 * However, some sockets MAY require privileged access
4422 * (bind to device, or to port < 1024, or to raw
4423 * sockets). Those sockets need to call suid up/down
4424 * themselves around the functions that need a privileged
4427 if (listen_init(cs, &head, spawn_flag) < 0) {
4431 mainconfig.listen = head;
4434 * At this point, no one has any business *ever* going
4437 fr_suid_down_permanent();
4444 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4446 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4448 request->master_state = REQUEST_STOP_PROCESSING;
4451 * Not done, or the child thread is still processing it.
4453 if (request->child_state != REQUEST_DONE) return 0; /* continue */
4455 #ifdef HAVE_PTHREAD_H
4456 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4459 request->in_proxy_hash = false;
4462 * Delete it from the list.
4469 static int request_delete_cb(UNUSED void *ctx, void *data)
4471 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4473 request->master_state = REQUEST_STOP_PROCESSING;
4476 * Not done, or the child thread is still processing it.
4478 if (request->child_state < REQUEST_REJECT_DELAY) return 0; /* continue */
4480 #ifdef HAVE_PTHREAD_H
4481 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4485 rad_assert(request->in_proxy_hash == false);
4488 request->in_request_hash = false;
4489 if (request->ev) fr_event_delete(el, &request->ev);
4491 if (mainconfig.memory_report) {
4492 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
4493 request->packet->id,
4494 (unsigned int) (request->timestamp - fr_start_time));
4497 request_free(&request);
4500 * Delete it from the list, and continue;
4506 void radius_event_free(void)
4512 * There are requests in the proxy hash that aren't
4513 * referenced from anywhere else. Remove them first.
4516 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4520 fr_packet_list_walk(pl, NULL, request_delete_cb);
4524 * Now that all requests have been marked "please stop",
4525 * ensure that all of the threads have exited.
4527 #ifdef HAVE_PTHREAD_H
4532 * Walk the lists again, ensuring that all
4533 * requests are done.
4535 if (mainconfig.memory_report) {
4540 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4541 num = fr_packet_list_num_elements(proxy_list);
4543 ERROR("Proxy list has %d requests still in it.", num);
4548 fr_packet_list_walk(pl, NULL, request_delete_cb);
4549 num = fr_packet_list_num_elements(pl);
4551 ERROR("Request list has %d requests still in it.", num);
4556 fr_packet_list_free(pl);
4560 fr_packet_list_free(proxy_list);
4566 if (debug_condition) talloc_free(debug_condition);
4569 int radius_event_process(void)
4573 return fr_event_loop(el);