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;
432 (void) talloc_steal(NULL, request);
438 * It doesn't hurt to send duplicate replies. All other
439 * signals are ignored, as the request will be cleaned up
444 if (request->reply->code != 0) {
445 request->listener->send(request->listener, request);
451 * This is only called from the master thread
452 * when there is a child thread processing the
455 case FR_ACTION_CONFLICTING:
456 if (request->child_state == REQUEST_DONE) break;
459 * If there's a reply packet, then we presume
460 * that the child has sent the reply, and we get
461 * pinged here before the child has a chance to
464 if (request->reply->data) break;
466 RERROR("Received conflicting packet from "
467 "client %s port %d - ID: %u due to "
468 "unfinished request. Giving up on old request.",
469 request->client->shortname,
470 request->packet->src_port, request->packet->id);
474 * Called only when there's an error remembering
475 * the packet, or when the socket gets closed from
479 #ifdef HAVE_PTHREAD_H
481 * Do NOT set child_state to DONE if it's still in the queue.
483 if (we_are_master() && (request->child_state == REQUEST_QUEUED)) {
488 * If we have child threads and we're NOT the
489 * thread handling the request, don't do anything.
492 !pthread_equal(pthread_self(), request->child_pid)) {
496 #ifdef DEBUG_STATE_MACHINE
497 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
498 request->number, __FUNCTION__,
499 child_state_names[request->child_state],
500 child_state_names[REQUEST_DONE]);
502 request->child_state = REQUEST_DONE;
506 * Called when the child is taking too long to
507 * finish. We've already marked it "please
508 * stop", so we don't complain any more.
510 case FR_ACTION_TIMER:
515 * Child is still alive, and we're receiving more
516 * packets from the home server.
518 case FR_ACTION_PROXY_REPLY:
519 DEBUG2("Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
520 inet_ntop(request->proxy->src_ipaddr.af,
521 &request->proxy->src_ipaddr.ipaddr,
522 buffer, sizeof(buffer)),
523 request->proxy->dst_port, request->proxy->id,
529 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
534 * Remove it from the request hash.
536 if (request->in_request_hash) {
538 if (!fr_packet_list_yank(pl, request->packet)) {
541 request->in_request_hash = false;
546 * Wait for the proxy ID to expire. This allows us to
547 * avoid re-use of proxy IDs for a while.
549 if (request->in_proxy_hash) {
550 rad_assert(request->proxy != NULL);
552 fr_event_now(el, &now);
553 when = request->proxy->timestamp;
556 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
557 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
558 (request->packet->code != request->proxy->code)) {
559 when.tv_sec += request->home_server->coa_mrd;
562 when.tv_sec += request->home_server->response_window;
565 * We haven't received all responses, AND there's still
566 * time to wait. Do so.
568 if ((request->num_proxied_requests > request->num_proxied_responses) &&
570 (request->home_server->proto != IPPROTO_TCP) &&
572 timercmp(&now, &when, <)) {
573 RDEBUG("Waiting for more responses from the home server");
580 remove_from_proxy_hash(request);
584 #ifdef HAVE_PTHREAD_H
586 * If there's no children, we can mark the request as done.
589 request->child_state = REQUEST_DONE;
593 if (request->child_state != REQUEST_DONE) {
594 gettimeofday(&now, NULL);
599 #ifdef HAVE_PTHREAD_H
601 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
602 RDEBUG("Waiting for child thread to stop");
607 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
608 tv_add(&when, request->delay);
609 request->delay += request->delay >> 1;
610 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
612 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
616 #ifdef HAVE_PTHREAD_H
617 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
621 * @todo: do final states for TCP sockets, too?
623 request_stats_final(request);
625 if (request->listener) request->listener->count--;
628 if (request->packet) {
629 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
631 (unsigned int) (request->timestamp - fr_start_time));
632 } /* else don't print anything */
634 if (request->ev) fr_event_delete(el, &request->ev);
636 request_free(&request);
640 static void request_cleanup_delay_init(REQUEST *request, struct timeval const *pnow)
642 struct timeval now, when;
644 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
646 if (!request->root->cleanup_delay) goto done;
651 gettimeofday(&now, NULL);
654 rad_assert(request->reply->timestamp.tv_sec != 0);
655 when = request->reply->timestamp;
657 request->delay = request->root->cleanup_delay;
658 when.tv_sec += request->delay;
661 * Set timer for when we need to clean it up.
663 if (timercmp(&when, &now, >)) {
664 #ifdef DEBUG_STATE_MACHINE
665 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
667 request->process = request_cleanup_delay;
668 request->child_state = REQUEST_DONE;
669 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
674 * Otherwise just clean it up.
677 request_done(request, FR_ACTION_DONE);
682 * Function to do all time-related events.
684 static void request_process_timer(REQUEST *request)
686 struct timeval now, when;
687 rad_assert(request->magic == REQUEST_MAGIC);
688 #ifdef DEBUG_STATE_MACHINE
689 int action = FR_ACTION_TIMER;
697 * If we originated a CoA request, divorce it from the
698 * parent. Then, set up the timers so that we can clean
699 * it up as appropriate.
701 if (request->coa) request_coa_separate(request->coa);
704 * If we're the request, OR it isn't originating a CoA
705 * request, check more things.
707 if (!request->proxy || (request->packet->code == request->proxy->code))
710 rad_assert(request->listener != NULL);
713 * The socket was closed. Tell the request that
714 * there is no point in continuing.
716 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
717 if ((request->master_state == REQUEST_ACTIVE) &&
718 (request->child_state < REQUEST_REJECT_DELAY)) {
719 WDEBUG("Socket was closed while processing request %u: Stopping it.", request->number);
720 request->master_state = REQUEST_STOP_PROCESSING;
725 gettimeofday(&now, NULL);
728 * The request was forcibly stopped.
730 if (request->master_state == REQUEST_STOP_PROCESSING) {
731 switch (request->child_state) {
733 case REQUEST_RUNNING:
734 #ifdef HAVE_PTHREAD_H
735 rad_assert(spawn_flag == true);
740 * Sleep for some more. We HOPE that the
741 * child will become responsive at some
742 * point in the future.
745 tv_add(&when, request->delay);
746 request->delay += request->delay >> 1;
747 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
751 * These should all be managed by the master thread
754 case REQUEST_PROXIED:
756 case REQUEST_REJECT_DELAY:
757 case REQUEST_CLEANUP_DELAY:
760 request_done(request, FR_ACTION_DONE);
765 rad_assert(request->master_state == REQUEST_ACTIVE);
768 * It's still supposed to be running.
770 switch (request->child_state) {
772 case REQUEST_RUNNING:
774 case REQUEST_PROXIED:
776 when = request->packet->timestamp;
777 when.tv_sec += request->root->max_request_time;
780 * Taking too long: tell it to die.
782 if (timercmp(&now, &when, >=)) {
783 #ifdef HAVE_PTHREAD_H
785 * If there's a child thread processing it,
789 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
790 ERROR("Unresponsive child for request %u, in component %s module %s",
792 request->component ? request->component : "<core>",
793 request->module ? request->module : "<core>");
794 exec_trigger(request, NULL, "server.thread.unresponsive", true);
797 request->master_state = REQUEST_STOP_PROCESSING;
802 * We should wait for the proxy reply.
804 if (request->child_state == REQUEST_PROXIED) {
805 if (request->proxy_reply) {
806 request->process = proxy_running;
808 request->process = proxy_wait_for_reply;
814 * If the request has been told to die, we wait.
815 * Otherwise, we wait for the child thread to
820 case REQUEST_REJECT_DELAY:
821 rad_assert(request->root->reject_delay > 0);
823 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
826 request->process = request_reject_delay;
828 when = request->reply->timestamp;
829 when.tv_sec += request->root->reject_delay;
831 if (timercmp(&when, &now, >)) {
832 #ifdef DEBUG_STATE_MACHINE
833 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_reject_delay");
835 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
837 } /* else it's time to send the reject */
839 RDEBUG2("Sending delayed reject");
840 DEBUG_PACKET(request, request->reply, 1);
841 request->listener->send(request->listener, request);
842 request->child_state = REQUEST_CLEANUP_DELAY;
845 case REQUEST_CLEANUP_DELAY:
846 rad_assert(request->root->cleanup_delay > 0);
849 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
852 request->process = request_cleanup_delay;
854 when = request->reply->timestamp;
855 when.tv_sec += request->root->cleanup_delay;
857 if (timercmp(&when, &now, >)) {
858 #ifdef DEBUG_STATE_MACHINE
859 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
861 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
863 } /* else it's time to clean up */
872 static void request_queue_or_run(UNUSED REQUEST *request,
873 fr_request_process_t process)
875 #ifdef DEBUG_STATE_MACHINE
876 int action = FR_ACTION_TIMER;
882 * Do this here so that fewer other functions need to do
885 if (request->master_state == REQUEST_STOP_PROCESSING) {
886 #ifdef DEBUG_STATE_MACHINE
887 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
888 request->number, __FUNCTION__,
889 master_state_names[request->master_state],
890 child_state_names[request->child_state],
891 child_state_names[REQUEST_DONE]);
893 request_done(request, FR_ACTION_DONE);
897 request->process = process;
899 if (we_are_master()) {
903 * (re) set the initial delay.
905 request->delay = USEC / 3;
906 gettimeofday(&when, NULL);
907 tv_add(&when, request->delay);
908 request->delay += request->delay >> 1;
910 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
912 #ifdef HAVE_PTHREAD_H
915 * A child thread will eventually pick it up.
917 if (request_enqueue(request)) return;
920 * Otherwise we're not going to do anything with
923 request_done(request, FR_ACTION_DONE);
929 request->child_state = REQUEST_RUNNING;
930 request->process(request, FR_ACTION_RUN);
934 * Requests that care about child process exit
935 * codes have already either called
936 * rad_waitpid(), or they've given up.
938 while (waitpid(-1, NULL, WNOHANG) > 0);
942 STATE_MACHINE_DECL(request_common)
952 * Bail out as early as possible.
954 if (request->master_state == REQUEST_STOP_PROCESSING) {
955 request_done(request, REQUEST_DONE);
963 * We're still waiting for a proxy reply.
965 if (request->child_state == REQUEST_PROXIED) {
966 proxy_wait_for_reply(request, action);
971 ERROR("(%u) Discarding duplicate request from "
972 "client %s port %d - ID: %u due to unfinished request",
973 request->number, request->client->shortname,
974 request->packet->src_port,request->packet->id);
977 case FR_ACTION_CONFLICTING:
979 * We're in the master thread, ask the child to
980 * stop processing the request.
982 request_done(request, action);
985 case FR_ACTION_TIMER:
986 request_process_timer(request);
990 case FR_ACTION_PROXY_REPLY:
991 DEBUG2("Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
992 inet_ntop(request->proxy->src_ipaddr.af,
993 &request->proxy->src_ipaddr.ipaddr,
994 buffer, sizeof(buffer)),
995 request->proxy->dst_port, request->proxy->id,
1001 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1006 STATE_MACHINE_DECL(request_cleanup_delay)
1008 struct timeval when;
1010 TRACE_STATE_MACHINE;
1015 if (request->reply->code != 0) {
1016 request->listener->send(request->listener, request);
1018 RDEBUG("No reply. Ignoring retransmit.");
1022 * Double the cleanup_delay to catch retransmits.
1024 when = request->reply->timestamp;
1025 request->delay += request->delay ;
1026 when.tv_sec += request->delay;
1028 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1032 case FR_ACTION_PROXY_REPLY:
1034 case FR_ACTION_CONFLICTING:
1035 case FR_ACTION_TIMER:
1036 request_common(request, action);
1040 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1045 STATE_MACHINE_DECL(request_reject_delay)
1047 TRACE_STATE_MACHINE;
1052 ERROR("(%u) Discarding duplicate request from "
1053 "client %s port %d - ID: %u due to delayed reject",
1054 request->number, request->client->shortname,
1055 request->packet->src_port,request->packet->id);
1059 case FR_ACTION_PROXY_REPLY:
1061 case FR_ACTION_CONFLICTING:
1062 case FR_ACTION_TIMER:
1063 request_common(request, action);
1067 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1073 static int request_pre_handler(REQUEST *request, UNUSED int action)
1075 TRACE_STATE_MACHINE;
1079 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1082 * Don't decode the packet if it's an internal "fake"
1083 * request. Instead, just return so that the caller can
1086 if (request->packet->dst_port == 0) {
1087 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1088 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1094 * Put the decoded packet into it's proper place.
1096 if (request->proxy_reply != NULL) {
1098 * There may be a proxy reply, but it may be too late.
1100 if (!request->proxy_listener) return 0;
1102 rcode = request->proxy_listener->decode(request->proxy_listener, request);
1103 DEBUG_PACKET(request, request->proxy_reply, 0);
1106 * Pro-actively remove it from the proxy hash.
1107 * This is later than in 2.1.x, but it means that
1108 * the replies are authenticated before being
1109 * removed from the hash.
1112 (request->num_proxied_requests <= request->num_proxied_responses)) {
1113 remove_from_proxy_hash(request);
1118 if (request->packet->vps == NULL) {
1119 rcode = request->listener->decode(request->listener, request);
1122 if (debug_condition) {
1124 * Ignore parse errors.
1126 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1127 request->options = 2;
1128 request->radlog = vradlog_request;
1133 DEBUG_PACKET(request, request->packet, 0);
1139 RDEBUG("Dropping packet without response because of error: %s", fr_strerror());
1140 request->reply->offset = -2; /* bad authenticator */
1144 if (!request->username) {
1145 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1149 if (action == FR_ACTION_PROXY_REPLY) {
1150 return process_proxy_reply(request);
1157 STATE_MACHINE_DECL(request_finish)
1161 TRACE_STATE_MACHINE;
1163 (void) action; /* -Wunused */
1165 if (request->master_state == REQUEST_STOP_PROCESSING) return;
1168 * Don't send replies if there are none to send.
1170 if (!request->in_request_hash) {
1172 if ((request->listener->type == RAD_LISTEN_AUTH)
1173 #ifdef WITH_ACCOUNTING
1174 || (request->listener->type == RAD_LISTEN_ACCT)
1177 listen_socket_t *sock = request->listener->data;
1179 if (sock->proto == IPPROTO_UDP) return;
1182 * TCP packets aren't in the request
1192 * Override the response code if a control:Response-Packet-Type attribute is present.
1194 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1196 if (vp->vp_integer == 256) {
1197 RDEBUG2("Not responding to request");
1198 request->reply->code = 0;
1200 request->reply->code = vp->vp_integer;
1204 * Catch Auth-Type := Reject BEFORE proxying the packet.
1206 else if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1207 if (request->reply->code == 0) {
1208 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1210 if (!vp || (vp->vp_integer != PW_CODE_AUTHENTICATION_REJECT)) {
1211 RDEBUG2("There was no response configured: "
1212 "rejecting request");
1215 request->reply->code = PW_CODE_AUTHENTICATION_REJECT;
1220 * Copy Proxy-State from the request to the reply.
1222 vp = paircopy2(request->reply, request->packet->vps,
1223 PW_PROXY_STATE, 0, TAG_ANY);
1224 if (vp) pairadd(&request->reply->vps, vp);
1226 switch (request->reply->code) {
1227 case PW_CODE_AUTHENTICATION_ACK:
1228 rad_postauth(request);
1230 case PW_CODE_ACCESS_CHALLENGE:
1231 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1233 vp = pairmake_config("Post-Auth-Type", "Challenge", T_OP_SET);
1234 if (vp) rad_postauth(request);
1241 * Run rejected packets through
1243 * Post-Auth-Type = Reject
1245 * We do this separately so ACK and challenge can change the code
1246 * to reject if a module returns reject.
1248 if (request->reply->code == PW_CODE_AUTHENTICATION_REJECT) {
1249 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1250 vp = pairmake_config("Post-Auth-Type", "Reject", T_OP_SET);
1251 if (vp) rad_postauth(request);
1255 * Clean up. These are no longer needed.
1257 pairfree(&request->config_items);
1259 pairfree(&request->packet->vps);
1260 request->username = NULL;
1261 request->password = NULL;
1264 if (request->proxy) {
1265 pairfree(&request->proxy->vps);
1267 if (request->proxy_reply) {
1268 pairfree(&request->proxy_reply->vps);
1272 gettimeofday(&request->reply->timestamp, NULL);
1277 if ((request->reply->code != PW_CODE_AUTHENTICATION_REJECT) ||
1278 (request->root->reject_delay == 0)) {
1279 DEBUG_PACKET(request, request->reply, 1);
1280 request->listener->send(request->listener,
1282 pairfree(&request->reply->vps);
1284 RDEBUG2("Finished request %u.", request->number);
1285 #ifdef WITH_ACCOUNTING
1286 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1288 request->child_state = REQUEST_DONE;
1292 if (request->root->cleanup_delay == 0) {
1294 request->child_state = REQUEST_DONE;
1297 request->child_state = REQUEST_CLEANUP_DELAY;
1300 RDEBUG2("Delaying reject of request %u for %d seconds",
1302 request->root->reject_delay);
1304 request->child_state = REQUEST_REJECT_DELAY;
1308 STATE_MACHINE_DECL(request_running)
1310 TRACE_STATE_MACHINE;
1313 case FR_ACTION_TIMER:
1314 request_process_timer(request);
1317 case FR_ACTION_CONFLICTING:
1319 request_common(request, action);
1324 * This can happen due to a race condition where
1325 * we send a proxied request, and immediately get
1326 * another reply, before the timer has a chance
1327 * to update the various states.
1329 case FR_ACTION_PROXY_REPLY:
1330 request->child_state = REQUEST_RUNNING;
1331 request->process = proxy_running;
1336 if (!request_pre_handler(request, action)) {
1337 #ifdef DEBUG_STATE_MACHINE
1338 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1339 request->number, __FUNCTION__,
1340 child_state_names[request->child_state],
1341 child_state_names[REQUEST_DONE]);
1345 request->child_state = REQUEST_DONE;
1349 rad_assert(request->handle != NULL);
1350 request->handle(request);
1354 * We may need to send a proxied request.
1356 if ((action == FR_ACTION_RUN) &&
1357 request_will_proxy(request)) {
1358 #ifdef DEBUG_STATE_MACHINE
1359 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1363 * takes care of setting
1364 * up the post proxy fail
1367 if (request_proxy(request, 0) < 0) goto finished;
1371 #ifdef DEBUG_STATE_MACHINE
1372 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1377 * Maybe originate a CoA request.
1379 if ((action == FR_ACTION_RUN) && request->coa) {
1380 request_coa_originate(request);
1387 request_finish(request, action);
1392 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1397 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1398 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1401 RADIUS_PACKET **packet_p;
1402 REQUEST *request = NULL;
1404 listen_socket_t *sock = NULL;
1407 * Set the last packet received.
1409 gettimeofday(&now, NULL);
1411 #ifdef WITH_ACCOUNTING
1412 if (listener->type != RAD_LISTEN_DETAIL)
1415 sock = listener->data;
1416 sock->last_packet = now.tv_sec;
1418 packet->timestamp = now;
1421 * Skip everything if required.
1423 if (listener->nodup) goto skip_dup;
1425 packet_p = fr_packet_list_find(pl, packet);
1427 request = fr_packet2myptr(REQUEST, packet, packet_p);
1428 rad_assert(request->in_request_hash);
1431 * Same src/dst ip/port, length, and
1432 * authentication vector: must be a duplicate.
1434 if ((request->packet->data_len == packet->data_len) &&
1435 (memcmp(request->packet->vector, packet->vector,
1436 sizeof(packet->vector)) == 0)) {
1439 switch (packet->code) {
1440 case PW_CODE_AUTHENTICATION_REQUEST:
1441 FR_STATS_INC(auth, total_dup_requests);
1444 #ifdef WITH_ACCOUNTING
1445 case PW_CODE_ACCOUNTING_REQUEST:
1446 FR_STATS_INC(acct, total_dup_requests);
1450 case PW_CODE_COA_REQUEST:
1451 FR_STATS_INC(coa, total_dup_requests);
1454 case PW_CODE_DISCONNECT_REQUEST:
1455 FR_STATS_INC(dsc, total_dup_requests);
1462 #endif /* WITH_STATS */
1464 request->process(request, FR_ACTION_DUP);
1469 * Say we're ignoring the old one, and continue
1470 * to process the new one.
1472 request->process(request, FR_ACTION_CONFLICTING);
1477 * Quench maximum number of outstanding requests.
1479 if (mainconfig.max_requests &&
1480 ((count = fr_packet_list_num_elements(pl)) > mainconfig.max_requests)) {
1481 static time_t last_complained = 0;
1483 if (last_complained == now.tv_sec) return 0;
1485 last_complained = now.tv_sec;
1487 ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1489 packet->src_port, packet->id);
1490 WARN("Please check the configuration file.\n"
1491 "\tThe value for 'max_requests' is probably set too low.\n");
1493 exec_trigger(NULL, NULL, "server.max_requests", true);
1499 * Rate-limit the incoming packets
1501 if (sock && sock->max_rate) {
1504 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now,
1505 &sock->rate_time, &now);
1507 if (pps > sock->max_rate) {
1508 DEBUG("Dropping request due to rate limiting");
1511 sock->rate_pps_now++;
1514 request = request_setup(listener, packet, client, fun);
1515 if (!request) return 1;
1518 * Remember the request in the list.
1520 if (!listener->nodup) {
1521 if (!fr_packet_list_insert(pl, &request->packet)) {
1522 RERROR("Failed to insert request in the list of live requests: discarding it");
1523 request_done(request, FR_ACTION_DONE);
1527 request->in_request_hash = true;
1531 * Process it. Send a response, and free it.
1533 if (listener->synchronous) {
1534 request->listener->decode(request->listener, request);
1535 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1536 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1539 request->listener->send(request->listener, request);
1540 request_free(&request);
1545 * Otherwise, insert it into the state machine.
1546 * The child threads will take care of processing it.
1548 request_queue_or_run(request, request_running);
1554 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
1555 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1560 * Create and initialize the new request.
1562 request = request_alloc(NULL);
1563 request->reply = rad_alloc(request, 0);
1564 if (!request->reply) {
1566 request_free(&request);
1570 request->listener = listener;
1571 request->client = client;
1572 request->packet = talloc_steal(request, packet);
1573 request->number = request_num_counter++;
1574 request->priority = listener->type;
1575 request->master_state = REQUEST_ACTIVE;
1576 #ifdef DEBUG_STATE_MACHINE
1577 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1578 request->number, __FUNCTION__,
1579 child_state_names[request->child_state],
1580 child_state_names[REQUEST_RUNNING]);
1582 request->child_state = REQUEST_RUNNING;
1583 request->handle = fun;
1587 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1588 if (packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1589 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1590 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1591 #ifdef WITH_ACCOUNTING
1592 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1593 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1594 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1597 #endif /* WITH_STATS */
1600 * Status-Server packets go to the head of the queue.
1602 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1605 * Set virtual server identity
1607 if (client->server) {
1608 request->server = client->server;
1609 } else if (listener->server) {
1610 request->server = listener->server;
1612 request->server = NULL;
1615 request->root = &mainconfig;
1617 request->listener->count++;
1621 * The request passes many of our sanity checks.
1622 * From here on in, if anything goes wrong, we
1623 * send a reject message, instead of dropping the
1628 * Build the reply template from the request.
1631 request->reply->sockfd = request->packet->sockfd;
1632 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1633 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1634 request->reply->dst_port = request->packet->src_port;
1635 request->reply->src_port = request->packet->dst_port;
1636 request->reply->id = request->packet->id;
1637 request->reply->code = 0; /* UNKNOWN code */
1638 memcpy(request->reply->vector, request->packet->vector,
1639 sizeof(request->reply->vector));
1640 request->reply->vps = NULL;
1641 request->reply->data = NULL;
1642 request->reply->data_len = 0;
1648 /***********************************************************************
1652 ***********************************************************************/
1655 * Timer function for all TCP sockets.
1657 static void tcp_socket_timer(void *ctx)
1659 rad_listen_t *listener = ctx;
1660 listen_socket_t *sock = listener->data;
1661 struct timeval end, now;
1663 fr_socket_limit_t *limit;
1665 fr_event_now(el, &now);
1667 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1669 switch (listener->type) {
1671 case RAD_LISTEN_PROXY:
1672 limit = &sock->home->limit;
1676 case RAD_LISTEN_AUTH:
1677 #ifdef WITH_ACCOUNTING
1678 case RAD_LISTEN_ACCT:
1680 limit = &sock->limit;
1688 * If we enforce a lifetime, do it now.
1690 if (limit->lifetime > 0) {
1691 end.tv_sec = sock->opened + limit->lifetime;
1694 if (timercmp(&end, &now, <=)) {
1695 listener->print(listener, buffer, sizeof(buffer));
1696 DEBUG("Reached maximum lifetime on socket %s", buffer);
1700 listener->status = RAD_LISTEN_STATUS_EOL;
1701 event_new_fd(listener);
1710 * Enforce an idle timeout.
1712 if (limit->idle_timeout > 0) {
1713 struct timeval idle;
1715 rad_assert(sock->last_packet != 0);
1716 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1719 if (timercmp(&idle, &now, <=)) {
1720 listener->print(listener, buffer, sizeof(buffer));
1721 DEBUG("Reached idle timeout on socket %s", buffer);
1726 * Enforce the minimum of idle timeout or lifetime.
1728 if (timercmp(&idle, &end, <)) {
1734 * Wake up at t + 0.5s. The code above checks if the timers
1735 * are <= t. This addition gives us a bit of leeway.
1737 end.tv_usec = USEC / 2;
1739 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1740 rad_panic("Failed to insert event");
1747 * Add +/- 2s of jitter, as suggested in RFC 3539
1750 static void add_jitter(struct timeval *when)
1757 jitter ^= (jitter >> 10);
1758 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1761 * Add in ~ (4 * USEC) of jitter.
1763 tv_add(when, jitter);
1767 * Called by socket_del to remove requests with this socket
1769 static int eol_proxy_listener(void *ctx, void *data)
1771 rad_listen_t *this = ctx;
1772 RADIUS_PACKET **proxy_p = data;
1775 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1776 if (request->proxy_listener != this) return 0;
1779 * The normal "remove_from_proxy_hash" tries to grab the
1780 * proxy mutex. We already have it held, so grabbing it
1781 * again will cause a deadlock. Instead, call the "no
1782 * lock" version of the function.
1784 rad_assert(request->in_proxy_hash == true);
1785 remove_from_proxy_hash_nl(request, false);
1788 * Don't mark it as DONE. The client can retransmit, and
1789 * the packet SHOULD be re-proxied somewhere else.
1791 * Return "2" means that the rbtree code will remove it
1792 * from the tree, and we don't need to do it ourselves.
1796 #endif /* WITH_PROXY */
1798 static int eol_listener(void *ctx, void *data)
1800 rad_listen_t *this = ctx;
1801 RADIUS_PACKET **packet_p = data;
1804 request = fr_packet2myptr(REQUEST, packet, packet_p);
1805 if (request->listener != this) return 0;
1807 request->master_state = REQUEST_STOP_PROCESSING;
1811 #endif /* WITH_TCP */
1814 /***********************************************************************
1816 * Proxy handlers for the state machine.
1818 ***********************************************************************/
1821 * Called with the proxy mutex held
1823 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1825 if (!request->in_proxy_hash) return;
1827 fr_packet_list_id_free(proxy_list, request->proxy, yank);
1828 request->in_proxy_hash = false;
1831 * On the FIRST reply, decrement the count of outstanding
1832 * requests. Note that this is NOT the count of sent
1833 * packets, but whether or not the home server has
1836 if (request->home_server &&
1837 request->home_server->currently_outstanding) {
1838 request->home_server->currently_outstanding--;
1841 * If we're NOT sending it packets, then we don't know
1842 * if it's alive or dead.
1844 if ((request->home_server->currently_outstanding == 0) &&
1845 (request->home_server->state == HOME_STATE_ALIVE)) {
1846 request->home_server->state = HOME_STATE_UNKNOWN;
1847 request->home_server->last_packet_sent = 0;
1848 request->home_server->last_packet_recv = 0;
1853 rad_assert(request->proxy_listener != NULL);
1854 request->proxy_listener->count--;
1856 request->proxy_listener = NULL;
1859 * Got from YES in hash, to NO, not in hash while we hold
1860 * the mutex. This guarantees that when another thread
1861 * grabs the mutex, the "not in hash" flag is correct.
1863 RDEBUG3("proxy: request is no longer in proxy hash");
1866 static void remove_from_proxy_hash(REQUEST *request)
1869 * Check this without grabbing the mutex because it's a
1870 * lot faster that way.
1872 if (!request->in_proxy_hash) return;
1875 * The "not in hash" flag is definitive. However, if the
1876 * flag says that it IS in the hash, there might still be
1877 * a race condition where it isn't.
1879 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1881 if (!request->in_proxy_hash) {
1882 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1886 remove_from_proxy_hash_nl(request, true);
1888 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1891 static int insert_into_proxy_hash(REQUEST *request)
1895 void *proxy_listener;
1897 rad_assert(request->proxy != NULL);
1898 rad_assert(request->home_server != NULL);
1899 rad_assert(proxy_list != NULL);
1902 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1903 proxy_listener = NULL;
1904 request->num_proxied_requests = 1;
1905 request->num_proxied_responses = 0;
1907 for (tries = 0; tries < 2; tries++) {
1910 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
1911 rcode = fr_packet_list_id_alloc(proxy_list,
1912 request->home_server->proto,
1913 &request->proxy, &proxy_listener);
1914 if ((debug_flag > 2) && (rcode == 0)) {
1915 RDEBUG("proxy: Failed allocating ID: %s", fr_strerror());
1917 if (rcode > 0) break;
1918 if (tries > 0) continue; /* try opening new socket only once */
1920 #ifdef HAVE_PTHREAD_H
1921 if (proxy_no_new_sockets) break;
1924 RDEBUG3("proxy: Trying to open a new listener to the home server");
1925 this = proxy_new_listener(request->home_server, 0);
1927 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1931 request->proxy->src_port = 0; /* Use any new socket */
1932 proxy_listener = this;
1935 * Add it to the event loop (and to the packet list)
1936 * before we try to grab another Id.
1938 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1939 if (!event_new_fd(this)) {
1940 RDEBUG3("proxy: Failed inserting new socket into event loop");
1944 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1947 if (!proxy_listener || (rcode == 0)) {
1948 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1949 REDEBUG2("proxy: Failed allocating Id for proxied request");
1951 request->proxy_listener = NULL;
1952 request->in_proxy_hash = false;
1956 rad_assert(request->proxy->id >= 0);
1958 request->proxy_listener = proxy_listener;
1959 request->in_proxy_hash = true;
1960 RDEBUG3("proxy: request is now in proxy hash");
1963 * Keep track of maximum outstanding requests to a
1964 * particular home server. 'max_outstanding' is
1965 * enforced in home_server_ldb(), in realms.c.
1967 request->home_server->currently_outstanding++;
1970 request->proxy_listener->count++;
1973 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1975 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
1976 inet_ntop(request->proxy->dst_ipaddr.af,
1977 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
1978 request->proxy->dst_port,
1979 request->proxy->id);
1984 static int process_proxy_reply(REQUEST *request)
1987 int post_proxy_type = 0;
1991 * Delete any reply we had accumulated until now.
1993 pairfree(&request->reply->vps);
1996 * Run the packet through the post-proxy stage,
1997 * BEFORE playing games with the attributes.
1999 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2002 * If we have a proxy_reply, and it was a reject, setup
2003 * post-proxy-type Reject
2005 if (!vp && request->proxy_reply &&
2006 request->proxy_reply->code == PW_CODE_AUTHENTICATION_REJECT) {
2009 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2011 vp = radius_paircreate(request, &request->config_items,
2012 PW_POST_PROXY_TYPE, 0);
2014 vp->vp_integer = dval->value;
2019 post_proxy_type = vp->vp_integer;
2021 RDEBUG2(" Found Post-Proxy-Type %s",
2022 dict_valnamebyattr(PW_POST_PROXY_TYPE, 0,
2026 if (request->home_pool && request->home_pool->virtual_server) {
2027 char const *old_server = request->server;
2029 request->server = request->home_pool->virtual_server;
2030 RDEBUG2(" server %s {", request->server);
2031 rcode = process_post_proxy(post_proxy_type, request);
2033 request->server = old_server;
2035 rcode = process_post_proxy(post_proxy_type, request);
2039 if (request->packet->code == request->proxy->code)
2041 * Don't run the next bit if we originated a CoA
2042 * packet, after receiving an Access-Request or
2043 * Accounting-Request.
2048 * There may NOT be a proxy reply, as we may be
2049 * running Post-Proxy-Type = Fail.
2051 if (request->proxy_reply) {
2053 * Delete the Proxy-State Attributes from
2054 * the reply. These include Proxy-State
2055 * attributes from us and remote server.
2057 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2060 * Add the attributes left in the proxy
2061 * reply to the reply list.
2063 pairfilter(request->reply, &request->reply->vps,
2064 &request->proxy_reply->vps, 0, 0, TAG_ANY);
2067 * Free proxy request pairs.
2069 pairfree(&request->proxy->vps);
2073 default: /* Don't do anything */
2075 case RLM_MODULE_FAIL:
2078 case RLM_MODULE_HANDLED:
2085 int request_proxy_reply(RADIUS_PACKET *packet)
2087 RADIUS_PACKET **proxy_p;
2092 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2093 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2096 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2097 PROXY( "No outstanding request was found for reply from host %s port %d - ID %u",
2098 inet_ntop(packet->src_ipaddr.af,
2099 &packet->src_ipaddr.ipaddr,
2100 buffer, sizeof(buffer)),
2101 packet->src_port, packet->id);
2105 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2106 request->num_proxied_responses++; /* needs to be protected by lock */
2108 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2111 * No reply, BUT the current packet fails verification:
2112 * ignore it. This does the MD5 calculations in the
2113 * server core, but I guess we can fix that later.
2115 if (!request->proxy_reply &&
2116 (rad_verify(packet, request->proxy,
2117 request->home_server->secret) != 0)) {
2118 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2123 * The home server sent us a packet which doesn't match
2124 * something we have: ignore it. This is done only to
2125 * catch the case of broken systems.
2127 if (request->proxy_reply &&
2128 (memcmp(request->proxy_reply->vector,
2130 sizeof(request->proxy_reply->vector)) != 0)) {
2131 RDEBUG2("Ignoring conflicting proxy reply");
2135 gettimeofday(&now, NULL);
2138 * Status-Server packets don't count as real packets.
2140 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2141 listen_socket_t *sock = request->proxy_listener->data;
2143 request->home_server->last_packet_recv = now.tv_sec;
2144 sock->last_packet = now.tv_sec;
2148 * If we have previously seen a reply, ignore the
2151 if (request->proxy_reply) {
2152 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2153 inet_ntop(packet->src_ipaddr.af,
2154 &packet->src_ipaddr.ipaddr,
2155 buffer, sizeof(buffer)),
2156 packet->src_port, packet->id);
2161 * Call the state machine to do something useful with the
2164 request->proxy_reply = packet;
2165 packet->timestamp = now;
2166 request->priority = RAD_LISTEN_PROXY;
2169 * We've received a reply. If we hadn't been sending it
2170 * packets for a while, just mark it alive.
2172 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2173 request->home_server->state = HOME_STATE_ALIVE;
2177 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2178 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2180 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2181 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2182 #ifdef WITH_ACCOUNTING
2183 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2184 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2187 #endif /* WITH_STATS */
2191 * When we originate CoA requests, we patch them in here
2192 * so that they don't affect the rest of the state
2195 if (request->parent) {
2196 rad_assert(request->parent->coa == request);
2197 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
2198 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
2199 rad_assert(request->process != NULL);
2200 request_coa_separate(request);
2204 request->process(request, FR_ACTION_PROXY_REPLY);
2210 static int setup_post_proxy_fail(REQUEST *request)
2212 DICT_VALUE const *dval = NULL;
2215 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2216 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2217 "Fail-Authentication");
2219 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2220 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2223 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2224 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2226 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2227 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2230 WDEBUG("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2234 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2237 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2241 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2242 if (!vp) vp = radius_paircreate(request, &request->config_items,
2243 PW_POST_PROXY_TYPE, 0);
2244 vp->vp_integer = dval->value;
2249 STATE_MACHINE_DECL(proxy_running)
2251 TRACE_STATE_MACHINE;
2254 case FR_ACTION_CONFLICTING:
2256 case FR_ACTION_TIMER:
2257 case FR_ACTION_PROXY_REPLY:
2258 request_common(request, action);
2262 request_running(request, action);
2266 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2271 STATE_MACHINE_DECL(request_virtual_server)
2275 TRACE_STATE_MACHINE;
2278 case FR_ACTION_CONFLICTING:
2280 case FR_ACTION_TIMER:
2281 case FR_ACTION_PROXY_REPLY:
2282 request_common(request, action);
2286 old = request->server;
2287 request->server = request->home_server->server;
2288 request_running(request, action);
2289 request->server = old;
2293 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2299 static int request_will_proxy(REQUEST *request)
2301 int rcode, pre_proxy_type = 0;
2302 char const *realmname = NULL;
2303 VALUE_PAIR *vp, *strippedname;
2304 home_server_t *home;
2305 REALM *realm = NULL;
2306 home_pool_t *pool = NULL;
2308 if (!request->root->proxy_requests) return 0;
2309 if (request->packet->dst_port == 0) return 0;
2310 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2311 if (request->in_proxy_hash) return 0;
2314 * FIXME: for 3.0, allow this only for rejects?
2316 if (request->reply->code != 0) return 0;
2318 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2320 realm = realm_find2(vp->vp_strvalue);
2322 REDEBUG2("Cannot proxy to unknown realm %s",
2327 realmname = vp->vp_strvalue;
2330 * Figure out which pool to use.
2332 if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
2333 pool = realm->auth_pool;
2335 #ifdef WITH_ACCOUNTING
2336 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2337 pool = realm->acct_pool;
2341 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2342 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2343 pool = realm->coa_pool;
2353 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2356 switch (request->packet->code) {
2357 case PW_CODE_AUTHENTICATION_REQUEST:
2358 pool_type = HOME_TYPE_AUTH;
2361 #ifdef WITH_ACCOUNTING
2362 case PW_CODE_ACCOUNTING_REQUEST:
2363 pool_type = HOME_TYPE_ACCT;
2368 case PW_CODE_COA_REQUEST:
2369 case PW_CODE_DISCONNECT_REQUEST:
2370 pool_type = HOME_TYPE_COA;
2378 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2382 RWDEBUG2("Cancelling proxy as no home pool exists");
2386 if (request->listener->synchronous) {
2387 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2391 request->home_pool = pool;
2393 home = home_server_ldb(realmname, pool, request);
2395 REDEBUG2("Failed to find live home server: Cancelling proxy");
2398 home_server_update_request(home, request);
2402 * Once we've decided to proxy a request, we cannot send
2403 * a CoA packet. So we free up any CoA packet here.
2405 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2409 * Remember that we sent the request to a Realm.
2411 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2414 * Strip the name, if told to.
2416 * Doing it here catches the case of proxied tunneled
2419 if (realm && (realm->striprealm == true) &&
2420 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2422 * If there's a Stripped-User-Name attribute in
2423 * the request, then use THAT as the User-Name
2424 * for the proxied request, instead of the
2427 * This is done by making a copy of the
2428 * Stripped-User-Name attribute, turning it into
2429 * a User-Name attribute, deleting the
2430 * Stripped-User-Name and User-Name attributes
2431 * from the vps list, and making the new
2432 * User-Name the head of the vps list.
2434 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2437 vp = radius_paircreate(request, NULL,
2439 rad_assert(vp != NULL); /* handled by above function */
2440 /* Insert at the START of the list */
2441 /* FIXME: Can't make assumptions about ordering */
2442 fr_cursor_init(&cursor, &vp);
2443 fr_cursor_insert(&cursor, request->proxy->vps);
2444 request->proxy->vps = vp;
2446 pairstrcpy(vp, strippedname->vp_strvalue);
2449 * Do NOT delete Stripped-User-Name.
2454 * If there is no PW_CHAP_CHALLENGE attribute but
2455 * there is a PW_CHAP_PASSWORD we need to add it
2456 * since we can't use the request authenticator
2457 * anymore - we changed it.
2459 if ((request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) &&
2460 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2461 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2462 vp = radius_paircreate(request, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2463 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2467 * The RFC's say we have to do this, but FreeRADIUS
2470 vp = radius_paircreate(request, &request->proxy->vps, PW_PROXY_STATE, 0);
2471 pairsprintf(vp, "%u", request->packet->id);
2474 * Should be done BEFORE inserting into proxy hash, as
2475 * pre-proxy may use this information, or change it.
2477 request->proxy->code = request->packet->code;
2480 * Call the pre-proxy routines.
2482 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2484 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2485 /* Must be a validation issue */
2487 RDEBUG2(" Found Pre-Proxy-Type %s", dval->name);
2488 pre_proxy_type = vp->vp_integer;
2491 rad_assert(request->home_pool != NULL);
2493 if (request->home_pool->virtual_server) {
2494 char const *old_server = request->server;
2496 request->server = request->home_pool->virtual_server;
2497 RDEBUG2(" server %s {", request->server);
2498 rcode = process_pre_proxy(pre_proxy_type, request);
2500 request->server = old_server;
2502 rcode = process_pre_proxy(pre_proxy_type, request);
2505 case RLM_MODULE_FAIL:
2506 case RLM_MODULE_INVALID:
2507 case RLM_MODULE_NOTFOUND:
2508 case RLM_MODULE_USERLOCK:
2510 /* FIXME: debug print failed stuff */
2513 case RLM_MODULE_REJECT:
2514 case RLM_MODULE_HANDLED:
2518 * Only proxy the packet if the pre-proxy code succeeded.
2520 case RLM_MODULE_NOOP:
2522 case RLM_MODULE_UPDATED:
2529 static int request_proxy(REQUEST *request, int retransmit)
2533 rad_assert(request->parent == NULL);
2534 rad_assert(request->home_server != NULL);
2536 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2540 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2541 request_done(request->coa, FR_ACTION_DONE);
2546 * The request may be sent to a virtual server. If we're
2547 * in a child thread, just process it here. If we're the
2548 * master, push it back onto the queue for later
2551 if (request->home_server->server) {
2552 DEBUG("Proxying to virtual server %s",
2553 request->home_server->server);
2555 if (!we_are_master()) {
2556 request_virtual_server(request, FR_ACTION_RUN);
2561 request_queue_or_run(request, request_virtual_server);
2566 * We're actually sending a proxied packet. Do that now.
2568 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2569 EDEBUG("Failed to insert request into the proxy list.");
2573 rad_assert(request->proxy->id >= 0);
2576 if (request->home_server->tls) {
2577 RDEBUG2("Proxying request to home server %s port %d (TLS)",
2578 inet_ntop(request->proxy->dst_ipaddr.af,
2579 &request->proxy->dst_ipaddr.ipaddr,
2580 buffer, sizeof(buffer)),
2581 request->proxy->dst_port);
2584 RDEBUG2("Proxying request to home server %s port %d",
2585 inet_ntop(request->proxy->dst_ipaddr.af,
2586 &request->proxy->dst_ipaddr.ipaddr,
2587 buffer, sizeof(buffer)),
2588 request->proxy->dst_port);
2590 DEBUG_PACKET(request, request->proxy, 1);
2592 gettimeofday(&request->proxy_retransmit, NULL);
2594 request->proxy->timestamp = request->proxy_retransmit;
2595 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2598 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2600 request->child_state = REQUEST_PROXIED;
2601 request->proxy_listener->send(request->proxy_listener,
2607 * Proxy the packet as if it was new.
2609 static int request_proxy_anew(REQUEST *request)
2611 home_server_t *home;
2614 * Delete the request from the proxy list.
2616 * The packet list code takes care of ensuring that IDs
2617 * aren't reused until all 256 IDs have been used. So
2618 * there's a 1/256 chance of re-using the same ID when
2619 * we're sending to the same home server. Which is
2622 remove_from_proxy_hash(request);
2625 * Find a live home server for the request.
2627 home = home_server_ldb(NULL, request->home_pool, request);
2629 REDEBUG2("Failed to find live home server for request");
2631 if (setup_post_proxy_fail(request)) {
2632 request_queue_or_run(request, proxy_running);
2634 gettimeofday(&request->reply->timestamp, NULL);
2635 request_cleanup_delay_init(request, NULL);
2639 home_server_update_request(home, request);
2641 if (!insert_into_proxy_hash(request)) {
2642 RPROXY("Failed to insert retransmission into the proxy list.");
2643 goto post_proxy_fail;
2647 * Free the old packet, to force re-encoding
2649 talloc_free(request->proxy->data);
2650 request->proxy->data = NULL;
2651 request->proxy->data_len = 0;
2653 #ifdef WITH_ACCOUNTING
2655 * Update the Acct-Delay-Time attribute.
2657 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2660 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2661 if (!vp) vp = radius_paircreate(request,
2662 &request->proxy->vps,
2663 PW_ACCT_DELAY_TIME, 0);
2667 gettimeofday(&now, NULL);
2668 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2673 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2678 STATE_MACHINE_DECL(request_ping)
2680 home_server_t *home = request->home_server;
2683 TRACE_STATE_MACHINE;
2687 case FR_ACTION_TIMER:
2688 ERROR("No response to status check %d for home server %s port %d",
2690 inet_ntop(request->proxy->dst_ipaddr.af,
2691 &request->proxy->dst_ipaddr.ipaddr,
2692 buffer, sizeof(buffer)),
2693 request->proxy->dst_port);
2696 case FR_ACTION_PROXY_REPLY:
2697 rad_assert(request->in_proxy_hash);
2699 request->home_server->num_received_pings++;
2700 RPROXY("Received response to status check %d (%d in current sequence)",
2701 request->number, home->num_received_pings);
2704 * Remove the request from any hashes
2706 fr_event_delete(el, &request->ev);
2707 remove_from_proxy_hash(request);
2710 * The control socket may have marked the home server as
2711 * alive. OR, it may have suddenly started responding to
2712 * requests again. If so, don't re-do the "make alive"
2715 if (home->state == HOME_STATE_ALIVE) break;
2718 * It's dead, and we haven't received enough ping
2719 * responses to mark it "alive". Wait a bit.
2721 * If it's zombie, we mark it alive immediately.
2723 if ((home->state == HOME_STATE_IS_DEAD) &&
2724 (home->num_received_pings < home->num_pings_to_alive)) {
2729 * Mark it alive and delete any outstanding
2732 home->state = HOME_STATE_ALIVE;
2733 exec_trigger(request, home->cs, "home_server.alive", false);
2734 home->currently_outstanding = 0;
2735 home->num_sent_pings = 0;
2736 home->num_received_pings = 0;
2737 gettimeofday(&home->revive_time, NULL);
2739 fr_event_delete(el, &home->ev);
2741 RPROXY("Marking home server %s port %d alive",
2742 inet_ntop(request->proxy->dst_ipaddr.af,
2743 &request->proxy->dst_ipaddr.ipaddr,
2744 buffer, sizeof(buffer)),
2745 request->proxy->dst_port);
2749 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2753 rad_assert(!request->in_request_hash);
2754 rad_assert(request->ev == NULL);
2755 request_done(request, FR_ACTION_DONE);
2759 * Called from start of zombie period, OR after control socket
2760 * marks the home server dead.
2762 static void ping_home_server(void *ctx)
2764 home_server_t *home = ctx;
2767 struct timeval when, now;
2769 if ((home->state == HOME_STATE_ALIVE) ||
2770 (home->ping_check == HOME_PING_CHECK_NONE) ||
2772 (home->proto == IPPROTO_TCP) ||
2774 (home->ev != NULL)) {
2778 gettimeofday(&now, NULL);
2780 if (home->state == HOME_STATE_ZOMBIE) {
2781 when = home->zombie_period_start;
2782 when.tv_sec += home->zombie_period;
2784 if (timercmp(&when, &now, <)) {
2785 DEBUG("PING: Zombie period is over for home server %s",
2787 mark_home_server_dead(home, &now);
2791 request = request_alloc(NULL);
2792 request->number = request_num_counter++;
2795 request->proxy = rad_alloc(request, 1);
2796 rad_assert(request->proxy != NULL);
2798 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2799 request->proxy->code = PW_CODE_STATUS_SERVER;
2801 pairmake(request->proxy, &request->proxy->vps,
2802 "Message-Authenticator", "0x00", T_OP_SET);
2804 } else if (home->type == HOME_TYPE_AUTH) {
2805 request->proxy->code = PW_CODE_AUTHENTICATION_REQUEST;
2807 pairmake(request->proxy, &request->proxy->vps,
2808 "User-Name", home->ping_user_name, T_OP_SET);
2809 pairmake(request->proxy, &request->proxy->vps,
2810 "User-Password", home->ping_user_password, T_OP_SET);
2811 pairmake(request->proxy, &request->proxy->vps,
2812 "Service-Type", "Authenticate-Only", T_OP_SET);
2813 pairmake(request->proxy, &request->proxy->vps,
2814 "Message-Authenticator", "0x00", T_OP_SET);
2817 #ifdef WITH_ACCOUNTING
2818 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
2820 pairmake(request->proxy, &request->proxy->vps,
2821 "User-Name", home->ping_user_name, T_OP_SET);
2822 pairmake(request->proxy, &request->proxy->vps,
2823 "Acct-Status-Type", "Stop", T_OP_SET);
2824 pairmake(request->proxy, &request->proxy->vps,
2825 "Acct-Session-Id", "00000000", T_OP_SET);
2826 vp = pairmake(request->proxy, &request->proxy->vps,
2827 "Event-Timestamp", "0", T_OP_SET);
2828 vp->vp_date = now.tv_sec;
2830 rad_assert("Internal sanity check failed");
2834 vp = pairmake(request->proxy, &request->proxy->vps,
2835 "NAS-Identifier", "", T_OP_SET);
2837 pairsprintf(vp, "Status Check %u. Are you alive?",
2838 home->num_sent_pings);
2841 request->proxy->src_ipaddr = home->src_ipaddr;
2842 request->proxy->dst_ipaddr = home->ipaddr;
2843 request->proxy->dst_port = home->port;
2844 request->home_server = home;
2845 #ifdef DEBUG_STATE_MACHINE
2846 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
2847 child_state_names[request->child_state],
2848 child_state_names[REQUEST_DONE]);
2849 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2851 #ifdef HAVE_PTHREAD_H
2852 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2854 request->child_state = REQUEST_DONE;
2855 request->process = request_ping;
2857 rad_assert(request->proxy_listener == NULL);
2859 if (!insert_into_proxy_hash(request)) {
2860 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
2863 rad_assert(!request->in_request_hash);
2864 rad_assert(!request->in_proxy_hash);
2865 rad_assert(request->ev == NULL);
2866 request_free(&request);
2871 * Set up the timer callback.
2874 when.tv_sec += home->ping_timeout;
2876 DEBUG("PING: Waiting %u seconds for response to ping",
2877 home->ping_timeout);
2879 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2880 home->num_sent_pings++;
2882 rad_assert(request->proxy_listener != NULL);
2883 request->proxy_listener->send(request->proxy_listener,
2887 * Add +/- 2s of jitter, as suggested in RFC 3539
2888 * and in the Issues and Fixes draft.
2891 home->when.tv_sec += home->ping_interval;
2893 add_jitter(&home->when);
2895 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
2896 INSERT_EVENT(ping_home_server, home);
2899 static void home_trigger(home_server_t *home, char const *trigger)
2902 RADIUS_PACKET my_packet;
2904 memset(&my_request, 0, sizeof(my_request));
2905 memset(&my_packet, 0, sizeof(my_packet));
2906 my_request.proxy = &my_packet;
2907 my_packet.dst_ipaddr = home->ipaddr;
2908 my_packet.src_ipaddr = home->src_ipaddr;
2910 exec_trigger(&my_request, home->cs, trigger, false);
2913 static void mark_home_server_zombie(home_server_t *home, struct timeval *now)
2920 rad_assert((home->state == HOME_STATE_ALIVE) ||
2921 (home->state == HOME_STATE_UNKNOWN));
2924 if (home->proto == IPPROTO_TCP) {
2925 WDEBUG("Not marking TCP server %s zombie", home->name);
2931 * We've received a real packet recently. Don't mark the
2932 * server as zombie until we've received NO packets for a
2933 * while. The "1/4" of zombie period was chosen rather
2934 * arbitrarily. It's a balance between too short, which
2935 * gives quick fail-over and fail-back, or too long,
2936 * where the proxy still sends packets to an unresponsive
2939 start = now->tv_sec - ((home->zombie_period + 3) / 4);
2940 if (home->last_packet_recv >= start) {
2941 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
2942 (int) (now->tv_sec - home->last_packet_recv));
2946 home->state = HOME_STATE_ZOMBIE;
2947 home_trigger(home, "home_server.zombie");
2950 * Set the home server to "zombie", as of the time
2953 home->zombie_period_start.tv_sec = start;
2954 home->zombie_period_start.tv_usec = USEC / 2;
2956 fr_event_delete(el, &home->ev);
2957 home->num_sent_pings = 0;
2958 home->num_received_pings = 0;
2960 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d seconds).",
2961 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2962 buffer, sizeof(buffer)),
2963 home->port, home->response_window);
2965 ping_home_server(home);
2969 void revive_home_server(void *ctx)
2971 home_server_t *home = ctx;
2975 rad_assert(home->proto != IPPROTO_TCP);
2978 home->state = HOME_STATE_ALIVE;
2979 home_trigger(home, "home_server.alive");
2980 home->currently_outstanding = 0;
2981 gettimeofday(&home->revive_time, NULL);
2984 * Delete any outstanding events.
2986 if (home->ev) fr_event_delete(el, &home->ev);
2988 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
2989 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2990 buffer, sizeof(buffer)),
2994 void mark_home_server_dead(home_server_t *home, struct timeval *when)
2996 int previous_state = home->state;
3000 if (home->proto == IPPROTO_TCP) {
3001 WDEBUG("Not marking TCP server dead");
3006 PROXY( "Marking home server %s port %d as dead.",
3007 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3008 buffer, sizeof(buffer)),
3011 home->state = HOME_STATE_IS_DEAD;
3012 home_trigger(home, "home_server.dead");
3014 if (home->ping_check != HOME_PING_CHECK_NONE) {
3016 * If the control socket marks us dead, start
3017 * pinging. Otherwise, we already started
3018 * pinging when it was marked "zombie".
3020 if (previous_state == HOME_STATE_ALIVE) {
3021 ping_home_server(home);
3023 DEBUG("PING: Already pinging home server %s",
3029 * Revive it after a fixed period of time. This
3030 * is very, very, bad.
3033 home->when.tv_sec += home->revive_interval;
3035 DEBUG("PING: Reviving home server %s in %u seconds",
3036 home->name, home->revive_interval);
3037 INSERT_EVENT(revive_home_server, home);
3041 STATE_MACHINE_DECL(proxy_wait_for_reply)
3043 struct timeval now, when;
3044 home_server_t *home = request->home_server;
3047 TRACE_STATE_MACHINE;
3049 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3050 rad_assert(request->home_server != NULL);
3052 if (request->master_state == REQUEST_STOP_PROCESSING) {
3053 request->child_state = REQUEST_DONE;
3057 gettimeofday(&now, NULL);
3061 if (request->proxy_reply) return;
3063 if ((home->state == HOME_STATE_IS_DEAD) ||
3064 !request->proxy_listener ||
3065 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3066 request_proxy_anew(request);
3071 if (home->proto == IPPROTO_TCP) {
3072 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3073 inet_ntop(request->proxy->dst_ipaddr.af,
3074 &request->proxy->dst_ipaddr.ipaddr,
3075 buffer, sizeof(buffer)),
3076 request->proxy->dst_port,
3077 request->proxy->id);
3083 * More than one retransmit a second is stupid,
3084 * and should be suppressed by the proxy.
3086 when = request->proxy_retransmit;
3089 if (timercmp(&now, &when, <)) {
3090 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3091 inet_ntop(request->proxy->dst_ipaddr.af,
3092 &request->proxy->dst_ipaddr.ipaddr,
3093 buffer, sizeof(buffer)),
3094 request->proxy->dst_port,
3095 request->proxy->id);
3099 #ifdef WITH_ACCOUNTING
3101 * If we update the Acct-Delay-Time, we need to
3104 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3105 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3106 request_proxy_anew(request);
3111 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3112 inet_ntop(request->proxy->dst_ipaddr.af,
3113 &request->proxy->dst_ipaddr.ipaddr,
3114 buffer, sizeof(buffer)),
3115 request->proxy->dst_port,
3116 request->proxy->id);
3117 request->num_proxied_requests++;
3119 rad_assert(request->proxy_listener != NULL);;
3120 DEBUG_PACKET(request, request->proxy, 1);
3121 FR_STATS_TYPE_INC(home->stats.total_requests);
3122 home->last_packet_sent = now.tv_sec;
3123 request->proxy_retransmit = now;
3124 request->proxy_listener->send(request->proxy_listener,
3128 case FR_ACTION_TIMER:
3130 if (!request->proxy_listener ||
3131 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3132 remove_from_proxy_hash(request);
3134 when = request->packet->timestamp;
3135 when.tv_sec += request->root->max_request_time;
3137 if (timercmp(&when, &now, >)) {
3138 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3139 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3146 * Wake up "response_window" time in the future.
3147 * i.e. when MY packet hasn't received a response.
3149 * Note that we DO NOT mark the home server as
3150 * zombie if it doesn't respond to us. It may be
3151 * responding to other (better looking) packets.
3153 when = request->proxy->timestamp;
3154 when.tv_sec += home->response_window;
3157 * Not at the response window. Set the timer for
3160 if (timercmp(&when, &now, >)) {
3161 RDEBUG("Expecting proxy response no later than %d seconds from now", home->response_window);
3162 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3167 RDEBUG("No proxy response, giving up on request and marking it done");
3170 * If we haven't received any packets for
3171 * "response_window", then mark the home server
3174 * If the connection is TCP, then another
3175 * "watchdog timer" function takes care of pings,
3176 * etc. So we don't need to do it here.
3178 * This check should really be part of a home
3179 * server state machine.
3181 if (((home->state == HOME_STATE_ALIVE) ||
3182 (home->state == HOME_STATE_UNKNOWN))
3184 && (home->proto != IPPROTO_TCP)
3187 mark_home_server_zombie(home, &now);
3190 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3191 if (home->type == HOME_TYPE_AUTH) {
3192 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3193 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3196 else if (home->type == HOME_TYPE_ACCT) {
3197 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3198 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3203 * There was no response within the window. Stop
3204 * the request. If the client retransmitted, it
3205 * may have failed over to another home server.
3206 * But that one may be dead, too.
3208 RERROR("Failing request - proxy ID %u, due to lack of any response from home server %s port %d",
3210 inet_ntop(request->proxy->dst_ipaddr.af,
3211 &request->proxy->dst_ipaddr.ipaddr,
3212 buffer, sizeof(buffer)),
3213 request->proxy->dst_port);
3215 if (!setup_post_proxy_fail(request)) {
3216 gettimeofday(&request->reply->timestamp, NULL);
3217 request_cleanup_delay_init(request, NULL);
3223 * Duplicate proxy replies have been quenched by
3224 * now. This state is only called ONCE, when we
3225 * receive a new reply from the home server.
3227 case FR_ACTION_PROXY_REPLY:
3228 request_queue_or_run(request, proxy_running);
3231 case FR_ACTION_CONFLICTING:
3232 request_done(request, action);
3236 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3240 #endif /* WITH_PROXY */
3242 /***********************************************************************
3246 ***********************************************************************/
3248 static int null_handler(UNUSED REQUEST *request)
3254 * See if we need to originate a CoA request.
3256 static void request_coa_originate(REQUEST *request)
3258 int rcode, pre_proxy_type = 0;
3264 rad_assert(request != NULL);
3265 rad_assert(request->coa != NULL);
3266 rad_assert(request->proxy == NULL);
3267 rad_assert(!request->in_proxy_hash);
3268 rad_assert(request->proxy_reply == NULL);
3271 * Check whether we want to originate one, or cancel one.
3273 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3275 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3279 if (vp->vp_integer == 0) {
3281 request_free(&request->coa);
3289 * src_ipaddr will be set up in proxy_encode.
3291 memset(&ipaddr, 0, sizeof(ipaddr));
3292 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3294 ipaddr.af = AF_INET;
3295 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3297 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3298 ipaddr.af = AF_INET6;
3299 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3301 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3302 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3304 if (!coa->home_pool) {
3305 RWDEBUG2("No such home_server_pool %s",
3311 * Prefer the pool to one server
3313 } else if (request->client->coa_pool) {
3314 coa->home_pool = request->client->coa_pool;
3316 } else if (request->client->coa_server) {
3317 coa->home_server = request->client->coa_server;
3321 * If all else fails, send it to the client that
3322 * originated this request.
3324 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3328 * Use the pool, if it exists.
3330 if (coa->home_pool) {
3331 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3332 if (!coa->home_server) {
3333 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3336 home_server_update_request(coa->home_server, coa);
3338 } else if (!coa->home_server) {
3339 int port = PW_COA_UDP_PORT;
3341 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3342 if (vp) port = vp->vp_integer;
3344 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3345 if (!coa->home_server) {
3346 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3347 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3348 buffer, sizeof(buffer)), port);
3353 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3355 switch (vp->vp_integer) {
3356 case PW_CODE_COA_REQUEST:
3357 case PW_CODE_DISCONNECT_REQUEST:
3358 coa->proxy->code = vp->vp_integer;
3362 DEBUG("Cannot set CoA Packet-Type to code %d",
3368 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3371 * The rest of the server code assumes that
3372 * request->packet && request->reply exist. Copy them
3373 * from the original request.
3375 rad_assert(coa->packet != NULL);
3376 rad_assert(coa->packet->vps == NULL);
3378 coa->packet = rad_copy_packet(coa, request->packet);
3379 coa->reply = rad_copy_packet(coa, request->reply);
3381 coa->config_items = paircopy(coa, request->config_items);
3382 coa->num_coa_requests = 0;
3383 coa->handle = null_handler;
3384 coa->number = request->number; /* it's associated with the same request */
3387 * Call the pre-proxy routines.
3389 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3391 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3392 /* Must be a validation issue */
3394 RDEBUG2(" Found Pre-Proxy-Type %s", dval->name);
3395 pre_proxy_type = vp->vp_integer;
3398 if (coa->home_pool && coa->home_pool->virtual_server) {
3399 char const *old_server = coa->server;
3401 coa->server = coa->home_pool->virtual_server;
3402 RDEBUG2(" server %s {", coa->server);
3403 rcode = process_pre_proxy(pre_proxy_type, coa);
3405 coa->server = old_server;
3407 rcode = process_pre_proxy(pre_proxy_type, coa);
3414 * Only send the CoA packet if the pre-proxy code succeeded.
3416 case RLM_MODULE_NOOP:
3418 case RLM_MODULE_UPDATED:
3423 * Source IP / port is set when the proxy socket
3426 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3427 coa->proxy->dst_port = coa->home_server->port;
3429 if (!insert_into_proxy_hash(coa)) {
3430 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list.");
3435 * We CANNOT divorce the CoA request from the parent
3436 * request. This function is running in a child thread,
3437 * and we need access to the main event loop in order to
3438 * to add the timers for the CoA packet.
3440 * Instead, we wait for the timer on the parent request
3443 gettimeofday(&coa->proxy->timestamp, NULL);
3444 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3445 coa->delay = 0; /* need to calculate a new delay */
3447 DEBUG_PACKET(coa, coa->proxy, 1);
3449 coa->process = coa_wait_for_reply;
3450 #ifdef DEBUG_STATE_MACHINE
3451 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3452 child_state_names[request->child_state],
3453 child_state_names[REQUEST_RUNNING]);
3455 coa->child_state = REQUEST_PROXIED;
3456 rad_assert(coa->proxy_reply == NULL);
3457 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3458 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3459 coa->proxy_listener->send(coa->proxy_listener, coa);
3463 static void coa_timer(REQUEST *request)
3466 struct timeval now, when, mrd;
3468 rad_assert(request->parent == NULL);
3470 if (request->proxy_reply) return request_process_timer(request);
3472 gettimeofday(&now, NULL);
3474 if (request->delay == 0) {
3476 * Implement re-transmit algorithm as per RFC 5080
3479 * We want IRT + RAND*IRT
3480 * or 0.9 IRT + rand(0,.2) IRT
3482 * 2^20 ~ USEC, and we want 2.
3483 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3485 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3486 request->delay = delay * request->home_server->coa_irt;
3487 delay = request->home_server->coa_irt * USEC;
3488 delay -= delay / 10;
3489 delay += request->delay;
3490 request->delay = delay;
3492 when = request->proxy->timestamp;
3493 tv_add(&when, delay);
3495 if (timercmp(&when, &now, >)) {
3496 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3502 * Retransmit CoA request.
3506 * Cap count at MRC, if it is non-zero.
3508 if (request->home_server->coa_mrc &&
3509 (request->num_coa_requests >= request->home_server->coa_mrc)) {
3510 if (!setup_post_proxy_fail(request)) {
3514 request_queue_or_run(request, coa_running);
3519 * RFC 5080 Section 2.2.1
3521 * RT = 2*RTprev + RAND*RTprev
3522 * = 1.9 * RTprev + rand(0,.2) * RTprev
3523 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3526 delay ^= (delay >> 16);
3528 frac = request->delay / 5;
3529 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3531 delay += (2 * request->delay) - (request->delay / 10);
3534 * Cap delay at MRT, if MRT is non-zero.
3536 if (request->home_server->coa_mrt &&
3537 (delay > (request->home_server->coa_mrt * USEC))) {
3538 int mrt_usec = request->home_server->coa_mrt * USEC;
3541 * delay = MRT + RAND * MRT
3542 * = 0.9 MRT + rand(0,.2) * MRT
3545 delay ^= (delay >> 15);
3547 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3548 delay += mrt_usec - (mrt_usec / 10);
3551 request->delay = delay;
3553 tv_add(&when, request->delay);
3554 mrd = request->proxy->timestamp;
3555 mrd.tv_sec += request->home_server->coa_mrd;
3558 * Cap duration at MRD.
3560 if (timercmp(&mrd, &when, <)) {
3563 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3565 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3567 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3570 * Status servers don't count as real packets sent.
3572 request->proxy_listener->send(request->proxy_listener,
3576 STATE_MACHINE_DECL(coa_wait_for_reply)
3578 rad_assert(request->parent == NULL);
3580 TRACE_STATE_MACHINE;
3583 case FR_ACTION_TIMER:
3585 * This is big enough to be in it's own function.
3590 case FR_ACTION_PROXY_REPLY:
3591 rad_assert(request->parent == NULL);
3592 #ifdef HAVE_PTHREAD_H
3594 * Catch the case of a proxy reply when called
3595 * from the main worker thread.
3597 if (we_are_master()) {
3598 request_queue_or_run(request, coa_running);
3604 request_running(request, action);
3608 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3613 static void request_coa_separate(REQUEST *request)
3615 #ifdef DEBUG_STATE_MACHINE
3616 int action = FR_ACTION_TIMER;
3618 TRACE_STATE_MACHINE;
3620 rad_assert(request->parent != NULL);
3621 rad_assert(request->parent->coa == request);
3622 rad_assert(request->ev == NULL);
3623 rad_assert(!request->in_request_hash);
3625 rad_assert(request->proxy_listener != NULL);
3627 (void) talloc_steal(NULL, request);
3628 request->parent->coa = NULL;
3629 request->parent = NULL;
3632 * Should be coa_wait_for_reply()
3634 request->process(request, FR_ACTION_TIMER);
3637 STATE_MACHINE_DECL(coa_running)
3639 TRACE_STATE_MACHINE;
3642 case FR_ACTION_TIMER:
3643 request_process_timer(request);
3646 case FR_ACTION_PROXY_REPLY:
3647 request_common(request, action);
3651 request_running(request, FR_ACTION_PROXY_REPLY);
3655 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3659 #endif /* WITH_COA */
3661 /***********************************************************************
3663 * End of the State machine. Start of additional helper code.
3665 ***********************************************************************/
3667 /***********************************************************************
3671 ***********************************************************************/
3672 static void event_socket_handler(UNUSED fr_event_list_t *xel, UNUSED int fd, void *ctx)
3674 rad_listen_t *listener = ctx;
3676 rad_assert(xel == el);
3680 (listener->type != RAD_LISTEN_DETAIL) &&
3682 (listener->fd < 0)) {
3685 listener->print(listener, buffer, sizeof(buffer));
3686 ERROR("FATAL: Asked to read from closed socket: %s",
3689 rad_panic("Socket was closed on us!");
3693 listener->recv(listener);
3698 * This function is called periodically to see if this detail
3699 * file is available for reading.
3701 static void event_poll_detail(void *ctx)
3704 rad_listen_t *this = ctx;
3705 struct timeval when, now;
3706 listen_detail_t *detail = this->data;
3708 rad_assert(this->type == RAD_LISTEN_DETAIL);
3711 event_socket_handler(el, this->fd, this);
3713 fr_event_now(el, &now);
3717 * Backdoor API to get the delay until the next poll
3720 delay = this->encode(this, NULL);
3721 if (delay == 0) goto redo;
3723 tv_add(&when, delay);
3725 if (!fr_event_insert(el, event_poll_detail, this,
3726 &when, &detail->ev)) {
3727 ERROR("Failed creating handler");
3733 static void event_status(struct timeval *wake)
3735 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3739 if (debug_flag == 0) {
3741 INFO("Ready to process requests.");
3742 just_started = false;
3748 INFO("Ready to process requests.");
3750 } else if ((wake->tv_sec != 0) ||
3751 (wake->tv_usec >= 100000)) {
3752 DEBUG("Waking up in %d.%01u seconds.",
3753 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3758 * FIXME: Put this somewhere else, where it isn't called
3759 * all of the time...
3762 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3764 * If there are no child threads, then there may
3765 * be child processes. In that case, wait for
3766 * their exit status, and throw that exit status
3767 * away. This helps get rid of zxombie children.
3769 while (waitpid(-1, &argval, WNOHANG) > 0) {
3777 static void listener_free_cb(void *ctx)
3779 rad_listen_t *this = ctx;
3782 if (this->count > 0) {
3783 struct timeval when;
3784 listen_socket_t *sock = this->data;
3786 fr_event_now(el, &when);
3789 if (!fr_event_insert(el, listener_free_cb, this, &when,
3791 rad_panic("Failed to insert event");
3798 * It's all free, close the socket.
3801 this->print(this, buffer, sizeof(buffer));
3802 DEBUG("... cleaning up socket %s", buffer);
3808 static int proxy_eol_cb(void *ctx, void *data)
3810 struct timeval when;
3811 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3813 if (request->proxy_listener != ctx) return 0;
3816 * We don't care if it's being processed in a child thread.
3819 #ifdef WITH_ACCOUNTING
3821 * Accounting packets should be deleted immediately.
3822 * They will never be retransmitted by the client.
3824 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
3825 RDEBUG("Stopping request due to failed connection to home server");
3826 request->master_state = REQUEST_STOP_PROCESSING;
3831 * Reset the timer to be now, so that the request is
3832 * quickly updated. But spread the requests randomly
3833 * over the next second, so that we don't overload the
3836 fr_event_now(el, &when);
3837 tv_add(&when, fr_rand() % USEC);
3838 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3841 * Don't delete it from the list.
3847 int event_new_fd(rad_listen_t *this)
3851 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
3853 this->print(this, buffer, sizeof(buffer));
3855 if (this->status == RAD_LISTEN_STATUS_INIT) {
3856 listen_socket_t *sock = this->data;
3859 DEBUG("Listening on %s", buffer);
3861 INFO(" ... adding new socket %s", buffer);
3866 * Add it to the list of sockets we can use.
3867 * Server sockets (i.e. auth/acct) are never
3868 * added to the packet list.
3870 if (this->type == RAD_LISTEN_PROXY) {
3871 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3872 if (!fr_packet_list_socket_add(proxy_list, this->fd,
3874 &sock->other_ipaddr, sock->other_port,
3877 #ifdef HAVE_PTHREAD_H
3878 proxy_no_new_sockets = true;
3880 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3883 * This is bad. However, the
3884 * packet list now supports 256
3885 * open sockets, which should
3886 * minimize this problem.
3888 ERROR("Failed adding proxy socket: %s",
3894 sock->home->limit.num_connections++;
3896 #ifdef HAVE_PTHREAD_H
3898 * If necessary, add it to the list of
3899 * new proxy listeners.
3901 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3902 this->next = proxy_listener_list;
3903 proxy_listener_list = this;
3907 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3910 * Tell the main thread that we've added
3911 * a proxy listener, but only if we need
3912 * to update the event list. Do this
3913 * with the mutex unlocked, to reduce
3917 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3918 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3926 * Detail files are always known, and aren't
3927 * put into the socket event loop.
3929 if (this->type == RAD_LISTEN_DETAIL) {
3930 this->status = RAD_LISTEN_STATUS_KNOWN;
3933 * Set up the first poll interval.
3935 event_poll_detail(this);
3942 * Add timers to child sockets, if necessary.
3944 if (sock->proto == IPPROTO_TCP && sock->opened &&
3945 (sock->limit.lifetime || sock->limit.idle_timeout)) {
3946 struct timeval when;
3950 when.tv_sec = sock->opened + 1;
3953 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3955 rad_panic("Failed to insert event");
3960 FD_MUTEX_LOCK(&fd_mutex);
3961 if (!fr_event_fd_insert(el, 0, this->fd,
3962 event_socket_handler, this)) {
3963 ERROR("Failed adding event handler for socket!");
3966 FD_MUTEX_UNLOCK(&fd_mutex);
3968 this->status = RAD_LISTEN_STATUS_KNOWN;
3974 * Stop using this socket, if at all possible.
3976 if (this->status == RAD_LISTEN_STATUS_EOL) {
3978 * Remove it from the list of live FD's.
3980 FD_MUTEX_LOCK(&fd_mutex);
3981 fr_event_fd_delete(el, 0, this->fd);
3982 FD_MUTEX_UNLOCK(&fd_mutex);
3986 * Proxy sockets get frozen, so that we don't use
3987 * them for new requests. But we do keep them
3988 * open to listen for replies to requests we had
3991 if (this->type == RAD_LISTEN_PROXY) {
3992 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3993 if (!fr_packet_list_socket_freeze(proxy_list,
3995 ERROR("Fatal error freezing socket: %s", fr_strerror());
3999 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4000 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4005 * Requests are still using the socket. Wait for
4008 if (this->count > 0) {
4009 struct timeval when;
4010 listen_socket_t *sock = this->data;
4013 * Try again to clean up the socket in 30
4016 gettimeofday(&when, NULL);
4019 if (!fr_event_insert(el,
4020 (fr_event_callback_t) event_new_fd,
4021 this, &when, &sock->ev)) {
4022 rad_panic("Failed to insert event");
4029 * No one is using the socket. We can remove it now.
4031 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4032 } /* socket is at EOL */
4038 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4041 listen_socket_t *sock = this->data;
4043 struct timeval when;
4046 * Re-open the socket, pointing it to /dev/null.
4047 * This means that all writes proceed without
4048 * blocking, and all reads return "no data".
4050 * This leaves the socket active, so any child
4051 * threads won't go insane. But it means that
4052 * they cannot send or receive any packets.
4054 * This is EXTRA work in the normal case, when
4055 * sockets are closed without error. But it lets
4056 * us have one simple processing method for all
4059 devnull = open("/dev/null", O_RDWR);
4061 ERROR("FATAL failure opening /dev/null: %s",
4062 fr_syserror(errno));
4065 if (dup2(devnull, this->fd) < 0) {
4066 ERROR("FATAL failure closing socket: %s",
4067 fr_syserror(errno));
4073 rad_assert(this->type != RAD_LISTEN_DETAIL);
4077 INFO(" ... shutting down socket %s", buffer);
4081 * The socket is dead. Force all proxied packets
4082 * to stop using it. And then remove it from the
4083 * list of outgoing sockets.
4085 if (this->type == RAD_LISTEN_PROXY) {
4086 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4087 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4089 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4090 ERROR("Fatal error removing socket %s: %s",
4091 buffer, fr_strerror());
4094 if (sock->home && sock->home->limit.num_connections) {
4095 sock->home->limit.num_connections--;
4097 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4102 * EOL all requests using this socket.
4104 fr_packet_list_walk(pl, this, eol_listener);
4108 * No child threads, clean it up now.
4111 if (sock->ev) fr_event_delete(el, &sock->ev);
4117 * Wait until all requests using this socket are done.
4119 gettimeofday(&when, NULL);
4122 if (!fr_event_insert(el, listener_free_cb, this, &when,
4124 rad_panic("Failed to insert event");
4127 #endif /* WITH_TCP */
4132 /***********************************************************************
4136 ***********************************************************************/
4138 static void handle_signal_self(int flag)
4140 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4141 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4142 INFO("Signalled to exit");
4143 fr_event_loop_exit(el, 1);
4145 INFO("Signalled to terminate");
4146 exec_trigger(NULL, NULL, "server.signal.term", true);
4147 fr_event_loop_exit(el, 2);
4151 } /* else exit/term flags weren't set */
4154 * Tell the even loop to stop processing.
4156 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4158 static time_t last_hup = 0;
4161 if ((int) (when - last_hup) < 5) {
4162 INFO("Ignoring HUP (less than 5s since last one)");
4166 INFO("Received HUP signal.");
4170 exec_trigger(NULL, NULL, "server.signal.hup", true);
4171 fr_event_loop_exit(el, 0x80);
4175 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4179 * FIXME: O(N) loops suck.
4181 for (this = mainconfig.listen;
4183 this = this->next) {
4184 if (this->type != RAD_LISTEN_DETAIL) continue;
4187 * This one didn't send the signal, skip
4190 if (!this->decode(this, NULL)) continue;
4193 * Go service the interrupt.
4195 event_poll_detail(this);
4202 #ifdef HAVE_PTHREAD_H
4204 * Add event handlers for idle timeouts && maximum lifetime.
4206 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4207 struct timeval when, now;
4209 fr_event_now(el, &now);
4211 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4213 while (proxy_listener_list) {
4214 rad_listen_t *this = proxy_listener_list;
4215 listen_socket_t *sock = this->data;
4217 rad_assert(sock->proto == IPPROTO_TCP);
4218 proxy_listener_list = this->next;
4221 if (!sock->home) continue; /* skip UDP sockets */
4226 * Sockets should only be added to the
4227 * proxy_listener_list if they have limits.
4230 rad_assert(sock->home->limit.lifetime || sock->home->limit.idle_timeout);
4232 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4234 rad_panic("Failed to insert event");
4238 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4240 #endif /* HAVE_PTHREAD_H */
4241 #endif /* WITH_PROXY */
4242 #endif /* WITH_TCP */
4245 #ifndef WITH_SELF_PIPE
4246 void radius_signal_self(int flag)
4248 handle_signal_self(flag);
4252 * Inform ourselves that we received a signal.
4254 void radius_signal_self(int flag)
4260 * The read MUST be non-blocking for this to work.
4262 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4266 for (i = 0; i < rcode; i++) {
4267 buffer[0] |= buffer[i];
4275 write(self_pipe[1], buffer, 1);
4279 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4280 UNUSED int fd, UNUSED void *ctx)
4285 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4286 if (rcode <= 0) return;
4289 * Merge pending signals.
4291 for (i = 0; i < rcode; i++) {
4292 buffer[0] |= buffer[i];
4295 handle_signal_self(buffer[0]);
4299 /***********************************************************************
4301 * Bootstrapping code.
4303 ***********************************************************************/
4306 * Externally-visibly functions.
4308 int radius_event_init(TALLOC_CTX *ctx) {
4309 el = fr_event_list_create(ctx, event_status);
4315 int radius_event_start(CONF_SECTION *cs, bool have_children)
4317 rad_listen_t *head = NULL;
4319 if (fr_start_time != (time_t)-1) return 0;
4321 time(&fr_start_time);
4324 * radius_event_init() must be called first
4327 if (fr_start_time == (time_t)-1) return 0;
4329 pl = fr_packet_list_create(0);
4330 if (!pl) return 0; /* leak el */
4332 request_num_counter = 0;
4335 if (mainconfig.proxy_requests) {
4337 * Create the tree for managing proxied requests and
4340 proxy_list = fr_packet_list_create(1);
4341 if (!proxy_list) return 0;
4343 #ifdef HAVE_PTHREAD_H
4344 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4345 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4346 fr_syserror(errno));
4354 * Move all of the thread calls to this file?
4356 * It may be best for the mutexes to be in this file...
4358 spawn_flag = have_children;
4360 #ifdef HAVE_PTHREAD_H
4361 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4364 * Initialize the threads ONLY if we're spawning, AND
4365 * we're running normally.
4367 if (have_children && !check_config &&
4368 (thread_pool_init(cs, &spawn_flag) < 0)) {
4374 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4376 if (listen_init(cs, &head, spawn_flag) < 0) {
4383 #ifdef WITH_SELF_PIPE
4385 * Child threads need a pipe to signal us, as do the
4388 if (pipe(self_pipe) < 0) {
4389 ERROR("radiusd: Error opening internal pipe: %s",
4390 fr_syserror(errno));
4393 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4394 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4395 ERROR("radiusd: Error setting internal flags: %s",
4396 fr_syserror(errno));
4399 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4400 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4401 ERROR("radiusd: Error setting internal flags: %s",
4402 fr_syserror(errno));
4406 if (!fr_event_fd_insert(el, 0, self_pipe[0],
4407 event_signal_handler, el)) {
4408 ERROR("Failed creating handler for signals");
4411 #endif /* WITH_SELF_PIPE */
4413 DEBUG("%s: #### Opening IP addresses and Ports ####",
4417 * The server temporarily switches to an unprivileged
4418 * user very early in the bootstrapping process.
4419 * However, some sockets MAY require privileged access
4420 * (bind to device, or to port < 1024, or to raw
4421 * sockets). Those sockets need to call suid up/down
4422 * themselves around the functions that need a privileged
4425 if (listen_init(cs, &head, spawn_flag) < 0) {
4429 mainconfig.listen = head;
4432 * At this point, no one has any business *ever* going
4435 fr_suid_down_permanent();
4442 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4444 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4446 request->master_state = REQUEST_STOP_PROCESSING;
4449 * Not done, or the child thread is still processing it.
4451 if (request->child_state != REQUEST_DONE) return 0; /* continue */
4453 #ifdef HAVE_PTHREAD_H
4454 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4457 request->in_proxy_hash = false;
4460 * Delete it from the list.
4467 static int request_delete_cb(UNUSED void *ctx, void *data)
4469 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4471 request->master_state = REQUEST_STOP_PROCESSING;
4474 * Not done, or the child thread is still processing it.
4476 if (request->child_state < REQUEST_REJECT_DELAY) return 0; /* continue */
4478 #ifdef HAVE_PTHREAD_H
4479 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4483 rad_assert(request->in_proxy_hash == false);
4486 request->in_request_hash = false;
4487 if (request->ev) fr_event_delete(el, &request->ev);
4489 if (mainconfig.memory_report) {
4490 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
4491 request->packet->id,
4492 (unsigned int) (request->timestamp - fr_start_time));
4495 request_free(&request);
4498 * Delete it from the list, and continue;
4504 void radius_event_free(void)
4510 * There are requests in the proxy hash that aren't
4511 * referenced from anywhere else. Remove them first.
4514 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4518 fr_packet_list_walk(pl, NULL, request_delete_cb);
4522 * Now that all requests have been marked "please stop",
4523 * ensure that all of the threads have exited.
4525 #ifdef HAVE_PTHREAD_H
4530 * Walk the lists again, ensuring that all
4531 * requests are done.
4533 if (mainconfig.memory_report) {
4538 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4539 num = fr_packet_list_num_elements(proxy_list);
4541 ERROR("Proxy list has %d requests still in it.", num);
4546 fr_packet_list_walk(pl, NULL, request_delete_cb);
4547 num = fr_packet_list_num_elements(pl);
4549 ERROR("Request list has %d requests still in it.", num);
4554 fr_packet_list_free(pl);
4558 fr_packet_list_free(proxy_list);
4564 if (debug_condition) talloc_free(debug_condition);
4567 int radius_event_process(void)
4571 return fr_event_loop(el);