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 = 0;
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);
1023 * We probbly should check if the request is
1024 * DONE. If so, delete it, and allow the new
1025 * request to continue. But we can't give
1026 * feedback to request_receive(), so we let it
1027 * take care of that.
1029 ERROR("(%u) Discarding duplicate request from "
1030 "client %s port %d - ID: %u due to unfinished request "
1031 "in component %s module %s",
1032 request->number, request->client->shortname,
1033 request->packet->src_port,request->packet->id,
1034 request->component, request->module);
1037 case FR_ACTION_CONFLICTING:
1039 * We're in the master thread, ask the child to
1040 * stop processing the request.
1042 request_done(request, action);
1045 case FR_ACTION_TIMER:
1046 request_process_timer(request);
1050 case FR_ACTION_PROXY_REPLY:
1051 RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. Try increasing 'retry_delay' or 'max_request_time'",
1052 inet_ntop(request->proxy->dst_ipaddr.af,
1053 &request->proxy->dst_ipaddr.ipaddr,
1054 buffer, sizeof(buffer)),
1055 request->proxy->dst_port, request->proxy->id);
1060 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1065 STATE_MACHINE_DECL(request_cleanup_delay)
1067 struct timeval when;
1069 TRACE_STATE_MACHINE;
1074 if (request->reply->code != 0) {
1075 request->listener->send(request->listener, request);
1077 RDEBUG("No reply. Ignoring retransmit");
1081 * Double the cleanup_delay to catch retransmits.
1083 when = request->reply->timestamp;
1084 request->delay += request->delay ;
1085 when.tv_sec += request->delay;
1087 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1090 case FR_ACTION_CONFLICTING:
1091 request_done(request, FR_ACTION_DONE);
1095 case FR_ACTION_PROXY_REPLY:
1097 case FR_ACTION_TIMER:
1098 request_common(request, action);
1102 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1107 STATE_MACHINE_DECL(request_response_delay)
1109 TRACE_STATE_MACHINE;
1114 ERROR("(%u) Discarding duplicate request from "
1115 "client %s port %d - ID: %u due to delayed response",
1116 request->number, request->client->shortname,
1117 request->packet->src_port,request->packet->id);
1121 case FR_ACTION_PROXY_REPLY:
1123 case FR_ACTION_CONFLICTING:
1124 case FR_ACTION_TIMER:
1125 request_common(request, action);
1129 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1135 static int CC_HINT(nonnull) request_pre_handler(REQUEST *request, UNUSED int action)
1137 TRACE_STATE_MACHINE;
1141 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1144 * Don't decode the packet if it's an internal "fake"
1145 * request. Instead, just return so that the caller can
1148 if (request->packet->dst_port == 0) {
1149 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1150 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1154 if (!request->packet->vps) { /* FIXME: check for correct state */
1155 rcode = request->listener->decode(request->listener, request);
1158 if (debug_condition) {
1160 * Ignore parse errors.
1162 if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1163 request->log.lvl = L_DBG_LVL_2;
1164 request->log.func = vradlog_request;
1169 DEBUG_PACKET(request, request->packet, 0);
1175 RDEBUG("Dropping packet without response because of error: %s", fr_strerror());
1176 request->reply->offset = -2; /* bad authenticator */
1180 if (!request->username) {
1181 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1187 STATE_MACHINE_DECL(request_finish)
1191 TRACE_STATE_MACHINE;
1193 (void) action; /* -Wunused */
1195 if (request->master_state == REQUEST_STOP_PROCESSING) {
1201 * Don't send replies if there are none to send.
1203 if (!request->in_request_hash) {
1205 if ((request->listener->type == RAD_LISTEN_AUTH)
1206 #ifdef WITH_ACCOUNTING
1207 || (request->listener->type == RAD_LISTEN_ACCT)
1210 listen_socket_t *sock = request->listener->data;
1212 if (sock->proto == IPPROTO_UDP) return;
1215 * TCP packets aren't in the request
1226 * Override the response code if a control:Response-Packet-Type attribute is present.
1228 vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1230 if (vp->vp_integer == 256) {
1231 RDEBUG2("Not responding to request");
1232 request->reply->code = 0;
1234 request->reply->code = vp->vp_integer;
1238 * Catch Auth-Type := Reject BEFORE proxying the packet.
1240 else if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1241 if (request->reply->code == 0) {
1242 vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1244 if (!vp || (vp->vp_integer != PW_CODE_AUTHENTICATION_REJECT)) {
1245 RDEBUG2("There was no response configured: "
1246 "rejecting request");
1249 request->reply->code = PW_CODE_AUTHENTICATION_REJECT;
1254 * Copy Proxy-State from the request to the reply.
1256 vp = paircopy2(request->reply, request->packet->vps,
1257 PW_PROXY_STATE, 0, TAG_ANY);
1258 if (vp) pairadd(&request->reply->vps, vp);
1260 switch (request->reply->code) {
1261 case PW_CODE_AUTHENTICATION_ACK:
1262 rad_postauth(request);
1264 case PW_CODE_ACCESS_CHALLENGE:
1265 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1267 vp = pairmake_config("Post-Auth-Type", "Challenge", T_OP_SET);
1268 if (vp) rad_postauth(request);
1275 * Run rejected packets through
1277 * Post-Auth-Type = Reject
1279 * We do this separately so ACK and challenge can change the code
1280 * to reject if a module returns reject.
1282 if (request->reply->code == PW_CODE_AUTHENTICATION_REJECT) {
1283 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1284 vp = pairmake_config("Post-Auth-Type", "Reject", T_OP_SET);
1285 if (vp) rad_postauth(request);
1289 * Clean up. These are no longer needed.
1291 pairfree(&request->config_items);
1293 pairfree(&request->packet->vps);
1294 request->username = NULL;
1295 request->password = NULL;
1298 if (request->proxy) {
1299 pairfree(&request->proxy->vps);
1301 if (request->proxy_reply) {
1302 pairfree(&request->proxy_reply->vps);
1306 gettimeofday(&request->reply->timestamp, NULL);
1309 * Ignore all "do not respond" packets.
1311 if (!request->reply->code) {
1312 RDEBUG("Not sending reply");
1317 * See if we need to delay an Access-Reject packet.
1319 if ((request->reply->code == PW_CODE_AUTHENTICATION_REJECT) &&
1320 (request->root->reject_delay > 0)) {
1321 request->response_delay = request->root->reject_delay;
1327 if (!request->response_delay) {
1328 DEBUG_PACKET(request, request->reply, 1);
1329 request->listener->send(request->listener,
1333 pairfree(&request->reply->vps);
1335 RDEBUG2("Finished request");
1336 #ifdef WITH_ACCOUNTING
1337 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1339 request->child_state = REQUEST_DONE;
1343 if (request->root->cleanup_delay == 0) {
1345 request->child_state = REQUEST_DONE;
1348 request->child_state = REQUEST_CLEANUP_DELAY;
1351 RDEBUG2("Delaying response for %d seconds",
1352 request->response_delay);
1354 request->child_state = REQUEST_RESPONSE_DELAY;
1358 STATE_MACHINE_DECL(request_running)
1360 TRACE_STATE_MACHINE;
1363 case FR_ACTION_TIMER:
1364 request_process_timer(request);
1367 case FR_ACTION_CONFLICTING:
1369 request_common(request, action);
1374 * This can happen due to a race condition where
1375 * we send a proxied request, and immediately get
1376 * another reply, before the timer has a chance
1377 * to update the various states.
1379 case FR_ACTION_PROXY_REPLY:
1380 request->child_state = REQUEST_RUNNING;
1381 request->process = proxy_running;
1382 request->process(request, FR_ACTION_RUN);
1387 if (!request_pre_handler(request, action)) {
1388 #ifdef DEBUG_STATE_MACHINE
1389 if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1390 request->number, __FUNCTION__,
1391 child_state_names[request->child_state],
1392 child_state_names[REQUEST_DONE]);
1396 request->child_state = REQUEST_DONE;
1400 rad_assert(request->handle != NULL);
1401 request->handle(request);
1405 * We may need to send a proxied request.
1407 if ((action == FR_ACTION_RUN) &&
1408 request_will_proxy(request)) {
1409 #ifdef DEBUG_STATE_MACHINE
1410 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1414 * takes care of setting
1415 * up the post proxy fail
1418 if (request_proxy(request, 0) < 0) goto finished;
1422 #ifdef DEBUG_STATE_MACHINE
1423 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1428 * Maybe originate a CoA request.
1430 if ((action == FR_ACTION_RUN) && request->coa) {
1431 request_coa_originate(request);
1438 request_finish(request, action);
1443 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1448 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1449 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1452 RADIUS_PACKET **packet_p;
1453 REQUEST *request = NULL;
1455 listen_socket_t *sock = NULL;
1458 * Set the last packet received.
1460 gettimeofday(&now, NULL);
1462 #ifdef WITH_ACCOUNTING
1463 if (listener->type != RAD_LISTEN_DETAIL)
1466 sock = listener->data;
1467 sock->last_packet = now.tv_sec;
1469 packet->timestamp = now;
1472 * Skip everything if required.
1474 if (listener->nodup) goto skip_dup;
1476 packet_p = fr_packet_list_find(pl, packet);
1478 request = fr_packet2myptr(REQUEST, packet, packet_p);
1479 rad_assert(request->in_request_hash);
1482 * Same src/dst ip/port, length, and
1483 * authentication vector: must be a duplicate.
1485 if ((request->packet->data_len == packet->data_len) &&
1486 (memcmp(request->packet->vector, packet->vector,
1487 sizeof(packet->vector)) == 0)) {
1490 * If the request is running, it'
1492 if (request->child_state != REQUEST_DONE) {
1493 request->process(request, FR_ACTION_DUP);
1496 switch (packet->code) {
1497 case PW_CODE_AUTHENTICATION_REQUEST:
1498 FR_STATS_INC(auth, total_dup_requests);
1501 #ifdef WITH_ACCOUNTING
1502 case PW_CODE_ACCOUNTING_REQUEST:
1503 FR_STATS_INC(acct, total_dup_requests);
1507 case PW_CODE_COA_REQUEST:
1508 FR_STATS_INC(coa, total_dup_requests);
1511 case PW_CODE_DISCONNECT_REQUEST:
1512 FR_STATS_INC(dsc, total_dup_requests);
1519 #endif /* WITH_STATS */
1520 return 0; /* duplicate of live request */
1522 #ifdef HAVE_PTHREAD_H
1524 * There should no longer be a child
1525 * thread associated with this request.
1527 rad_assert(pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) != 0);
1531 * Clean up the old request, and allow
1532 * the new one to continue.
1534 request_done(request, FR_ACTION_DONE);
1539 * Say we're ignoring the old one, and continue
1540 * to process the new one.
1542 request->process(request, FR_ACTION_CONFLICTING);
1548 * Quench maximum number of outstanding requests.
1550 if (main_config.max_requests &&
1551 ((count = fr_packet_list_num_elements(pl)) > main_config.max_requests)) {
1552 RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1554 packet->src_port, packet->id);
1555 WARN("Please check the configuration file.\n"
1556 "\tThe value for 'max_requests' is probably set too low.\n"));
1558 exec_trigger(NULL, NULL, "server.max_requests", true);
1564 * Rate-limit the incoming packets
1566 if (sock && sock->max_rate) {
1569 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1570 if (pps > sock->max_rate) {
1571 DEBUG("Dropping request due to rate limiting");
1574 sock->rate_pps_now++;
1577 request = request_setup(listener, packet, client, fun);
1578 if (!request) return 1;
1581 * Remember the request in the list.
1583 if (!listener->nodup) {
1584 if (!fr_packet_list_insert(pl, &request->packet)) {
1585 RERROR("Failed to insert request in the list of live requests: discarding it");
1586 request_done(request, FR_ACTION_DONE);
1590 request->in_request_hash = true;
1594 * Process it. Send a response, and free it.
1596 if (listener->synchronous) {
1597 request->listener->decode(request->listener, request);
1598 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1599 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1603 if (request->reply->code != 0) {
1604 request->listener->send(request->listener, request);
1606 RDEBUG("Not sending reply");
1608 request_free(&request);
1613 * Otherwise, insert it into the state machine.
1614 * The child threads will take care of processing it.
1616 request_queue_or_run(request, request_running);
1622 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
1623 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1628 * Create and initialize the new request.
1630 request = request_alloc(NULL);
1631 request->reply = rad_alloc(request, 0);
1632 if (!request->reply) {
1634 request_free(&request);
1638 request->listener = listener;
1639 request->client = client;
1640 request->packet = talloc_steal(request, packet);
1641 request->number = request_num_counter++;
1642 request->priority = listener->type;
1643 request->master_state = REQUEST_ACTIVE;
1644 #ifdef DEBUG_STATE_MACHINE
1645 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1646 request->number, __FUNCTION__,
1647 child_state_names[request->child_state],
1648 child_state_names[REQUEST_RUNNING]);
1650 request->child_state = REQUEST_RUNNING;
1651 request->handle = fun;
1655 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1656 if (packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1657 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1658 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1659 #ifdef WITH_ACCOUNTING
1660 } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1661 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1662 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1665 #endif /* WITH_STATS */
1668 * Status-Server packets go to the head of the queue.
1670 if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1673 * Set virtual server identity
1675 if (client->server) {
1676 request->server = client->server;
1677 } else if (listener->server) {
1678 request->server = listener->server;
1680 request->server = NULL;
1683 request->root = &main_config;
1685 request->listener->count++;
1689 * The request passes many of our sanity checks.
1690 * From here on in, if anything goes wrong, we
1691 * send a reject message, instead of dropping the
1696 * Build the reply template from the request.
1699 request->reply->sockfd = request->packet->sockfd;
1700 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1701 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1702 request->reply->dst_port = request->packet->src_port;
1703 request->reply->src_port = request->packet->dst_port;
1704 request->reply->id = request->packet->id;
1705 request->reply->code = 0; /* UNKNOWN code */
1706 memcpy(request->reply->vector, request->packet->vector,
1707 sizeof(request->reply->vector));
1708 request->reply->vps = NULL;
1709 request->reply->data = NULL;
1710 request->reply->data_len = 0;
1716 /***********************************************************************
1720 ***********************************************************************/
1723 * Timer function for all TCP sockets.
1725 static void tcp_socket_timer(void *ctx)
1727 rad_listen_t *listener = ctx;
1728 listen_socket_t *sock = listener->data;
1729 struct timeval end, now;
1731 fr_socket_limit_t *limit;
1735 fr_event_now(el, &now);
1737 if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1739 switch (listener->type) {
1741 case RAD_LISTEN_PROXY:
1742 limit = &sock->home->limit;
1746 case RAD_LISTEN_AUTH:
1747 #ifdef WITH_ACCOUNTING
1748 case RAD_LISTEN_ACCT:
1750 limit = &sock->limit;
1758 * If we enforce a lifetime, do it now.
1760 if (limit->lifetime > 0) {
1761 end.tv_sec = sock->opened + limit->lifetime;
1764 if (timercmp(&end, &now, <=)) {
1765 listener->print(listener, buffer, sizeof(buffer));
1766 DEBUG("Reached maximum lifetime on socket %s", buffer);
1770 listener->status = RAD_LISTEN_STATUS_EOL;
1771 event_new_fd(listener);
1780 * Enforce an idle timeout.
1782 if (limit->idle_timeout > 0) {
1783 struct timeval idle;
1785 rad_assert(sock->last_packet != 0);
1786 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1789 if (timercmp(&idle, &now, <=)) {
1790 listener->print(listener, buffer, sizeof(buffer));
1791 DEBUG("Reached idle timeout on socket %s", buffer);
1796 * Enforce the minimum of idle timeout or lifetime.
1798 if (timercmp(&idle, &end, <)) {
1804 * Wake up at t + 0.5s. The code above checks if the timers
1805 * are <= t. This addition gives us a bit of leeway.
1807 end.tv_usec = USEC / 2;
1809 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1810 rad_panic("Failed to insert event");
1817 * Add +/- 2s of jitter, as suggested in RFC 3539
1820 static void add_jitter(struct timeval *when)
1827 jitter ^= (jitter >> 10);
1828 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1831 * Add in ~ (4 * USEC) of jitter.
1833 tv_add(when, jitter);
1837 * Called by socket_del to remove requests with this socket
1839 static int eol_proxy_listener(void *ctx, void *data)
1841 rad_listen_t *this = ctx;
1842 RADIUS_PACKET **proxy_p = data;
1845 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1846 if (request->proxy_listener != this) return 0;
1849 * The normal "remove_from_proxy_hash" tries to grab the
1850 * proxy mutex. We already have it held, so grabbing it
1851 * again will cause a deadlock. Instead, call the "no
1852 * lock" version of the function.
1854 rad_assert(request->in_proxy_hash == true);
1855 remove_from_proxy_hash_nl(request, false);
1858 * Don't mark it as DONE. The client can retransmit, and
1859 * the packet SHOULD be re-proxied somewhere else.
1861 * Return "2" means that the rbtree code will remove it
1862 * from the tree, and we don't need to do it ourselves.
1866 #endif /* WITH_PROXY */
1868 static int eol_listener(void *ctx, void *data)
1870 rad_listen_t *this = ctx;
1871 RADIUS_PACKET **packet_p = data;
1874 request = fr_packet2myptr(REQUEST, packet, packet_p);
1875 if (request->listener != this) return 0;
1877 request->master_state = REQUEST_STOP_PROCESSING;
1881 #endif /* WITH_TCP */
1884 /***********************************************************************
1886 * Proxy handlers for the state machine.
1888 ***********************************************************************/
1891 * Called with the proxy mutex held
1893 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1895 if (!request->in_proxy_hash) return;
1897 fr_packet_list_id_free(proxy_list, request->proxy, yank);
1898 request->in_proxy_hash = false;
1901 * On the FIRST reply, decrement the count of outstanding
1902 * requests. Note that this is NOT the count of sent
1903 * packets, but whether or not the home server has
1906 if (request->home_server &&
1907 request->home_server->currently_outstanding) {
1908 request->home_server->currently_outstanding--;
1911 * If we're NOT sending it packets, then we don't know
1912 * if it's alive or dead.
1914 if ((request->home_server->currently_outstanding == 0) &&
1915 (request->home_server->state == HOME_STATE_ALIVE)) {
1916 request->home_server->state = HOME_STATE_UNKNOWN;
1917 request->home_server->last_packet_sent = 0;
1918 request->home_server->last_packet_recv = 0;
1923 rad_assert(request->proxy_listener != NULL);
1924 request->proxy_listener->count--;
1926 request->proxy_listener = NULL;
1929 * Got from YES in hash, to NO, not in hash while we hold
1930 * the mutex. This guarantees that when another thread
1931 * grabs the mutex, the "not in hash" flag is correct.
1933 RDEBUG3("proxy: request is no longer in proxy hash");
1936 static void remove_from_proxy_hash(REQUEST *request)
1939 * Check this without grabbing the mutex because it's a
1940 * lot faster that way.
1942 if (!request->in_proxy_hash) return;
1945 * The "not in hash" flag is definitive. However, if the
1946 * flag says that it IS in the hash, there might still be
1947 * a race condition where it isn't.
1949 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1951 if (!request->in_proxy_hash) {
1952 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1956 remove_from_proxy_hash_nl(request, true);
1958 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1961 static int insert_into_proxy_hash(REQUEST *request)
1965 void *proxy_listener;
1967 rad_assert(request->proxy != NULL);
1968 rad_assert(request->home_server != NULL);
1969 rad_assert(proxy_list != NULL);
1972 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1973 proxy_listener = NULL;
1974 request->num_proxied_requests = 1;
1975 request->num_proxied_responses = 0;
1977 for (tries = 0; tries < 2; tries++) {
1980 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
1981 rcode = fr_packet_list_id_alloc(proxy_list,
1982 request->home_server->proto,
1983 &request->proxy, &proxy_listener);
1984 if ((debug_flag > 2) && (rcode == 0)) {
1985 RDEBUG("proxy: Failed allocating ID: %s", fr_strerror());
1987 if (rcode > 0) break;
1988 if (tries > 0) continue; /* try opening new socket only once */
1990 #ifdef HAVE_PTHREAD_H
1991 if (proxy_no_new_sockets) break;
1994 RDEBUG3("proxy: Trying to open a new listener to the home server");
1995 this = proxy_new_listener(request->home_server, 0);
1997 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2001 request->proxy->src_port = 0; /* Use any new socket */
2002 proxy_listener = this;
2005 * Add it to the event loop. Ensure that we have
2006 * only one mutex locked at a time.
2008 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2009 radius_update_listener(this);
2010 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2013 if (!proxy_listener || (rcode == 0)) {
2014 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2015 REDEBUG2("proxy: Failed allocating Id for proxied request");
2017 request->proxy_listener = NULL;
2018 request->in_proxy_hash = false;
2022 rad_assert(request->proxy->id >= 0);
2024 request->proxy_listener = proxy_listener;
2025 request->in_proxy_hash = true;
2026 RDEBUG3("proxy: request is now in proxy hash");
2029 * Keep track of maximum outstanding requests to a
2030 * particular home server. 'max_outstanding' is
2031 * enforced in home_server_ldb(), in realms.c.
2033 request->home_server->currently_outstanding++;
2036 request->proxy_listener->count++;
2039 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2041 RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2042 inet_ntop(request->proxy->dst_ipaddr.af,
2043 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
2044 request->proxy->dst_port,
2045 request->proxy->id);
2050 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2053 int post_proxy_type = 0;
2057 * There may be a proxy reply, but it may be too late.
2059 if (!request->proxy_listener) return 0;
2062 * Delete any reply we had accumulated until now.
2064 pairfree(&request->reply->vps);
2067 * Run the packet through the post-proxy stage,
2068 * BEFORE playing games with the attributes.
2070 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2073 * If we have a proxy_reply, and it was a reject, setup
2074 * post-proxy-type Reject
2077 reply->code == PW_CODE_AUTHENTICATION_REJECT) {
2080 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2082 vp = radius_paircreate(request, &request->config_items,
2083 PW_POST_PROXY_TYPE, 0);
2085 vp->vp_integer = dval->value;
2090 post_proxy_type = vp->vp_integer;
2092 RDEBUG2("Found Post-Proxy-Type %s", dict_valnamebyattr(PW_POST_PROXY_TYPE, 0, post_proxy_type));
2097 * Decode the packet.
2099 rcode = request->proxy_listener->decode(request->proxy_listener, request);
2100 DEBUG_PACKET(request, reply, 0);
2103 * Pro-actively remove it from the proxy hash.
2104 * This is later than in 2.1.x, but it means that
2105 * the replies are authenticated before being
2106 * removed from the hash.
2109 (request->num_proxied_requests <= request->num_proxied_responses)) {
2110 remove_from_proxy_hash(request);
2113 remove_from_proxy_hash(request);
2116 if (request->home_pool && request->home_pool->virtual_server) {
2117 char const *old_server = request->server;
2119 request->server = request->home_pool->virtual_server;
2120 RDEBUG2("server %s {", request->server);
2122 rcode = process_post_proxy(post_proxy_type, request);
2125 request->server = old_server;
2127 rcode = process_post_proxy(post_proxy_type, request);
2131 if (request->packet->code == request->proxy->code)
2133 * Don't run the next bit if we originated a CoA
2134 * packet, after receiving an Access-Request or
2135 * Accounting-Request.
2140 * There may NOT be a proxy reply, as we may be
2141 * running Post-Proxy-Type = Fail.
2144 request->reply->vps = paircopy(request->reply, reply->vps);
2147 * Delete the Proxy-State Attributes from
2148 * the reply. These include Proxy-State
2149 * attributes from us and remote server.
2151 pairdelete(&request->reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2155 default: /* Don't do anything */
2157 case RLM_MODULE_FAIL:
2160 case RLM_MODULE_HANDLED:
2167 int request_proxy_reply(RADIUS_PACKET *packet)
2169 RADIUS_PACKET **proxy_p;
2174 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2175 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2178 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2179 PROXY( "No outstanding request was found for reply from host %s port %d - ID %u",
2180 inet_ntop(packet->src_ipaddr.af,
2181 &packet->src_ipaddr.ipaddr,
2182 buffer, sizeof(buffer)),
2183 packet->src_port, packet->id);
2187 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2188 request->num_proxied_responses++; /* needs to be protected by lock */
2190 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2193 * No reply, BUT the current packet fails verification:
2194 * ignore it. This does the MD5 calculations in the
2195 * server core, but I guess we can fix that later.
2197 if (!request->proxy_reply &&
2198 (rad_verify(packet, request->proxy,
2199 request->home_server->secret) != 0)) {
2200 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2205 * The home server sent us a packet which doesn't match
2206 * something we have: ignore it. This is done only to
2207 * catch the case of broken systems.
2209 if (request->proxy_reply &&
2210 (memcmp(request->proxy_reply->vector,
2212 sizeof(request->proxy_reply->vector)) != 0)) {
2213 RDEBUG2("Ignoring conflicting proxy reply");
2217 gettimeofday(&now, NULL);
2220 * Status-Server packets don't count as real packets.
2222 if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2223 listen_socket_t *sock = request->proxy_listener->data;
2225 request->home_server->last_packet_recv = now.tv_sec;
2226 sock->last_packet = now.tv_sec;
2230 * If we have previously seen a reply, ignore the
2233 if (request->proxy_reply) {
2234 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2235 inet_ntop(packet->src_ipaddr.af,
2236 &packet->src_ipaddr.ipaddr,
2237 buffer, sizeof(buffer)),
2238 packet->src_port, packet->id);
2243 * Call the state machine to do something useful with the
2246 request->proxy_reply = talloc_steal(request, packet);
2247 packet->timestamp = now;
2248 request->priority = RAD_LISTEN_PROXY;
2251 * We've received a reply. If we hadn't been sending it
2252 * packets for a while, just mark it alive.
2254 if (request->home_server->state == HOME_STATE_UNKNOWN) {
2255 request->home_server->state = HOME_STATE_ALIVE;
2259 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2260 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2262 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2263 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2264 #ifdef WITH_ACCOUNTING
2265 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2266 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2269 #endif /* WITH_STATS */
2273 * When we originate CoA requests, we patch them in here
2274 * so that they don't affect the rest of the state
2277 if (request->parent) {
2278 rad_assert(request->parent->coa == request);
2279 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
2280 (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
2281 rad_assert(request->process != NULL);
2282 request_coa_separate(request);
2286 request->process(request, FR_ACTION_PROXY_REPLY);
2292 static int setup_post_proxy_fail(REQUEST *request)
2294 DICT_VALUE const *dval = NULL;
2297 if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2298 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2299 "Fail-Authentication");
2301 } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2302 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2305 } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2306 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2308 } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2309 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2312 WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2316 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2319 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2323 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2324 if (!vp) vp = radius_paircreate(request, &request->config_items,
2325 PW_POST_PROXY_TYPE, 0);
2326 vp->vp_integer = dval->value;
2331 STATE_MACHINE_DECL(proxy_no_reply)
2333 TRACE_STATE_MACHINE;
2336 case FR_ACTION_CONFLICTING:
2338 case FR_ACTION_TIMER:
2339 case FR_ACTION_PROXY_REPLY:
2340 request_common(request, action);
2344 (void) process_proxy_reply(request, NULL);
2345 request_done(request, FR_ACTION_DONE);
2349 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2354 STATE_MACHINE_DECL(proxy_running)
2356 TRACE_STATE_MACHINE;
2359 case FR_ACTION_CONFLICTING:
2361 case FR_ACTION_TIMER:
2362 case FR_ACTION_PROXY_REPLY:
2363 request_common(request, action);
2367 if (process_proxy_reply(request, request->proxy_reply)) {
2368 request->handle(request);
2369 request_finish(request, action);
2371 request_done(request, FR_ACTION_DONE);
2376 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2381 static int request_will_proxy(REQUEST *request)
2383 int rcode, pre_proxy_type = 0;
2384 char const *realmname = NULL;
2385 VALUE_PAIR *vp, *strippedname;
2386 home_server_t *home;
2387 REALM *realm = NULL;
2388 home_pool_t *pool = NULL;
2390 if (!request->root->proxy_requests) return 0;
2391 if (request->packet->dst_port == 0) return 0;
2392 if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2393 if (request->in_proxy_hash) return 0;
2396 * FIXME: for 3.0, allow this only for rejects?
2398 if (request->reply->code != 0) return 0;
2400 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2402 realm = realm_find2(vp->vp_strvalue);
2404 REDEBUG2("Cannot proxy to unknown realm %s",
2409 realmname = vp->vp_strvalue;
2412 * Figure out which pool to use.
2414 if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
2415 pool = realm->auth_pool;
2417 #ifdef WITH_ACCOUNTING
2418 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2419 pool = realm->acct_pool;
2423 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2424 (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2425 pool = realm->coa_pool;
2435 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2438 switch (request->packet->code) {
2439 case PW_CODE_AUTHENTICATION_REQUEST:
2440 pool_type = HOME_TYPE_AUTH;
2443 #ifdef WITH_ACCOUNTING
2444 case PW_CODE_ACCOUNTING_REQUEST:
2445 pool_type = HOME_TYPE_ACCT;
2450 case PW_CODE_COA_REQUEST:
2451 case PW_CODE_DISCONNECT_REQUEST:
2452 pool_type = HOME_TYPE_COA;
2460 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2464 RWDEBUG2("Cancelling proxy as no home pool exists");
2468 if (request->listener->synchronous) {
2469 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2473 request->home_pool = pool;
2475 home = home_server_ldb(realmname, pool, request);
2477 REDEBUG2("Failed to find live home server: Cancelling proxy");
2480 home_server_update_request(home, request);
2484 * Once we've decided to proxy a request, we cannot send
2485 * a CoA packet. So we free up any CoA packet here.
2487 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2491 * Remember that we sent the request to a Realm.
2493 if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2496 * Strip the name, if told to.
2498 * Doing it here catches the case of proxied tunneled
2501 if (realm && (realm->striprealm == true) &&
2502 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2504 * If there's a Stripped-User-Name attribute in
2505 * the request, then use THAT as the User-Name
2506 * for the proxied request, instead of the
2509 * This is done by making a copy of the
2510 * Stripped-User-Name attribute, turning it into
2511 * a User-Name attribute, deleting the
2512 * Stripped-User-Name and User-Name attributes
2513 * from the vps list, and making the new
2514 * User-Name the head of the vps list.
2516 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2519 vp = radius_paircreate(NULL, NULL,
2521 rad_assert(vp != NULL); /* handled by above function */
2522 /* Insert at the START of the list */
2523 /* FIXME: Can't make assumptions about ordering */
2524 fr_cursor_init(&cursor, &vp);
2525 fr_cursor_insert(&cursor, request->proxy->vps);
2526 request->proxy->vps = vp;
2528 pairstrcpy(vp, strippedname->vp_strvalue);
2531 * Do NOT delete Stripped-User-Name.
2536 * If there is no PW_CHAP_CHALLENGE attribute but
2537 * there is a PW_CHAP_PASSWORD we need to add it
2538 * since we can't use the request authenticator
2539 * anymore - we changed it.
2541 if ((request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) &&
2542 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2543 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2544 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2545 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2549 * The RFC's say we have to do this, but FreeRADIUS
2552 vp = radius_paircreate(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2553 pairsprintf(vp, "%u", request->packet->id);
2556 * Should be done BEFORE inserting into proxy hash, as
2557 * pre-proxy may use this information, or change it.
2559 request->proxy->code = request->packet->code;
2562 * Call the pre-proxy routines.
2564 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2566 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2567 /* Must be a validation issue */
2569 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
2570 pre_proxy_type = vp->vp_integer;
2573 rad_assert(request->home_pool != NULL);
2575 if (request->home_pool->virtual_server) {
2576 char const *old_server = request->server;
2578 request->server = request->home_pool->virtual_server;
2580 RDEBUG2("server %s {", request->server);
2582 rcode = process_pre_proxy(pre_proxy_type, request);
2586 request->server = old_server;
2588 rcode = process_pre_proxy(pre_proxy_type, request);
2591 case RLM_MODULE_FAIL:
2592 case RLM_MODULE_INVALID:
2593 case RLM_MODULE_NOTFOUND:
2594 case RLM_MODULE_USERLOCK:
2596 /* FIXME: debug print failed stuff */
2599 case RLM_MODULE_REJECT:
2600 case RLM_MODULE_HANDLED:
2604 * Only proxy the packet if the pre-proxy code succeeded.
2606 case RLM_MODULE_NOOP:
2608 case RLM_MODULE_UPDATED:
2615 static int request_proxy(REQUEST *request, int retransmit)
2619 rad_assert(request->parent == NULL);
2620 rad_assert(request->home_server != NULL);
2622 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2626 RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2627 request_done(request->coa, FR_ACTION_DONE);
2632 * The request may need sending to a virtual server.
2633 * This code is more than a little screwed up. The rest
2634 * of the state machine doesn't handle parent / child
2635 * relationships well. i.e. if the child request takes
2636 * too long, the core will mark the *parent* as "stop
2637 * processing". And the child will continue without
2638 * knowing anything...
2640 * So, we have some horrible hacks to get around that.
2642 if (request->home_server->server) {
2645 if (request->packet->dst_port == 0) {
2646 WARN("Cannot proxy an internal request");
2650 DEBUG("Proxying to virtual server %s",
2651 request->home_server->server);
2654 * Packets to virtual serrers don't get
2655 * retransmissions sent to them. And the virtual
2656 * server is run ONLY if we have no child
2657 * threads, or we're running in a child thread.
2659 rad_assert(retransmit == 0);
2660 rad_assert(!spawn_flag || !we_are_master());
2662 fake = request_alloc_fake(request);
2664 fake->packet->vps = paircopy(fake->packet, request->packet->vps);
2665 talloc_free(request->proxy);
2667 fake->server = request->home_server->server;
2668 fake->handle = request->handle;
2669 fake->process = NULL; /* should never be run for anything */
2672 * Run the virtual server.
2674 request_running(fake, FR_ACTION_RUN);
2676 request->proxy = talloc_steal(request, fake->packet);
2677 fake->packet = NULL;
2678 request->proxy_reply = talloc_steal(request, fake->reply);
2681 request_free(&fake);
2684 * Just do the work here, rather than trying to
2685 * run the "decode proxy reply" stuff...
2687 process_proxy_reply(request, request->proxy_reply);
2689 request->handle(request); /* to do more post-proxy stuff */
2691 return -1; /* so we call request_finish */
2695 * We're actually sending a proxied packet. Do that now.
2697 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2698 ERROR("Failed to insert request into the proxy list");
2702 rad_assert(request->proxy->id >= 0);
2705 if (request->home_server->tls) {
2706 RDEBUG2("Proxying request to home server %s port %d (TLS)",
2707 inet_ntop(request->proxy->dst_ipaddr.af,
2708 &request->proxy->dst_ipaddr.ipaddr,
2709 buffer, sizeof(buffer)),
2710 request->proxy->dst_port);
2713 RDEBUG2("Proxying request to home server %s port %d",
2714 inet_ntop(request->proxy->dst_ipaddr.af,
2715 &request->proxy->dst_ipaddr.ipaddr,
2716 buffer, sizeof(buffer)),
2717 request->proxy->dst_port);
2719 DEBUG_PACKET(request, request->proxy, 1);
2721 gettimeofday(&request->proxy_retransmit, NULL);
2723 request->proxy->timestamp = request->proxy_retransmit;
2724 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2727 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2729 request->child_state = REQUEST_PROXIED;
2730 request->proxy_listener->send(request->proxy_listener,
2736 * Proxy the packet as if it was new.
2738 static int request_proxy_anew(REQUEST *request)
2740 home_server_t *home;
2743 * Delete the request from the proxy list.
2745 * The packet list code takes care of ensuring that IDs
2746 * aren't reused until all 256 IDs have been used. So
2747 * there's a 1/256 chance of re-using the same ID when
2748 * we're sending to the same home server. Which is
2751 remove_from_proxy_hash(request);
2754 * Find a live home server for the request.
2756 home = home_server_ldb(NULL, request->home_pool, request);
2758 REDEBUG2("Failed to find live home server for request");
2760 if (setup_post_proxy_fail(request)) {
2761 request_queue_or_run(request, proxy_running);
2763 gettimeofday(&request->reply->timestamp, NULL);
2764 request_cleanup_delay_init(request, NULL);
2768 home_server_update_request(home, request);
2770 if (!insert_into_proxy_hash(request)) {
2771 RPROXY("Failed to insert retransmission into the proxy list");
2772 goto post_proxy_fail;
2776 * Free the old packet, to force re-encoding
2778 talloc_free(request->proxy->data);
2779 request->proxy->data = NULL;
2780 request->proxy->data_len = 0;
2782 #ifdef WITH_ACCOUNTING
2784 * Update the Acct-Delay-Time attribute.
2786 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2789 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2790 if (!vp) vp = radius_paircreate(request->proxy,
2791 &request->proxy->vps,
2792 PW_ACCT_DELAY_TIME, 0);
2796 gettimeofday(&now, NULL);
2797 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2802 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2807 STATE_MACHINE_DECL(request_ping)
2809 home_server_t *home = request->home_server;
2812 TRACE_STATE_MACHINE;
2816 case FR_ACTION_TIMER:
2817 ERROR("No response to status check %d for home server %s port %d",
2819 inet_ntop(request->proxy->dst_ipaddr.af,
2820 &request->proxy->dst_ipaddr.ipaddr,
2821 buffer, sizeof(buffer)),
2822 request->proxy->dst_port);
2825 case FR_ACTION_PROXY_REPLY:
2826 rad_assert(request->in_proxy_hash);
2828 request->home_server->num_received_pings++;
2829 RPROXY("Received response to status check %d (%d in current sequence)",
2830 request->number, home->num_received_pings);
2833 * Remove the request from any hashes
2835 fr_event_delete(el, &request->ev);
2836 remove_from_proxy_hash(request);
2839 * The control socket may have marked the home server as
2840 * alive. OR, it may have suddenly started responding to
2841 * requests again. If so, don't re-do the "make alive"
2844 if (home->state == HOME_STATE_ALIVE) break;
2847 * It's dead, and we haven't received enough ping
2848 * responses to mark it "alive". Wait a bit.
2850 * If it's zombie, we mark it alive immediately.
2852 if ((home->state == HOME_STATE_IS_DEAD) &&
2853 (home->num_received_pings < home->num_pings_to_alive)) {
2858 * Mark it alive and delete any outstanding
2861 home->state = HOME_STATE_ALIVE;
2862 exec_trigger(request, home->cs, "home_server.alive", false);
2863 home->currently_outstanding = 0;
2864 home->num_sent_pings = 0;
2865 home->num_received_pings = 0;
2866 gettimeofday(&home->revive_time, NULL);
2868 fr_event_delete(el, &home->ev);
2870 RPROXY("Marking home server %s port %d alive",
2871 inet_ntop(request->proxy->dst_ipaddr.af,
2872 &request->proxy->dst_ipaddr.ipaddr,
2873 buffer, sizeof(buffer)),
2874 request->proxy->dst_port);
2878 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2882 rad_assert(!request->in_request_hash);
2883 rad_assert(request->ev == NULL);
2884 request_done(request, FR_ACTION_DONE);
2888 * Called from start of zombie period, OR after control socket
2889 * marks the home server dead.
2891 static void ping_home_server(void *ctx)
2893 home_server_t *home = ctx;
2896 struct timeval when, now;
2898 if ((home->state == HOME_STATE_ALIVE) ||
2899 (home->ping_check == HOME_PING_CHECK_NONE) ||
2901 (home->proto == IPPROTO_TCP) ||
2903 (home->ev != NULL)) {
2907 gettimeofday(&now, NULL);
2909 if (home->state == HOME_STATE_ZOMBIE) {
2910 when = home->zombie_period_start;
2911 when.tv_sec += home->zombie_period;
2913 if (timercmp(&when, &now, <)) {
2914 DEBUG("PING: Zombie period is over for home server %s",
2916 mark_home_server_dead(home, &now);
2920 request = request_alloc(NULL);
2921 request->number = request_num_counter++;
2924 request->proxy = rad_alloc(request, 1);
2925 rad_assert(request->proxy != NULL);
2927 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2928 request->proxy->code = PW_CODE_STATUS_SERVER;
2930 pairmake(request->proxy, &request->proxy->vps,
2931 "Message-Authenticator", "0x00", T_OP_SET);
2933 } else if (home->type == HOME_TYPE_AUTH) {
2934 request->proxy->code = PW_CODE_AUTHENTICATION_REQUEST;
2936 pairmake(request->proxy, &request->proxy->vps,
2937 "User-Name", home->ping_user_name, T_OP_SET);
2938 pairmake(request->proxy, &request->proxy->vps,
2939 "User-Password", home->ping_user_password, T_OP_SET);
2940 pairmake(request->proxy, &request->proxy->vps,
2941 "Service-Type", "Authenticate-Only", T_OP_SET);
2942 pairmake(request->proxy, &request->proxy->vps,
2943 "Message-Authenticator", "0x00", T_OP_SET);
2946 #ifdef WITH_ACCOUNTING
2947 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
2949 pairmake(request->proxy, &request->proxy->vps,
2950 "User-Name", home->ping_user_name, T_OP_SET);
2951 pairmake(request->proxy, &request->proxy->vps,
2952 "Acct-Status-Type", "Stop", T_OP_SET);
2953 pairmake(request->proxy, &request->proxy->vps,
2954 "Acct-Session-Id", "00000000", T_OP_SET);
2955 vp = pairmake(request->proxy, &request->proxy->vps,
2956 "Event-Timestamp", "0", T_OP_SET);
2957 vp->vp_date = now.tv_sec;
2959 rad_assert("Internal sanity check failed");
2963 vp = pairmake(request->proxy, &request->proxy->vps,
2964 "NAS-Identifier", "", T_OP_SET);
2966 pairsprintf(vp, "Status Check %u. Are you alive?",
2967 home->num_sent_pings);
2970 request->proxy->src_ipaddr = home->src_ipaddr;
2971 request->proxy->dst_ipaddr = home->ipaddr;
2972 request->proxy->dst_port = home->port;
2973 request->home_server = home;
2974 #ifdef DEBUG_STATE_MACHINE
2975 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
2976 child_state_names[request->child_state],
2977 child_state_names[REQUEST_DONE]);
2978 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2980 #ifdef HAVE_PTHREAD_H
2981 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2983 request->child_state = REQUEST_DONE;
2984 request->process = request_ping;
2986 rad_assert(request->proxy_listener == NULL);
2988 if (!insert_into_proxy_hash(request)) {
2989 RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
2992 rad_assert(!request->in_request_hash);
2993 rad_assert(!request->in_proxy_hash);
2994 rad_assert(request->ev == NULL);
2995 request_free(&request);
3000 * Set up the timer callback.
3003 when.tv_sec += home->ping_timeout;
3005 DEBUG("PING: Waiting %u seconds for response to ping",
3006 home->ping_timeout);
3008 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3009 home->num_sent_pings++;
3011 rad_assert(request->proxy_listener != NULL);
3012 request->proxy_listener->send(request->proxy_listener,
3016 * Add +/- 2s of jitter, as suggested in RFC 3539
3017 * and in the Issues and Fixes draft.
3020 home->when.tv_sec += home->ping_interval;
3022 add_jitter(&home->when);
3024 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3025 INSERT_EVENT(ping_home_server, home);
3028 static void home_trigger(home_server_t *home, char const *trigger)
3031 RADIUS_PACKET my_packet;
3033 memset(&my_request, 0, sizeof(my_request));
3034 memset(&my_packet, 0, sizeof(my_packet));
3035 my_request.proxy = &my_packet;
3036 my_packet.dst_ipaddr = home->ipaddr;
3037 my_packet.src_ipaddr = home->src_ipaddr;
3039 exec_trigger(&my_request, home->cs, trigger, false);
3042 static void mark_home_server_zombie(home_server_t *home, struct timeval *now)
3049 rad_assert((home->state == HOME_STATE_ALIVE) ||
3050 (home->state == HOME_STATE_UNKNOWN));
3053 if (home->proto == IPPROTO_TCP) {
3054 WARN("Not marking TCP server %s zombie", home->name);
3060 * We've received a real packet recently. Don't mark the
3061 * server as zombie until we've received NO packets for a
3062 * while. The "1/4" of zombie period was chosen rather
3063 * arbitrarily. It's a balance between too short, which
3064 * gives quick fail-over and fail-back, or too long,
3065 * where the proxy still sends packets to an unresponsive
3068 start = now->tv_sec - ((home->zombie_period + 3) / 4);
3069 if (home->last_packet_recv >= start) {
3070 DEBUG("Recieved reply from home server %d seconds ago. Might not be zombie.",
3071 (int) (now->tv_sec - home->last_packet_recv));
3075 home->state = HOME_STATE_ZOMBIE;
3076 home_trigger(home, "home_server.zombie");
3079 * Set the home server to "zombie", as of the time
3082 home->zombie_period_start.tv_sec = start;
3083 home->zombie_period_start.tv_usec = USEC / 2;
3085 fr_event_delete(el, &home->ev);
3086 home->num_sent_pings = 0;
3087 home->num_received_pings = 0;
3089 PROXY( "Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3090 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3091 buffer, sizeof(buffer)),
3092 home->port, (int) home->response_window.tv_sec, (int) home->response_window.tv_usec);
3094 ping_home_server(home);
3098 void revive_home_server(void *ctx)
3100 home_server_t *home = ctx;
3104 rad_assert(home->proto != IPPROTO_TCP);
3107 home->state = HOME_STATE_ALIVE;
3108 home_trigger(home, "home_server.alive");
3109 home->currently_outstanding = 0;
3110 gettimeofday(&home->revive_time, NULL);
3113 * Delete any outstanding events.
3115 if (home->ev) fr_event_delete(el, &home->ev);
3117 PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3118 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3119 buffer, sizeof(buffer)),
3123 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3125 int previous_state = home->state;
3129 if (home->proto == IPPROTO_TCP) {
3130 WARN("Not marking TCP server dead");
3135 PROXY( "Marking home server %s port %d as dead.",
3136 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3137 buffer, sizeof(buffer)),
3140 home->state = HOME_STATE_IS_DEAD;
3141 home_trigger(home, "home_server.dead");
3143 if (home->ping_check != HOME_PING_CHECK_NONE) {
3145 * If the control socket marks us dead, start
3146 * pinging. Otherwise, we already started
3147 * pinging when it was marked "zombie".
3149 if (previous_state == HOME_STATE_ALIVE) {
3150 ping_home_server(home);
3152 DEBUG("PING: Already pinging home server %s",
3158 * Revive it after a fixed period of time. This
3159 * is very, very, bad.
3162 home->when.tv_sec += home->revive_interval;
3164 DEBUG("PING: Reviving home server %s in %u seconds",
3165 home->name, home->revive_interval);
3166 INSERT_EVENT(revive_home_server, home);
3170 STATE_MACHINE_DECL(proxy_wait_for_reply)
3172 struct timeval now, when;
3173 home_server_t *home = request->home_server;
3176 TRACE_STATE_MACHINE;
3178 rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3179 rad_assert(request->home_server != NULL);
3181 if (request->master_state == REQUEST_STOP_PROCESSING) {
3182 request->child_state = REQUEST_DONE;
3186 gettimeofday(&now, NULL);
3191 * We have a reply, ignore the retransmit.
3193 if (request->proxy_reply) return;
3196 * The request was proxied to a virtual server.
3197 * Ignore the retransmit.
3199 if (request->home_server->server) return;
3201 if ((home->state == HOME_STATE_IS_DEAD) ||
3202 !request->proxy_listener ||
3203 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3204 request_proxy_anew(request);
3209 if (home->proto == IPPROTO_TCP) {
3210 DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3211 inet_ntop(request->proxy->dst_ipaddr.af,
3212 &request->proxy->dst_ipaddr.ipaddr,
3213 buffer, sizeof(buffer)),
3214 request->proxy->dst_port,
3215 request->proxy->id);
3221 * More than one retransmit a second is stupid,
3222 * and should be suppressed by the proxy.
3224 when = request->proxy_retransmit;
3227 if (timercmp(&now, &when, <)) {
3228 DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3229 inet_ntop(request->proxy->dst_ipaddr.af,
3230 &request->proxy->dst_ipaddr.ipaddr,
3231 buffer, sizeof(buffer)),
3232 request->proxy->dst_port,
3233 request->proxy->id);
3237 #ifdef WITH_ACCOUNTING
3239 * If we update the Acct-Delay-Time, we need to
3242 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3243 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3244 request_proxy_anew(request);
3249 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3250 inet_ntop(request->proxy->dst_ipaddr.af,
3251 &request->proxy->dst_ipaddr.ipaddr,
3252 buffer, sizeof(buffer)),
3253 request->proxy->dst_port,
3254 request->proxy->id);
3255 request->num_proxied_requests++;
3257 rad_assert(request->proxy_listener != NULL);;
3258 DEBUG_PACKET(request, request->proxy, 1);
3259 FR_STATS_TYPE_INC(home->stats.total_requests);
3260 home->last_packet_sent = now.tv_sec;
3261 request->proxy_retransmit = now;
3262 request->proxy_listener->send(request->proxy_listener,
3266 case FR_ACTION_TIMER:
3268 if (!request->proxy_listener ||
3269 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3270 remove_from_proxy_hash(request);
3272 when = request->packet->timestamp;
3273 when.tv_sec += request->root->max_request_time;
3275 if (timercmp(&when, &now, >)) {
3276 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3277 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3284 * Wake up "response_window" time in the future.
3285 * i.e. when MY packet hasn't received a response.
3287 * Note that we DO NOT mark the home server as
3288 * zombie if it doesn't respond to us. It may be
3289 * responding to other (better looking) packets.
3291 when = request->proxy->timestamp;
3292 timeradd(&when, &home->response_window, &when);
3295 * Not at the response window. Set the timer for
3298 if (timercmp(&when, &now, >)) {
3299 RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3300 (int) home->response_window.tv_sec, (int) home->response_window.tv_usec);
3301 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3306 RDEBUG("No proxy response, giving up on request and marking it done");
3309 * If we haven't received any packets for
3310 * "response_window", then mark the home server
3313 * If the connection is TCP, then another
3314 * "watchdog timer" function takes care of pings,
3315 * etc. So we don't need to do it here.
3317 * This check should really be part of a home
3318 * server state machine.
3320 if (((home->state == HOME_STATE_ALIVE) ||
3321 (home->state == HOME_STATE_UNKNOWN))
3323 && (home->proto != IPPROTO_TCP)
3326 mark_home_server_zombie(home, &now);
3329 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3330 if (home->type == HOME_TYPE_AUTH) {
3331 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3332 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3335 else if (home->type == HOME_TYPE_ACCT) {
3336 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3337 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3342 * There was no response within the window. Stop
3343 * the request. If the client retransmitted, it
3344 * may have failed over to another home server.
3345 * But that one may be dead, too.
3347 RERROR("Failing request - proxy ID %u, due to lack of any response from home server %s port %d",
3349 inet_ntop(request->proxy->dst_ipaddr.af,
3350 &request->proxy->dst_ipaddr.ipaddr,
3351 buffer, sizeof(buffer)),
3352 request->proxy->dst_port);
3354 if (!setup_post_proxy_fail(request)) {
3355 gettimeofday(&request->reply->timestamp, NULL);
3356 request_cleanup_delay_init(request, NULL);
3361 * Remember that we didn't have a reply.
3363 request_queue_or_run(request, proxy_no_reply);
3367 * Duplicate proxy replies have been quenched by
3368 * now. This state is only called ONCE, when we
3369 * receive a new reply from the home server.
3371 case FR_ACTION_PROXY_REPLY:
3372 request_queue_or_run(request, proxy_running);
3375 case FR_ACTION_CONFLICTING:
3376 request_done(request, action);
3380 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3384 #endif /* WITH_PROXY */
3386 /***********************************************************************
3390 ***********************************************************************/
3392 static int null_handler(UNUSED REQUEST *request)
3398 * See if we need to originate a CoA request.
3400 static void request_coa_originate(REQUEST *request)
3402 int rcode, pre_proxy_type = 0;
3408 rad_assert(request != NULL);
3409 rad_assert(request->coa != NULL);
3410 rad_assert(request->proxy == NULL);
3411 rad_assert(!request->in_proxy_hash);
3412 rad_assert(request->proxy_reply == NULL);
3415 * Check whether we want to originate one, or cancel one.
3417 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3419 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3423 if (vp->vp_integer == 0) {
3425 request_free(&request->coa);
3433 * src_ipaddr will be set up in proxy_encode.
3435 memset(&ipaddr, 0, sizeof(ipaddr));
3436 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3438 ipaddr.af = AF_INET;
3439 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3441 } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3442 ipaddr.af = AF_INET6;
3443 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3445 } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3446 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3448 if (!coa->home_pool) {
3449 RWDEBUG2("No such home_server_pool %s",
3455 * Prefer the pool to one server
3457 } else if (request->client->coa_pool) {
3458 coa->home_pool = request->client->coa_pool;
3460 } else if (request->client->coa_server) {
3461 coa->home_server = request->client->coa_server;
3465 * If all else fails, send it to the client that
3466 * originated this request.
3468 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3472 * Use the pool, if it exists.
3474 if (coa->home_pool) {
3475 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3476 if (!coa->home_server) {
3477 RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3480 home_server_update_request(coa->home_server, coa);
3482 } else if (!coa->home_server) {
3483 uint16_t port = PW_COA_UDP_PORT;
3485 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3486 if (vp) port = vp->vp_integer;
3488 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3489 if (!coa->home_server) {
3490 RWDEBUG2("Unknown destination %s:%d for CoA request.",
3491 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3492 buffer, sizeof(buffer)), port);
3497 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3499 switch (vp->vp_integer) {
3500 case PW_CODE_COA_REQUEST:
3501 case PW_CODE_DISCONNECT_REQUEST:
3502 coa->proxy->code = vp->vp_integer;
3506 DEBUG("Cannot set CoA Packet-Type to code %d",
3512 if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3515 * The rest of the server code assumes that
3516 * request->packet && request->reply exist. Copy them
3517 * from the original request.
3519 rad_assert(coa->packet != NULL);
3520 rad_assert(coa->packet->vps == NULL);
3522 coa->packet = rad_copy_packet(coa, request->packet);
3523 coa->reply = rad_copy_packet(coa, request->reply);
3525 coa->config_items = paircopy(coa, request->config_items);
3526 coa->num_coa_requests = 0;
3527 coa->handle = null_handler;
3528 coa->number = request->number; /* it's associated with the same request */
3531 * Call the pre-proxy routines.
3533 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3535 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3536 /* Must be a validation issue */
3538 RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3539 pre_proxy_type = vp->vp_integer;
3542 if (coa->home_pool && coa->home_pool->virtual_server) {
3543 char const *old_server = coa->server;
3545 coa->server = coa->home_pool->virtual_server;
3546 RDEBUG2("server %s {", coa->server);
3548 rcode = process_pre_proxy(pre_proxy_type, coa);
3551 coa->server = old_server;
3553 rcode = process_pre_proxy(pre_proxy_type, coa);
3560 * Only send the CoA packet if the pre-proxy code succeeded.
3562 case RLM_MODULE_NOOP:
3564 case RLM_MODULE_UPDATED:
3569 * Source IP / port is set when the proxy socket
3572 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3573 coa->proxy->dst_port = coa->home_server->port;
3575 if (!insert_into_proxy_hash(coa)) {
3576 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
3581 * We CANNOT divorce the CoA request from the parent
3582 * request. This function is running in a child thread,
3583 * and we need access to the main event loop in order to
3584 * to add the timers for the CoA packet.
3586 * Instead, we wait for the timer on the parent request
3589 gettimeofday(&coa->proxy->timestamp, NULL);
3590 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3591 coa->delay = 0; /* need to calculate a new delay */
3593 DEBUG_PACKET(coa, coa->proxy, 1);
3595 coa->process = coa_wait_for_reply;
3596 #ifdef DEBUG_STATE_MACHINE
3597 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3598 child_state_names[request->child_state],
3599 child_state_names[REQUEST_RUNNING]);
3601 #ifdef HAVE_PTHREAD_H
3602 coa->child_pid = NO_SUCH_CHILD_PID;
3604 coa->child_state = REQUEST_PROXIED;
3605 rad_assert(coa->proxy_reply == NULL);
3606 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3607 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3608 coa->proxy_listener->send(coa->proxy_listener, coa);
3612 static void coa_timer(REQUEST *request)
3614 uint32_t delay, frac;
3615 struct timeval now, when, mrd;
3617 rad_assert(request->parent == NULL);
3619 if (request->proxy_reply) return request_process_timer(request);
3621 gettimeofday(&now, NULL);
3623 if (request->delay == 0) {
3625 * Implement re-transmit algorithm as per RFC 5080
3628 * We want IRT + RAND*IRT
3629 * or 0.9 IRT + rand(0,.2) IRT
3631 * 2^20 ~ USEC, and we want 2.
3632 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3634 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3635 request->delay = delay * request->home_server->coa_irt;
3636 delay = request->home_server->coa_irt * USEC;
3637 delay -= delay / 10;
3638 delay += request->delay;
3639 request->delay = delay;
3641 when = request->proxy->timestamp;
3642 tv_add(&when, delay);
3644 if (timercmp(&when, &now, >)) {
3645 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3651 * Retransmit CoA request.
3655 * Cap count at MRC, if it is non-zero.
3657 if (request->home_server->coa_mrc &&
3658 (request->num_coa_requests >= request->home_server->coa_mrc)) {
3661 RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
3663 inet_ntop(request->proxy->dst_ipaddr.af,
3664 &request->proxy->dst_ipaddr.ipaddr,
3665 buffer, sizeof(buffer)),
3666 request->proxy->dst_port);
3667 if (!setup_post_proxy_fail(request)) {
3668 request_done(request, FR_ACTION_DONE);
3672 request_queue_or_run(request, coa_no_reply);
3677 * RFC 5080 Section 2.2.1
3679 * RT = 2*RTprev + RAND*RTprev
3680 * = 1.9 * RTprev + rand(0,.2) * RTprev
3681 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3684 delay ^= (delay >> 16);
3686 frac = request->delay / 5;
3687 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3689 delay += (2 * request->delay) - (request->delay / 10);
3692 * Cap delay at MRT, if MRT is non-zero.
3694 if (request->home_server->coa_mrt &&
3695 (delay > (request->home_server->coa_mrt * USEC))) {
3696 int mrt_usec = request->home_server->coa_mrt * USEC;
3699 * delay = MRT + RAND * MRT
3700 * = 0.9 MRT + rand(0,.2) * MRT
3703 delay ^= (delay >> 15);
3705 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3706 delay += mrt_usec - (mrt_usec / 10);
3709 request->delay = delay;
3711 tv_add(&when, request->delay);
3712 mrd = request->proxy->timestamp;
3713 mrd.tv_sec += request->home_server->coa_mrd;
3716 * Cap duration at MRD.
3718 if (timercmp(&mrd, &when, <)) {
3721 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3723 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3725 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3728 * Status servers don't count as real packets sent.
3730 request->proxy_listener->send(request->proxy_listener,
3734 STATE_MACHINE_DECL(coa_wait_for_reply)
3736 rad_assert(request->parent == NULL);
3738 TRACE_STATE_MACHINE;
3741 case FR_ACTION_TIMER:
3743 * This is big enough to be in it's own function.
3748 case FR_ACTION_PROXY_REPLY:
3749 rad_assert(request->parent == NULL);
3750 request_queue_or_run(request, coa_running);
3754 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3759 static void request_coa_separate(REQUEST *request)
3761 #ifdef DEBUG_STATE_MACHINE
3762 int action = FR_ACTION_TIMER;
3764 TRACE_STATE_MACHINE;
3766 rad_assert(request->parent != NULL);
3767 rad_assert(request->parent->coa == request);
3768 rad_assert(request->ev == NULL);
3769 rad_assert(!request->in_request_hash);
3770 rad_assert(request->coa == NULL);
3772 rad_assert(request->proxy_listener != NULL);
3774 (void) talloc_steal(NULL, request);
3775 request->parent->coa = NULL;
3776 request->parent = NULL;
3779 * Should be coa_wait_for_reply()
3781 request->process(request, FR_ACTION_TIMER);
3784 STATE_MACHINE_DECL(coa_no_reply)
3788 TRACE_STATE_MACHINE;
3791 case FR_ACTION_TIMER:
3792 request_common(request, action);
3795 case FR_ACTION_PROXY_REPLY: /* too late! */
3796 RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
3797 inet_ntop(request->proxy->src_ipaddr.af,
3798 &request->proxy->src_ipaddr.ipaddr,
3799 buffer, sizeof(buffer)),
3800 request->proxy->dst_port, request->proxy->id);
3805 * FIXME: do recv_coa Fail
3807 (void) process_proxy_reply(request, NULL);
3808 request_done(request, FR_ACTION_DONE);
3812 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3817 STATE_MACHINE_DECL(coa_running)
3819 TRACE_STATE_MACHINE;
3822 case FR_ACTION_TIMER:
3823 request_process_timer(request);
3826 case FR_ACTION_PROXY_REPLY:
3827 request_common(request, action);
3831 if (process_proxy_reply(request, request->proxy_reply)) {
3832 request->handle(request);
3833 request_finish(request, action);
3835 request_done(request, FR_ACTION_DONE);
3840 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3844 #endif /* WITH_COA */
3846 /***********************************************************************
3848 * End of the State machine. Start of additional helper code.
3850 ***********************************************************************/
3852 /***********************************************************************
3856 ***********************************************************************/
3857 static void event_socket_handler(UNUSED fr_event_list_t *xel, UNUSED int fd, void *ctx)
3859 rad_listen_t *listener = ctx;
3861 rad_assert(xel == el);
3865 (listener->type != RAD_LISTEN_DETAIL) &&
3867 (listener->fd < 0)) {
3870 listener->print(listener, buffer, sizeof(buffer));
3871 ERROR("FATAL: Asked to read from closed socket: %s",
3874 rad_panic("Socket was closed on us!");
3878 listener->recv(listener);
3882 #ifdef WITH_DETAIL_THREAD
3885 * This function is called periodically to see if this detail
3886 * file is available for reading.
3888 static void event_poll_detail(void *ctx)
3891 rad_listen_t *this = ctx;
3892 struct timeval when, now;
3893 listen_detail_t *detail = this->data;
3895 rad_assert(this->type == RAD_LISTEN_DETAIL);
3898 event_socket_handler(el, this->fd, this);
3900 fr_event_now(el, &now);
3904 * Backdoor API to get the delay until the next poll
3907 delay = this->encode(this, NULL);
3908 if (delay == 0) goto redo;
3910 tv_add(&when, delay);
3912 if (!fr_event_insert(el, event_poll_detail, this,
3913 &when, &detail->ev)) {
3914 ERROR("Failed creating handler");
3918 #endif /* WITH_DETAIL_THREAD */
3919 #endif /* WITH_DETAIL */
3921 static void event_status(struct timeval *wake)
3923 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3927 if (debug_flag == 0) {
3929 INFO("Ready to process requests");
3930 just_started = false;
3936 INFO("Ready to process requests");
3938 } else if ((wake->tv_sec != 0) ||
3939 (wake->tv_usec >= 100000)) {
3940 DEBUG("Waking up in %d.%01u seconds.",
3941 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3946 * FIXME: Put this somewhere else, where it isn't called
3947 * all of the time...
3950 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3952 * If there are no child threads, then there may
3953 * be child processes. In that case, wait for
3954 * their exit status, and throw that exit status
3955 * away. This helps get rid of zxombie children.
3957 while (waitpid(-1, &argval, WNOHANG) > 0) {
3965 static void listener_free_cb(void *ctx)
3967 rad_listen_t *this = ctx;
3970 if (this->count > 0) {
3971 struct timeval when;
3972 listen_socket_t *sock = this->data;
3974 fr_event_now(el, &when);
3977 if (!fr_event_insert(el, listener_free_cb, this, &when,
3979 rad_panic("Failed to insert event");
3986 * It's all free, close the socket.
3989 this->print(this, buffer, sizeof(buffer));
3990 DEBUG("... cleaning up socket %s", buffer);
3996 static int proxy_eol_cb(void *ctx, void *data)
3998 struct timeval when;
3999 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4001 if (request->proxy_listener != ctx) return 0;
4004 * We don't care if it's being processed in a child thread.
4007 #ifdef WITH_ACCOUNTING
4009 * Accounting packets should be deleted immediately.
4010 * They will never be retransmitted by the client.
4012 if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4013 RDEBUG("Stopping request due to failed connection to home server");
4014 request->master_state = REQUEST_STOP_PROCESSING;
4019 * Reset the timer to be now, so that the request is
4020 * quickly updated. But spread the requests randomly
4021 * over the next second, so that we don't overload the
4024 fr_event_now(el, &when);
4025 tv_add(&when, fr_rand() % USEC);
4026 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
4029 * Don't delete it from the list.
4035 static int event_new_fd(rad_listen_t *this)
4041 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4043 this->print(this, buffer, sizeof(buffer));
4045 if (this->status == RAD_LISTEN_STATUS_INIT) {
4046 listen_socket_t *sock = this->data;
4049 DEBUG("Listening on %s", buffer);
4051 INFO(" ... adding new socket %s", buffer);
4054 switch (this->type) {
4057 * Detail files are always known, and aren't
4058 * put into the socket event loop.
4060 case RAD_LISTEN_DETAIL:
4061 this->status = RAD_LISTEN_STATUS_KNOWN;
4063 #ifndef WITH_DETAIL_THREAD
4065 * Set up the first poll interval.
4067 event_poll_detail(this);
4070 break; /* add the FD to the list */
4072 #endif /* WITH_DETAIL */
4076 * Add it to the list of sockets we can use.
4077 * Server sockets (i.e. auth/acct) are never
4078 * added to the packet list.
4080 case RAD_LISTEN_PROXY:
4081 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4082 if (!fr_packet_list_socket_add(proxy_list, this->fd,
4084 &sock->other_ipaddr, sock->other_port,
4087 #ifdef HAVE_PTHREAD_H
4088 proxy_no_new_sockets = true;
4090 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4093 * This is bad. However, the
4094 * packet list now supports 256
4095 * open sockets, which should
4096 * minimize this problem.
4098 ERROR("Failed adding proxy socket: %s",
4102 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4106 * Add timers to outgoing child sockets, if necessary.
4108 if (sock->proto == IPPROTO_TCP && sock->opened &&
4109 (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4110 struct timeval when;
4112 when.tv_sec = sock->opened + 1;
4115 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4117 rad_panic("Failed to insert event");
4122 #endif /* WITH_PROXY */
4125 * FIXME: put idle timers on command sockets.
4131 * Add timers to incoming child sockets, if necessary.
4133 if (sock->proto == IPPROTO_TCP && sock->opened &&
4134 (sock->limit.lifetime || sock->limit.idle_timeout)) {
4135 struct timeval when;
4137 when.tv_sec = sock->opened + 1;
4140 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4142 rad_panic("Failed to insert event");
4147 } /* switch over listener types */
4150 * All sockets: add the FD to the event handler.
4152 if (!fr_event_fd_insert(el, 0, this->fd,
4153 event_socket_handler, this)) {
4154 ERROR("Failed adding event handler for socket!");
4158 this->status = RAD_LISTEN_STATUS_KNOWN;
4164 * Stop using this socket, if at all possible.
4166 if (this->status == RAD_LISTEN_STATUS_EOL) {
4168 * Remove it from the list of live FD's.
4170 fr_event_fd_delete(el, 0, this->fd);
4174 * Proxy sockets get frozen, so that we don't use
4175 * them for new requests. But we do keep them
4176 * open to listen for replies to requests we had
4179 if (this->type == RAD_LISTEN_PROXY) {
4180 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4181 if (!fr_packet_list_socket_freeze(proxy_list,
4183 ERROR("Fatal error freezing socket: %s", fr_strerror());
4187 fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4188 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4193 * Requests are still using the socket. Wait for
4196 if (this->count > 0) {
4197 struct timeval when;
4198 listen_socket_t *sock = this->data;
4201 * Try again to clean up the socket in 30
4204 gettimeofday(&when, NULL);
4207 if (!fr_event_insert(el,
4208 (fr_event_callback_t) event_new_fd,
4209 this, &when, &sock->ev)) {
4210 rad_panic("Failed to insert event");
4217 * No one is using the socket. We can remove it now.
4219 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4220 } /* socket is at EOL */
4226 if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4229 listen_socket_t *sock = this->data;
4231 struct timeval when;
4234 * Re-open the socket, pointing it to /dev/null.
4235 * This means that all writes proceed without
4236 * blocking, and all reads return "no data".
4238 * This leaves the socket active, so any child
4239 * threads won't go insane. But it means that
4240 * they cannot send or receive any packets.
4242 * This is EXTRA work in the normal case, when
4243 * sockets are closed without error. But it lets
4244 * us have one simple processing method for all
4247 devnull = open("/dev/null", O_RDWR);
4249 ERROR("FATAL failure opening /dev/null: %s",
4250 fr_syserror(errno));
4253 if (dup2(devnull, this->fd) < 0) {
4254 ERROR("FATAL failure closing socket: %s",
4255 fr_syserror(errno));
4261 rad_assert(this->type != RAD_LISTEN_DETAIL);
4265 INFO(" ... shutting down socket %s", buffer);
4269 * The socket is dead. Force all proxied packets
4270 * to stop using it. And then remove it from the
4271 * list of outgoing sockets.
4273 if (this->type == RAD_LISTEN_PROXY) {
4274 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4275 fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4277 if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4278 ERROR("Fatal error removing socket %s: %s",
4279 buffer, fr_strerror());
4282 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4287 * EOL all requests using this socket.
4289 fr_packet_list_walk(pl, this, eol_listener);
4293 * No child threads, clean it up now.
4296 if (sock->ev) fr_event_delete(el, &sock->ev);
4302 * Wait until all requests using this socket are done.
4304 gettimeofday(&when, NULL);
4307 if (!fr_event_insert(el, listener_free_cb, this, &when,
4309 rad_panic("Failed to insert event");
4312 #endif /* WITH_TCP */
4317 /***********************************************************************
4321 ***********************************************************************/
4323 static void handle_signal_self(int flag)
4327 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4328 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4329 INFO("Signalled to exit");
4330 fr_event_loop_exit(el, 1);
4332 INFO("Signalled to terminate");
4333 exec_trigger(NULL, NULL, "server.signal.term", true);
4334 fr_event_loop_exit(el, 2);
4338 } /* else exit/term flags weren't set */
4341 * Tell the even loop to stop processing.
4343 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4345 static time_t last_hup = 0;
4348 if ((int) (when - last_hup) < 5) {
4349 INFO("Ignoring HUP (less than 5s since last one)");
4353 INFO("Received HUP signal");
4357 exec_trigger(NULL, NULL, "server.signal.hup", true);
4358 fr_event_loop_exit(el, 0x80);
4362 #ifndef WITH_DETAIL_THREAD
4363 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4367 * FIXME: O(N) loops suck.
4369 for (this = main_config.listen;
4371 this = this->next) {
4372 if (this->type != RAD_LISTEN_DETAIL) continue;
4375 * This one didn't send the signal, skip
4378 if (!this->decode(this, NULL)) continue;
4381 * Go service the interrupt.
4383 event_poll_detail(this);
4391 #ifdef HAVE_PTHREAD_H
4393 * There are new listeners in the list. Run
4394 * event_new_fd() on them.
4396 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4397 rad_listen_t *this, *next;
4399 FD_MUTEX_LOCK(&fd_mutex);
4402 * FIXME: unlock the mutex before calling
4405 for (this = new_listeners; this != NULL; this = next) {
4412 new_listeners = NULL;
4413 FD_MUTEX_UNLOCK(&fd_mutex);
4415 #endif /* HAVE_PTHREAD_H */
4416 #endif /* WITH_PROXY */
4417 #endif /* WITH_TCP */
4420 #ifndef HAVE_PTHREAD_H
4421 void radius_signal_self(int flag)
4423 return handle_signal_self(flag);
4427 static int self_pipe[2] = { -1, -1 };
4430 * Inform ourselves that we received a signal.
4432 void radius_signal_self(int flag)
4438 * The read MUST be non-blocking for this to work.
4440 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4444 for (i = 0; i < rcode; i++) {
4445 buffer[0] |= buffer[i];
4453 if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
4457 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4458 UNUSED int fd, UNUSED void *ctx)
4463 rcode = read(self_pipe[0], buffer, sizeof(buffer));
4464 if (rcode <= 0) return;
4467 * Merge pending signals.
4469 for (i = 0; i < rcode; i++) {
4470 buffer[0] |= buffer[i];
4473 handle_signal_self(buffer[0]);
4475 #endif /* HAVE_PTHREAD_H */
4477 /***********************************************************************
4479 * Bootstrapping code.
4481 ***********************************************************************/
4484 * Externally-visibly functions.
4486 int radius_event_init(TALLOC_CTX *ctx) {
4487 el = fr_event_list_create(ctx, event_status);
4493 int radius_event_start(CONF_SECTION *cs, bool have_children)
4495 rad_listen_t *head = NULL;
4497 if (fr_start_time != (time_t)-1) return 0;
4499 time(&fr_start_time);
4502 * radius_event_init() must be called first
4505 if (fr_start_time == (time_t)-1) return 0;
4507 pl = fr_packet_list_create(0);
4508 if (!pl) return 0; /* leak el */
4510 request_num_counter = 0;
4513 if (main_config.proxy_requests) {
4515 * Create the tree for managing proxied requests and
4518 proxy_list = fr_packet_list_create(1);
4519 if (!proxy_list) return 0;
4521 #ifdef HAVE_PTHREAD_H
4522 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4523 ERROR("FATAL: Failed to initialize proxy mutex: %s",
4524 fr_syserror(errno));
4532 * Move all of the thread calls to this file?
4534 * It may be best for the mutexes to be in this file...
4536 spawn_flag = have_children;
4538 #ifdef HAVE_PTHREAD_H
4539 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4542 * Initialize the threads ONLY if we're spawning, AND
4543 * we're running normally.
4545 if (have_children && !check_config &&
4546 (thread_pool_init(cs, &spawn_flag) < 0)) {
4552 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4554 if (listen_init(cs, &head, spawn_flag) < 0) {
4561 #ifdef HAVE_PTHREAD_H
4563 * Child threads need a pipe to signal us, as do the
4566 if (pipe(self_pipe) < 0) {
4567 ERROR("radiusd: Error opening internal pipe: %s",
4568 fr_syserror(errno));
4571 if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4572 (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4573 ERROR("radiusd: Error setting internal flags: %s",
4574 fr_syserror(errno));
4577 if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4578 (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4579 ERROR("radiusd: Error setting internal flags: %s",
4580 fr_syserror(errno));
4584 if (!fr_event_fd_insert(el, 0, self_pipe[0],
4585 event_signal_handler, el)) {
4586 ERROR("Failed creating handler for signals");
4591 DEBUG("%s: #### Opening IP addresses and Ports ####",
4595 * The server temporarily switches to an unprivileged
4596 * user very early in the bootstrapping process.
4597 * However, some sockets MAY require privileged access
4598 * (bind to device, or to port < 1024, or to raw
4599 * sockets). Those sockets need to call suid up/down
4600 * themselves around the functions that need a privileged
4603 if (listen_init(cs, &head, spawn_flag) < 0) {
4607 main_config.listen = head;
4610 * At this point, no one has any business *ever* going
4613 fr_suid_down_permanent();
4620 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4622 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4624 request->master_state = REQUEST_STOP_PROCESSING;
4626 #ifdef HAVE_PTHREAD_H
4627 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4631 * If it's queued we can't delete it from the queue.
4633 * Otherwise, it's OK to delete it. Even RUNNING, because
4634 * that will get caught by the check above.
4636 if (request->child_state == REQUEST_QUEUED) return 0;
4638 request->in_proxy_hash = false;
4640 if (!request->in_request_hash) {
4641 request_done(request, FR_ACTION_DONE);
4645 * Delete it from the list.
4652 static int request_delete_cb(UNUSED void *ctx, void *data)
4654 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4656 request->master_state = REQUEST_STOP_PROCESSING;
4659 * Not done, or the child thread is still processing it.
4661 if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
4663 #ifdef HAVE_PTHREAD_H
4664 if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4668 rad_assert(request->in_proxy_hash == false);
4671 request->in_request_hash = false;
4672 if (request->ev) fr_event_delete(el, &request->ev);
4674 if (main_config.memory_report) {
4675 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
4676 request->packet->id,
4677 (unsigned int) (request->timestamp - fr_start_time));
4682 rad_assert(!request->coa->in_proxy_hash);
4686 request_free(&request);
4689 * Delete it from the list, and continue;
4695 void radius_event_free(void)
4701 * There are requests in the proxy hash that aren't
4702 * referenced from anywhere else. Remove them first.
4705 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4709 fr_packet_list_walk(pl, NULL, request_delete_cb);
4713 * Now that all requests have been marked "please stop",
4714 * ensure that all of the threads have exited.
4716 #ifdef HAVE_PTHREAD_H
4721 * Walk the lists again, ensuring that all
4722 * requests are done.
4724 if (main_config.memory_report) {
4729 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4730 num = fr_packet_list_num_elements(proxy_list);
4732 ERROR("Proxy list has %d requests still in it.", num);
4737 fr_packet_list_walk(pl, NULL, request_delete_cb);
4738 num = fr_packet_list_num_elements(pl);
4740 ERROR("Request list has %d requests still in it.", num);
4745 fr_packet_list_free(pl);
4749 fr_packet_list_free(proxy_list);
4755 if (debug_condition) talloc_free(debug_condition);
4758 int radius_event_process(void)
4762 return fr_event_loop(el);