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 CC_HINT(nonnull) _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 "response_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 bool proxy_no_new_sockets = false;
197 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
198 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
200 static pthread_t NO_SUCH_CHILD_PID;
201 #define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
205 * This is easier than ifdef's throughout the code.
207 #define PTHREAD_MUTEX_LOCK(_x)
208 #define PTHREAD_MUTEX_UNLOCK(_x)
209 #define NO_CHILD_THREAD
212 #if defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
213 static bool we_are_master(void)
216 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
222 #define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
225 #define we_are_master(_x) (1)
226 #define ASSERT_MASTER
229 static int event_new_fd(rad_listen_t *this);
232 * We need mutexes around the event FD list *only* in certain
235 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
236 static rad_listen_t *new_listeners = NULL;
238 static pthread_mutex_t fd_mutex;
239 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
240 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
242 void radius_update_listener(rad_listen_t *this)
245 * Just do it ourselves.
247 if (we_are_master()) {
252 FD_MUTEX_LOCK(&fd_mutex);
255 * If it's already in the list, don't add it again.
258 FD_MUTEX_UNLOCK(&fd_mutex);
263 * Otherwise, add it to the list
265 this->next = new_listeners;
266 new_listeners = this;
267 FD_MUTEX_UNLOCK(&fd_mutex);
268 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
271 void radius_update_listener(rad_listen_t *this)
274 * No threads. Just insert it.
279 * This is easier than ifdef's throughout the code.
281 #define FD_MUTEX_LOCK(_x)
282 #define FD_MUTEX_UNLOCK(_x)
285 static int request_num_counter = 1;
287 static int request_will_proxy(REQUEST *request);
288 static int request_proxy(REQUEST *request, int retransmit);
289 STATE_MACHINE_DECL(proxy_wait_for_reply);
290 STATE_MACHINE_DECL(proxy_no_reply);
291 STATE_MACHINE_DECL(proxy_running);
292 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply);
293 static void remove_from_proxy_hash(REQUEST *request);
294 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank);
295 static int insert_into_proxy_hash(REQUEST *request);
298 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
299 RADCLIENT *client, RAD_REQUEST_FUNP fun);
301 STATE_MACHINE_DECL(request_common);
302 STATE_MACHINE_DECL(request_response_delay);
303 STATE_MACHINE_DECL(request_cleanup_delay);
304 STATE_MACHINE_DECL(request_running);
306 static void request_coa_originate(REQUEST *request);
307 STATE_MACHINE_DECL(coa_running);
308 STATE_MACHINE_DECL(coa_wait_for_reply);
309 STATE_MACHINE_DECL(coa_no_reply);
310 static void request_coa_separate(REQUEST *coa);
314 #define USEC (1000000)
316 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
318 static void _rad_panic(char const *file, unsigned int line, char const *msg)
320 ERROR("[%s:%d] %s", file, line, msg);
327 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
329 static void tv_add(struct timeval *tv, int usec_delay)
331 if (usec_delay >= USEC) {
332 tv->tv_sec += usec_delay / USEC;
335 tv->tv_usec += usec_delay;
337 if (tv->tv_usec >= USEC) {
338 tv->tv_sec += tv->tv_usec / USEC;
344 * In daemon mode, AND this request has debug flags set.
346 #define DEBUG_PACKET if (!debug_flag && request->log.lvl && request->log.func) debug_packet
348 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
353 char const *received, *from;
354 fr_ipaddr_t const *ip;
359 rad_assert(request->log.func != NULL);
361 if (direction == 0) {
362 received = "Received";
363 from = "from"; /* what else? */
364 ip = &packet->src_ipaddr;
365 port = packet->src_port;
368 received = "Sending";
369 from = "to"; /* hah! */
370 ip = &packet->dst_ipaddr;
371 port = packet->dst_port;
375 * Client-specific debugging re-prints the input
376 * packet into the client log.
378 * This really belongs in a utility library
380 if (is_radius_code(packet->code)) {
381 RDEBUG("%s %s packet %s host %s port %i, id=%i, length=%zu",
382 received, fr_packet_codes[packet->code], from,
383 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
384 port, packet->id, packet->data_len);
386 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%zu",
388 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
390 packet->code, packet->id, packet->data_len);
393 for (vp = fr_cursor_init(&cursor, &packet->vps);
395 vp = fr_cursor_next(&cursor)) {
396 vp_prints(buffer, sizeof(buffer), vp);
397 RDEBUG("\t%s", buffer);
402 /***********************************************************************
404 * Start of RADIUS server state machine.
406 ***********************************************************************/
409 * Callback for ALL timer events related to the request.
411 static void request_timer(void *ctx)
413 REQUEST *request = ctx;
414 int action = request->timer_action;
418 request->process(request, action);
422 * Only ever called from the master thread.
424 STATE_MACHINE_DECL(request_done)
426 struct timeval now, when;
435 * CoA requests can be cleaned up in the child thread,
436 * but ONLY if they aren't tied into anything.
438 if (request->parent && (request->parent->coa == request)) {
439 rad_assert(!request->in_request_hash);
440 rad_assert(!request->in_proxy_hash);
441 rad_assert(action == FR_ACTION_DONE);
442 rad_assert(request->ev == NULL);
446 #ifdef HAVE_PTHREAD_H
448 * If called from a child thread, mark ourselves as done,
449 * and wait for the master thread timer to clean us up.
451 if (!we_are_master()) {
452 request->child_state = REQUEST_DONE;
460 * Move the CoA request to its own handler.
463 request_coa_separate(request->coa);
464 } else if (request->parent && (request->parent->coa == request)) {
465 request_coa_separate(request);
471 * It doesn't hurt to send duplicate replies. All other
472 * signals are ignored, as the request will be cleaned up
477 if (request->reply->code != 0) {
478 request->listener->send(request->listener, request);
481 RDEBUG("No reply. Ignoring retransmit");
486 * This is only called from the master thread
487 * when there is a child thread processing the
490 case FR_ACTION_CONFLICTING:
491 if (request->child_state == REQUEST_DONE) break;
494 * If there's a reply packet, then we presume
495 * that the child has sent the reply, and we get
496 * pinged here before the child has a chance to
499 if (request->reply->data) break;
501 RERROR("Received conflicting packet from "
502 "client %s port %d - ID: %u due to "
503 "unfinished request. Giving up on old request.",
504 request->client->shortname,
505 request->packet->src_port, request->packet->id);
509 * Called only when there's an error remembering
510 * the packet, or when the socket gets closed from
514 #ifdef HAVE_PTHREAD_H
516 * Do NOT set child_state to DONE if it's still in the queue.
518 if (we_are_master() && (request->child_state == REQUEST_QUEUED)) {
523 * If we have child threads and we're NOT the
524 * thread handling the request, don't do anything.
527 !pthread_equal(pthread_self(), request->child_pid)) {
531 #ifdef DEBUG_STATE_MACHINE
532 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
533 request->number, __FUNCTION__,
534 child_state_names[request->child_state],
535 child_state_names[REQUEST_DONE]);
537 request->child_state = REQUEST_DONE;
541 * Called when the child is taking too long to
542 * finish. We've already marked it "please
543 * stop", so we don't complain any more.
545 case FR_ACTION_TIMER:
550 * Child is still alive, and we're receiving more
551 * packets from the home server.
553 case FR_ACTION_PROXY_REPLY:
554 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
555 inet_ntop(request->proxy->src_ipaddr.af,
556 &request->proxy->src_ipaddr.ipaddr,
557 buffer, sizeof(buffer)),
558 request->proxy->dst_port, request->proxy->id);
563 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
568 * Remove it from the request hash.
570 if (request->in_request_hash) {
572 if (!fr_packet_list_yank(pl, request->packet)) {
575 request->in_request_hash = false;
580 * Wait for the proxy ID to expire. This allows us to
581 * avoid re-use of proxy IDs for a while.
583 if (request->in_proxy_hash) {
584 rad_assert(request->proxy != NULL);
586 fr_event_now(el, &now);
587 when = request->proxy->timestamp;
590 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
591 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
592 (request->packet->code != request->proxy->code)) {
593 when.tv_sec += request->home_server->coa_mrd;
596 timeradd(&when, &request->home_server->response_window, &when);
599 * We haven't received all responses, AND there's still
600 * time to wait. Do so.
602 if ((request->num_proxied_requests > request->num_proxied_responses) &&
604 (request->home_server->proto != IPPROTO_TCP) &&
606 timercmp(&now, &when, <)) {
607 RDEBUG("Waiting for more responses from the home server");
614 remove_from_proxy_hash(request);
618 #ifdef HAVE_PTHREAD_H
620 * If there's no children, we can mark the request as done.
623 request->child_state = REQUEST_DONE;
627 if (request->child_state != REQUEST_DONE) {
628 gettimeofday(&now, NULL);
633 #ifdef HAVE_PTHREAD_H
635 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
636 RDEBUG("Waiting for child thread to stop");
641 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
642 tv_add(&when, request->delay);
643 request->delay += request->delay >> 1;
644 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
646 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
650 #ifdef HAVE_PTHREAD_H
651 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
655 * @todo: do final states for TCP sockets, too?
657 request_stats_final(request);
659 if (request->listener) request->listener->count--;
662 if (request->packet) {
663 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
665 (unsigned int) (request->timestamp - fr_start_time));
666 } /* else don't print anything */
668 if (request->ev) fr_event_delete(el, &request->ev);
670 request_free(&request);
674 static void request_cleanup_delay_init(REQUEST *request, struct timeval const *pnow)
676 struct timeval now, when;
678 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
680 if (!request->root->cleanup_delay) goto done;
685 gettimeofday(&now, NULL);
688 rad_assert(request->reply->timestamp.tv_sec != 0);
689 when = request->reply->timestamp;
691 request->delay = request->root->cleanup_delay;
692 when.tv_sec += request->delay;
695 * Set timer for when we need to clean it up.
697 if (timercmp(&when, &now, >)) {
698 #ifdef DEBUG_STATE_MACHINE
699 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
701 request->process = request_cleanup_delay;
702 request->child_state = REQUEST_DONE;
703 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
708 * Otherwise just clean it up.
711 request_done(request, FR_ACTION_DONE);
716 * Function to do all time-related events.
718 static void request_process_timer(REQUEST *request)
720 struct timeval now, when;
721 rad_assert(request->magic == REQUEST_MAGIC);
722 #ifdef DEBUG_STATE_MACHINE
723 int action = FR_ACTION_TIMER;
731 * If we originated a CoA request, divorce it from the
732 * parent. Then, set up the timers so that we can clean
733 * it up as appropriate.
735 if (request->coa) request_coa_separate(request->coa);
738 * If we're the request, OR it isn't originating a CoA
739 * request, check more things.
741 if (!request->proxy || (request->packet->code == request->proxy->code))
744 rad_assert(request->listener != NULL);
747 * The socket was closed. Tell the request that
748 * there is no point in continuing.
750 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
751 if ((request->master_state == REQUEST_ACTIVE) &&
752 (request->child_state < REQUEST_RESPONSE_DELAY)) {
753 WARN("Socket was closed while processing request %u: Stopping it.", request->number);
754 request->master_state = REQUEST_STOP_PROCESSING;
759 gettimeofday(&now, NULL);
762 * The request was forcibly stopped.
764 if (request->master_state == REQUEST_STOP_PROCESSING) {
765 switch (request->child_state) {
767 case REQUEST_RUNNING:
768 #ifdef HAVE_PTHREAD_H
769 rad_assert(spawn_flag == true);
774 * Sleep for some more. We HOPE that the
775 * child will become responsive at some
776 * point in the future.
779 tv_add(&when, request->delay);
780 request->delay += request->delay >> 1;
781 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
785 * These should all be managed by the master thread
788 case REQUEST_PROXIED:
790 case REQUEST_RESPONSE_DELAY:
791 case REQUEST_CLEANUP_DELAY:
794 request_done(request, FR_ACTION_DONE);
799 rad_assert(request->master_state == REQUEST_ACTIVE);
802 * It's still supposed to be running.
804 switch (request->child_state) {
806 case REQUEST_RUNNING:
808 case REQUEST_PROXIED:
810 when = request->packet->timestamp;
811 when.tv_sec += request->root->max_request_time;
814 * Taking too long: tell it to die.
816 if (timercmp(&now, &when, >=)) {
817 #ifdef HAVE_PTHREAD_H
819 * If there's a child thread processing it,
823 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
824 ERROR("Unresponsive child for request %u, in component %s module %s",
826 request->component ? request->component : "<core>",
827 request->module ? request->module : "<core>");
828 exec_trigger(request, NULL, "server.thread.unresponsive", true);
831 request->master_state = REQUEST_STOP_PROCESSING;
836 * We should wait for the proxy reply.
838 if (request->child_state == REQUEST_PROXIED) {
839 rad_assert(request->proxy != NULL);
845 if (request->packet->code != request->proxy->code) {
846 if (request->proxy_reply) {
847 request->process = coa_running;
849 request->process = coa_wait_for_reply;
854 if (request->proxy_reply) {
855 request->process = proxy_running;
857 request->process = proxy_wait_for_reply;
863 * If the request has been told to die, we wait.
864 * Otherwise, we wait for the child thread to
869 case REQUEST_RESPONSE_DELAY:
870 rad_assert(request->response_delay > 0);
872 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
875 request->process = request_response_delay;
877 when = request->reply->timestamp;
879 tv_add(&when, request->response_delay * USEC);
881 if (timercmp(&when, &now, >)) {
882 #ifdef DEBUG_STATE_MACHINE
883 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
885 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
887 } /* else it's time to send the reject */
889 RDEBUG2("Sending delayed response");
890 DEBUG_PACKET(request, request->reply, 1);
891 request->listener->send(request->listener, request);
892 request->child_state = REQUEST_CLEANUP_DELAY;
895 case REQUEST_CLEANUP_DELAY:
896 rad_assert(request->root->cleanup_delay > 0);
899 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
902 request->process = request_cleanup_delay;
904 when = request->reply->timestamp;
905 when.tv_sec += request->root->cleanup_delay;
907 if (timercmp(&when, &now, >)) {
908 #ifdef DEBUG_STATE_MACHINE
909 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
911 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
913 } /* else it's time to clean up */
922 static void request_queue_or_run(UNUSED REQUEST *request,
923 fr_request_process_t process)
925 #ifdef DEBUG_STATE_MACHINE
926 int action = FR_ACTION_TIMER;
932 * Do this here so that fewer other functions need to do
935 if (request->master_state == REQUEST_STOP_PROCESSING) {
936 #ifdef DEBUG_STATE_MACHINE
937 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
938 request->number, __FUNCTION__,
939 master_state_names[request->master_state],
940 child_state_names[request->child_state],
941 child_state_names[REQUEST_DONE]);
943 request_done(request, FR_ACTION_DONE);
947 request->process = process;
949 if (we_are_master()) {
953 * (re) set the initial delay.
955 request->delay = USEC / 3;
956 gettimeofday(&when, NULL);
957 tv_add(&when, request->delay);
958 request->delay += request->delay >> 1;
960 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
962 #ifdef HAVE_PTHREAD_H
965 * A child thread will eventually pick it up.
967 if (request_enqueue(request)) return;
970 * Otherwise we're not going to do anything with
973 request_done(request, FR_ACTION_DONE);
979 request->child_state = REQUEST_RUNNING;
980 request->process(request, FR_ACTION_RUN);
984 * Requests that care about child process exit
985 * codes have already either called
986 * rad_waitpid(), or they've given up.
988 while (waitpid(-1, NULL, WNOHANG) > 0);
992 STATE_MACHINE_DECL(request_common)
1002 * Bail out as early as possible.
1004 if (request->master_state == REQUEST_STOP_PROCESSING) {
1005 request_done(request, FR_ACTION_DONE);
1013 * We're still waiting for a proxy reply.
1015 if (request->child_state == REQUEST_PROXIED) {
1016 request->process = proxy_wait_for_reply;
1017 proxy_wait_for_reply(request, action);
1022 ERROR("(%u) Ignoring duplicate packet from "
1023 "client %s port %d - ID: %u due to unfinished request "
1024 "in component %s module %s",
1025 request->number, request->client->shortname,
1026 request->packet->src_port,request->packet->id,
1027 request->component, request->module);
1030 case FR_ACTION_CONFLICTING:
1032 * We're in the master thread, ask the child to
1033 * stop processing the request.
1035 request_done(request, action);
1038 case FR_ACTION_TIMER:
1039 request_process_timer(request);
1043 case FR_ACTION_PROXY_REPLY:
1044 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
1045 inet_ntop(request->proxy->dst_ipaddr.af,
1046 &request->proxy->dst_ipaddr.ipaddr,
1047 buffer, sizeof(buffer)),
1048 request->proxy->dst_port, request->proxy->id);
1053 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1058 STATE_MACHINE_DECL(request_cleanup_delay)
1060 struct timeval when;
1062 TRACE_STATE_MACHINE;
1067 if (request->reply->code != 0) {
1068 request->listener->send(request->listener, request);
1070 RDEBUG("No reply. Ignoring retransmit");
1074 * Double the cleanup_delay to catch retransmits.
1076 when = request->reply->timestamp;
1077 request->delay += request->delay ;
1078 when.tv_sec += request->delay;
1080 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1083 case FR_ACTION_CONFLICTING:
1084 request_done(request, FR_ACTION_DONE);
1088 case FR_ACTION_PROXY_REPLY:
1090 case FR_ACTION_TIMER:
1091 request_common(request, action);
1095 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1100 STATE_MACHINE_DECL(request_response_delay)
1102 TRACE_STATE_MACHINE;
1107 ERROR("(%u) Discarding duplicate request from "
1108 "client %s port %d - ID: %u due to delayed response",
1109 request->number, request->client->shortname,
1110 request->packet->src_port,request->packet->id);
1114 case FR_ACTION_PROXY_REPLY:
1116 case FR_ACTION_CONFLICTING:
1117 case FR_ACTION_TIMER:
1118 request_common(request, action);
1122 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1128 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1130 TRACE_STATE_MACHINE;
1134 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1137 * Don't decode the packet if it's an internal "fake"
1138 * request. Instead, just return so that the caller can
1141 if (request->packet->dst_port == 0) {
1142 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1143 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1147 if (!request->packet->vps) { /* FIXME: check for correct state */
1148 rcode = request->listener->decode(request->listener, request);
1151 if (debug_condition) {
1153 * Ignore parse errors.
1155 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1156 request->log.lvl = L_DBG_LVL_2;
1157 request->log.func = vradlog_request;
1162 DEBUG_PACKET(request, request->packet, 0);
1168 RDEBUG("Dropping packet without response because of error: %s", fr_strerror());
1169 request->reply->offset = -2; /* bad authenticator */
1173 if (!request->username) {
1174 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1180 STATE_MACHINE_DECL(request_finish)
1184 TRACE_STATE_MACHINE;
1186 (void) action; /* -Wunused */
1188 if (request->master_state == REQUEST_STOP_PROCESSING) {
1194 * Don't send replies if there are none to send.
1196 if (!request->in_request_hash) {
1198 if ((request->listener->type == RAD_LISTEN_AUTH)
1199 #ifdef WITH_ACCOUNTING
1200 || (request->listener->type == RAD_LISTEN_ACCT)
1203 listen_socket_t *sock = request->listener->data;
1205 if (sock->proto == IPPROTO_UDP) return;
1208 * TCP packets aren't in the request
1219 * Override the response code if a control:Response-Packet-Type attribute is present.
1221 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1223 if (vp->vp_integer == 256) {
1224 RDEBUG2("Not responding to request");
1225 request->reply->code = 0;
1227 request->reply->code = vp->vp_integer;
1231 * Catch Auth-Type := Reject BEFORE proxying the packet.
1233 else if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1234 if (request->reply->code == 0) {
1235 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1237 if (!vp || (vp->vp_integer != PW_CODE_AUTHENTICATION_REJECT)) {
1238 RDEBUG2("There was no response configured: "
1239 "rejecting request");
1242 request->reply->code = PW_CODE_AUTHENTICATION_REJECT;
1247 * Copy Proxy-State from the request to the reply.
1249 vp = paircopy2(request->reply, request->packet->vps,
1250 PW_PROXY_STATE, 0, TAG_ANY);
1251 if (vp) pairadd(&request->reply->vps, vp);
1253 switch (request->reply->code) {
1254 case PW_CODE_AUTHENTICATION_ACK:
1255 rad_postauth(request);
1257 case PW_CODE_ACCESS_CHALLENGE:
1258 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1260 vp = pairmake_config("Post-Auth-Type", "Challenge", T_OP_SET);
1261 if (vp) rad_postauth(request);
1268 * Run rejected packets through
1270 * Post-Auth-Type = Reject
1272 * We do this separately so ACK and challenge can change the code
1273 * to reject if a module returns reject.
1275 if (request->reply->code == PW_CODE_AUTHENTICATION_REJECT) {
1276 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1277 vp = pairmake_config("Post-Auth-Type", "Reject", T_OP_SET);
1278 if (vp) rad_postauth(request);
1282 * Clean up. These are no longer needed.
1284 pairfree(&request->config_items);
1286 pairfree(&request->packet->vps);
1287 request->username = NULL;
1288 request->password = NULL;
1291 if (request->proxy) {
1292 pairfree(&request->proxy->vps);
1294 if (request->proxy_reply) {
1295 pairfree(&request->proxy_reply->vps);
1299 gettimeofday(&request->reply->timestamp, NULL);
1302 * Ignore all "do not respond" packets.
1304 if (!request->reply->code) {
1305 RDEBUG("Not sending reply");
1310 * See if we need to delay an Access-Reject packet.
1312 if ((request->reply->code == PW_CODE_AUTHENTICATION_REJECT) &&
1313 (request->root->reject_delay > 0)) {
1314 request->response_delay = request->root->reject_delay;
1318 * If we timed out a proxy packet, don't delay
1319 * the reject any more.
1321 if (request->proxy && !request->proxy_reply) {
1322 request->response_delay = 0;
1331 if (!request->response_delay) {
1332 DEBUG_PACKET(request, request->reply, 1);
1333 request->listener->send(request->listener,
1337 pairfree(&request->reply->vps);
1339 RDEBUG2("Finished request");
1340 #ifdef WITH_ACCOUNTING
1341 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1343 request->child_state = REQUEST_DONE;
1347 if (request->root->cleanup_delay == 0) {
1349 request->child_state = REQUEST_DONE;
1352 request->child_state = REQUEST_CLEANUP_DELAY;
1355 RDEBUG2("Delaying response for %d seconds",
1356 request->response_delay);
1358 request->child_state = REQUEST_RESPONSE_DELAY;
1362 STATE_MACHINE_DECL(request_running)
1364 TRACE_STATE_MACHINE;
1367 case FR_ACTION_TIMER:
1368 request_process_timer(request);
1371 case FR_ACTION_CONFLICTING:
1373 request_common(request, action);
1378 * This can happen due to a race condition where
1379 * we send a proxied request, and immediately get
1380 * another reply, before the timer has a chance
1381 * to update the various states.
1383 case FR_ACTION_PROXY_REPLY:
1384 request->child_state = REQUEST_RUNNING;
1385 request->process = proxy_running;
1386 request->process(request, FR_ACTION_RUN);
1391 if (!request_pre_handler(request, action)) {
1392 #ifdef DEBUG_STATE_MACHINE
1393 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1394 request->number, __FUNCTION__,
1395 child_state_names[request->child_state],
1396 child_state_names[REQUEST_DONE]);
1400 request->child_state = REQUEST_DONE;
1404 rad_assert(request->handle != NULL);
1405 request->handle(request);
1409 * We may need to send a proxied request.
1411 if ((action == FR_ACTION_RUN) &&
1412 request_will_proxy(request)) {
1413 #ifdef DEBUG_STATE_MACHINE
1414 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1418 * takes care of setting
1419 * up the post proxy fail
1422 if (request_proxy(request, 0) < 0) goto finished;
1426 #ifdef DEBUG_STATE_MACHINE
1427 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1432 * Maybe originate a CoA request.
1434 if ((action == FR_ACTION_RUN) && request->coa) {
1435 request_coa_originate(request);
1442 request_finish(request, action);
1447 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1452 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1453 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1456 RADIUS_PACKET **packet_p;
1457 REQUEST *request = NULL;
1459 listen_socket_t *sock = NULL;
1462 * Set the last packet received.
1464 gettimeofday(&now, NULL);
1466 #ifdef WITH_ACCOUNTING
1467 if (listener->type != RAD_LISTEN_DETAIL)
1470 sock = listener->data;
1471 sock->last_packet = now.tv_sec;
1473 packet->timestamp = now;
1476 * Skip everything if required.
1478 if (listener->nodup) goto skip_dup;
1480 packet_p = fr_packet_list_find(pl, packet);
1482 request = fr_packet2myptr(REQUEST, packet, packet_p);
1483 rad_assert(request->in_request_hash);
1486 * Same src/dst ip/port, length, and
1487 * authentication vector: must be a duplicate.
1489 if ((request->packet->data_len == packet->data_len) &&
1490 (memcmp(request->packet->vector, packet->vector,
1491 sizeof(packet->vector)) == 0)) {
1494 * If the request is running, it'
1496 if (request->child_state != REQUEST_DONE) {
1497 request->process(request, FR_ACTION_DUP);
1500 switch (packet->code) {
1501 case PW_CODE_AUTHENTICATION_REQUEST:
1502 FR_STATS_INC(auth, total_dup_requests);
1505 #ifdef WITH_ACCOUNTING
1506 case PW_CODE_ACCOUNTING_REQUEST:
1507 FR_STATS_INC(acct, total_dup_requests);
1511 case PW_CODE_COA_REQUEST:
1512 FR_STATS_INC(coa, total_dup_requests);
1515 case PW_CODE_DISCONNECT_REQUEST:
1516 FR_STATS_INC(dsc, total_dup_requests);
1523 #endif /* WITH_STATS */
1524 return 0; /* duplicate of live request */
1526 #ifdef HAVE_PTHREAD_H
1528 * There should no longer be a child
1529 * thread associated with this request.
1531 rad_assert(pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) != 0);
1535 * Clean up the old request, and allow
1536 * the new one to continue.
1538 request_done(request, FR_ACTION_DONE);
1543 * Say we're ignoring the old one, and continue
1544 * to process the new one.
1546 request->process(request, FR_ACTION_CONFLICTING);
1552 * Quench maximum number of outstanding requests.
1554 if (main_config.max_requests &&
1555 ((count = fr_packet_list_num_elements(pl)) > main_config.max_requests)) {
1556 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1558 packet->src_port, packet->id);
1559 WARN("Please check the configuration file.\n"
1560 "\tThe value for 'max_requests' is probably set too low.\n"));
1562 exec_trigger(NULL, NULL, "server.max_requests", true);
1568 * Rate-limit the incoming packets
1570 if (sock && sock->max_rate) {
1573 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1574 if (pps > sock->max_rate) {
1575 DEBUG("Dropping request due to rate limiting");
1578 sock->rate_pps_now++;
1581 request = request_setup(listener, packet, client, fun);
1582 if (!request) return 1;
1585 * Remember the request in the list.
1587 if (!listener->nodup) {
1588 if (!fr_packet_list_insert(pl, &request->packet)) {
1589 RERROR("Failed to insert request in the list of live requests: discarding it");
1590 request_done(request, FR_ACTION_DONE);
1594 request->in_request_hash = true;
1598 * Process it. Send a response, and free it.
1600 if (listener->synchronous) {
1601 request->listener->decode(request->listener, request);
1602 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1603 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1607 if (request->reply->code != 0) {
1608 request->listener->send(request->listener, request);
1610 RDEBUG("Not sending reply");
1612 request_free(&request);
1617 * Otherwise, insert it into the state machine.
1618 * The child threads will take care of processing it.
1620 request_queue_or_run(request, request_running);
1626 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
1627 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1632 * Create and initialize the new request.
1634 request = request_alloc(NULL);
1635 request->reply = rad_alloc(request, 0);
1636 if (!request->reply) {
1638 request_free(&request);
1642 request->listener = listener;
1643 request->client = client;
1644 request->packet = talloc_steal(request, packet);
1645 request->number = request_num_counter++;
1646 request->priority = listener->type;
1647 request->master_state = REQUEST_ACTIVE;
1648 #ifdef DEBUG_STATE_MACHINE
1649 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1650 request->number, __FUNCTION__,
1651 child_state_names[request->child_state],
1652 child_state_names[REQUEST_RUNNING]);
1654 request->child_state = REQUEST_RUNNING;
1655 request->handle = fun;
1659 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1660 if (packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1661 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1662 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1663 #ifdef WITH_ACCOUNTING
1664 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1665 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1666 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1669 #endif /* WITH_STATS */
1672 * Status-Server packets go to the head of the queue.
1674 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1677 * Set virtual server identity
1679 if (client->server) {
1680 request->server = client->server;
1681 } else if (listener->server) {
1682 request->server = listener->server;
1684 request->server = NULL;
1687 request->root = &main_config;
1689 request->listener->count++;
1693 * The request passes many of our sanity checks.
1694 * From here on in, if anything goes wrong, we
1695 * send a reject message, instead of dropping the
1700 * Build the reply template from the request.
1703 request->reply->sockfd = request->packet->sockfd;
1704 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1705 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1706 request->reply->dst_port = request->packet->src_port;
1707 request->reply->src_port = request->packet->dst_port;
1708 request->reply->id = request->packet->id;
1709 request->reply->code = 0; /* UNKNOWN code */
1710 memcpy(request->reply->vector, request->packet->vector,
1711 sizeof(request->reply->vector));
1712 request->reply->vps = NULL;
1713 request->reply->data = NULL;
1714 request->reply->data_len = 0;
1720 /***********************************************************************
1724 ***********************************************************************/
1727 * Timer function for all TCP sockets.
1729 static void tcp_socket_timer(void *ctx)
1731 rad_listen_t *listener = ctx;
1732 listen_socket_t *sock = listener->data;
1733 struct timeval end, now;
1735 fr_socket_limit_t *limit;
1739 fr_event_now(el, &now);
1741 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1743 switch (listener->type) {
1745 case RAD_LISTEN_PROXY:
1746 limit = &sock->home->limit;
1750 case RAD_LISTEN_AUTH:
1751 #ifdef WITH_ACCOUNTING
1752 case RAD_LISTEN_ACCT:
1754 limit = &sock->limit;
1762 * If we enforce a lifetime, do it now.
1764 if (limit->lifetime > 0) {
1765 end.tv_sec = sock->opened + limit->lifetime;
1768 if (timercmp(&end, &now, <=)) {
1769 listener->print(listener, buffer, sizeof(buffer));
1770 DEBUG("Reached maximum lifetime on socket %s", buffer);
1774 listener->status = RAD_LISTEN_STATUS_EOL;
1775 event_new_fd(listener);
1784 * Enforce an idle timeout.
1786 if (limit->idle_timeout > 0) {
1787 struct timeval idle;
1789 rad_assert(sock->last_packet != 0);
1790 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1793 if (timercmp(&idle, &now, <=)) {
1794 listener->print(listener, buffer, sizeof(buffer));
1795 DEBUG("Reached idle timeout on socket %s", buffer);
1800 * Enforce the minimum of idle timeout or lifetime.
1802 if (timercmp(&idle, &end, <)) {
1808 * Wake up at t + 0.5s. The code above checks if the timers
1809 * are <= t. This addition gives us a bit of leeway.
1811 end.tv_usec = USEC / 2;
1813 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1814 rad_panic("Failed to insert event");
1821 * Add +/- 2s of jitter, as suggested in RFC 3539
1824 static void add_jitter(struct timeval *when)
1831 jitter ^= (jitter >> 10);
1832 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1835 * Add in ~ (4 * USEC) of jitter.
1837 tv_add(when, jitter);
1841 * Called by socket_del to remove requests with this socket
1843 static int eol_proxy_listener(void *ctx, void *data)
1845 rad_listen_t *this = ctx;
1846 RADIUS_PACKET **proxy_p = data;
1849 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1850 if (request->proxy_listener != this) return 0;
1853 * The normal "remove_from_proxy_hash" tries to grab the
1854 * proxy mutex. We already have it held, so grabbing it
1855 * again will cause a deadlock. Instead, call the "no
1856 * lock" version of the function.
1858 rad_assert(request->in_proxy_hash == true);
1859 remove_from_proxy_hash_nl(request, false);
1862 * Don't mark it as DONE. The client can retransmit, and
1863 * the packet SHOULD be re-proxied somewhere else.
1865 * Return "2" means that the rbtree code will remove it
1866 * from the tree, and we don't need to do it ourselves.
1870 #endif /* WITH_PROXY */
1872 static int eol_listener(void *ctx, void *data)
1874 rad_listen_t *this = ctx;
1875 RADIUS_PACKET **packet_p = data;
1878 request = fr_packet2myptr(REQUEST, packet, packet_p);
1879 if (request->listener != this) return 0;
1881 request->master_state = REQUEST_STOP_PROCESSING;
1885 #endif /* WITH_TCP */
1888 /***********************************************************************
1890 * Proxy handlers for the state machine.
1892 ***********************************************************************/
1895 * Called with the proxy mutex held
1897 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1899 if (!request->in_proxy_hash) return;
1901 fr_packet_list_id_free(proxy_list, request->proxy, yank);
1902 request->in_proxy_hash = false;
1905 * On the FIRST reply, decrement the count of outstanding
1906 * requests. Note that this is NOT the count of sent
1907 * packets, but whether or not the home server has
1910 if (request->home_server &&
1911 request->home_server->currently_outstanding) {
1912 request->home_server->currently_outstanding--;
1915 * If we're NOT sending it packets, then we don't know
1916 * if it's alive or dead.
1918 if ((request->home_server->currently_outstanding == 0) &&
1919 (request->home_server->state == HOME_STATE_ALIVE)) {
1920 request->home_server->state = HOME_STATE_UNKNOWN;
1921 request->home_server->last_packet_sent = 0;
1922 request->home_server->last_packet_recv = 0;
1927 rad_assert(request->proxy_listener != NULL);
1928 request->proxy_listener->count--;
1930 request->proxy_listener = NULL;
1933 * Got from YES in hash, to NO, not in hash while we hold
1934 * the mutex. This guarantees that when another thread
1935 * grabs the mutex, the "not in hash" flag is correct.
1937 RDEBUG3("proxy: request is no longer in proxy hash");
1940 static void remove_from_proxy_hash(REQUEST *request)
1943 * Check this without grabbing the mutex because it's a
1944 * lot faster that way.
1946 if (!request->in_proxy_hash) return;
1949 * The "not in hash" flag is definitive. However, if the
1950 * flag says that it IS in the hash, there might still be
1951 * a race condition where it isn't.
1953 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1955 if (!request->in_proxy_hash) {
1956 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1960 remove_from_proxy_hash_nl(request, true);
1962 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1965 static int insert_into_proxy_hash(REQUEST *request)
1969 void *proxy_listener;
1971 rad_assert(request->proxy != NULL);
1972 rad_assert(request->home_server != NULL);
1973 rad_assert(proxy_list != NULL);
1976 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1977 proxy_listener = NULL;
1978 request->num_proxied_requests = 1;
1979 request->num_proxied_responses = 0;
1981 for (tries = 0; tries < 2; tries++) {
1983 listen_socket_t *sock;
1985 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
1986 rcode = fr_packet_list_id_alloc(proxy_list,
1987 request->home_server->proto,
1988 &request->proxy, &proxy_listener);
1989 if ((debug_flag > 2) && (rcode == 0)) {
1990 RDEBUG("proxy: Failed allocating ID: %s", fr_strerror());
1992 if (rcode > 0) break;
1993 if (tries > 0) continue; /* try opening new socket only once */
1995 #ifdef HAVE_PTHREAD_H
1996 if (proxy_no_new_sockets) break;
1999 RDEBUG3("proxy: Trying to open a new listener to the home server");
2000 this = proxy_new_listener(request->home_server, 0);
2002 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2006 request->proxy->src_port = 0; /* Use any new socket */
2007 proxy_listener = this;
2010 if (!fr_packet_list_socket_add(proxy_list, this->fd,
2012 &sock->other_ipaddr, sock->other_port,
2015 #ifdef HAVE_PTHREAD_H
2016 proxy_no_new_sockets = true;
2018 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2021 * This is bad. However, the
2022 * packet list now supports 256
2023 * open sockets, which should
2024 * minimize this problem.
2026 ERROR("Failed adding proxy socket: %s",
2032 * Add it to the event loop. Ensure that we have
2033 * only one mutex locked at a time.
2035 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2036 radius_update_listener(this);
2037 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2040 if (!proxy_listener || (rcode == 0)) {
2041 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2042 REDEBUG2("proxy: Failed allocating Id for proxied request");
2044 request->proxy_listener = NULL;
2045 request->in_proxy_hash = false;
2049 rad_assert(request->proxy->id >= 0);
2051 request->proxy_listener = proxy_listener;
2052 request->in_proxy_hash = true;
2053 RDEBUG3("proxy: request is now in proxy hash");
2056 * Keep track of maximum outstanding requests to a
2057 * particular home server. 'max_outstanding' is
2058 * enforced in home_server_ldb(), in realms.c.
2060 request->home_server->currently_outstanding++;
2063 request->proxy_listener->count++;
2066 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2068 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2069 inet_ntop(request->proxy->dst_ipaddr.af,
2070 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2071 request->proxy->dst_port,
2072 request->proxy->id);
2077 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2080 int post_proxy_type = 0;
2084 * There may be a proxy reply, but it may be too late.
2086 if (!request->proxy_listener) return 0;
2089 * Delete any reply we had accumulated until now.
2091 pairfree(&request->reply->vps);
2094 * Run the packet through the post-proxy stage,
2095 * BEFORE playing games with the attributes.
2097 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2100 * If we have a proxy_reply, and it was a reject, setup
2101 * post-proxy-type Reject
2104 reply->code == PW_CODE_AUTHENTICATION_REJECT) {
2107 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2109 vp = radius_paircreate(request, &request->config_items,
2110 PW_POST_PROXY_TYPE, 0);
2112 vp->vp_integer = dval->value;
2117 post_proxy_type = vp->vp_integer;
2119 RDEBUG2("Found Post-Proxy-Type %s", dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2124 * Decode the packet.
2126 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2127 DEBUG_PACKET(request, reply, 0);
2130 * Pro-actively remove it from the proxy hash.
2131 * This is later than in 2.1.x, but it means that
2132 * the replies are authenticated before being
2133 * removed from the hash.
2136 (request->num_proxied_requests <= request->num_proxied_responses)) {
2137 remove_from_proxy_hash(request);
2140 remove_from_proxy_hash(request);
2143 if (request->home_pool && request->home_pool->virtual_server) {
2144 char const *old_server = request->server;
2146 request->server = request->home_pool->virtual_server;
2147 RDEBUG2("server %s {", request->server);
2149 rcode = process_post_proxy(post_proxy_type, request);
2152 request->server = old_server;
2154 rcode = process_post_proxy(post_proxy_type, request);
2158 if (request->packet->code == request->proxy->code)
2160 * Don't run the next bit if we originated a CoA
2161 * packet, after receiving an Access-Request or
2162 * Accounting-Request.
2167 * There may NOT be a proxy reply, as we may be
2168 * running Post-Proxy-Type = Fail.
2171 request->reply->vps = paircopy(request->reply, reply->vps);
2174 * Delete the Proxy-State Attributes from
2175 * the reply. These include Proxy-State
2176 * attributes from us and remote server.
2178 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2182 default: /* Don't do anything */
2184 case RLM_MODULE_FAIL:
2187 case RLM_MODULE_HANDLED:
2194 int request_proxy_reply(RADIUS_PACKET *packet)
2196 RADIUS_PACKET **proxy_p;
2201 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2202 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2205 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2206 PROXY( "No outstanding request was found for reply from host %s port %d - ID %u",
2207 inet_ntop(packet->src_ipaddr.af,
2208 &packet->src_ipaddr.ipaddr,
2209 buffer, sizeof(buffer)),
2210 packet->src_port, packet->id);
2214 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2215 request->num_proxied_responses++; /* needs to be protected by lock */
2217 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2220 * No reply, BUT the current packet fails verification:
2221 * ignore it. This does the MD5 calculations in the
2222 * server core, but I guess we can fix that later.
2224 if (!request->proxy_reply &&
2225 (rad_verify(packet, request->proxy,
2226 request->home_server->secret) != 0)) {
2227 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2232 * The home server sent us a packet which doesn't match
2233 * something we have: ignore it. This is done only to
2234 * catch the case of broken systems.
2236 if (request->proxy_reply &&
2237 (memcmp(request->proxy_reply->vector,
2239 sizeof(request->proxy_reply->vector)) != 0)) {
2240 RDEBUG2("Ignoring conflicting proxy reply");
2244 gettimeofday(&now, NULL);
2247 * Status-Server packets don't count as real packets.
2249 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2250 listen_socket_t *sock = request->proxy_listener->data;
2252 request->home_server->last_packet_recv = now.tv_sec;
2253 sock->last_packet = now.tv_sec;
2257 * If we have previously seen a reply, ignore the
2260 if (request->proxy_reply) {
2261 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2262 inet_ntop(packet->src_ipaddr.af,
2263 &packet->src_ipaddr.ipaddr,
2264 buffer, sizeof(buffer)),
2265 packet->src_port, packet->id);
2270 * Call the state machine to do something useful with the
2273 request->proxy_reply = talloc_steal(request, packet);
2274 packet->timestamp = now;
2275 request->priority = RAD_LISTEN_PROXY;
2278 * We've received a reply. If we hadn't been sending it
2279 * packets for a while, just mark it alive.
2281 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2282 request->home_server->state = HOME_STATE_ALIVE;
2286 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2287 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2289 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2290 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2291 #ifdef WITH_ACCOUNTING
2292 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2293 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2296 #endif /* WITH_STATS */
2300 * When we originate CoA requests, we patch them in here
2301 * so that they don't affect the rest of the state
2304 if (request->parent) {
2305 rad_assert(request->parent->coa == request);
2306 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
2307 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
2308 rad_assert(request->process != NULL);
2309 request_coa_separate(request);
2313 request->process(request, FR_ACTION_PROXY_REPLY);
2319 static int setup_post_proxy_fail(REQUEST *request)
2321 DICT_VALUE const *dval = NULL;
2324 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2325 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2326 "Fail-Authentication");
2328 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2329 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2332 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2333 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2335 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2336 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2339 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2343 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2346 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2350 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2351 if (!vp) vp = radius_paircreate(request, &request->config_items,
2352 PW_POST_PROXY_TYPE, 0);
2353 vp->vp_integer = dval->value;
2358 STATE_MACHINE_DECL(proxy_no_reply)
2360 TRACE_STATE_MACHINE;
2363 case FR_ACTION_CONFLICTING:
2365 case FR_ACTION_TIMER:
2366 case FR_ACTION_PROXY_REPLY:
2367 request_common(request, action);
2371 if (process_proxy_reply(request, NULL)) {
2372 request_finish(request, action);
2374 request_done(request, FR_ACTION_DONE);
2378 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2383 STATE_MACHINE_DECL(proxy_running)
2385 TRACE_STATE_MACHINE;
2388 case FR_ACTION_CONFLICTING:
2390 case FR_ACTION_TIMER:
2391 case FR_ACTION_PROXY_REPLY:
2392 request_common(request, action);
2396 if (process_proxy_reply(request, request->proxy_reply)) {
2397 request->handle(request);
2398 request_finish(request, action);
2400 request_done(request, FR_ACTION_DONE);
2405 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2410 static int request_will_proxy(REQUEST *request)
2412 int rcode, pre_proxy_type = 0;
2413 char const *realmname = NULL;
2414 VALUE_PAIR *vp, *strippedname;
2415 home_server_t *home;
2416 REALM *realm = NULL;
2417 home_pool_t *pool = NULL;
2419 if (!request->root->proxy_requests) return 0;
2420 if (request->packet->dst_port == 0) return 0;
2421 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2422 if (request->in_proxy_hash) return 0;
2425 * FIXME: for 3.0, allow this only for rejects?
2427 if (request->reply->code != 0) return 0;
2429 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2431 realm = realm_find2(vp->vp_strvalue);
2433 REDEBUG2("Cannot proxy to unknown realm %s",
2438 realmname = vp->vp_strvalue;
2441 * Figure out which pool to use.
2443 if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
2444 pool = realm->auth_pool;
2446 #ifdef WITH_ACCOUNTING
2447 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2448 pool = realm->acct_pool;
2452 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2453 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2454 pool = realm->coa_pool;
2464 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2467 switch (request->packet->code) {
2468 case PW_CODE_AUTHENTICATION_REQUEST:
2469 pool_type = HOME_TYPE_AUTH;
2472 #ifdef WITH_ACCOUNTING
2473 case PW_CODE_ACCOUNTING_REQUEST:
2474 pool_type = HOME_TYPE_ACCT;
2479 case PW_CODE_COA_REQUEST:
2480 case PW_CODE_DISCONNECT_REQUEST:
2481 pool_type = HOME_TYPE_COA;
2489 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2493 RWDEBUG2("Cancelling proxy as no home pool exists");
2497 if (request->listener->synchronous) {
2498 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2502 request->home_pool = pool;
2504 home = home_server_ldb(realmname, pool, request);
2506 REDEBUG2("Failed to find live home server: Cancelling proxy");
2509 home_server_update_request(home, request);
2513 * Once we've decided to proxy a request, we cannot send
2514 * a CoA packet. So we free up any CoA packet here.
2516 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2520 * Remember that we sent the request to a Realm.
2522 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2525 * Strip the name, if told to.
2527 * Doing it here catches the case of proxied tunneled
2530 if (realm && (realm->striprealm == true) &&
2531 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2533 * If there's a Stripped-User-Name attribute in
2534 * the request, then use THAT as the User-Name
2535 * for the proxied request, instead of the
2538 * This is done by making a copy of the
2539 * Stripped-User-Name attribute, turning it into
2540 * a User-Name attribute, deleting the
2541 * Stripped-User-Name and User-Name attributes
2542 * from the vps list, and making the new
2543 * User-Name the head of the vps list.
2545 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2548 vp = radius_paircreate(NULL, NULL,
2550 rad_assert(vp != NULL); /* handled by above function */
2551 /* Insert at the START of the list */
2552 /* FIXME: Can't make assumptions about ordering */
2553 fr_cursor_init(&cursor, &vp);
2554 fr_cursor_insert(&cursor, request->proxy->vps);
2555 request->proxy->vps = vp;
2557 pairstrcpy(vp, strippedname->vp_strvalue);
2560 * Do NOT delete Stripped-User-Name.
2565 * If there is no PW_CHAP_CHALLENGE attribute but
2566 * there is a PW_CHAP_PASSWORD we need to add it
2567 * since we can't use the request authenticator
2568 * anymore - we changed it.
2570 if ((request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) &&
2571 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2572 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2573 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2574 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2578 * The RFC's say we have to do this, but FreeRADIUS
2581 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2582 pairsprintf(vp, "%u", request->packet->id);
2585 * Should be done BEFORE inserting into proxy hash, as
2586 * pre-proxy may use this information, or change it.
2588 request->proxy->code = request->packet->code;
2591 * Call the pre-proxy routines.
2593 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2595 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2596 /* Must be a validation issue */
2598 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2599 pre_proxy_type = vp->vp_integer;
2602 rad_assert(request->home_pool != NULL);
2604 if (request->home_pool->virtual_server) {
2605 char const *old_server = request->server;
2607 request->server = request->home_pool->virtual_server;
2609 RDEBUG2("server %s {", request->server);
2611 rcode = process_pre_proxy(pre_proxy_type, request);
2615 request->server = old_server;
2617 rcode = process_pre_proxy(pre_proxy_type, request);
2620 case RLM_MODULE_FAIL:
2621 case RLM_MODULE_INVALID:
2622 case RLM_MODULE_NOTFOUND:
2623 case RLM_MODULE_USERLOCK:
2625 /* FIXME: debug print failed stuff */
2628 case RLM_MODULE_REJECT:
2629 case RLM_MODULE_HANDLED:
2633 * Only proxy the packet if the pre-proxy code succeeded.
2635 case RLM_MODULE_NOOP:
2637 case RLM_MODULE_UPDATED:
2644 static int request_proxy(REQUEST *request, int retransmit)
2648 rad_assert(request->parent == NULL);
2649 rad_assert(request->home_server != NULL);
2651 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2655 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2656 request_done(request->coa, FR_ACTION_DONE);
2661 * The request may need sending to a virtual server.
2662 * This code is more than a little screwed up. The rest
2663 * of the state machine doesn't handle parent / child
2664 * relationships well. i.e. if the child request takes
2665 * too long, the core will mark the *parent* as "stop
2666 * processing". And the child will continue without
2667 * knowing anything...
2669 * So, we have some horrible hacks to get around that.
2671 if (request->home_server->server) {
2674 if (request->packet->dst_port == 0) {
2675 WARN("Cannot proxy an internal request");
2679 DEBUG("Proxying to virtual server %s",
2680 request->home_server->server);
2683 * Packets to virtual serrers don't get
2684 * retransmissions sent to them. And the virtual
2685 * server is run ONLY if we have no child
2686 * threads, or we're running in a child thread.
2688 rad_assert(retransmit == 0);
2689 rad_assert(!spawn_flag || !we_are_master());
2691 fake = request_alloc_fake(request);
2693 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
2694 talloc_free(request->proxy);
2696 fake->server = request->home_server->server;
2697 fake->handle = request->handle;
2698 fake->process = NULL; /* should never be run for anything */
2701 * Run the virtual server.
2703 request_running(fake, FR_ACTION_RUN);
2705 request->proxy = talloc_steal(request, fake->packet);
2706 fake->packet = NULL;
2707 request->proxy_reply = talloc_steal(request, fake->reply);
2710 request_free(&fake);
2713 * Just do the work here, rather than trying to
2714 * run the "decode proxy reply" stuff...
2716 process_proxy_reply(request, request->proxy_reply);
2718 request->handle(request); /* to do more post-proxy stuff */
2720 return -1; /* so we call request_finish */
2724 * We're actually sending a proxied packet. Do that now.
2726 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2727 ERROR("Failed to insert request into the proxy list");
2731 rad_assert(request->proxy->id >= 0);
2734 if (request->home_server->tls) {
2735 RDEBUG2("Proxying request to home server %s port %d (TLS)",
2736 inet_ntop(request->proxy->dst_ipaddr.af,
2737 &request->proxy->dst_ipaddr.ipaddr,
2738 buffer, sizeof(buffer)),
2739 request->proxy->dst_port);
2742 RDEBUG2("Proxying request to home server %s port %d",
2743 inet_ntop(request->proxy->dst_ipaddr.af,
2744 &request->proxy->dst_ipaddr.ipaddr,
2745 buffer, sizeof(buffer)),
2746 request->proxy->dst_port);
2748 DEBUG_PACKET(request, request->proxy, 1);
2750 gettimeofday(&request->proxy_retransmit, NULL);
2752 request->proxy->timestamp = request->proxy_retransmit;
2753 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2756 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2758 request->child_state = REQUEST_PROXIED;
2759 request->proxy_listener->send(request->proxy_listener,
2765 * Proxy the packet as if it was new.
2767 static int request_proxy_anew(REQUEST *request)
2769 home_server_t *home;
2772 * Delete the request from the proxy list.
2774 * The packet list code takes care of ensuring that IDs
2775 * aren't reused until all 256 IDs have been used. So
2776 * there's a 1/256 chance of re-using the same ID when
2777 * we're sending to the same home server. Which is
2780 remove_from_proxy_hash(request);
2783 * Find a live home server for the request.
2785 home = home_server_ldb(NULL, request->home_pool, request);
2787 REDEBUG2("Failed to find live home server for request");
2789 if (setup_post_proxy_fail(request)) {
2790 request_queue_or_run(request, proxy_running);
2792 gettimeofday(&request->reply->timestamp, NULL);
2793 request_cleanup_delay_init(request, NULL);
2797 home_server_update_request(home, request);
2799 if (!insert_into_proxy_hash(request)) {
2800 RPROXY("Failed to insert retransmission into the proxy list");
2801 goto post_proxy_fail;
2805 * Free the old packet, to force re-encoding
2807 talloc_free(request->proxy->data);
2808 request->proxy->data = NULL;
2809 request->proxy->data_len = 0;
2811 #ifdef WITH_ACCOUNTING
2813 * Update the Acct-Delay-Time attribute.
2815 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2818 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2819 if (!vp) vp = radius_paircreate(request->proxy,
2820 &request->proxy->vps,
2821 PW_ACCT_DELAY_TIME, 0);
2825 gettimeofday(&now, NULL);
2826 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2831 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2836 STATE_MACHINE_DECL(request_ping)
2838 home_server_t *home = request->home_server;
2841 TRACE_STATE_MACHINE;
2845 case FR_ACTION_TIMER:
2846 ERROR("No response to status check %d for home server %s port %d",
2848 inet_ntop(request->proxy->dst_ipaddr.af,
2849 &request->proxy->dst_ipaddr.ipaddr,
2850 buffer, sizeof(buffer)),
2851 request->proxy->dst_port);
2854 case FR_ACTION_PROXY_REPLY:
2855 rad_assert(request->in_proxy_hash);
2857 request->home_server->num_received_pings++;
2858 RPROXY("Received response to status check %d (%d in current sequence)",
2859 request->number, home->num_received_pings);
2862 * Remove the request from any hashes
2864 fr_event_delete(el, &request->ev);
2865 remove_from_proxy_hash(request);
2868 * The control socket may have marked the home server as
2869 * alive. OR, it may have suddenly started responding to
2870 * requests again. If so, don't re-do the "make alive"
2873 if (home->state == HOME_STATE_ALIVE) break;
2876 * It's dead, and we haven't received enough ping
2877 * responses to mark it "alive". Wait a bit.
2879 * If it's zombie, we mark it alive immediately.
2881 if ((home->state == HOME_STATE_IS_DEAD) &&
2882 (home->num_received_pings < home->num_pings_to_alive)) {
2887 * Mark it alive and delete any outstanding
2890 home->state = HOME_STATE_ALIVE;
2891 exec_trigger(request, home->cs, "home_server.alive", false);
2892 home->currently_outstanding = 0;
2893 home->num_sent_pings = 0;
2894 home->num_received_pings = 0;
2895 gettimeofday(&home->revive_time, NULL);
2897 fr_event_delete(el, &home->ev);
2899 RPROXY("Marking home server %s port %d alive",
2900 inet_ntop(request->proxy->dst_ipaddr.af,
2901 &request->proxy->dst_ipaddr.ipaddr,
2902 buffer, sizeof(buffer)),
2903 request->proxy->dst_port);
2907 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2911 rad_assert(!request->in_request_hash);
2912 rad_assert(request->ev == NULL);
2913 request_done(request, FR_ACTION_DONE);
2917 * Called from start of zombie period, OR after control socket
2918 * marks the home server dead.
2920 static void ping_home_server(void *ctx)
2922 home_server_t *home = ctx;
2925 struct timeval when, now;
2927 if ((home->state == HOME_STATE_ALIVE) ||
2928 (home->ping_check == HOME_PING_CHECK_NONE) ||
2930 (home->proto == IPPROTO_TCP) ||
2932 (home->ev != NULL)) {
2936 gettimeofday(&now, NULL);
2938 if (home->state == HOME_STATE_ZOMBIE) {
2939 when = home->zombie_period_start;
2940 when.tv_sec += home->zombie_period;
2942 if (timercmp(&when, &now, <)) {
2943 DEBUG("PING: Zombie period is over for home server %s",
2945 mark_home_server_dead(home, &now);
2949 request = request_alloc(NULL);
2950 request->number = request_num_counter++;
2953 request->proxy = rad_alloc(request, 1);
2954 rad_assert(request->proxy != NULL);
2956 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2957 request->proxy->code = PW_CODE_STATUS_SERVER;
2959 pairmake(request->proxy, &request->proxy->vps,
2960 "Message-Authenticator", "0x00", T_OP_SET);
2962 } else if (home->type == HOME_TYPE_AUTH) {
2963 request->proxy->code = PW_CODE_AUTHENTICATION_REQUEST;
2965 pairmake(request->proxy, &request->proxy->vps,
2966 "User-Name", home->ping_user_name, T_OP_SET);
2967 pairmake(request->proxy, &request->proxy->vps,
2968 "User-Password", home->ping_user_password, T_OP_SET);
2969 pairmake(request->proxy, &request->proxy->vps,
2970 "Service-Type", "Authenticate-Only", T_OP_SET);
2971 pairmake(request->proxy, &request->proxy->vps,
2972 "Message-Authenticator", "0x00", T_OP_SET);
2975 #ifdef WITH_ACCOUNTING
2976 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
2978 pairmake(request->proxy, &request->proxy->vps,
2979 "User-Name", home->ping_user_name, T_OP_SET);
2980 pairmake(request->proxy, &request->proxy->vps,
2981 "Acct-Status-Type", "Stop", T_OP_SET);
2982 pairmake(request->proxy, &request->proxy->vps,
2983 "Acct-Session-Id", "00000000", T_OP_SET);
2984 vp = pairmake(request->proxy, &request->proxy->vps,
2985 "Event-Timestamp", "0", T_OP_SET);
2986 vp->vp_date = now.tv_sec;
2988 rad_assert("Internal sanity check failed");
2992 vp = pairmake(request->proxy, &request->proxy->vps,
2993 "NAS-Identifier", "", T_OP_SET);
2995 pairsprintf(vp, "Status Check %u. Are you alive?",
2996 home->num_sent_pings);
2999 request->proxy->src_ipaddr = home->src_ipaddr;
3000 request->proxy->dst_ipaddr = home->ipaddr;
3001 request->proxy->dst_port = home->port;
3002 request->home_server = home;
3003 #ifdef DEBUG_STATE_MACHINE
3004 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3005 child_state_names[request->child_state],
3006 child_state_names[REQUEST_DONE]);
3007 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3009 #ifdef HAVE_PTHREAD_H
3010 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3012 request->child_state = REQUEST_DONE;
3013 request->process = request_ping;
3015 rad_assert(request->proxy_listener == NULL);
3017 if (!insert_into_proxy_hash(request)) {
3018 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3021 rad_assert(!request->in_request_hash);
3022 rad_assert(!request->in_proxy_hash);
3023 rad_assert(request->ev == NULL);
3024 request_free(&request);
3029 * Set up the timer callback.
3032 when.tv_sec += home->ping_timeout;
3034 DEBUG("PING: Waiting %u seconds for response to ping",
3035 home->ping_timeout);
3037 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3038 home->num_sent_pings++;
3040 rad_assert(request->proxy_listener != NULL);
3041 request->proxy_listener->send(request->proxy_listener,
3045 * Add +/- 2s of jitter, as suggested in RFC 3539
3046 * and in the Issues and Fixes draft.
3049 home->when.tv_sec += home->ping_interval;
3051 add_jitter(&home->when);
3053 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3054 INSERT_EVENT(ping_home_server, home);
3057 static void home_trigger(home_server_t *home, char const *trigger)
3060 RADIUS_PACKET my_packet;
3062 memset(&my_request, 0, sizeof(my_request));
3063 memset(&my_packet, 0, sizeof(my_packet));
3064 my_request.proxy = &my_packet;
3065 my_packet.dst_ipaddr = home->ipaddr;
3066 my_packet.src_ipaddr = home->src_ipaddr;
3068 exec_trigger(&my_request, home->cs, trigger, false);
3071 static void mark_home_server_zombie(home_server_t *home, struct timeval *now)
3078 rad_assert((home->state == HOME_STATE_ALIVE) ||
3079 (home->state == HOME_STATE_UNKNOWN));
3082 if (home->proto == IPPROTO_TCP) {
3083 WARN("Not marking TCP server %s zombie", home->name);
3089 * We've received a real packet recently. Don't mark the
3090 * server as zombie until we've received NO packets for a
3091 * while. The "1/4" of zombie period was chosen rather
3092 * arbitrarily. It's a balance between too short, which
3093 * gives quick fail-over and fail-back, or too long,
3094 * where the proxy still sends packets to an unresponsive
3097 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3098 if (home->last_packet_recv >= start) {
3099 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3100 (int) (now->tv_sec - home->last_packet_recv));
3104 home->state = HOME_STATE_ZOMBIE;
3105 home_trigger(home, "home_server.zombie");
3108 * Set the home server to "zombie", as of the time
3111 home->zombie_period_start.tv_sec = start;
3112 home->zombie_period_start.tv_usec = USEC / 2;
3114 fr_event_delete(el, &home->ev);
3115 home->num_sent_pings = 0;
3116 home->num_received_pings = 0;
3118 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3119 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3120 buffer, sizeof(buffer)),
3121 home->port, (int) home->response_window.tv_sec, (int) home->response_window.tv_usec);
3123 ping_home_server(home);
3127 void revive_home_server(void *ctx)
3129 home_server_t *home = ctx;
3133 rad_assert(home->proto != IPPROTO_TCP);
3136 home->state = HOME_STATE_ALIVE;
3137 home_trigger(home, "home_server.alive");
3138 home->currently_outstanding = 0;
3139 gettimeofday(&home->revive_time, NULL);
3142 * Delete any outstanding events.
3144 if (home->ev) fr_event_delete(el, &home->ev);
3146 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3147 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3148 buffer, sizeof(buffer)),
3152 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3154 int previous_state = home->state;
3158 if (home->proto == IPPROTO_TCP) {
3159 WARN("Not marking TCP server dead");
3164 PROXY( "Marking home server %s port %d as dead.",
3165 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3166 buffer, sizeof(buffer)),
3169 home->state = HOME_STATE_IS_DEAD;
3170 home_trigger(home, "home_server.dead");
3172 if (home->ping_check != HOME_PING_CHECK_NONE) {
3174 * If the control socket marks us dead, start
3175 * pinging. Otherwise, we already started
3176 * pinging when it was marked "zombie".
3178 if (previous_state == HOME_STATE_ALIVE) {
3179 ping_home_server(home);
3181 DEBUG("PING: Already pinging home server %s",
3187 * Revive it after a fixed period of time. This
3188 * is very, very, bad.
3191 home->when.tv_sec += home->revive_interval;
3193 DEBUG("PING: Reviving home server %s in %u seconds",
3194 home->name, home->revive_interval);
3195 INSERT_EVENT(revive_home_server, home);
3199 STATE_MACHINE_DECL(proxy_wait_for_reply)
3201 struct timeval now, when;
3202 home_server_t *home = request->home_server;
3205 TRACE_STATE_MACHINE;
3207 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3208 rad_assert(request->home_server != NULL);
3210 if (request->master_state == REQUEST_STOP_PROCESSING) {
3211 request->child_state = REQUEST_DONE;
3215 gettimeofday(&now, NULL);
3220 * We have a reply, ignore the retransmit.
3222 if (request->proxy_reply) return;
3225 * The request was proxied to a virtual server.
3226 * Ignore the retransmit.
3228 if (request->home_server->server) return;
3230 if ((home->state == HOME_STATE_IS_DEAD) ||
3231 !request->proxy_listener ||
3232 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3233 request_proxy_anew(request);
3238 if (home->proto == IPPROTO_TCP) {
3239 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3240 inet_ntop(request->proxy->dst_ipaddr.af,
3241 &request->proxy->dst_ipaddr.ipaddr,
3242 buffer, sizeof(buffer)),
3243 request->proxy->dst_port,
3244 request->proxy->id);
3250 * More than one retransmit a second is stupid,
3251 * and should be suppressed by the proxy.
3253 when = request->proxy_retransmit;
3256 if (timercmp(&now, &when, <)) {
3257 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3258 inet_ntop(request->proxy->dst_ipaddr.af,
3259 &request->proxy->dst_ipaddr.ipaddr,
3260 buffer, sizeof(buffer)),
3261 request->proxy->dst_port,
3262 request->proxy->id);
3266 #ifdef WITH_ACCOUNTING
3268 * If we update the Acct-Delay-Time, we need to
3271 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3272 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3273 request_proxy_anew(request);
3278 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3279 inet_ntop(request->proxy->dst_ipaddr.af,
3280 &request->proxy->dst_ipaddr.ipaddr,
3281 buffer, sizeof(buffer)),
3282 request->proxy->dst_port,
3283 request->proxy->id);
3284 request->num_proxied_requests++;
3286 rad_assert(request->proxy_listener != NULL);;
3287 DEBUG_PACKET(request, request->proxy, 1);
3288 FR_STATS_TYPE_INC(home->stats.total_requests);
3289 home->last_packet_sent = now.tv_sec;
3290 request->proxy_retransmit = now;
3291 request->proxy_listener->send(request->proxy_listener,
3295 case FR_ACTION_TIMER:
3297 if (!request->proxy_listener ||
3298 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3299 remove_from_proxy_hash(request);
3301 when = request->packet->timestamp;
3302 when.tv_sec += request->root->max_request_time;
3304 if (timercmp(&when, &now, >)) {
3305 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3306 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3313 * Wake up "response_window" time in the future.
3314 * i.e. when MY packet hasn't received a response.
3316 * Note that we DO NOT mark the home server as
3317 * zombie if it doesn't respond to us. It may be
3318 * responding to other (better looking) packets.
3320 when = request->proxy->timestamp;
3321 timeradd(&when, &home->response_window, &when);
3324 * Not at the response window. Set the timer for
3327 if (timercmp(&when, &now, >)) {
3328 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3329 (int) home->response_window.tv_sec, (int) home->response_window.tv_usec);
3330 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3335 RDEBUG("No proxy response, giving up on request and marking it done");
3338 * If we haven't received any packets for
3339 * "response_window", then mark the home server
3342 * If the connection is TCP, then another
3343 * "watchdog timer" function takes care of pings,
3344 * etc. So we don't need to do it here.
3346 * This check should really be part of a home
3347 * server state machine.
3349 if (((home->state == HOME_STATE_ALIVE) ||
3350 (home->state == HOME_STATE_UNKNOWN))
3352 && (home->proto != IPPROTO_TCP)
3355 mark_home_server_zombie(home, &now);
3358 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3359 if (home->type == HOME_TYPE_AUTH) {
3360 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3361 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3364 else if (home->type == HOME_TYPE_ACCT) {
3365 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3366 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3371 * There was no response within the window. Stop
3372 * the request. If the client retransmitted, it
3373 * may have failed over to another home server.
3374 * But that one may be dead, too.
3376 RERROR("Failing request - proxy ID %u, due to lack of any response from home server %s port %d",
3378 inet_ntop(request->proxy->dst_ipaddr.af,
3379 &request->proxy->dst_ipaddr.ipaddr,
3380 buffer, sizeof(buffer)),
3381 request->proxy->dst_port);
3383 if (setup_post_proxy_fail(request)) {
3384 request_queue_or_run(request, proxy_no_reply);
3386 gettimeofday(&request->reply->timestamp, NULL);
3387 request_cleanup_delay_init(request, NULL);
3392 * Duplicate proxy replies have been quenched by
3393 * now. This state is only called ONCE, when we
3394 * receive a new reply from the home server.
3396 case FR_ACTION_PROXY_REPLY:
3397 request_queue_or_run(request, proxy_running);
3400 case FR_ACTION_CONFLICTING:
3401 request_done(request, action);
3405 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3409 #endif /* WITH_PROXY */
3411 /***********************************************************************
3415 ***********************************************************************/
3417 static int null_handler(UNUSED REQUEST *request)
3423 * See if we need to originate a CoA request.
3425 static void request_coa_originate(REQUEST *request)
3427 int rcode, pre_proxy_type = 0;
3433 rad_assert(request != NULL);
3434 rad_assert(request->coa != NULL);
3435 rad_assert(request->proxy == NULL);
3436 rad_assert(!request->in_proxy_hash);
3437 rad_assert(request->proxy_reply == NULL);
3440 * Check whether we want to originate one, or cancel one.
3442 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3444 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3448 if (vp->vp_integer == 0) {
3450 request_free(&request->coa);
3458 * src_ipaddr will be set up in proxy_encode.
3460 memset(&ipaddr, 0, sizeof(ipaddr));
3461 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3463 ipaddr.af = AF_INET;
3464 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3466 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3467 ipaddr.af = AF_INET6;
3468 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3470 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3471 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3473 if (!coa->home_pool) {
3474 RWDEBUG2("No such home_server_pool %s",
3480 * Prefer the pool to one server
3482 } else if (request->client->coa_pool) {
3483 coa->home_pool = request->client->coa_pool;
3485 } else if (request->client->coa_server) {
3486 coa->home_server = request->client->coa_server;
3490 * If all else fails, send it to the client that
3491 * originated this request.
3493 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3497 * Use the pool, if it exists.
3499 if (coa->home_pool) {
3500 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3501 if (!coa->home_server) {
3502 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3505 home_server_update_request(coa->home_server, coa);
3507 } else if (!coa->home_server) {
3508 uint16_t port = PW_COA_UDP_PORT;
3510 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3511 if (vp) port = vp->vp_integer;
3513 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3514 if (!coa->home_server) {
3515 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3516 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3517 buffer, sizeof(buffer)), port);
3522 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3524 switch (vp->vp_integer) {
3525 case PW_CODE_COA_REQUEST:
3526 case PW_CODE_DISCONNECT_REQUEST:
3527 coa->proxy->code = vp->vp_integer;
3531 DEBUG("Cannot set CoA Packet-Type to code %d",
3537 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3540 * The rest of the server code assumes that
3541 * request->packet && request->reply exist. Copy them
3542 * from the original request.
3544 rad_assert(coa->packet != NULL);
3545 rad_assert(coa->packet->vps == NULL);
3547 coa->packet = rad_copy_packet(coa, request->packet);
3548 coa->reply = rad_copy_packet(coa, request->reply);
3550 coa->config_items = paircopy(coa, request->config_items);
3551 coa->num_coa_requests = 0;
3552 coa->handle = null_handler;
3553 coa->number = request->number; /* it's associated with the same request */
3556 * Call the pre-proxy routines.
3558 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3560 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3561 /* Must be a validation issue */
3563 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3564 pre_proxy_type = vp->vp_integer;
3567 if (coa->home_pool && coa->home_pool->virtual_server) {
3568 char const *old_server = coa->server;
3570 coa->server = coa->home_pool->virtual_server;
3571 RDEBUG2("server %s {", coa->server);
3573 rcode = process_pre_proxy(pre_proxy_type, coa);
3576 coa->server = old_server;
3578 rcode = process_pre_proxy(pre_proxy_type, coa);
3585 * Only send the CoA packet if the pre-proxy code succeeded.
3587 case RLM_MODULE_NOOP:
3589 case RLM_MODULE_UPDATED:
3594 * Source IP / port is set when the proxy socket
3597 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3598 coa->proxy->dst_port = coa->home_server->port;
3600 if (!insert_into_proxy_hash(coa)) {
3601 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
3606 * We CANNOT divorce the CoA request from the parent
3607 * request. This function is running in a child thread,
3608 * and we need access to the main event loop in order to
3609 * to add the timers for the CoA packet.
3611 * Instead, we wait for the timer on the parent request
3614 gettimeofday(&coa->proxy->timestamp, NULL);
3615 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3616 coa->delay = 0; /* need to calculate a new delay */
3618 DEBUG_PACKET(coa, coa->proxy, 1);
3620 coa->process = coa_wait_for_reply;
3621 #ifdef DEBUG_STATE_MACHINE
3622 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3623 child_state_names[request->child_state],
3624 child_state_names[REQUEST_RUNNING]);
3626 #ifdef HAVE_PTHREAD_H
3627 coa->child_pid = NO_SUCH_CHILD_PID;
3629 coa->child_state = REQUEST_PROXIED;
3630 rad_assert(coa->proxy_reply == NULL);
3631 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3632 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3633 coa->proxy_listener->send(coa->proxy_listener, coa);
3637 static void coa_timer(REQUEST *request)
3639 uint32_t delay, frac;
3640 struct timeval now, when, mrd;
3642 rad_assert(request->parent == NULL);
3644 if (request->proxy_reply) return request_process_timer(request);
3646 gettimeofday(&now, NULL);
3648 if (request->delay == 0) {
3650 * Implement re-transmit algorithm as per RFC 5080
3653 * We want IRT + RAND*IRT
3654 * or 0.9 IRT + rand(0,.2) IRT
3656 * 2^20 ~ USEC, and we want 2.
3657 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3659 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3660 request->delay = delay * request->home_server->coa_irt;
3661 delay = request->home_server->coa_irt * USEC;
3662 delay -= delay / 10;
3663 delay += request->delay;
3664 request->delay = delay;
3666 when = request->proxy->timestamp;
3667 tv_add(&when, delay);
3669 if (timercmp(&when, &now, >)) {
3670 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3676 * Retransmit CoA request.
3680 * Cap count at MRC, if it is non-zero.
3682 if (request->home_server->coa_mrc &&
3683 (request->num_coa_requests >= request->home_server->coa_mrc)) {
3686 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
3688 inet_ntop(request->proxy->dst_ipaddr.af,
3689 &request->proxy->dst_ipaddr.ipaddr,
3690 buffer, sizeof(buffer)),
3691 request->proxy->dst_port);
3693 if (setup_post_proxy_fail(request)) {
3694 request_queue_or_run(request, coa_no_reply);
3696 request_done(request, FR_ACTION_DONE);
3702 * RFC 5080 Section 2.2.1
3704 * RT = 2*RTprev + RAND*RTprev
3705 * = 1.9 * RTprev + rand(0,.2) * RTprev
3706 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3709 delay ^= (delay >> 16);
3711 frac = request->delay / 5;
3712 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3714 delay += (2 * request->delay) - (request->delay / 10);
3717 * Cap delay at MRT, if MRT is non-zero.
3719 if (request->home_server->coa_mrt &&
3720 (delay > (request->home_server->coa_mrt * USEC))) {
3721 int mrt_usec = request->home_server->coa_mrt * USEC;
3724 * delay = MRT + RAND * MRT
3725 * = 0.9 MRT + rand(0,.2) * MRT
3728 delay ^= (delay >> 15);
3730 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3731 delay += mrt_usec - (mrt_usec / 10);
3734 request->delay = delay;
3736 tv_add(&when, request->delay);
3737 mrd = request->proxy->timestamp;
3738 mrd.tv_sec += request->home_server->coa_mrd;
3741 * Cap duration at MRD.
3743 if (timercmp(&mrd, &when, <)) {
3746 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3748 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3750 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3753 * Status servers don't count as real packets sent.
3755 request->proxy_listener->send(request->proxy_listener,
3759 STATE_MACHINE_DECL(coa_wait_for_reply)
3761 rad_assert(request->parent == NULL);
3763 TRACE_STATE_MACHINE;
3766 case FR_ACTION_TIMER:
3768 * This is big enough to be in it's own function.
3773 case FR_ACTION_PROXY_REPLY:
3774 rad_assert(request->parent == NULL);
3775 request_queue_or_run(request, coa_running);
3779 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3784 static void request_coa_separate(REQUEST *request)
3786 #ifdef DEBUG_STATE_MACHINE
3787 int action = FR_ACTION_TIMER;
3789 TRACE_STATE_MACHINE;
3791 rad_assert(request->parent != NULL);
3792 rad_assert(request->parent->coa == request);
3793 rad_assert(request->ev == NULL);
3794 rad_assert(!request->in_request_hash);
3795 rad_assert(request->coa == NULL);
3797 rad_assert(request->proxy_listener != NULL);
3799 (void) talloc_steal(NULL, request);
3800 request->parent->coa = NULL;
3801 request->parent = NULL;
3804 * Should be coa_wait_for_reply()
3806 request->process(request, FR_ACTION_TIMER);
3809 STATE_MACHINE_DECL(coa_no_reply)
3813 TRACE_STATE_MACHINE;
3816 case FR_ACTION_TIMER:
3817 request_common(request, action);
3820 case FR_ACTION_PROXY_REPLY: /* too late! */
3821 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
3822 inet_ntop(request->proxy->src_ipaddr.af,
3823 &request->proxy->src_ipaddr.ipaddr,
3824 buffer, sizeof(buffer)),
3825 request->proxy->dst_port, request->proxy->id);
3830 * FIXME: do recv_coa Fail
3832 (void) process_proxy_reply(request, NULL);
3833 request_done(request, FR_ACTION_DONE);
3837 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3842 STATE_MACHINE_DECL(coa_running)
3844 TRACE_STATE_MACHINE;
3847 case FR_ACTION_TIMER:
3848 request_process_timer(request);
3851 case FR_ACTION_PROXY_REPLY:
3852 request_common(request, action);
3856 if (process_proxy_reply(request, request->proxy_reply)) {
3857 request->handle(request);
3858 request_finish(request, action);
3860 request_done(request, FR_ACTION_DONE);
3865 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3869 #endif /* WITH_COA */
3871 /***********************************************************************
3873 * End of the State machine. Start of additional helper code.
3875 ***********************************************************************/
3877 /***********************************************************************
3881 ***********************************************************************/
3882 static void event_socket_handler(UNUSED fr_event_list_t *xel, UNUSED int fd, void *ctx)
3884 rad_listen_t *listener = ctx;
3886 rad_assert(xel == el);
3890 (listener->type != RAD_LISTEN_DETAIL) &&
3892 (listener->fd < 0)) {
3895 listener->print(listener, buffer, sizeof(buffer));
3896 ERROR("FATAL: Asked to read from closed socket: %s",
3899 rad_panic("Socket was closed on us!");
3903 listener->recv(listener);
3907 #ifdef WITH_DETAIL_THREAD
3910 * This function is called periodically to see if this detail
3911 * file is available for reading.
3913 static void event_poll_detail(void *ctx)
3916 rad_listen_t *this = ctx;
3917 struct timeval when, now;
3918 listen_detail_t *detail = this->data;
3920 rad_assert(this->type == RAD_LISTEN_DETAIL);
3923 event_socket_handler(el, this->fd, this);
3925 fr_event_now(el, &now);
3929 * Backdoor API to get the delay until the next poll
3932 delay = this->encode(this, NULL);
3933 if (delay == 0) goto redo;
3935 tv_add(&when, delay);
3937 if (!fr_event_insert(el, event_poll_detail, this,
3938 &when, &detail->ev)) {
3939 ERROR("Failed creating handler");
3943 #endif /* WITH_DETAIL_THREAD */
3944 #endif /* WITH_DETAIL */
3946 static void event_status(struct timeval *wake)
3948 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3952 if (debug_flag == 0) {
3954 INFO("Ready to process requests");
3955 just_started = false;
3961 INFO("Ready to process requests");
3963 } else if ((wake->tv_sec != 0) ||
3964 (wake->tv_usec >= 100000)) {
3965 DEBUG("Waking up in %d.%01u seconds.",
3966 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3971 * FIXME: Put this somewhere else, where it isn't called
3972 * all of the time...
3975 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3977 * If there are no child threads, then there may
3978 * be child processes. In that case, wait for
3979 * their exit status, and throw that exit status
3980 * away. This helps get rid of zxombie children.
3982 while (waitpid(-1, &argval, WNOHANG) > 0) {
3990 static void listener_free_cb(void *ctx)
3992 rad_listen_t *this = ctx;
3995 if (this->count > 0) {
3996 struct timeval when;
3997 listen_socket_t *sock = this->data;
3999 fr_event_now(el, &when);
4002 if (!fr_event_insert(el, listener_free_cb, this, &when,
4004 rad_panic("Failed to insert event");
4011 * It's all free, close the socket.
4014 this->print(this, buffer, sizeof(buffer));
4015 DEBUG("... cleaning up socket %s", buffer);
4021 static int proxy_eol_cb(void *ctx, void *data)
4023 struct timeval when;
4024 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4026 if (request->proxy_listener != ctx) return 0;
4029 * We don't care if it's being processed in a child thread.
4032 #ifdef WITH_ACCOUNTING
4034 * Accounting packets should be deleted immediately.
4035 * They will never be retransmitted by the client.
4037 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4038 RDEBUG("Stopping request due to failed connection to home server");
4039 request->master_state = REQUEST_STOP_PROCESSING;
4044 * Reset the timer to be now, so that the request is
4045 * quickly updated. But spread the requests randomly
4046 * over the next second, so that we don't overload the
4049 fr_event_now(el, &when);
4050 tv_add(&when, fr_rand() % USEC);
4051 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4054 * Don't delete it from the list.
4060 static int event_new_fd(rad_listen_t *this)
4066 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4068 this->print(this, buffer, sizeof(buffer));
4070 if (this->status == RAD_LISTEN_STATUS_INIT) {
4071 listen_socket_t *sock = this->data;
4074 DEBUG("Listening on %s", buffer);
4076 INFO(" ... adding new socket %s", buffer);
4079 switch (this->type) {
4082 * Detail files are always known, and aren't
4083 * put into the socket event loop.
4085 case RAD_LISTEN_DETAIL:
4086 this->status = RAD_LISTEN_STATUS_KNOWN;
4088 #ifndef WITH_DETAIL_THREAD
4090 * Set up the first poll interval.
4092 event_poll_detail(this);
4095 break; /* add the FD to the list */
4097 #endif /* WITH_DETAIL */
4101 * Add it to the list of sockets we can use.
4102 * Server sockets (i.e. auth/acct) are never
4103 * added to the packet list.
4105 case RAD_LISTEN_PROXY:
4108 * Add timers to outgoing child sockets, if necessary.
4110 if (sock->proto == IPPROTO_TCP && sock->opened &&
4111 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4112 struct timeval when;
4114 when.tv_sec = sock->opened + 1;
4117 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4119 rad_panic("Failed to insert event");
4124 #endif /* WITH_PROXY */
4127 * FIXME: put idle timers on command sockets.
4133 * Add timers to incoming child sockets, if necessary.
4135 if (sock->proto == IPPROTO_TCP && sock->opened &&
4136 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4137 struct timeval when;
4139 when.tv_sec = sock->opened + 1;
4142 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4144 rad_panic("Failed to insert event");
4149 } /* switch over listener types */
4152 * All sockets: add the FD to the event handler.
4154 if (!fr_event_fd_insert(el, 0, this->fd,
4155 event_socket_handler, this)) {
4156 ERROR("Failed adding event handler for socket!");
4160 this->status = RAD_LISTEN_STATUS_KNOWN;
4166 * Stop using this socket, if at all possible.
4168 if (this->status == RAD_LISTEN_STATUS_EOL) {
4170 * Remove it from the list of live FD's.
4172 fr_event_fd_delete(el, 0, this->fd);
4176 * Proxy sockets get frozen, so that we don't use
4177 * them for new requests. But we do keep them
4178 * open to listen for replies to requests we had
4181 if (this->type == RAD_LISTEN_PROXY) {
4182 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4183 if (!fr_packet_list_socket_freeze(proxy_list,
4185 ERROR("Fatal error freezing socket: %s", fr_strerror());
4189 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4190 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4195 * Requests are still using the socket. Wait for
4198 if (this->count > 0) {
4199 struct timeval when;
4200 listen_socket_t *sock = this->data;
4203 * Try again to clean up the socket in 30
4206 gettimeofday(&when, NULL);
4209 if (!fr_event_insert(el,
4210 (fr_event_callback_t) event_new_fd,
4211 this, &when, &sock->ev)) {
4212 rad_panic("Failed to insert event");
4219 * No one is using the socket. We can remove it now.
4221 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4222 } /* socket is at EOL */
4228 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4231 listen_socket_t *sock = this->data;
4233 struct timeval when;
4236 * Re-open the socket, pointing it to /dev/null.
4237 * This means that all writes proceed without
4238 * blocking, and all reads return "no data".
4240 * This leaves the socket active, so any child
4241 * threads won't go insane. But it means that
4242 * they cannot send or receive any packets.
4244 * This is EXTRA work in the normal case, when
4245 * sockets are closed without error. But it lets
4246 * us have one simple processing method for all
4249 devnull = open("/dev/null", O_RDWR);
4251 ERROR("FATAL failure opening /dev/null: %s",
4252 fr_syserror(errno));
4255 if (dup2(devnull, this->fd) < 0) {
4256 ERROR("FATAL failure closing socket: %s",
4257 fr_syserror(errno));
4263 rad_assert(this->type != RAD_LISTEN_DETAIL);
4267 INFO(" ... shutting down socket %s", buffer);
4271 * The socket is dead. Force all proxied packets
4272 * to stop using it. And then remove it from the
4273 * list of outgoing sockets.
4275 if (this->type == RAD_LISTEN_PROXY) {
4276 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4277 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4279 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4280 ERROR("Fatal error removing socket %s: %s",
4281 buffer, fr_strerror());
4284 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4289 * EOL all requests using this socket.
4291 fr_packet_list_walk(pl, this, eol_listener);
4295 * No child threads, clean it up now.
4298 if (sock->ev) fr_event_delete(el, &sock->ev);
4304 * Wait until all requests using this socket are done.
4306 gettimeofday(&when, NULL);
4309 if (!fr_event_insert(el, listener_free_cb, this, &when,
4311 rad_panic("Failed to insert event");
4314 #endif /* WITH_TCP */
4319 /***********************************************************************
4323 ***********************************************************************/
4325 static void handle_signal_self(int flag)
4329 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4330 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4331 INFO("Signalled to exit");
4332 fr_event_loop_exit(el, 1);
4334 INFO("Signalled to terminate");
4335 exec_trigger(NULL, NULL, "server.signal.term", true);
4336 fr_event_loop_exit(el, 2);
4340 } /* else exit/term flags weren't set */
4343 * Tell the even loop to stop processing.
4345 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4347 static time_t last_hup = 0;
4350 if ((int) (when - last_hup) < 5) {
4351 INFO("Ignoring HUP (less than 5s since last one)");
4355 INFO("Received HUP signal");
4359 exec_trigger(NULL, NULL, "server.signal.hup", true);
4360 fr_event_loop_exit(el, 0x80);
4364 #ifndef WITH_DETAIL_THREAD
4365 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4369 * FIXME: O(N) loops suck.
4371 for (this = main_config.listen;
4373 this = this->next) {
4374 if (this->type != RAD_LISTEN_DETAIL) continue;
4377 * This one didn't send the signal, skip
4380 if (!this->decode(this, NULL)) continue;
4383 * Go service the interrupt.
4385 event_poll_detail(this);
4393 #ifdef HAVE_PTHREAD_H
4395 * There are new listeners in the list. Run
4396 * event_new_fd() on them.
4398 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4399 rad_listen_t *this, *next;
4401 FD_MUTEX_LOCK(&fd_mutex);
4404 * FIXME: unlock the mutex before calling
4407 for (this = new_listeners; this != NULL; this = next) {
4414 new_listeners = NULL;
4415 FD_MUTEX_UNLOCK(&fd_mutex);
4417 #endif /* HAVE_PTHREAD_H */
4418 #endif /* WITH_PROXY */
4419 #endif /* WITH_TCP */
4422 #ifndef HAVE_PTHREAD_H
4423 void radius_signal_self(int flag)
4425 return handle_signal_self(flag);
4429 static int self_pipe[2] = { -1, -1 };
4432 * Inform ourselves that we received a signal.
4434 void radius_signal_self(int flag)
4440 * The read MUST be non-blocking for this to work.
4442 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4446 for (i = 0; i < rcode; i++) {
4447 buffer[0] |= buffer[i];
4455 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4459 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4460 UNUSED int fd, UNUSED void *ctx)
4465 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4466 if (rcode <= 0) return;
4469 * Merge pending signals.
4471 for (i = 0; i < rcode; i++) {
4472 buffer[0] |= buffer[i];
4475 handle_signal_self(buffer[0]);
4477 #endif /* HAVE_PTHREAD_H */
4479 /***********************************************************************
4481 * Bootstrapping code.
4483 ***********************************************************************/
4486 * Externally-visibly functions.
4488 int radius_event_init(TALLOC_CTX *ctx) {
4489 el = fr_event_list_create(ctx, event_status);
4495 int radius_event_start(CONF_SECTION *cs, bool have_children)
4497 rad_listen_t *head = NULL;
4499 if (fr_start_time != (time_t)-1) return 0;
4501 time(&fr_start_time);
4504 * radius_event_init() must be called first
4507 if (fr_start_time == (time_t)-1) return 0;
4509 pl = fr_packet_list_create(0);
4510 if (!pl) return 0; /* leak el */
4512 request_num_counter = 0;
4515 if (main_config.proxy_requests) {
4517 * Create the tree for managing proxied requests and
4520 proxy_list = fr_packet_list_create(1);
4521 if (!proxy_list) return 0;
4523 #ifdef HAVE_PTHREAD_H
4524 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4525 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4526 fr_syserror(errno));
4534 * Move all of the thread calls to this file?
4536 * It may be best for the mutexes to be in this file...
4538 spawn_flag = have_children;
4540 #ifdef HAVE_PTHREAD_H
4541 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4544 * Initialize the threads ONLY if we're spawning, AND
4545 * we're running normally.
4547 if (have_children && !check_config &&
4548 (thread_pool_init(cs, &spawn_flag) < 0)) {
4554 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4556 if (listen_init(cs, &head, spawn_flag) < 0) {
4563 #ifdef HAVE_PTHREAD_H
4565 * Child threads need a pipe to signal us, as do the
4568 if (pipe(self_pipe) < 0) {
4569 ERROR("radiusd: Error opening internal pipe: %s",
4570 fr_syserror(errno));
4573 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4574 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4575 ERROR("radiusd: Error setting internal flags: %s",
4576 fr_syserror(errno));
4579 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4580 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4581 ERROR("radiusd: Error setting internal flags: %s",
4582 fr_syserror(errno));
4586 if (!fr_event_fd_insert(el, 0, self_pipe[0],
4587 event_signal_handler, el)) {
4588 ERROR("Failed creating handler for signals");
4593 DEBUG("%s: #### Opening IP addresses and Ports ####",
4597 * The server temporarily switches to an unprivileged
4598 * user very early in the bootstrapping process.
4599 * However, some sockets MAY require privileged access
4600 * (bind to device, or to port < 1024, or to raw
4601 * sockets). Those sockets need to call suid up/down
4602 * themselves around the functions that need a privileged
4605 if (listen_init(cs, &head, spawn_flag) < 0) {
4609 main_config.listen = head;
4612 * At this point, no one has any business *ever* going
4615 fr_suid_down_permanent();
4622 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4624 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4626 request->master_state = REQUEST_STOP_PROCESSING;
4628 #ifdef HAVE_PTHREAD_H
4629 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4633 * If it's queued we can't delete it from the queue.
4635 * Otherwise, it's OK to delete it. Even RUNNING, because
4636 * that will get caught by the check above.
4638 if (request->child_state == REQUEST_QUEUED) return 0;
4640 request->in_proxy_hash = false;
4642 if (!request->in_request_hash) {
4643 request_done(request, FR_ACTION_DONE);
4647 * Delete it from the list.
4654 static int request_delete_cb(UNUSED void *ctx, void *data)
4656 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4658 request->master_state = REQUEST_STOP_PROCESSING;
4661 * Not done, or the child thread is still processing it.
4663 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
4665 #ifdef HAVE_PTHREAD_H
4666 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4670 rad_assert(request->in_proxy_hash == false);
4673 request->in_request_hash = false;
4674 if (request->ev) fr_event_delete(el, &request->ev);
4676 if (main_config.memory_report) {
4677 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
4678 request->packet->id,
4679 (unsigned int) (request->timestamp - fr_start_time));
4684 rad_assert(!request->coa->in_proxy_hash);
4688 request_free(&request);
4691 * Delete it from the list, and continue;
4697 void radius_event_free(void)
4703 * There are requests in the proxy hash that aren't
4704 * referenced from anywhere else. Remove them first.
4707 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4711 fr_packet_list_walk(pl, NULL, request_delete_cb);
4715 * Now that all requests have been marked "please stop",
4716 * ensure that all of the threads have exited.
4718 #ifdef HAVE_PTHREAD_H
4723 * Walk the lists again, ensuring that all
4724 * requests are done.
4726 if (main_config.memory_report) {
4731 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4732 num = fr_packet_list_num_elements(proxy_list);
4734 ERROR("Proxy list has %d requests still in it.", num);
4739 fr_packet_list_walk(pl, NULL, request_delete_cb);
4740 num = fr_packet_list_num_elements(pl);
4742 ERROR("Request list has %d requests still in it.", num);
4747 fr_packet_list_free(pl);
4751 fr_packet_list_free(proxy_list);
4757 if (debug_condition) talloc_free(debug_condition);
4760 int radius_event_process(void)
4764 return fr_event_loop(el);