3 * @brief Handle requests
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * Copyright 2012 The FreeRADIUS server project
22 * Copyright 2012 Alan DeKok <aland@deployingradius.com>
25 #include <freeradius-devel/ident.h>
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/event.h>
31 #include <freeradius-devel/packet.h>
32 #include <freeradius-devel/modules.h>
34 #include <freeradius-devel/rad_assert.h>
37 #include <freeradius-devel/detail.h>
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
49 extern pid_t radius_pid;
50 extern int check_config;
51 extern char *debug_condition;
53 static int spawn_flag = 0;
54 static int just_started = TRUE;
56 static fr_packet_list_t *pl = NULL;
57 static fr_event_list_t *el = NULL;
59 static const char *action_codes[] = {
71 #ifdef DEBUG_STATE_MACHINE
72 #define TRACE_STATE_MACHINE if (debug_flag) printf("(%u) ********\tSTATE %s action %s live M%u C%u\t********\n", request->number, __FUNCTION__, action_codes[action], request->master_state, request->child_state)
74 #define TRACE_STATE_MACHINE {}
78 * Declare a state in the state machine.
81 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
83 #define STATE_MACHINE_TIMER(_x) request->timer_action = _x; \
84 fr_event_insert(el, request_timer, request, \
90 * @section request_timeline
92 * Time sequence of a request
95 * RQ-----------------P=============================Y-J-C
96 * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
99 * - R: received. Duplicate detection is done, and request is
102 * - Q: Request is placed onto a queue for child threads to pick up.
103 * If there are no child threads, the request goes immediately
106 * - P: Processing the request through the modules.
108 * - Y: Reply is ready. Rejects MAY be delayed here. All other
109 * replies are sent immediately.
111 * - J: Reject is sent "reject_delay" after the reply is ready.
113 * - C: For Access-Requests, After "cleanup_delay", the request is
114 * deleted. Accounting-Request packets go directly from Y to C.
116 * - M: Max request time. If the request hits this timer, it is
119 * Other considerations include duplicate and conflicting
120 * packets. When a dupicate packet is received, it is ignored
121 * until we've reached Y, as no response is ready. If the reply
122 * is a reject, duplicates are ignored until J, when we're ready
123 * to send the reply. In between the reply being sent (Y or J),
124 * and C, the server responds to duplicates by sending the cached
127 * Conflicting packets are sent in 2 situations.
129 * The first is in between R and Y. In that case, we consider
130 * it as a hint that we're taking too long, and the NAS has given
131 * up on the request. We then behave just as if the M timer was
132 * reached, and we discard the current request. This allows us
133 * to process the new one.
135 * The second case is when we're at Y, but we haven't yet
136 * finished processing the request. This is a race condition in
137 * the threading code (avoiding locks is faster). It means that
138 * a thread has actually encoded and sent the reply, and that the
139 * NAS has responded with a new packet. The server can then
140 * safely mark the current request as "OK to delete", and behaves
141 * just as if the M timer was reached. This usually happens only
142 * in high-load situations.
144 * Duplicate packets are sent when the NAS thinks we're taking
145 * too long, and wants a reply. From R-Y, duplicates are
146 * ignored. From Y-J (for Access-Rejects), duplicates are also
147 * ignored. From Y-C, duplicates get a duplicate reply. *And*,
148 * they cause the "cleanup_delay" time to be extended. This
149 * extension means that we're more likely to send a duplicate
150 * reply (if we have one), or to suppress processing the packet
151 * twice if we didn't reply to it.
153 * All functions in this file should be thread-safe, and should
154 * assume thet the REQUEST structure is being accessed
155 * simultaneously by the main thread, and by the child worker
156 * threads. This means that timers, etc. cannot be updated in
159 * Instead, the master thread periodically calls request->process
160 * with action TIMER. It's up to the individual functions to
161 * determine how to handle that. They need to check if they're
162 * being called from a child thread or the master, and then do
163 * different things based on that.
168 static fr_packet_list_t *proxy_list = NULL;
171 #ifdef HAVE_PTHREAD_H
173 static pthread_mutex_t proxy_mutex;
174 static rad_listen_t *proxy_listener_list = NULL;
175 static int proxy_no_new_sockets = FALSE;
178 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
179 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
181 static pthread_t NO_SUCH_CHILD_PID;
184 * This is easier than ifdef's throughout the code.
186 #define PTHREAD_MUTEX_LOCK(_x)
187 #define PTHREAD_MUTEX_UNLOCK(_x)
191 * We need mutexes around the event FD list *only* in certain
194 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
195 static pthread_mutex_t fd_mutex;
196 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
197 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
200 * This is easier than ifdef's throughout the code.
202 #define FD_MUTEX_LOCK(_x)
203 #define FD_MUTEX_UNLOCK(_x)
206 static int request_num_counter = 0;
208 static int request_will_proxy(REQUEST *request);
209 static int request_proxy(REQUEST *request, int retransmit);
210 STATE_MACHINE_DECL(proxy_wait_for_reply);
211 STATE_MACHINE_DECL(proxy_running);
212 static int process_proxy_reply(REQUEST *request);
213 static void remove_from_proxy_hash(REQUEST *request);
214 static void remove_from_proxy_hash_nl(REQUEST *request);
215 static int insert_into_proxy_hash(REQUEST *request);
218 STATE_MACHINE_DECL(request_common);
220 #if defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
221 static int we_are_master(void)
224 (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
230 #define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
233 #define we_are_master(_x) (1)
234 #define ASSERT_MASTER
237 STATE_MACHINE_DECL(request_reject_delay);
238 STATE_MACHINE_DECL(request_cleanup_delay);
239 STATE_MACHINE_DECL(request_running);
241 static void request_coa_timer(REQUEST *request);
242 static void request_coa_originate(REQUEST *request);
243 STATE_MACHINE_DECL(request_coa_process);
244 static void request_coa_separate(REQUEST *coa);
248 #define USEC (1000000)
250 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
252 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
255 radlog(L_ERR, "[%s:%d] %s", file, line, msg);
259 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
261 static void tv_add(struct timeval *tv, int usec_delay)
263 if (usec_delay >= USEC) {
264 tv->tv_sec += usec_delay / USEC;
267 tv->tv_usec += usec_delay;
269 if (tv->tv_usec >= USEC) {
270 tv->tv_sec += tv->tv_usec / USEC;
276 * In daemon mode, AND this request has debug flags set.
278 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
280 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
284 const char *received, *from;
285 const fr_ipaddr_t *ip;
290 rad_assert(request->radlog != NULL);
292 if (direction == 0) {
293 received = "Received";
294 from = "from"; /* what else? */
295 ip = &packet->src_ipaddr;
296 port = packet->src_port;
299 received = "Sending";
300 from = "to"; /* hah! */
301 ip = &packet->dst_ipaddr;
302 port = packet->dst_port;
306 * Client-specific debugging re-prints the input
307 * packet into the client log.
309 * This really belongs in a utility library
311 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
312 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
313 received, fr_packet_codes[packet->code], from,
314 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
315 port, packet->id, packet->data_len);
317 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
319 inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
321 packet->code, packet->id, packet->data_len);
324 for (vp = packet->vps; vp != NULL; vp = vp->next) {
325 vp_prints(buffer, sizeof(buffer), vp);
326 request->radlog(L_DBG, 0, request, "\t%s", buffer);
331 /***********************************************************************
333 * Start of RADIUS server state machine.
335 ***********************************************************************/
338 * Callback for ALL timer events related to the request.
340 static void request_timer(void *ctx)
342 REQUEST *request = ctx;
343 int action = request->timer_action;
347 request->process(request, action);
350 #define USEC (1000000)
353 * Only ever called from the master thread.
355 STATE_MACHINE_DECL(request_done)
357 struct timeval now, when;
363 * CoA requests can be cleaned up in the child thread,
364 * but ONLY if they aren't tied into anything.
366 if (request->parent && (request->parent->coa == request)) {
367 rad_assert(!request->in_request_hash);
368 rad_assert(!request->in_proxy_hash);
369 rad_assert(action == FR_ACTION_DONE);
370 rad_assert(request->ev == NULL);
378 * Mark ourselves as handling the request.
380 request->process = request_done;
381 request->master_state = REQUEST_STOP_PROCESSING;
385 * Move the CoA request to its own handler.
387 if (request->coa) request_coa_separate(request->coa);
390 * If we're the CoA request, make the parent forget about
393 if (request->parent && (request->parent->coa == request)) {
394 request->parent->coa = NULL;
400 * It doesn't hurt to send duplicate replies. All other
401 * signals are ignored, as the request will be cleaned up
406 if (request->reply->code != 0) {
407 request->listener->send(request->listener, request);
413 * This is only called from the master thread
414 * when there is a child thread processing the
417 case FR_ACTION_CONFLICTING:
418 if (request->child_state == REQUEST_DONE) break;
421 * If there's a reply packet, then we presume
422 * that the child has sent the reply, and we get
423 * pinged here before the child has a chance to
426 if (request->reply->data) break;
428 radlog_request(L_ERR, 0, request,
429 "Received conflicting packet from "
430 "client %s port %d - ID: %d due to "
431 "unfinished request. Giving up on old request.",
432 request->client->shortname,
433 request->packet->src_port, request->packet->id);
437 * Called only when there's an error remembering
438 * the packet, or when the socket gets closed from
442 #ifdef HAVE_PTHREAD_H
444 * If we have child threads and we're NOT the
445 * thread handling the request, don't do anything.
448 !pthread_equal(pthread_self(), request->child_pid)) {
452 #ifdef DEBUG_STATE_MACHINE
453 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
455 request->child_state = REQUEST_DONE;
459 * Called when the child is taking too long to
460 * finish. We've already marked it "please
461 * stop", so we don't complain any more.
463 case FR_ACTION_TIMER:
468 * Child is still alive, and we're receiving more
469 * packets from the home server.
471 case FR_ACTION_PROXY_REPLY:
472 request_common(request, action);
477 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
482 * Remove it from the request hash.
484 if (request->in_request_hash) {
485 fr_packet_list_yank(pl, request->packet);
486 request->in_request_hash = FALSE;
488 request_stats_final(request);
491 request->listener->count--;
497 * Wait for the proxy ID to expire. This allows us to
498 * avoid re-use of proxy IDs for a while.
500 if (request->in_proxy_hash) {
501 rad_assert(request->proxy != NULL);
503 fr_event_now(el, &now);
504 when = request->proxy->timestamp;
507 if (((request->proxy->code == PW_COA_REQUEST) ||
508 (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
509 (request->packet->code != request->proxy->code)) {
510 when.tv_sec += request->home_server->coa_mrd;
513 when.tv_sec += request->home_server->response_window;
516 * We haven't received all responses, AND there's still
517 * time to wait. Do so.
519 if ((request->num_proxied_requests > request->num_proxied_responses) &&
521 (request->home_server->proto != IPPROTO_TCP) &&
523 timercmp(&now, &when, <)) {
524 RDEBUG("Waiting for more responses from the home server");
531 remove_from_proxy_hash(request);
535 if (request->child_state != REQUEST_DONE) {
537 #ifdef HAVE_PTHREAD_H
541 rad_assert("Internal sanity check failed");
545 gettimeofday(&now, NULL);
550 #ifdef HAVE_PTHREAD_H
552 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
553 RDEBUG("Waiting for child thread to stop");
558 tv_add(&when, request->delay);
559 request->delay += request->delay >> 1;
560 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
562 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
566 #ifdef HAVE_PTHREAD_H
567 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
570 if (request->packet) {
571 RDEBUG2("Cleaning up request packet ID %d with timestamp +%d",
573 (unsigned int) (request->timestamp - fr_start_time));
574 } /* else don't print anything */
576 if (request->ev) fr_event_delete(el, &request->ev);
578 request_free(&request);
582 static void request_cleanup_delay_init(REQUEST *request, const struct timeval *pnow)
584 struct timeval now, when;
586 if (request->packet->code == PW_ACCOUNTING_REQUEST) goto done;
587 if (!request->root->cleanup_delay) goto done;
592 gettimeofday(&now, NULL);
595 if (request->reply->timestamp.tv_sec == 0) {
598 when = request->reply->timestamp;
600 request->delay = request->root->cleanup_delay;
601 when.tv_sec += request->delay;
604 * Set timer for when we need to clean it up.
606 if (timercmp(&when, &now, >)) {
607 #ifdef DEBUG_STATE_MACHINE
608 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
610 request->process = request_cleanup_delay;
611 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
616 * Otherwise just clean it up.
619 request_done(request, FR_ACTION_DONE);
624 * Function to do all time-related events.
626 static void request_process_timer(REQUEST *request)
628 struct timeval now, when;
629 rad_assert(request->magic == REQUEST_MAGIC);
630 #ifdef DEBUG_STATE_MACHINE
631 int action = FR_ACTION_TIMER;
639 * If we originated a CoA request, divorce it from the
640 * parent. Then, set up the timers so that we can clean
641 * it up as appropriate.
643 if (request->coa) request_coa_separate(request->coa);
646 * Check request stuff ONLY if we're running the request.
648 if (!request->proxy || (request->packet->code == request->proxy->code))
651 rad_assert(request->listener != NULL);
654 * The socket was closed. Tell the request that
655 * there is no point in continuing.
657 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
658 DEBUG("WARNING: Socket was closed while processing request %u: Stopping it.", request->number);
663 gettimeofday(&now, NULL);
666 * A child thread is still working on the request,
667 * OR it was proxied, and there was no response,
668 * OR it was sitting in the queue for too long.
670 if ((request->child_state != REQUEST_DONE) &&
671 (request->master_state != REQUEST_STOP_PROCESSING)) {
672 when = request->packet->timestamp;
673 when.tv_sec += request->root->max_request_time;
676 * Taking too long: tell it to die.
678 if (timercmp(&now, &when, >=)) {
679 #ifdef HAVE_PTHREAD_H
681 * If there's a child thread processing it,
685 (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
686 radlog(L_ERR, "WARNING: Unresponsive child for request %u, in component %s module %s",
688 request->component ? request->component : "<server core>",
689 request->module ? request->module : "<server core>");
690 exec_trigger(request, NULL, "server.thread.unresponsive", TRUE);
695 * Tell the request to stop it.
698 } /* else we're not at max_request_time */
701 if ((request->master_state != REQUEST_STOP_PROCESSING) &&
703 (request->process == request_running)) {
704 #ifdef DEBUG_STATE_MACHINE
705 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_proxied");
707 request->process = proxy_wait_for_reply;
712 * Wake up again in the future, to check for
716 tv_add(&when, request->delay);
717 request->delay += request->delay >> 1;
719 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
723 #ifdef WITH_ACCOUNTING
724 if (request->reply->code == PW_ACCOUNTING_RESPONSE) {
726 request_done(request, FR_ACTION_DONE);
732 if (!request->proxy || (request->packet->code == request->proxy->code))
735 if ((request->reply->code == PW_AUTHENTICATION_REJECT) &&
736 (request->root->reject_delay)) {
737 when = request->reply->timestamp;
738 when.tv_sec += request->root->reject_delay;
741 * Set timer for when we need to send it.
743 if (timercmp(&when, &now, >)) {
744 #ifdef DEBUG_STATE_MACHINE
745 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_reject_delay");
747 request->process = request_reject_delay;
749 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
753 if (request->process == request_reject_delay) {
755 * Assume we're at (or near) the reject
758 request->reply->timestamp = now;
760 RDEBUG2("Sending delayed reject");
761 DEBUG_PACKET(request, request->reply, 1);
762 request->process = request_cleanup_delay;
763 request->listener->send(request->listener, request);
768 * The cleanup_delay is zero for accounting packets, and
769 * enforced for all other packets. We do the
770 * cleanup_delay even if we don't respond to the NAS, so
771 * that any retransmit is *not* processed as a new packet.
773 request_cleanup_delay_init(request, &now);
777 static void request_queue_or_run(UNUSED REQUEST *request,
778 fr_request_process_t process)
781 #ifdef DEBUG_STATE_MACHINE
782 int action = FR_ACTION_TIMER;
789 * (re) set the initial delay.
791 request->delay = USEC / 3;
792 gettimeofday(&when, NULL);
793 tv_add(&when, request->delay);
794 request->delay += request->delay >> 1;
796 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
799 * Do this here so that fewer other functions need to do
802 if (request->master_state == REQUEST_STOP_PROCESSING) {
803 #ifdef DEBUG_STATE_MACHINE
804 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
806 request_done(request, FR_ACTION_DONE);
810 request->process = process;
812 #ifdef HAVE_PTHREAD_H
814 if (!request_enqueue(request)) {
815 request_done(request, FR_ACTION_DONE);
822 request->process(request, FR_ACTION_RUN);
826 * Requests that care about child process exit
827 * codes have already either called
828 * rad_waitpid(), or they've given up.
835 STATE_MACHINE_DECL(request_common)
846 if ((request->master_state != REQUEST_STOP_PROCESSING) &&
847 request->proxy && !request->proxy_reply) {
849 * TODO: deal with this in a better way?
851 proxy_wait_for_reply(request, action);
855 radlog(L_ERR, "(%u) Discarding duplicate request from "
856 "client %s port %d - ID: %u due to unfinished request",
857 request->number, request->client->shortname,
858 request->packet->src_port,request->packet->id);
861 case FR_ACTION_CONFLICTING:
863 * We're in the master thread, ask the child to
864 * stop processing the request.
866 request_done(request, action);
869 case FR_ACTION_TIMER:
870 request_process_timer(request);
874 case FR_ACTION_PROXY_REPLY:
875 DEBUG2("Reply from home server %s port %d - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
876 inet_ntop(request->proxy->src_ipaddr.af,
877 &request->proxy->src_ipaddr.ipaddr,
878 buffer, sizeof(buffer)),
879 request->proxy->dst_port, request->proxy->id,
885 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
890 STATE_MACHINE_DECL(request_cleanup_delay)
899 if (request->reply->code != 0) {
900 request->listener->send(request->listener, request);
902 RDEBUG("No reply. Ignoring retransmit.");
906 * Double the cleanup_delay to catch retransmits.
908 when = request->reply->timestamp;
909 request->delay += request->delay ;
910 when.tv_sec += request->delay;
912 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
916 case FR_ACTION_PROXY_REPLY:
918 case FR_ACTION_CONFLICTING:
919 case FR_ACTION_TIMER:
920 request_common(request, action);
924 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
929 STATE_MACHINE_DECL(request_reject_delay)
936 radlog(L_ERR, "(%u) Discarding duplicate request from "
937 "client %s port %d - ID: %u due to delayed reject",
938 request->number, request->client->shortname,
939 request->packet->src_port,request->packet->id);
943 case FR_ACTION_PROXY_REPLY:
945 case FR_ACTION_CONFLICTING:
946 case FR_ACTION_TIMER:
947 request_common(request, action);
951 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
957 static int request_pre_handler(REQUEST *request, UNUSED int action)
963 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
966 * Don't decode the packet if it's an internal "fake"
967 * request. Instead, just return so that the caller can
970 if (request->packet->dst_port == 0) {
971 request->username = pairfind(request->packet->vps,
973 request->password = pairfind(request->packet->vps,
974 PW_USER_PASSWORD, 0);
980 * Put the decoded packet into it's proper place.
982 if (request->proxy_reply != NULL) {
983 rcode = request->proxy_listener->decode(request->proxy_listener, request);
984 DEBUG_PACKET(request, request->proxy_reply, 0);
987 * Pro-actively remove it from the proxy hash.
988 * This is later than in 2.1.x, but it means that
989 * the replies are authenticated before being
990 * removed from the hash.
993 (request->num_proxied_requests <= request->num_proxied_responses)) {
994 remove_from_proxy_hash(request);
999 if (request->packet->vps == NULL) {
1000 rcode = request->listener->decode(request->listener, request);
1003 if (debug_condition) {
1005 const char *my_debug = debug_condition;
1008 * Ignore parse errors.
1010 radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1014 request->options = 2;
1015 request->radlog = radlog_request;
1020 DEBUG_PACKET(request, request->packet, 0);
1026 RDEBUG("Dropping packet without response because of error %s", fr_strerror());
1027 request->reply->offset = -2; /* bad authenticator */
1031 if (!request->username) {
1032 request->username = pairfind(request->packet->vps,
1037 if (action == FR_ACTION_PROXY_REPLY) {
1038 return process_proxy_reply(request);
1045 STATE_MACHINE_DECL(request_finish)
1049 TRACE_STATE_MACHINE;
1051 action = action; /* -Wunused */
1053 if (request->master_state == REQUEST_STOP_PROCESSING) return;
1056 * Don't send replies if there are none to send.
1058 if (!request->in_request_hash) return;
1061 * Catch Auth-Type := Reject BEFORE proxying the packet.
1063 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1064 (request->reply->code == 0)) {
1065 if (((vp = pairfind(request->config_items, PW_AUTH_TYPE, 0)) != NULL) &&
1066 (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1067 request->reply->code = PW_AUTHENTICATION_REJECT;
1071 * Check if the lack of response is
1074 vp = pairfind(request->config_items,
1075 PW_RESPONSE_PACKET_TYPE, 0);
1077 RDEBUG2("There was no response configured: rejecting request");
1078 request->reply->code = PW_AUTHENTICATION_REJECT;
1080 } else if (vp->vp_integer == 256) {
1081 RDEBUG2("Not responding to request");
1084 request->reply->code = vp->vp_integer;
1090 * Copy Proxy-State from the request to the reply.
1092 vp = paircopy2(request->packet->vps, PW_PROXY_STATE, 0, -1);
1093 if (vp) pairadd(&request->reply->vps, vp);
1096 * Run rejected packets through
1098 * Post-Auth-Type = Reject
1100 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1101 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, -1);
1102 vp = radius_pairmake(request, &request->config_items,
1103 "Post-Auth-Type", "Reject",
1105 if (vp) rad_postauth(request);
1108 if (request->reply->code == PW_AUTHENTICATION_ACK) {
1109 rad_postauth(request);
1113 * Send the reply here.
1115 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1116 (request->root->reject_delay == 0)) {
1117 DEBUG_PACKET(request, request->reply, 1);
1118 request->listener->send(request->listener,
1122 gettimeofday(&request->reply->timestamp, NULL);
1125 * Clean up. These are no longer needed.
1127 pairfree(&request->config_items);
1129 pairfree(&request->packet->vps);
1130 request->username = NULL;
1131 request->password = NULL;
1133 if (request->reply->code != PW_AUTHENTICATION_REJECT) {
1134 pairfree(&request->reply->vps);
1138 if (request->proxy) {
1139 pairfree(&request->proxy->vps);
1141 if (request->proxy_reply) {
1142 pairfree(&request->proxy_reply->vps);
1147 RDEBUG2("Finished request %u.", request->number);
1150 STATE_MACHINE_DECL(request_running)
1152 TRACE_STATE_MACHINE;
1155 case FR_ACTION_CONFLICTING:
1157 case FR_ACTION_TIMER:
1158 request_common(request, action);
1162 case FR_ACTION_PROXY_REPLY:
1163 #ifdef HAVE_PTHREAD_H
1165 * Catch the case of a proxy reply when called
1166 * from the main worker thread.
1168 if (we_are_master() &&
1169 (request->process != proxy_running)) {
1170 request_queue_or_run(request, proxy_running);
1178 if (!request_pre_handler(request, action)) goto done;
1180 rad_assert(request->handle != NULL);
1181 request->handle(request);
1185 * We may need to send a proxied request.
1187 if ((action == FR_ACTION_RUN) &&
1188 request_will_proxy(request)) {
1189 #ifdef DEBUG_STATE_MACHINE
1190 if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1194 * takes care of setting
1195 * up the post proxy fail
1198 if (request_proxy(request, 0) < 0) goto finished;
1202 #ifdef DEBUG_STATE_MACHINE
1203 if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1208 * Maybe originate a CoA request.
1210 if ((action == FR_ACTION_RUN) && request->coa) {
1211 request_coa_originate(request);
1216 request_finish(request, action);
1219 #ifdef DEBUG_STATE_MACHINE
1220 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
1223 #ifdef HAVE_PTHREAD_H
1224 request->child_pid = NO_SUCH_CHILD_PID;
1226 request->child_state = REQUEST_DONE;
1231 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1236 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1237 RADCLIENT *client, RAD_REQUEST_FUNP fun)
1240 RADIUS_PACKET **packet_p;
1241 REQUEST *request = NULL;
1243 listen_socket_t *sock = listener->data;
1246 * Set the last packet received.
1248 gettimeofday(&now, NULL);
1249 sock->last_packet = now.tv_sec;
1251 packet_p = fr_packet_list_find(pl, packet);
1253 request = fr_packet2myptr(REQUEST, packet, packet_p);
1254 rad_assert(request->in_request_hash);
1257 * Same src/dst ip/port, length, and
1258 * authentication vector: must be a duplicate.
1260 if ((request->packet->data_len == packet->data_len) &&
1261 (memcmp(request->packet->vector, packet->vector,
1262 sizeof(packet->vector)) == 0)) {
1265 switch (packet->code) {
1266 case PW_AUTHENTICATION_REQUEST:
1267 FR_STATS_INC(auth, total_dup_requests);
1270 #ifdef WITH_ACCOUNTING
1271 case PW_ACCOUNTING_REQUEST:
1272 FR_STATS_INC(acct, total_dup_requests);
1276 case PW_COA_REQUEST:
1277 FR_STATS_INC(coa, total_dup_requests);
1280 case PW_DISCONNECT_REQUEST:
1281 FR_STATS_INC(dsc, total_dup_requests);
1288 #endif /* WITH_STATS */
1290 request->process(request, FR_ACTION_DUP);
1295 * Say we're ignoring the old one, and continue
1296 * to process the new one.
1298 request->process(request, FR_ACTION_CONFLICTING);
1303 * Quench maximum number of outstanding requests.
1305 if (mainconfig.max_requests &&
1306 ((count = fr_packet_list_num_elements(pl)) > mainconfig.max_requests)) {
1307 radlog(L_ERR, "Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1309 packet->src_port, packet->id);
1310 radlog(L_INFO, "WARNING: Please check the configuration file.\n"
1311 "\tThe value for 'max_requests' is probably set too low.\n");
1313 exec_trigger(NULL, NULL, "server.max_requests", TRUE);
1318 * Rate-limit the incoming packets
1320 if (sock->max_rate) {
1323 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now,
1324 &sock->rate_time, &now);
1326 if (pps > sock->max_rate) {
1327 DEBUG("Dropping request due to rate limiting");
1330 sock->rate_pps_now++;
1333 return request_insert(listener, packet, client, fun, &now);
1336 int request_insert(rad_listen_t *listener, RADIUS_PACKET *packet,
1337 RADCLIENT *client, RAD_REQUEST_FUNP fun,
1338 struct timeval *pnow)
1343 * Create and initialize the new request.
1345 request = request_alloc(); /* never fails */
1347 if ((request->reply = rad_alloc(0)) == NULL) {
1348 radlog(L_ERR, "No memory");
1349 request_free(&request);
1353 request->listener = listener;
1354 request->client = client;
1355 request->packet = packet;
1356 request->packet->timestamp = *pnow;
1357 request->number = request_num_counter++;
1358 request->priority = listener->type;
1359 request->master_state = REQUEST_ACTIVE;
1360 #ifdef DEBUG_STATE_MACHINE
1361 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_ACTIVE);
1363 request->child_state = REQUEST_ACTIVE;
1364 request->handle = fun;
1365 request->options = RAD_REQUEST_OPTION_DEBUG2;
1366 #ifdef HAVE_PTHREAD_H
1367 request->child_pid = NO_SUCH_CHILD_PID;
1371 request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1372 if (packet->code == PW_AUTHENTICATION_REQUEST) {
1373 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1374 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1375 #ifdef WITH_ACCOUNTING
1376 } else if (packet->code == PW_ACCOUNTING_REQUEST) {
1377 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1378 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1381 #endif /* WITH_STATS */
1384 * Status-Server packets go to the head of the queue.
1386 if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
1389 * Set virtual server identity
1391 if (client->server) {
1392 request->server = client->server;
1393 } else if (listener->server) {
1394 request->server = listener->server;
1396 request->server = NULL;
1400 * Remember the request in the list.
1402 if (!fr_packet_list_insert(pl, &request->packet)) {
1403 radlog_request(L_ERR, 0, request, "Failed to insert request in the list of live requests: discarding it");
1404 request_done(request, FR_ACTION_DONE);
1408 request->in_request_hash = TRUE;
1409 request->root = &mainconfig;
1410 mainconfig.refcount++;
1412 request->listener->count++;
1416 * The request passes many of our sanity checks.
1417 * From here on in, if anything goes wrong, we
1418 * send a reject message, instead of dropping the
1423 * Build the reply template from the request.
1426 request->reply->sockfd = request->packet->sockfd;
1427 request->reply->dst_ipaddr = request->packet->src_ipaddr;
1428 request->reply->src_ipaddr = request->packet->dst_ipaddr;
1429 request->reply->dst_port = request->packet->src_port;
1430 request->reply->src_port = request->packet->dst_port;
1431 request->reply->id = request->packet->id;
1432 request->reply->code = 0; /* UNKNOWN code */
1433 memcpy(request->reply->vector, request->packet->vector,
1434 sizeof(request->reply->vector));
1435 request->reply->vps = NULL;
1436 request->reply->data = NULL;
1437 request->reply->data_len = 0;
1439 request_queue_or_run(request, request_running);
1446 /***********************************************************************
1450 ***********************************************************************/
1453 * Timer function for all TCP sockets.
1455 static void tcp_socket_timer(void *ctx)
1457 rad_listen_t *listener = ctx;
1458 listen_socket_t *sock = listener->data;
1459 struct timeval end, now;
1461 fr_socket_limit_t *limit;
1463 fr_event_now(el, &now);
1465 switch (listener->type) {
1466 case RAD_LISTEN_PROXY:
1467 limit = &sock->home->limit;
1470 case RAD_LISTEN_AUTH:
1471 case RAD_LISTEN_ACCT:
1472 limit = &sock->limit;
1480 * If we enforce a lifetime, do it now.
1482 if (limit->lifetime > 0) {
1483 end.tv_sec = sock->opened + limit->lifetime;
1486 if (timercmp(&end, &now, <=)) {
1487 listener->print(listener, buffer, sizeof(buffer));
1488 DEBUG("Reached maximum lifetime on socket %s", buffer);
1492 listener->status = RAD_LISTEN_STATUS_CLOSED;
1493 event_new_fd(listener);
1502 * Enforce an idle timeout.
1504 if (limit->idle_timeout > 0) {
1505 struct timeval idle;
1507 rad_assert(sock->last_packet != 0);
1508 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1511 if (timercmp(&idle, &now, <=)) {
1512 listener->print(listener, buffer, sizeof(buffer));
1513 DEBUG("Reached idle timeout on socket %s", buffer);
1518 * Enforce the minimum of idle timeout or lifetime.
1520 if (timercmp(&idle, &end, <)) {
1526 * Wake up at t + 0.5s. The code above checks if the timers
1527 * are <= t. This addition gives us a bit of leeway.
1529 end.tv_usec = USEC / 2;
1531 if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1532 rad_panic("Failed to insert event");
1538 * Add +/- 2s of jitter, as suggested in RFC 3539
1541 static void add_jitter(struct timeval *when)
1548 jitter ^= (jitter >> 10);
1549 jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1552 * Add in ~ (4 * USEC) of jitter.
1554 tv_add(when, jitter);
1558 static int disconnect_all_proxied_requests(void *ctx, void *data)
1560 rad_listen_t *this = ctx;
1561 RADIUS_PACKET **proxy_p = data;
1564 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1565 if (request->proxy->sockfd != this->fd) return 0;
1568 * The normal "remove_from_proxy_hash" tries to grab the
1569 * proxy mutex. We already have it held, so grabbing it
1570 * again will cause a deadlock. Instead, call the "no
1571 * lock" version of the function.
1573 if (request->in_proxy_hash) {
1574 remove_from_proxy_hash_nl(request);
1576 request->proxy_listener = NULL;
1579 * Don't mark it as DONE. The client can retransmit, and
1580 * the packet SHOULD be re-proxied somewhere else.
1584 #endif /* WITH_PROXY */
1586 static int remove_all_requests(void *ctx, void *data)
1588 rad_listen_t *this = ctx;
1589 RADIUS_PACKET **packet_p = data;
1592 request = fr_packet2myptr(REQUEST, packet, packet_p);
1593 if (request->packet->sockfd != this->fd) return 0;
1595 request_done(request, FR_ACTION_DONE);
1598 #endif /* WITH_TCP */
1601 /***********************************************************************
1603 * Proxy handlers for the state machine.
1605 ***********************************************************************/
1607 static void remove_from_proxy_hash_nl(REQUEST *request)
1609 fr_packet_list_yank(proxy_list, request->proxy);
1610 fr_packet_list_id_free(proxy_list, request->proxy);
1613 * On the FIRST reply, decrement the count of outstanding
1614 * requests. Note that this is NOT the count of sent
1615 * packets, but whether or not the home server has
1618 if (request->home_server &&
1619 request->home_server->currently_outstanding) {
1620 request->home_server->currently_outstanding--;
1623 * If we're NOT sending it packets, then we don't know
1624 * if it's alive or dead.
1626 if ((request->home_server->currently_outstanding == 0) &&
1627 (request->home_server->state == HOME_STATE_ALIVE)) {
1628 request->home_server->state = HOME_STATE_UNKNOWN;
1629 request->home_server->last_packet_sent = 0;
1630 request->home_server->last_packet_recv = 0;
1635 request->proxy_listener->count--;
1637 request->proxy_listener = NULL;
1640 * Got from YES in hash, to NO, not in hash while we hold
1641 * the mutex. This guarantees that when another thread
1642 * grabs the mutex, the "not in hash" flag is correct.
1644 request->in_proxy_hash = FALSE;
1647 static void remove_from_proxy_hash(REQUEST *request)
1650 * Check this without grabbing the mutex because it's a
1651 * lot faster that way.
1653 if (!request->in_proxy_hash) return;
1656 * The "not in hash" flag is definitive. However, if the
1657 * flag says that it IS in the hash, there might still be
1658 * a race condition where it isn't.
1660 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1662 if (!request->in_proxy_hash) {
1663 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1667 remove_from_proxy_hash_nl(request);
1669 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1672 static int insert_into_proxy_hash(REQUEST *request)
1676 void *proxy_listener;
1678 rad_assert(request->proxy != NULL);
1679 rad_assert(proxy_list != NULL);
1683 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1684 rcode = fr_packet_list_id_alloc(proxy_list,
1685 request->home_server->proto,
1686 request->proxy, &proxy_listener);
1687 request->num_proxied_requests = 1;
1688 request->num_proxied_responses = 0;
1689 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1692 #ifdef HAVE_PTHREAD_H
1693 if (proxy_no_new_sockets) return 0;
1697 * Also locks the proxy mutex, so we have to call
1698 * it with the mutex unlocked. Some systems
1699 * don't support recursive mutexes.
1701 if (!proxy_new_listener(request->home_server, 0)) {
1702 radlog(L_ERR, "Failed to create a new socket for proxying requests.");
1705 request->proxy->src_port = 0; /* Use any new socket */
1709 RDEBUG2("ERROR: Failed allocating Id for new socket when proxying requests.");
1716 request->proxy_listener = proxy_listener;
1718 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1719 if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
1720 fr_packet_list_id_free(proxy_list, request->proxy);
1721 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1722 radlog_request(L_PROXY, 0, request, "Failed to insert entry into proxy list.");
1726 request->in_proxy_hash = TRUE;
1729 * Keep track of maximum outstanding requests to a
1730 * particular home server. 'max_outstanding' is
1731 * enforced in home_server_ldb(), in realms.c.
1733 if (request->home_server) {
1734 request->home_server->currently_outstanding++;
1738 request->proxy_listener->count++;
1741 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1743 RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
1744 inet_ntop(request->proxy->dst_ipaddr.af,
1745 &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
1746 request->proxy->dst_port,
1747 request->proxy->id);
1752 static int process_proxy_reply(REQUEST *request)
1755 int post_proxy_type = 0;
1759 * Delete any reply we had accumulated until now.
1761 pairfree(&request->reply->vps);
1764 * Run the packet through the post-proxy stage,
1765 * BEFORE playing games with the attributes.
1767 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0);
1769 RDEBUG2(" Found Post-Proxy-Type %s", vp->vp_strvalue);
1770 post_proxy_type = vp->vp_integer;
1773 if (request->home_pool && request->home_pool->virtual_server) {
1774 const char *old_server = request->server;
1776 request->server = request->home_pool->virtual_server;
1777 RDEBUG2(" server %s {", request->server);
1778 rcode = module_post_proxy(post_proxy_type, request);
1780 request->server = old_server;
1782 rcode = module_post_proxy(post_proxy_type, request);
1786 if (request->packet->code == request->proxy->code)
1788 * Don't run the next bit if we originated a CoA
1789 * packet, after receiving an Access-Request or
1790 * Accounting-Request.
1795 * There may NOT be a proxy reply, as we may be
1796 * running Post-Proxy-Type = Fail.
1798 if (request->proxy_reply) {
1800 * Delete the Proxy-State Attributes from
1801 * the reply. These include Proxy-State
1802 * attributes from us and remote server.
1804 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE, 0, -1);
1807 * Add the attributes left in the proxy
1808 * reply to the reply list.
1810 pairadd(&request->reply->vps, request->proxy_reply->vps);
1811 request->proxy_reply->vps = NULL;
1814 * Free proxy request pairs.
1816 pairfree(&request->proxy->vps);
1820 default: /* Don't do anything */
1822 case RLM_MODULE_FAIL:
1825 case RLM_MODULE_HANDLED:
1832 int request_proxy_reply(RADIUS_PACKET *packet)
1834 RADIUS_PACKET **proxy_p;
1839 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1840 proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
1843 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1844 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
1845 inet_ntop(packet->src_ipaddr.af,
1846 &packet->src_ipaddr.ipaddr,
1847 buffer, sizeof(buffer)),
1848 packet->src_port, packet->id);
1852 request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1853 request->num_proxied_responses++; /* needs to be protected by lock */
1855 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1858 * No reply, BUT the current packet fails verification:
1859 * ignore it. This does the MD5 calculations in the
1860 * server core, but I guess we can fix that later.
1862 if (!request->proxy_reply &&
1863 (rad_verify(packet, request->proxy,
1864 request->home_server->secret) != 0)) {
1865 DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
1870 * The home server sent us a packet which doesn't match
1871 * something we have: ignore it. This is done only to
1872 * catch the case of broken systems.
1874 if (request->proxy_reply &&
1875 (memcmp(request->proxy_reply->vector,
1877 sizeof(request->proxy_reply->vector)) != 0)) {
1878 RDEBUG2("Ignoring conflicting proxy reply");
1882 gettimeofday(&now, NULL);
1885 * Status-Server packets don't count as real packets.
1887 if (request->proxy->code != PW_STATUS_SERVER) {
1888 listen_socket_t *sock = request->proxy_listener->data;
1890 request->home_server->last_packet_recv = now.tv_sec;
1891 sock->last_packet = now.tv_sec;
1895 * If we have previously seen a reply, ignore the
1898 if (request->proxy_reply) {
1899 RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
1900 inet_ntop(packet->src_ipaddr.af,
1901 &packet->src_ipaddr.ipaddr,
1902 buffer, sizeof(buffer)),
1903 packet->src_port, packet->id);
1908 * Call the state machine to do something useful with the
1911 request->proxy_reply = packet;
1912 packet->timestamp = now;
1913 request->priority = RAD_LISTEN_PROXY;
1916 * We've received a reply. If we hadn't been sending it
1917 * packets for a while, just mark it alive.
1919 if (request->home_server->state == HOME_STATE_UNKNOWN) {
1920 request->home_server->state = HOME_STATE_ALIVE;
1924 request->home_server->stats.last_packet = packet->timestamp.tv_sec;
1925 request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
1927 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1928 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
1929 #ifdef WITH_ACCOUNTING
1930 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1931 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
1934 #endif /* WITH_STATS */
1938 * When we originate CoA requests, we patch them in here
1939 * so that they don't affect the rest of the state
1942 if (request->parent) {
1943 rad_assert(request->parent->coa == request);
1944 rad_assert((request->proxy->code == PW_COA_REQUEST) ||
1945 (request->proxy->code == PW_DISCONNECT_REQUEST));
1946 rad_assert(request->process != NULL);
1947 request_coa_separate(request);
1951 request->process(request, FR_ACTION_PROXY_REPLY);
1957 static int setup_post_proxy_fail(REQUEST *request)
1959 const DICT_VALUE *dval = NULL;
1962 if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1963 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
1964 "Fail-Authentication");
1966 } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1967 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
1970 } else if (request->proxy->code == PW_COA_REQUEST) {
1971 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
1973 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
1974 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
1977 DEBUG("WARNING: Unknown packet type in Post-Proxy-Type Fail: ignoring");
1978 request_cleanup_delay_init(request, NULL);
1982 if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
1985 DEBUG("No Post-Proxy-Type Fail: ignoring");
1986 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, -1);
1987 request_cleanup_delay_init(request, NULL);
1991 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0);
1992 if (!vp) vp = radius_paircreate(request, &request->config_items,
1993 PW_POST_PROXY_TYPE, 0, PW_TYPE_INTEGER);
1994 vp->vp_integer = dval->value;
1999 STATE_MACHINE_DECL(proxy_running)
2001 TRACE_STATE_MACHINE;
2004 case FR_ACTION_CONFLICTING:
2006 case FR_ACTION_TIMER:
2007 case FR_ACTION_PROXY_REPLY:
2008 request_common(request, action);
2012 request_running(request, FR_ACTION_PROXY_REPLY);
2016 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2021 STATE_MACHINE_DECL(request_virtual_server)
2023 TRACE_STATE_MACHINE;
2026 case FR_ACTION_CONFLICTING:
2028 case FR_ACTION_TIMER:
2029 case FR_ACTION_PROXY_REPLY:
2030 request_common(request, action);
2034 request_running(request, action);
2038 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2044 static int request_will_proxy(REQUEST *request)
2046 int rcode, pre_proxy_type = 0;
2047 const char *realmname = NULL;
2048 VALUE_PAIR *vp, *strippedname;
2050 REALM *realm = NULL;
2051 home_pool_t *pool = NULL;
2053 if (!request->root->proxy_requests) return 0;
2054 if (request->packet->dst_port == 0) return 0;
2055 if (request->packet->code == PW_STATUS_SERVER) return 0;
2056 if (request->in_proxy_hash) return 0;
2059 * FIXME: for 3.0, allow this only for rejects?
2061 if (request->reply->code != 0) return 0;
2063 vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0);
2065 realm = realm_find2(vp->vp_strvalue);
2067 RDEBUG2("ERROR: Cannot proxy to unknown realm %s",
2072 realmname = vp->vp_strvalue;
2075 * Figure out which pool to use.
2077 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2078 pool = realm->auth_pool;
2080 #ifdef WITH_ACCOUNTING
2081 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2082 pool = realm->acct_pool;
2086 } else if ((request->packet->code == PW_COA_REQUEST) ||
2087 (request->packet->code == PW_DISCONNECT_REQUEST)) {
2088 pool = realm->coa_pool;
2098 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0);
2101 switch (request->packet->code) {
2102 case PW_AUTHENTICATION_REQUEST:
2103 pool_type = HOME_TYPE_AUTH;
2106 #ifdef WITH_ACCOUNTING
2107 case PW_ACCOUNTING_REQUEST:
2108 pool_type = HOME_TYPE_ACCT;
2113 case PW_COA_REQUEST:
2114 case PW_DISCONNECT_REQUEST:
2115 pool_type = HOME_TYPE_COA;
2123 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2127 RDEBUG2(" WARNING: Cancelling proxy as no home pool exists");
2131 request->home_pool = pool;
2133 home = home_server_ldb(realmname, pool, request);
2135 RDEBUG2("ERROR: Failed to find live home server: Cancelling proxy");
2138 home_server_update_request(home, request);
2142 * Once we've decided to proxy a request, we cannot send
2143 * a CoA packet. So we free up any CoA packet here.
2145 if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2149 * Remember that we sent the request to a Realm.
2151 if (realmname) pairadd(&request->packet->vps,
2152 pairmake("Realm", realmname, T_OP_EQ));
2155 * Strip the name, if told to.
2157 * Doing it here catches the case of proxied tunneled
2160 if (realm && (realm->striprealm == TRUE) &&
2161 (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0)) != NULL) {
2163 * If there's a Stripped-User-Name attribute in
2164 * the request, then use THAT as the User-Name
2165 * for the proxied request, instead of the
2168 * This is done by making a copy of the
2169 * Stripped-User-Name attribute, turning it into
2170 * a User-Name attribute, deleting the
2171 * Stripped-User-Name and User-Name attributes
2172 * from the vps list, and making the new
2173 * User-Name the head of the vps list.
2175 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0);
2177 vp = radius_paircreate(request, NULL,
2178 PW_USER_NAME, 0, PW_TYPE_STRING);
2179 rad_assert(vp != NULL); /* handled by above function */
2180 /* Insert at the START of the list */
2181 vp->next = request->proxy->vps;
2182 request->proxy->vps = vp;
2184 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2185 sizeof(vp->vp_strvalue));
2186 vp->length = strippedname->length;
2189 * Do NOT delete Stripped-User-Name.
2194 * If there is no PW_CHAP_CHALLENGE attribute but
2195 * there is a PW_CHAP_PASSWORD we need to add it
2196 * since we can't use the request authenticator
2197 * anymore - we changed it.
2199 if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2200 pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0) &&
2201 pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0) == NULL) {
2202 vp = radius_paircreate(request, &request->proxy->vps,
2203 PW_CHAP_CHALLENGE, 0, PW_TYPE_OCTETS);
2204 memcpy(vp->vp_strvalue, request->packet->vector,
2205 sizeof(request->packet->vector));
2206 vp->length = sizeof(request->packet->vector);
2210 * The RFC's say we have to do this, but FreeRADIUS
2213 vp = radius_paircreate(request, &request->proxy->vps,
2214 PW_PROXY_STATE, 0, PW_TYPE_OCTETS);
2215 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2216 request->packet->id);
2217 vp->length = strlen(vp->vp_strvalue);
2220 * Should be done BEFORE inserting into proxy hash, as
2221 * pre-proxy may use this information, or change it.
2223 request->proxy->code = request->packet->code;
2226 * Call the pre-proxy routines.
2228 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0);
2230 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
2231 pre_proxy_type = vp->vp_integer;
2234 rad_assert(request->home_pool != NULL);
2236 if (request->home_pool->virtual_server) {
2237 const char *old_server = request->server;
2239 request->server = request->home_pool->virtual_server;
2240 RDEBUG2(" server %s {", request->server);
2241 rcode = module_pre_proxy(pre_proxy_type, request);
2243 request->server = old_server;
2245 rcode = module_pre_proxy(pre_proxy_type, request);
2248 case RLM_MODULE_FAIL:
2249 case RLM_MODULE_INVALID:
2250 case RLM_MODULE_NOTFOUND:
2251 case RLM_MODULE_USERLOCK:
2253 /* FIXME: debug print failed stuff */
2256 case RLM_MODULE_REJECT:
2257 case RLM_MODULE_HANDLED:
2261 * Only proxy the packet if the pre-proxy code succeeded.
2263 case RLM_MODULE_NOOP:
2265 case RLM_MODULE_UPDATED:
2272 static int request_proxy(REQUEST *request, int retransmit)
2276 rad_assert(request->parent == NULL);
2277 rad_assert(request->home_server != NULL);
2279 if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2283 RDEBUG("WARNING: Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
2284 request_done(request->coa, FR_ACTION_DONE);
2289 * The request may be sent to a virtual server. If we're
2290 * in a child thread, just process it here. If we're the
2291 * master, push it back onto the queue for later
2294 if (request->home_server->server) {
2295 DEBUG("Proxying to virtual server %s",
2296 request->home_server->server);
2298 if (!we_are_master()) {
2299 request_virtual_server(request, FR_ACTION_RUN);
2300 #ifdef HAVE_PTHREAD_H
2301 request->child_pid = NO_SUCH_CHILD_PID;
2306 request_queue_or_run(request, request_virtual_server);
2311 * We're actually sending a proxied packet. Do that now.
2313 if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2314 radlog_request(L_PROXY, 0, request, "Failed to insert initial packet into the proxy list.");
2318 RDEBUG2("Proxying request to home server %s port %d",
2319 inet_ntop(request->proxy->dst_ipaddr.af,
2320 &request->proxy->dst_ipaddr.ipaddr,
2321 buffer, sizeof(buffer)),
2322 request->proxy->dst_port);
2324 DEBUG_PACKET(request, request->proxy, 1);
2326 gettimeofday(&request->proxy_retransmit, NULL);
2328 request->proxy->timestamp = request->proxy_retransmit;
2329 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2332 #ifdef HAVE_PTHREAD_H
2333 request->child_pid = NO_SUCH_CHILD_PID;
2335 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2336 request->proxy_listener->send(request->proxy_listener,
2342 * Proxy the packet as if it was new.
2344 static int request_proxy_anew(REQUEST *request)
2347 * Keep a copy of the old Id so that the
2348 * re-transmitted request doesn't re-use the old
2349 * Id. Note that in certain cases (socket crash)
2350 * there is no Id as they have been purged from
2351 * proxy_list, but there should still be a leftover
2352 * packet hung off this request.
2354 RADIUS_PACKET old = *request->proxy;
2355 int old_hash = request->in_proxy_hash;
2357 home_server *old_home = request->home_server;
2359 rad_listen_t *listener = request->proxy_listener;
2362 rad_assert(old_home != NULL);
2365 * Find a live home server for the request.
2367 home = home_server_ldb(NULL, request->home_pool, request);
2369 RDEBUG2("ERROR: Failed to find live home server for request");
2371 remove_from_proxy_hash(request);
2373 if (!setup_post_proxy_fail(request)) {
2377 request_queue_or_run(request, proxy_running);
2380 home_server_update_request(home, request);
2383 * Don't free the old Id (if any) on error.
2385 if (!insert_into_proxy_hash(request)) {
2386 radlog_request(L_PROXY, 0, request, "Failed to insert retransmission into the proxy list.");
2387 goto post_proxy_fail;
2391 * Now that we have a new Id, free the old one (if any)
2392 * and update the various statistics.
2394 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2396 fr_packet_list_yank(proxy_list, &old);
2397 fr_packet_list_id_free(proxy_list, &old);
2398 old_home->currently_outstanding--;
2400 if (listener) listener->count--;
2403 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2406 * Free the old packet, to force re-encoding
2408 free(request->proxy->data);
2409 request->proxy->data = NULL;
2410 request->proxy->data_len = 0;
2412 #ifdef WITH_ACCOUNTING
2414 * Update the Acct-Delay-Time attribute.
2416 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2419 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0);
2420 if (!vp) vp = radius_paircreate(request,
2421 &request->proxy->vps,
2422 PW_ACCT_DELAY_TIME, 0,
2427 gettimeofday(&now, NULL);
2428 vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2433 if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2438 STATE_MACHINE_DECL(request_ping)
2440 home_server *home = request->home_server;
2443 TRACE_STATE_MACHINE;
2447 case FR_ACTION_TIMER:
2448 radlog(L_ERR, "No response to status check %d for home server %s port %d",
2450 inet_ntop(request->proxy->dst_ipaddr.af,
2451 &request->proxy->dst_ipaddr.ipaddr,
2452 buffer, sizeof(buffer)),
2453 request->proxy->dst_port);
2456 case FR_ACTION_PROXY_REPLY:
2457 rad_assert(request->in_proxy_hash);
2459 request->home_server->num_received_pings++;
2460 radlog_request(L_PROXY, 0, request, "Received response to status check %d (%d in current sequence)",
2461 request->number, home->num_received_pings);
2464 * Remove the request from any hashes
2466 fr_event_delete(el, &request->ev);
2467 remove_from_proxy_hash(request);
2470 * The control socket may have marked the home server as
2471 * alive. OR, it may have suddenly started responding to
2472 * requests again. If so, don't re-do the "make alive"
2475 if (home->state == HOME_STATE_ALIVE) break;
2478 * We haven't received enough ping responses to mark it
2479 * "alive". Wait a bit.
2481 if (home->num_received_pings < home->num_pings_to_alive) {
2486 * Mark it alive and delete any outstanding
2489 home->state = HOME_STATE_ALIVE;
2490 exec_trigger(request, request->home_server->cs, "home_server.alive", FALSE);
2491 home->currently_outstanding = 0;
2492 home->num_sent_pings = 0;
2493 home->num_received_pings = 0;
2494 gettimeofday(&home->revive_time, NULL);
2496 fr_event_delete(el, &home->ev);
2498 radlog_request(L_PROXY, 0, request, "Marking home server %s port %d alive",
2499 inet_ntop(request->proxy->dst_ipaddr.af,
2500 &request->proxy->dst_ipaddr.ipaddr,
2501 buffer, sizeof(buffer)),
2502 request->proxy->dst_port);
2506 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2510 rad_assert(!request->in_request_hash);
2511 rad_assert(request->ev == NULL);
2512 request_done(request, FR_ACTION_DONE);
2516 * Called from start of zombie period, OR after control socket
2517 * marks the home server dead.
2519 static void ping_home_server(void *ctx)
2521 home_server *home = ctx;
2524 struct timeval when, now;
2526 if ((home->state == HOME_STATE_ALIVE) ||
2527 (home->ping_check == HOME_PING_CHECK_NONE) ||
2529 (home->proto == IPPROTO_TCP) ||
2531 (home->ev != NULL)) {
2535 gettimeofday(&now, NULL);
2537 if (home->state == HOME_STATE_ZOMBIE) {
2538 when = home->zombie_period_start;
2539 when.tv_sec += home->zombie_period;
2541 if (timercmp(&when, &now, <)) {
2542 DEBUG("PING: Zombie period is over for home server %s",
2544 mark_home_server_dead(home, &now);
2548 request = request_alloc();
2549 request->number = request_num_counter++;
2550 #ifdef HAVE_PTHREAD_H
2551 request->child_pid = NO_SUCH_CHILD_PID;
2554 request->proxy = rad_alloc(1);
2555 rad_assert(request->proxy != NULL);
2557 if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2558 request->proxy->code = PW_STATUS_SERVER;
2560 radius_pairmake(request, &request->proxy->vps,
2561 "Message-Authenticator", "0x00", T_OP_SET);
2563 } else if (home->type == HOME_TYPE_AUTH) {
2564 request->proxy->code = PW_AUTHENTICATION_REQUEST;
2566 radius_pairmake(request, &request->proxy->vps,
2567 "User-Name", home->ping_user_name, T_OP_SET);
2568 radius_pairmake(request, &request->proxy->vps,
2569 "User-Password", home->ping_user_password, T_OP_SET);
2570 radius_pairmake(request, &request->proxy->vps,
2571 "Service-Type", "Authenticate-Only", T_OP_SET);
2572 radius_pairmake(request, &request->proxy->vps,
2573 "Message-Authenticator", "0x00", T_OP_SET);
2576 #ifdef WITH_ACCOUNTING
2577 request->proxy->code = PW_ACCOUNTING_REQUEST;
2579 radius_pairmake(request, &request->proxy->vps,
2580 "User-Name", home->ping_user_name, T_OP_SET);
2581 radius_pairmake(request, &request->proxy->vps,
2582 "Acct-Status-Type", "Stop", T_OP_SET);
2583 radius_pairmake(request, &request->proxy->vps,
2584 "Acct-Session-Id", "00000000", T_OP_SET);
2585 vp = radius_pairmake(request, &request->proxy->vps,
2586 "Event-Timestamp", "0", T_OP_SET);
2587 vp->vp_date = now.tv_sec;
2589 rad_assert("Internal sanity check failed");
2593 vp = radius_pairmake(request, &request->proxy->vps,
2594 "NAS-Identifier", "", T_OP_SET);
2596 snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue),
2597 "Status Check %u. Are you alive?",
2598 home->num_sent_pings);
2599 vp->length = strlen(vp->vp_strvalue);
2602 request->proxy->src_ipaddr = home->src_ipaddr;
2603 request->proxy->dst_ipaddr = home->ipaddr;
2604 request->proxy->dst_port = home->port;
2605 request->home_server = home;
2606 #ifdef DEBUG_STATE_MACHINE
2607 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_DONE);
2608 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2610 #ifdef HAVE_PTHREAD_H
2611 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2613 request->child_state = REQUEST_DONE;
2614 request->process = request_ping;
2616 rad_assert(request->proxy_listener == NULL);
2618 if (!insert_into_proxy_hash(request)) {
2619 radlog_request(L_PROXY, 0, request, "Failed to insert status check %d into proxy list. Discarding it.",
2622 rad_assert(!request->in_request_hash);
2623 rad_assert(!request->in_proxy_hash);
2624 rad_assert(request->ev == NULL);
2625 request_free(&request);
2630 * Set up the timer callback.
2633 when.tv_sec += home->ping_timeout;
2635 DEBUG("PING: Waiting %u seconds for response to ping",
2636 home->ping_timeout);
2638 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2639 home->num_sent_pings++;
2641 rad_assert(request->proxy_listener != NULL);
2642 request->proxy_listener->send(request->proxy_listener,
2646 * Add +/- 2s of jitter, as suggested in RFC 3539
2647 * and in the Issues and Fixes draft.
2650 home->when.tv_sec += home->ping_interval;
2652 add_jitter(&home->when);
2654 DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
2655 INSERT_EVENT(ping_home_server, home);
2658 static void home_trigger(home_server *home, const char *trigger)
2661 RADIUS_PACKET my_packet;
2663 memset(&my_request, 0, sizeof(my_request));
2664 memset(&my_packet, 0, sizeof(my_packet));
2665 my_request.proxy = &my_packet;
2666 my_packet.dst_ipaddr = home->ipaddr;
2667 my_packet.src_ipaddr = home->src_ipaddr;
2669 exec_trigger(&my_request, home->cs, trigger, FALSE);
2672 static void mark_home_server_zombie(home_server *home)
2678 rad_assert((home->state == HOME_STATE_ALIVE) ||
2679 (home->state == HOME_STATE_UNKNOWN));
2682 if (home->proto == IPPROTO_TCP) {
2683 DEBUG("WARNING: Not marking TCP server %s zombie", home->name);
2688 home->state = HOME_STATE_ZOMBIE;
2689 home_trigger(home, "home_server.zombie");
2692 * Back-date the zombie period to when we last expected
2693 * to see a response. i.e. when we last sent a request.
2695 if (home->last_packet_sent == 0) {
2696 gettimeofday(&home->zombie_period_start, NULL);
2698 home->zombie_period_start.tv_sec = home->last_packet_sent;
2699 home->zombie_period_start.tv_usec = 0;
2702 fr_event_delete(el, &home->ev);
2703 home->num_sent_pings = 0;
2704 home->num_received_pings = 0;
2706 radlog(L_PROXY, "Marking home server %s port %d as zombie (it has not responded in %d seconds).",
2707 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2708 buffer, sizeof(buffer)),
2709 home->port, home->response_window);
2711 ping_home_server(home);
2715 void revive_home_server(void *ctx)
2717 home_server *home = ctx;
2721 rad_assert(home->proto != IPPROTO_TCP);
2724 home->state = HOME_STATE_ALIVE;
2725 home_trigger(home, "home_server.alive");
2726 home->currently_outstanding = 0;
2727 gettimeofday(&home->revive_time, NULL);
2730 * Delete any outstanding events.
2732 if (home->ev) fr_event_delete(el, &home->ev);
2734 radlog(L_PROXY, "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
2735 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2736 buffer, sizeof(buffer)),
2740 void mark_home_server_dead(home_server *home, struct timeval *when)
2742 int previous_state = home->state;
2746 if (home->proto == IPPROTO_TCP) {
2747 DEBUG("WARNING: Not marking TCP server dead");
2752 radlog(L_PROXY, "Marking home server %s port %d as dead.",
2753 inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2754 buffer, sizeof(buffer)),
2757 home->state = HOME_STATE_IS_DEAD;
2758 home_trigger(home, "home_server.dead");
2760 if (home->ping_check != HOME_PING_CHECK_NONE) {
2762 * If the control socket marks us dead, start
2763 * pinging. Otherwise, we already started
2764 * pinging when it was marked "zombie".
2766 if (previous_state == HOME_STATE_ALIVE) {
2767 ping_home_server(home);
2769 DEBUG("PING: Already pinging home server %s",
2775 * Revive it after a fixed period of time. This
2776 * is very, very, bad.
2779 home->when.tv_sec += home->revive_interval;
2781 DEBUG("PING: Reviving home server %s in %u seconds",
2782 home->name, home->revive_interval);
2783 INSERT_EVENT(revive_home_server, home);
2787 STATE_MACHINE_DECL(proxy_wait_for_reply)
2789 struct timeval now, when;
2790 home_server *home = request->home_server;
2793 TRACE_STATE_MACHINE;
2795 rad_assert(request->packet->code != PW_STATUS_SERVER);
2796 rad_assert(request->home_server != NULL);
2798 gettimeofday(&now, NULL);
2800 rad_assert(request->child_state != REQUEST_DONE);
2802 if (request->master_state == REQUEST_STOP_PROCESSING) {
2803 request_done(request, FR_ACTION_DONE);
2809 if (request->proxy_reply) return;
2811 if ((home->state == HOME_STATE_IS_DEAD) ||
2812 !request->proxy_listener ||
2813 (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
2814 request_proxy_anew(request);
2819 if (home->proto == IPPROTO_TCP) {
2820 DEBUG2("Suppressing duplicate proxied request to home server %s port %d proto TCP - ID: %d",
2821 inet_ntop(request->proxy->dst_ipaddr.af,
2822 &request->proxy->dst_ipaddr.ipaddr,
2823 buffer, sizeof(buffer)),
2824 request->proxy->dst_port,
2825 request->proxy->id);
2830 #ifdef WITH_ACCOUNTING
2832 * If we update the Acct-Delay-Time, we need to
2835 if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
2836 pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0)) {
2837 request_proxy_anew(request);
2842 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2843 inet_ntop(request->proxy->dst_ipaddr.af,
2844 &request->proxy->dst_ipaddr.ipaddr,
2845 buffer, sizeof(buffer)),
2846 request->proxy->dst_port,
2847 request->proxy->id);
2848 request->num_proxied_requests++;
2850 rad_assert(request->proxy_listener != NULL);;
2851 DEBUG_PACKET(request, request->proxy, 1);
2852 FR_STATS_TYPE_INC(home->stats.total_requests);
2853 home->last_packet_sent = now.tv_sec;
2854 request->proxy_listener->send(request->proxy_listener,
2858 case FR_ACTION_TIMER:
2860 * Wake up "response_window" time in the future.
2861 * i.e. when MY packet hasn't received a response.
2863 * Note that we DO NOT mark the home server as
2864 * zombie if it doesn't respond to us. It may be
2865 * responding to other (better looking) packets.
2867 when = request->proxy->timestamp;
2868 when.tv_sec += home->response_window;
2871 * Not at the response window. Set the timer for
2874 if (timercmp(&when, &now, >)) {
2875 RDEBUG("Expecting proxy response no later than %d seconds from now", home->response_window);
2876 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2880 RDEBUG("No proxy response, giving up on request and marking it done");
2883 * If we haven't received any packets for
2884 * "response_window", then mark the home server
2887 * If the connection is TCP, then another
2888 * "watchdog timer" function takes care of pings,
2889 * etc. So we don't need to do it here.
2891 * This check should really be part of a home
2892 * server state machine.
2894 if (((home->state == HOME_STATE_ALIVE) ||
2895 (home->state == HOME_STATE_UNKNOWN)) &&
2897 (home->proto != IPPROTO_TCP) &&
2899 ((home->last_packet_recv + home->response_window) <= now.tv_sec)) {
2900 mark_home_server_zombie(home);
2903 FR_STATS_TYPE_INC(home->stats.total_timeouts);
2904 if (home->type == HOME_TYPE_AUTH) {
2905 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
2906 FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
2909 else if (home->type == HOME_TYPE_ACCT) {
2910 if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
2911 FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
2916 * There was no response within the window. Stop
2917 * the request. If the client retransmitted, it
2918 * may have failed over to another home server.
2919 * But that one may be dead, too.
2921 radlog_request(L_ERR, 0, request, "Failing request due to lack of any response from home server %s port %d",
2922 inet_ntop(request->proxy->dst_ipaddr.af,
2923 &request->proxy->dst_ipaddr.ipaddr,
2924 buffer, sizeof(buffer)),
2925 request->proxy->dst_port);
2927 if (!setup_post_proxy_fail(request)) {
2933 * Duplicate proxy replies have been quenched by
2934 * now. This state is only called ONCE, when we
2935 * receive a new reply from the home server.
2937 case FR_ACTION_PROXY_REPLY:
2938 request_queue_or_run(request, proxy_running);
2941 case FR_ACTION_CONFLICTING:
2942 request_done(request, action);
2946 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2950 #endif /* WITH_PROXY */
2952 /***********************************************************************
2956 ***********************************************************************/
2958 static int null_handler(UNUSED REQUEST *request)
2964 * See if we need to originate a CoA request.
2966 static void request_coa_originate(REQUEST *request)
2968 int rcode, pre_proxy_type = 0;
2974 rad_assert(request != NULL);
2975 rad_assert(request->coa != NULL);
2976 rad_assert(request->proxy == NULL);
2977 rad_assert(!request->in_proxy_hash);
2978 rad_assert(request->proxy_reply == NULL);
2981 * Check whether we want to originate one, or cancel one.
2983 vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0);
2985 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0);
2989 if (vp->vp_integer == 0) {
2991 request_done(request->coa, FR_ACTION_DONE);
2999 * src_ipaddr will be set up in proxy_encode.
3001 memset(&ipaddr, 0, sizeof(ipaddr));
3002 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0);
3004 ipaddr.af = AF_INET;
3005 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3007 } else if ((vp = pairfind(coa->proxy->vps,
3008 PW_PACKET_DST_IPV6_ADDRESS, 0)) != NULL) {
3009 ipaddr.af = AF_INET6;
3010 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3012 } else if ((vp = pairfind(coa->proxy->vps,
3013 PW_HOME_SERVER_POOL, 0)) != NULL) {
3014 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3016 if (!coa->home_pool) {
3017 RDEBUG2("WARNING: No such home_server_pool %s",
3023 * Prefer the pool to one server
3025 } else if (request->client->coa_pool) {
3026 coa->home_pool = request->client->coa_pool;
3028 } else if (request->client->coa_server) {
3029 coa->home_server = request->client->coa_server;
3033 * If all else fails, send it to the client that
3034 * originated this request.
3036 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3040 * Use the pool, if it exists.
3042 if (coa->home_pool) {
3043 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3044 if (!coa->home_server) {
3045 RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
3048 home_server_update_request(coa->home_server, coa);
3050 } else if (!coa->home_server) {
3051 int port = PW_COA_UDP_PORT;
3053 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0);
3054 if (vp) port = vp->vp_integer;
3056 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3057 if (!coa->home_server) {
3058 RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
3059 inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3060 buffer, sizeof(buffer)), port);
3065 vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0);
3067 switch (vp->vp_integer) {
3068 case PW_COA_REQUEST:
3069 case PW_DISCONNECT_REQUEST:
3070 coa->proxy->code = vp->vp_integer;
3074 DEBUG("Cannot set CoA Packet-Type to code %d",
3080 if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
3083 * The rest of the server code assumes that
3084 * request->packet && request->reply exist. Copy them
3085 * from the original request.
3087 rad_assert(coa->packet != NULL);
3088 rad_assert(coa->packet->vps == NULL);
3089 memcpy(coa->packet, request->packet, sizeof(*request->packet));
3090 coa->packet->vps = paircopy(request->packet->vps);
3091 coa->packet->data = NULL;
3092 rad_assert(coa->reply != NULL);
3093 rad_assert(coa->reply->vps == NULL);
3094 memcpy(coa->reply, request->reply, sizeof(*request->reply));
3095 coa->reply->vps = paircopy(request->reply->vps);
3096 coa->reply->data = NULL;
3097 coa->config_items = paircopy(request->config_items);
3098 coa->num_coa_requests = 0;
3099 coa->handle = null_handler;
3100 coa->number = request->number ^ (1 << 24);
3103 * Call the pre-proxy routines.
3105 vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0);
3107 RDEBUG2(" Found Pre-Proxy-Type %s", vp->vp_strvalue);
3108 pre_proxy_type = vp->vp_integer;
3111 if (coa->home_pool && coa->home_pool->virtual_server) {
3112 const char *old_server = coa->server;
3114 coa->server = coa->home_pool->virtual_server;
3115 RDEBUG2(" server %s {", coa->server);
3116 rcode = module_pre_proxy(pre_proxy_type, coa);
3118 coa->server = old_server;
3120 rcode = module_pre_proxy(pre_proxy_type, coa);
3127 * Only send the CoA packet if the pre-proxy code succeeded.
3129 case RLM_MODULE_NOOP:
3131 case RLM_MODULE_UPDATED:
3136 * Source IP / port is set when the proxy socket
3139 coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3140 coa->proxy->dst_port = coa->home_server->port;
3142 if (!insert_into_proxy_hash(coa)) {
3143 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list.");
3148 * We CANNOT divorce the CoA request from the parent
3149 * request. This function is running in a child thread,
3150 * and we need access to the main event loop in order to
3151 * to add the timers for the CoA packet.
3153 * Instead, we wait for the timer on the parent request
3156 gettimeofday(&coa->proxy->timestamp, NULL);
3157 coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3158 coa->delay = 0; /* need to calculate a new delay */
3160 DEBUG_PACKET(coa, coa->proxy, 1);
3162 coa->process = request_coa_process;
3163 #ifdef DEBUG_STATE_MACHINE
3164 if (debug_flag) printf("(%u) ********\tSTATE %s C%u -> C%u\t********\n", request->number, __FUNCTION__, request->child_state, REQUEST_ACTIVE);
3166 coa->child_state = REQUEST_ACTIVE;
3167 rad_assert(coa->proxy_reply == NULL);
3168 FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3169 coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3170 coa->proxy_listener->send(coa->proxy_listener, coa);
3174 static void request_coa_separate(REQUEST *request)
3176 #ifdef DEBUG_STATE_MACHINE
3177 int action = FR_ACTION_TIMER;
3179 TRACE_STATE_MACHINE;
3181 rad_assert(request->parent != NULL);
3182 rad_assert(request->parent->coa == request);
3183 rad_assert(request->ev == NULL);
3184 rad_assert(!request->in_request_hash);
3186 request->parent->coa = NULL;
3187 request->parent = NULL;
3190 * Set up timers for the CoA request. These do all kinds
3191 * of different things....
3193 request_coa_timer(request);
3196 static void request_coa_timer(REQUEST *request)
3199 struct timeval now, when, mrd;
3201 rad_assert(request->parent == NULL);
3203 if (request->proxy_reply) return request_process_timer(request);
3205 gettimeofday(&now, NULL);
3207 if (request->delay == 0) {
3209 * Implement re-transmit algorithm as per RFC 5080
3212 * We want IRT + RAND*IRT
3213 * or 0.9 IRT + rand(0,.2) IRT
3215 * 2^20 ~ USEC, and we want 2.
3216 * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3218 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3219 request->delay = delay * request->home_server->coa_irt;
3220 delay = request->home_server->coa_irt * USEC;
3221 delay -= delay / 10;
3222 delay += request->delay;
3223 request->delay = delay;
3225 when = request->proxy->timestamp;
3226 tv_add(&when, delay);
3228 if (timercmp(&when, &now, >)) {
3229 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3235 * Retransmit CoA request.
3239 * Cap count at MRC, if it is non-zero.
3241 if (request->home_server->coa_mrc &&
3242 (request->num_coa_requests >= request->home_server->coa_mrc)) {
3243 if (!setup_post_proxy_fail(request)) {
3247 request_queue_or_run(request, proxy_running);
3252 * RFC 5080 Section 2.2.1
3254 * RT = 2*RTprev + RAND*RTprev
3255 * = 1.9 * RTprev + rand(0,.2) * RTprev
3256 * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3259 delay ^= (delay >> 16);
3261 frac = request->delay / 5;
3262 delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3264 delay += (2 * request->delay) - (request->delay / 10);
3267 * Cap delay at MRT, if MRT is non-zero.
3269 if (request->home_server->coa_mrt &&
3270 (delay > (request->home_server->coa_mrt * USEC))) {
3271 int mrt_usec = request->home_server->coa_mrt * USEC;
3274 * delay = MRT + RAND * MRT
3275 * = 0.9 MRT + rand(0,.2) * MRT
3278 delay ^= (delay >> 15);
3280 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3281 delay += mrt_usec - (mrt_usec / 10);
3284 request->delay = delay;
3286 tv_add(&when, request->delay);
3287 mrd = request->proxy->timestamp;
3288 mrd.tv_sec += request->home_server->coa_mrd;
3291 * Cap duration at MRD.
3293 if (timercmp(&mrd, &when, <)) {
3296 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3298 request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3300 FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3303 * Status servers don't count as real packets sent.
3305 request->proxy_listener->send(request->proxy_listener,
3310 #ifdef HAVE_PTHREAD_H
3311 STATE_MACHINE_DECL(coa_running)
3313 TRACE_STATE_MACHINE;
3316 case FR_ACTION_TIMER:
3317 request_coa_timer(request);
3320 case FR_ACTION_PROXY_REPLY:
3321 request_common(request, action);
3325 request_running(request, FR_ACTION_PROXY_REPLY);
3329 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3333 #endif /* HAVE_PTHREAD_H */
3337 * Process CoA requests that we originated.
3339 STATE_MACHINE_DECL(request_coa_process)
3341 TRACE_STATE_MACHINE;
3344 case FR_ACTION_TIMER:
3345 request_coa_timer(request);
3348 case FR_ACTION_PROXY_REPLY:
3349 rad_assert(request->parent == NULL);
3350 #ifdef HAVE_PTHREAD_H
3352 * Catch the case of a proxy reply when called
3353 * from the main worker thread.
3355 if (we_are_master() &&
3356 (request->process != coa_running)) {
3357 request_queue_or_run(request, coa_running);
3363 request_running(request, action);
3367 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3372 #endif /* WITH_COA */
3374 /***********************************************************************
3376 * End of the State machine. Start of additional helper code.
3378 ***********************************************************************/
3380 /***********************************************************************
3384 ***********************************************************************/
3385 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3388 rad_listen_t *listener = ctx;
3390 rad_assert(xel == el);
3396 (listener->type != RAD_LISTEN_DETAIL) &&
3398 (listener->fd < 0)) {
3401 listener->print(listener, buffer, sizeof(buffer));
3402 radlog(L_ERR, "FATAL: Asked to read from closed socket: %s",
3405 rad_panic("Socket was closed on us!");
3409 listener->recv(listener);
3414 * This function is called periodically to see if this detail
3415 * file is available for reading.
3417 static void event_poll_detail(void *ctx)
3420 rad_listen_t *this = ctx;
3421 struct timeval when, now;
3422 listen_detail_t *detail = this->data;
3424 rad_assert(this->type == RAD_LISTEN_DETAIL);
3427 event_socket_handler(el, this->fd, this);
3429 fr_event_now(el, &now);
3433 * Backdoor API to get the delay until the next poll
3436 delay = this->encode(this, NULL);
3437 if (delay == 0) goto redo;
3439 tv_add(&when, delay);
3441 if (!fr_event_insert(el, event_poll_detail, this,
3442 &when, &detail->ev)) {
3443 radlog(L_ERR, "Failed creating handler");
3449 static void event_status(struct timeval *wake)
3451 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3455 if (debug_flag == 0) {
3457 radlog(L_INFO, "Ready to process requests.");
3458 just_started = FALSE;
3464 radlog(L_INFO, "Ready to process requests.");
3466 } else if ((wake->tv_sec != 0) ||
3467 (wake->tv_usec >= 100000)) {
3468 DEBUG("Waking up in %d.%01u seconds.",
3469 (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3474 * FIXME: Put this somewhere else, where it isn't called
3475 * all of the time...
3478 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3480 * If there are no child threads, then there may
3481 * be child processes. In that case, wait for
3482 * their exit status, and throw that exit status
3483 * away. This helps get rid of zxombie children.
3485 while (waitpid(-1, &argval, WNOHANG) > 0) {
3493 int event_new_fd(rad_listen_t *this)
3497 if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
3499 this->print(this, buffer, sizeof(buffer));
3501 if (this->status == RAD_LISTEN_STATUS_INIT) {
3502 listen_socket_t *sock = this->data;
3505 DEBUG("Listening on %s", buffer);
3507 radlog(L_INFO, " ... adding new socket %s", buffer);
3512 * Add it to the list of sockets we can use.
3513 * Server sockets (i.e. auth/acct) are never
3514 * added to the packet list.
3516 if (this->type == RAD_LISTEN_PROXY) {
3517 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3518 if (!fr_packet_list_socket_add(proxy_list, this->fd,
3520 &sock->other_ipaddr, sock->other_port,
3523 #ifdef HAVE_PTHREAD_H
3524 proxy_no_new_sockets = TRUE;
3526 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3529 * This is bad. However, the
3530 * packet list now supports 256
3531 * open sockets, which should
3532 * minimize this problem.
3534 radlog(L_ERR, "Failed adding proxy socket: %s",
3540 sock->home->limit.num_connections++;
3542 #ifdef HAVE_PTHREAD_H
3544 * If necessary, add it to the list of
3545 * new proxy listeners.
3547 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3548 this->next = proxy_listener_list;
3549 proxy_listener_list = this;
3553 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3556 * Tell the main thread that we've added
3557 * a proxy listener, but only if we need
3558 * to update the event list. Do this
3559 * with the mutex unlocked, to reduce
3563 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3564 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3572 * Detail files are always known, and aren't
3573 * put into the socket event loop.
3575 if (this->type == RAD_LISTEN_DETAIL) {
3576 this->status = RAD_LISTEN_STATUS_KNOWN;
3579 * Set up the first poll interval.
3581 event_poll_detail(this);
3588 * Add timers to child sockets, if necessary.
3590 if (sock->proto == IPPROTO_TCP && sock->opened &&
3591 (sock->limit.lifetime || sock->limit.idle_timeout)) {
3592 struct timeval when;
3596 when.tv_sec = sock->opened + 1;
3599 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3601 rad_panic("Failed to insert event");
3606 FD_MUTEX_LOCK(&fd_mutex);
3607 if (!fr_event_fd_insert(el, 0, this->fd,
3608 event_socket_handler, this)) {
3609 radlog(L_ERR, "Failed adding event handler for socket!");
3612 FD_MUTEX_UNLOCK(&fd_mutex);
3614 this->status = RAD_LISTEN_STATUS_KNOWN;
3619 * Something went wrong with the socket: make it harmless.
3621 if (this->status == RAD_LISTEN_STATUS_REMOVE_FD) {
3625 * Remove it from the list of live FD's.
3627 FD_MUTEX_LOCK(&fd_mutex);
3628 fr_event_fd_delete(el, 0, this->fd);
3629 FD_MUTEX_UNLOCK(&fd_mutex);
3633 * We track requests using this socket only for
3634 * TCP. For UDP, we don't currently close
3638 if (this->type != RAD_LISTEN_PROXY)
3641 if (this->count != 0) {
3642 fr_packet_list_walk(pl, this,
3643 remove_all_requests);
3646 if (this->count == 0) {
3647 this->status = RAD_LISTEN_STATUS_FINISH;
3658 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3659 if (!fr_packet_list_socket_freeze(proxy_list,
3661 radlog(L_ERR, "Fatal error freezing socket: %s",
3667 * Doing this with the proxy mutex held
3668 * is a Bad Thing. We should move to
3669 * finer-grained mutexes.
3671 count = this->count;
3673 fr_packet_list_walk(proxy_list, this,
3674 disconnect_all_proxied_requests);
3676 count = this->count; /* protected by mutex */
3677 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3680 this->status = RAD_LISTEN_STATUS_FINISH;
3684 #endif /* WITH_PROXY */
3685 #endif /* WITH_TCP */
3688 * Re-open the socket, pointing it to /dev/null.
3689 * This means that all writes proceed without
3690 * blocking, and all reads return "no data".
3692 * This leaves the socket active, so any child
3693 * threads won't go insane. But it means that
3694 * they cannot send or receive any packets.
3696 * This is EXTRA work in the normal case, when
3697 * sockets are closed without error. But it lets
3698 * us have one simple processing method for all
3701 devnull = open("/dev/null", O_RDWR);
3703 radlog(L_ERR, "FATAL failure opening /dev/null: %s",
3707 if (dup2(devnull, this->fd) < 0) {
3708 radlog(L_ERR, "FATAL failure closing socket: %s",
3714 this->status = RAD_LISTEN_STATUS_CLOSED;
3717 * Fall through to the next section.
3723 * Called ONLY from the main thread. On the following
3729 * (and falling through from "forcibly close FD" above)
3730 * client closed connection on us
3731 * client sent us a bad packet.
3733 if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3734 int count = this->count;
3737 rad_assert(this->type != RAD_LISTEN_DETAIL);
3742 * Remove it from the list of active sockets, so
3743 * that it isn't used when proxying new packets.
3745 if (this->type == RAD_LISTEN_PROXY) {
3746 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3747 if (!fr_packet_list_socket_freeze(proxy_list,
3749 radlog(L_ERR, "Fatal error freezing socket: %s",
3753 count = this->count; /* protected by mutex */
3754 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3759 * Requests are still using the socket. Wait for
3763 struct timeval when;
3764 listen_socket_t *sock = this->data;
3767 * Try again to clean up the socket in 30
3770 gettimeofday(&when, NULL);
3773 if (!fr_event_insert(el,
3774 (fr_event_callback_t) event_new_fd,
3775 this, &when, &sock->ev)) {
3776 rad_panic("Failed to insert event");
3783 * No one is using this socket: we can delete it
3786 this->status = RAD_LISTEN_STATUS_FINISH;
3790 if (this->status == RAD_LISTEN_STATUS_FINISH) {
3791 listen_socket_t *sock = this->data;
3793 rad_assert(this->count == 0);
3794 radlog(L_INFO, " ... closing socket %s", buffer);
3797 * Remove it from the list of live FD's. Note
3798 * that it MAY also have been removed above. We
3799 * do it again here, to catch the case of sockets
3800 * closing on idle timeout, or max
3801 * lifetime... AFTER all requests have finished
3804 FD_MUTEX_LOCK(&fd_mutex);
3805 fr_event_fd_delete(el, 0, this->fd);
3806 FD_MUTEX_UNLOCK(&fd_mutex);
3810 * Remove it from the list of sockets to be used
3813 if (this->type == RAD_LISTEN_PROXY) {
3814 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3815 if (!fr_packet_list_socket_remove(proxy_list,
3817 radlog(L_ERR, "Fatal error removing socket: %s",
3821 if (sock->home) sock->home->limit.num_connections--;
3822 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3827 * Remove any pending cleanups.
3829 if (sock->ev) fr_event_delete(el, &sock->ev);
3832 * And finally, close the socket.
3836 #endif /* WITH_TCP */
3841 /***********************************************************************
3845 ***********************************************************************/
3847 static void handle_signal_self(int flag)
3849 if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3850 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3851 radlog(L_INFO, "Signalled to exit");
3852 fr_event_loop_exit(el, 1);
3854 radlog(L_INFO, "Signalled to terminate");
3855 exec_trigger(NULL, NULL, "server.signal.term", TRUE);
3856 fr_event_loop_exit(el, 2);
3860 } /* else exit/term flags weren't set */
3863 * Tell the even loop to stop processing.
3865 if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3867 static time_t last_hup = 0;
3870 if ((int) (when - last_hup) < 5) {
3871 radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3875 radlog(L_INFO, "Received HUP signal.");
3879 exec_trigger(NULL, NULL, "server.signal.hup", TRUE);
3880 fr_event_loop_exit(el, 0x80);
3884 if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3888 * FIXME: O(N) loops suck.
3890 for (this = mainconfig.listen;
3892 this = this->next) {
3893 if (this->type != RAD_LISTEN_DETAIL) continue;
3896 * This one didn't send the signal, skip
3899 if (!this->decode(this, NULL)) continue;
3902 * Go service the interrupt.
3904 event_poll_detail(this);
3911 #ifdef HAVE_PTHREAD_H
3913 * Add event handlers for idle timeouts && maximum lifetime.
3915 if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3916 struct timeval when, now;
3918 fr_event_now(el, &now);
3920 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3922 while (proxy_listener_list) {
3923 rad_listen_t *this = proxy_listener_list;
3924 listen_socket_t *sock = this->data;
3926 rad_assert(sock->proto == IPPROTO_TCP);
3927 proxy_listener_list = this->next;
3930 if (!sock->home) continue; /* skip UDP sockets */
3935 * Sockets should only be added to the
3936 * proxy_listener_list if they have limits.
3939 rad_assert(sock->home->limit.lifetime || sock->home->limit.idle_timeout);
3941 if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3943 rad_panic("Failed to insert event");
3947 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3949 #endif /* HAVE_PTHREAD_H */
3950 #endif /* WITH_PROXY */
3951 #endif /* WITH_TCP */
3954 #ifndef WITH_SELF_PIPE
3955 void radius_signal_self(int flag)
3957 handle_signal_self(flag);
3961 * Inform ourselves that we received a signal.
3963 void radius_signal_self(int flag)
3969 * The read MUST be non-blocking for this to work.
3971 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3975 for (i = 0; i < rcode; i++) {
3976 buffer[0] |= buffer[i];
3984 write(self_pipe[1], buffer, 1);
3988 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3989 UNUSED int fd, UNUSED void *ctx)
3994 rcode = read(self_pipe[0], buffer, sizeof(buffer));
3995 if (rcode <= 0) return;
3998 * Merge pending signals.
4000 for (i = 0; i < rcode; i++) {
4001 buffer[0] |= buffer[i];
4004 handle_signal_self(buffer[0]);
4008 /***********************************************************************
4010 * Bootstrapping code.
4012 ***********************************************************************/
4015 * Externally-visibly functions.
4017 int radius_event_init(CONF_SECTION *cs, int have_children)
4019 rad_listen_t *head = NULL;
4023 time(&fr_start_time);
4025 el = fr_event_list_create(event_status);
4028 pl = fr_packet_list_create(0);
4029 if (!pl) return 0; /* leak el */
4031 request_num_counter = 0;
4034 if (mainconfig.proxy_requests) {
4036 * Create the tree for managing proxied requests and
4039 proxy_list = fr_packet_list_create(1);
4040 if (!proxy_list) return 0;
4042 #ifdef HAVE_PTHREAD_H
4043 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4044 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
4052 #ifdef HAVE_PTHREAD_H
4053 NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4056 * Initialize the threads ONLY if we're spawning, AND
4057 * we're running normally.
4059 if (have_children && !check_config &&
4060 (thread_pool_init(cs, &have_children) < 0)) {
4066 * Move all of the thread calls to this file?
4068 * It may be best for the mutexes to be in this file...
4070 spawn_flag = have_children;
4073 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4075 if (listen_init(cs, &head, spawn_flag) < 0) {
4082 #ifdef WITH_SELF_PIPE
4084 * Child threads need a pipe to signal us, as do the
4087 if (pipe(self_pipe) < 0) {
4088 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
4092 if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
4093 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
4097 if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
4098 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
4103 if (!fr_event_fd_insert(el, 0, self_pipe[0],
4104 event_signal_handler, el)) {
4105 radlog(L_ERR, "Failed creating handler for signals");
4108 #endif /* WITH_SELF_PIPE */
4110 DEBUG("%s: #### Opening IP addresses and Ports ####",
4114 * The server temporarily switches to an unprivileged
4115 * user very early in the bootstrapping process.
4116 * However, some sockets MAY require privileged access
4117 * (bind to device, or to port < 1024, or to raw
4118 * sockets). Those sockets need to call suid up/down
4119 * themselves around the functions that need a privileged
4122 if (listen_init(cs, &head, spawn_flag) < 0) {
4126 mainconfig.listen = head;
4129 * At this point, no one has any business *ever* going
4132 fr_suid_down_permanent();
4138 static int request_hash_cb(UNUSED void *ctx, void *data)
4140 REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4143 rad_assert(request->in_proxy_hash == FALSE);
4146 request_done(request, FR_ACTION_DONE);
4153 static int proxy_hash_cb(UNUSED void *ctx, void *data)
4155 REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4157 request_done(request, FR_ACTION_DONE);
4163 void radius_event_free(void)
4166 * Stop and join all threads.
4168 #ifdef HAVE_PTHREAD_H
4174 * There are requests in the proxy hash that aren't
4175 * referenced from anywhere else. Remove them first.
4178 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
4179 fr_packet_list_free(proxy_list);
4184 fr_packet_list_walk(pl, NULL, request_hash_cb);
4186 fr_packet_list_free(pl);
4189 fr_event_list_free(el);
4192 int radius_event_process(void)
4196 return fr_event_loop(el);