radius_copy_packet for coa->packet instead of memcpy.
[freeradius.git] / src / main / process.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /*
18  * $Id$
19  *
20  * @file process.c
21  * @brief Defines the state machines that control how requests are processed.
22  *
23  * @copyright 2012  The FreeRADIUS server project
24  * @copyright 2012  Alan DeKok <aland@deployingradius.com>
25  */
26
27 RCSID("$Id$")
28
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32
33 #include <freeradius-devel/rad_assert.h>
34
35 #ifdef WITH_DETAIL
36 #include <freeradius-devel/detail.h>
37 #endif
38
39 #include <signal.h>
40 #include <fcntl.h>
41
42 #ifdef HAVE_SYS_WAIT_H
43 #       include <sys/wait.h>
44 #endif
45
46 extern pid_t radius_pid;
47 extern bool check_config;
48 extern fr_cond_t *debug_condition;
49
50 static bool spawn_flag = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static fr_packet_list_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
55
56 fr_event_list_t *radius_event_list_corral(UNUSED event_corral_t hint) {
57         /* Currently we do not run a second event loop for modules. */
58         return el;
59 }
60
61 static char const *action_codes[] = {
62         "INVALID",
63         "run",
64         "done",
65         "dup",
66         "conflicting",
67         "timer",
68 #ifdef WITH_PROXY
69         "proxy-reply"
70 #endif
71 };
72
73 #ifdef DEBUG_STATE_MACHINE
74 #define TRACE_STATE_MACHINE if (debug_flag) printf("(%u) ********\tSTATE %s action %s live M-%s C-%s\t********\n", request->number, __FUNCTION__, action_codes[action], master_state_names[request->master_state], child_state_names[request->child_state])
75
76 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
77         "?",
78         "active",
79         "stop-processing",
80         "counted"
81 };
82
83 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
84         "?",
85         "queued",
86         "running",
87         "proxied",
88         "reject-delay",
89         "cleanup-delay",
90         "done"
91 };
92
93 #else
94 #define TRACE_STATE_MACHINE {}
95 #endif
96
97 /*
98  *      Declare a state in the state machine.
99  *
100  */
101 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
102
103 #define STATE_MACHINE_TIMER(_x) request->timer_action = _x; \
104                 fr_event_insert(el, request_timer, request, \
105                                 &when, &request->ev);
106
107
108
109 /**
110  * @section request_timeline
111  *
112  *      Time sequence of a request
113  * @code
114  *
115  *      RQ-----------------P=============================Y-J-C
116  *       ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
117  * @endcode
118  *
119  * -    R: received.  Duplicate detection is done, and request is
120  *         cached.
121  *
122  * -    Q: Request is placed onto a queue for child threads to pick up.
123  *         If there are no child threads, the request goes immediately
124  *         to P.
125  *
126  * -    P: Processing the request through the modules.
127  *
128  * -    Y: Reply is ready.  Rejects MAY be delayed here.  All other
129  *         replies are sent immediately.
130  *
131  * -    J: Reject is sent "reject_delay" after the reply is ready.
132  *
133  * -    C: For Access-Requests, After "cleanup_delay", the request is
134  *         deleted.  Accounting-Request packets go directly from Y to C.
135  *
136  * -    M: Max request time.  If the request hits this timer, it is
137  *         forcibly stopped.
138  *
139  *      Other considerations include duplicate and conflicting
140  *      packets.  When a dupicate packet is received, it is ignored
141  *      until we've reached Y, as no response is ready.  If the reply
142  *      is a reject, duplicates are ignored until J, when we're ready
143  *      to send the reply.  In between the reply being sent (Y or J),
144  *      and C, the server responds to duplicates by sending the cached
145  *      reply.
146  *
147  *      Conflicting packets are sent in 2 situations.
148  *
149  *      The first is in between R and Y.  In that case, we consider
150  *      it as a hint that we're taking too long, and the NAS has given
151  *      up on the request.  We then behave just as if the M timer was
152  *      reached, and we discard the current request.  This allows us
153  *      to process the new one.
154  *
155  *      The second case is when we're at Y, but we haven't yet
156  *      finished processing the request.  This is a race condition in
157  *      the threading code (avoiding locks is faster).  It means that
158  *      a thread has actually encoded and sent the reply, and that the
159  *      NAS has responded with a new packet.  The server can then
160  *      safely mark the current request as "OK to delete", and behaves
161  *      just as if the M timer was reached.  This usually happens only
162  *      in high-load situations.
163  *
164  *      Duplicate packets are sent when the NAS thinks we're taking
165  *      too long, and wants a reply.  From R-Y, duplicates are
166  *      ignored.  From Y-J (for Access-Rejects), duplicates are also
167  *      ignored.  From Y-C, duplicates get a duplicate reply.  *And*,
168  *      they cause the "cleanup_delay" time to be extended.  This
169  *      extension means that we're more likely to send a duplicate
170  *      reply (if we have one), or to suppress processing the packet
171  *      twice if we didn't reply to it.
172  *
173  *      All functions in this file should be thread-safe, and should
174  *      assume thet the REQUEST structure is being accessed
175  *      simultaneously by the main thread, and by the child worker
176  *      threads.  This means that timers, etc. cannot be updated in
177  *      the child thread.
178  *
179  *      Instead, the master thread periodically calls request->process
180  *      with action TIMER.  It's up to the individual functions to
181  *      determine how to handle that.  They need to check if they're
182  *      being called from a child thread or the master, and then do
183  *      different things based on that.
184  */
185
186
187 #ifdef WITH_PROXY
188 static fr_packet_list_t *proxy_list = NULL;
189 #endif
190
191 #ifdef HAVE_PTHREAD_H
192 #ifdef WITH_PROXY
193 static pthread_mutex_t  proxy_mutex;
194 static rad_listen_t *proxy_listener_list = NULL;
195 static bool proxy_no_new_sockets = false;
196 #endif
197
198 #define PTHREAD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
199 #define PTHREAD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
200
201 static pthread_t NO_SUCH_CHILD_PID;
202 #define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
203
204 #else
205 /*
206  *      This is easier than ifdef's throughout the code.
207  */
208 #define PTHREAD_MUTEX_LOCK(_x)
209 #define PTHREAD_MUTEX_UNLOCK(_x)
210 #define NO_CHILD_THREAD
211 #endif
212
213 /*
214  *      We need mutexes around the event FD list *only* in certain
215  *      cases.
216  */
217 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
218 static pthread_mutex_t  fd_mutex;
219 #define FD_MUTEX_LOCK if (spawn_flag) pthread_mutex_lock
220 #define FD_MUTEX_UNLOCK if (spawn_flag) pthread_mutex_unlock
221 #else
222 /*
223  *      This is easier than ifdef's throughout the code.
224  */
225 #define FD_MUTEX_LOCK(_x)
226 #define FD_MUTEX_UNLOCK(_x)
227 #endif
228
229 static int request_num_counter = 0;
230 #ifdef WITH_PROXY
231 static int request_will_proxy(REQUEST *request);
232 static int request_proxy(REQUEST *request, int retransmit);
233 STATE_MACHINE_DECL(proxy_wait_for_reply);
234 STATE_MACHINE_DECL(proxy_running);
235 static int process_proxy_reply(REQUEST *request);
236 static void remove_from_proxy_hash(REQUEST *request);
237 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank);
238 static int insert_into_proxy_hash(REQUEST *request);
239 #endif
240
241 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
242                               RADCLIENT *client, RAD_REQUEST_FUNP fun);
243
244 STATE_MACHINE_DECL(request_common);
245
246 #if  defined(HAVE_PTHREAD_H) && !defined (NDEBUG)
247 static bool we_are_master(void)
248 {
249         if (spawn_flag &&
250             (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
251                 return false;
252         }
253
254         return true;
255 }
256 #define ASSERT_MASTER   if (!we_are_master()) rad_panic("We are not master")
257
258 #else
259 #define we_are_master(_x) (1)
260 #define ASSERT_MASTER
261 #endif
262
263 STATE_MACHINE_DECL(request_reject_delay);
264 STATE_MACHINE_DECL(request_cleanup_delay);
265 STATE_MACHINE_DECL(request_running);
266 #ifdef WITH_COA
267 static void request_coa_originate(REQUEST *request);
268 STATE_MACHINE_DECL(coa_running);
269 STATE_MACHINE_DECL(coa_wait_for_reply);
270 static void request_coa_separate(REQUEST *coa);
271 #endif
272
273 #undef USEC
274 #define USEC (1000000)
275
276 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
277
278 static void _rad_panic(char const *file, unsigned int line, char const *msg)
279 {
280         ERROR("[%s:%d] %s", file, line, msg);
281 #ifndef NDEBUG
282         rad_assert(0 == 1);
283 #endif
284         fr_exit(1);
285 }
286
287 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
288
289 static void tv_add(struct timeval *tv, int usec_delay)
290 {
291         if (usec_delay >= USEC) {
292                 tv->tv_sec += usec_delay / USEC;
293                 usec_delay %= USEC;
294         }
295         tv->tv_usec += usec_delay;
296
297         if (tv->tv_usec >= USEC) {
298                 tv->tv_sec += tv->tv_usec / USEC;
299                 tv->tv_usec %= USEC;
300         }
301 }
302
303 /*
304  *      In daemon mode, AND this request has debug flags set.
305  */
306 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
307
308 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
309 {
310         vp_cursor_t cursor;
311         VALUE_PAIR *vp;
312         char buffer[1024];
313         char const *received, *from;
314         fr_ipaddr_t const *ip;
315         int port;
316
317         if (!packet) return;
318
319         rad_assert(request->radlog != NULL);
320
321         if (direction == 0) {
322                 received = "Received";
323                 from = "from";  /* what else? */
324                 ip = &packet->src_ipaddr;
325                 port = packet->src_port;
326
327         } else {
328                 received = "Sending";
329                 from = "to";    /* hah! */
330                 ip = &packet->dst_ipaddr;
331                 port = packet->dst_port;
332         }
333
334         /*
335          *      Client-specific debugging re-prints the input
336          *      packet into the client log.
337          *
338          *      This really belongs in a utility library
339          */
340         if (is_radius_code(packet->code)) {
341                 RDEBUG("%s %s packet %s host %s port %i, id=%i, length=%zu",
342                        received, fr_packet_codes[packet->code], from,
343                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
344                        port, packet->id, packet->data_len);
345         } else {
346                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%zu",
347                        received, from,
348                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
349                        port,
350                        packet->code, packet->id, packet->data_len);
351         }
352
353         for (vp = fr_cursor_init(&cursor, &packet->vps);
354              vp;
355              vp = fr_cursor_next(&cursor)) {
356                 vp_prints(buffer, sizeof(buffer), vp);
357                 RDEBUG("\t%s", buffer);
358         }
359 }
360
361
362 /***********************************************************************
363  *
364  *      Start of RADIUS server state machine.
365  *
366  ***********************************************************************/
367
368 /*
369  *      Callback for ALL timer events related to the request.
370  */
371 static void request_timer(void *ctx)
372 {
373         REQUEST *request = ctx;
374         int action = request->timer_action;
375
376         TRACE_STATE_MACHINE;
377
378         request->process(request, action);
379 }
380
381 #define USEC (1000000)
382
383 /*
384  *      Only ever called from the master thread.
385  */
386 STATE_MACHINE_DECL(request_done)
387 {
388         struct timeval now, when;
389 #ifdef WITH_PROXY
390         char buffer[128];
391 #endif
392
393         TRACE_STATE_MACHINE;
394
395 #ifdef WITH_COA
396         /*
397          *      CoA requests can be cleaned up in the child thread,
398          *      but ONLY if they aren't tied into anything.
399          */
400         if (request->parent && (request->parent->coa == request)) {
401                 rad_assert(!request->in_request_hash);
402                 rad_assert(!request->in_proxy_hash);
403                 rad_assert(action == FR_ACTION_DONE);
404                 rad_assert(request->ev == NULL);
405         }
406 #endif
407
408 #ifdef HAVE_PTHREAD_H
409         /*
410          *      If called from a child thread, mark ourselves as done,
411          *      and wait for the master thread timer to clean us up.
412          */
413         if (!we_are_master()) {
414                 request->child_state = REQUEST_DONE;
415                 NO_CHILD_THREAD;
416                 return;
417         }
418 #endif
419
420 #ifdef WITH_COA
421         /*
422          *      Move the CoA request to its own handler.
423          */
424         if (request->coa) request_coa_separate(request->coa);
425
426         /*
427          *      If we're the CoA request, make the parent forget about
428          *      us.
429          */
430         if (request->parent && (request->parent->coa == request)) {
431                 request->parent->coa = NULL;
432                 (void) talloc_steal(NULL, request);
433         }
434
435 #endif
436
437         /*
438          *      It doesn't hurt to send duplicate replies.  All other
439          *      signals are ignored, as the request will be cleaned up
440          *      soon anyways.
441          */
442         switch (action) {
443         case FR_ACTION_DUP:
444                 if (request->reply->code != 0) {
445                         request->listener->send(request->listener, request);
446                         return;
447                 }
448                 break;
449
450                 /*
451                  *      This is only called from the master thread
452                  *      when there is a child thread processing the
453                  *      request.
454                  */
455         case FR_ACTION_CONFLICTING:
456                 if (request->child_state == REQUEST_DONE) break;
457
458                 /*
459                  *      If there's a reply packet, then we presume
460                  *      that the child has sent the reply, and we get
461                  *      pinged here before the child has a chance to
462                  *      say "I'm done!"
463                  */
464                 if (request->reply->data) break;
465
466                 RERROR("Received conflicting packet from "
467                                "client %s port %d - ID: %u due to "
468                                "unfinished request.  Giving up on old request.",
469                                request->client->shortname,
470                                request->packet->src_port, request->packet->id);
471                 break;
472
473                 /*
474                  *      Called only when there's an error remembering
475                  *      the packet, or when the socket gets closed from
476                  *      under us.
477                  */
478         case FR_ACTION_DONE:
479 #ifdef HAVE_PTHREAD_H
480                 /*
481                  *      Do NOT set child_state to DONE if it's still in the queue.
482                  */
483                 if (we_are_master() && (request->child_state == REQUEST_QUEUED)) {
484                         break;
485                 }
486
487                 /*
488                  *      If we have child threads and we're NOT the
489                  *      thread handling the request, don't do anything.
490                  */
491                 if (spawn_flag &&
492                     !pthread_equal(pthread_self(), request->child_pid)) {
493                         break;
494                 }
495 #endif
496 #ifdef DEBUG_STATE_MACHINE
497                 if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
498                                        request->number, __FUNCTION__,
499                                        child_state_names[request->child_state],
500                                        child_state_names[REQUEST_DONE]);
501 #endif
502                 request->child_state = REQUEST_DONE;
503                 break;
504
505                 /*
506                  *      Called when the child is taking too long to
507                  *      finish.  We've already marked it "please
508                  *      stop", so we don't complain any more.
509                  */
510         case FR_ACTION_TIMER:
511                 break;
512
513 #ifdef WITH_PROXY
514                 /*
515                  *      Child is still alive, and we're receiving more
516                  *      packets from the home server.
517                  */
518         case FR_ACTION_PROXY_REPLY:
519                 DEBUG2("Reply from home server %s port %d  - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
520                        inet_ntop(request->proxy->src_ipaddr.af,
521                                  &request->proxy->src_ipaddr.ipaddr,
522                                  buffer, sizeof(buffer)),
523                        request->proxy->dst_port, request->proxy->id,
524                        request->number);
525                 return;
526 #endif
527
528         default:
529                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
530                 break;
531         }
532
533         /*
534          *      Remove it from the request hash.
535          */
536         if (request->in_request_hash) {
537                 ASSERT_MASTER;
538                 if (!fr_packet_list_yank(pl, request->packet)) {
539                         rad_assert(0 == 1);
540                 }
541                 request->in_request_hash = false;
542         }
543
544 #ifdef WITH_PROXY
545         /*
546          *      Wait for the proxy ID to expire.  This allows us to
547          *      avoid re-use of proxy IDs for a while.
548          */
549         if (request->in_proxy_hash) {
550                 rad_assert(request->proxy != NULL);
551
552                 fr_event_now(el, &now);
553                 when = request->proxy->timestamp;
554
555 #ifdef WITH_COA
556                 if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
557                      (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
558                     (request->packet->code != request->proxy->code)) {
559                         when.tv_sec += request->home_server->coa_mrd;
560                 } else
561 #endif
562                 when.tv_sec += request->home_server->response_window;
563
564                 /*
565                  *      We haven't received all responses, AND there's still
566                  *      time to wait.  Do so.
567                  */
568                 if ((request->num_proxied_requests > request->num_proxied_responses) &&
569 #ifdef WITH_TCP
570                     (request->home_server->proto != IPPROTO_TCP) &&
571 #endif
572                     timercmp(&now, &when, <)) {
573                         RDEBUG("Waiting for more responses from the home server");
574                         goto wait_some_more;
575                 }
576
577                 /*
578                  *      Time to remove it.
579                  */
580                 remove_from_proxy_hash(request);
581         }
582 #endif
583
584 #ifdef HAVE_PTHREAD_H
585         /*
586          *      If there's no children, we can mark the request as done.
587          */
588         if (!spawn_flag) {
589                 request->child_state = REQUEST_DONE;
590         }
591 #endif
592
593         if (request->child_state != REQUEST_DONE) {
594                 gettimeofday(&now, NULL);
595 #ifdef WITH_PROXY
596         wait_some_more:
597 #endif
598
599 #ifdef HAVE_PTHREAD_H
600                 if (spawn_flag &&
601                     (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
602                         RDEBUG("Waiting for child thread to stop");
603                 }
604 #endif
605
606                 when = now;
607                 if (request->delay < (USEC / 3)) request->delay = USEC / 3;
608                 tv_add(&when, request->delay);
609                 request->delay += request->delay >> 1;
610                 if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
611
612                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
613                 return;
614         }
615
616 #ifdef HAVE_PTHREAD_H
617         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
618 #endif
619
620         /*
621          *      @todo: do final states for TCP sockets, too?
622          */
623         request_stats_final(request);
624 #ifdef WITH_TCP
625         if (request->listener) request->listener->count--;
626 #endif
627
628         if (request->packet) {
629                 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
630                         request->packet->id,
631                         (unsigned int) (request->timestamp - fr_start_time));
632         } /* else don't print anything */
633
634         if (request->ev) fr_event_delete(el, &request->ev);
635
636         request_free(&request);
637 }
638
639
640 static void request_cleanup_delay_init(REQUEST *request, struct timeval const *pnow)
641 {
642         struct timeval now, when;
643
644         if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
645
646         if (!request->root->cleanup_delay) goto done;
647
648         if (pnow) {
649                 now = *pnow;
650         } else {
651                 gettimeofday(&now, NULL);
652         }
653
654         rad_assert(request->reply->timestamp.tv_sec != 0);
655         when = request->reply->timestamp;
656
657         request->delay = request->root->cleanup_delay;
658         when.tv_sec += request->delay;
659
660         /*
661          *      Set timer for when we need to clean it up.
662          */
663         if (timercmp(&when, &now, >)) {
664 #ifdef DEBUG_STATE_MACHINE
665                 if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
666 #endif
667                 request->process = request_cleanup_delay;
668                 request->child_state = REQUEST_DONE;
669                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
670                 return;
671         }
672
673         /*
674          *      Otherwise just clean it up.
675          */
676 done:
677         request_done(request, FR_ACTION_DONE);
678 }
679
680
681 /*
682  *      Function to do all time-related events.
683  */
684 static void request_process_timer(REQUEST *request)
685 {
686         struct timeval now, when;
687         rad_assert(request->magic == REQUEST_MAGIC);
688 #ifdef DEBUG_STATE_MACHINE
689         int action = FR_ACTION_TIMER;
690 #endif
691
692         TRACE_STATE_MACHINE;
693         ASSERT_MASTER;
694
695 #ifdef WITH_COA
696         /*
697          *      If we originated a CoA request, divorce it from the
698          *      parent.  Then, set up the timers so that we can clean
699          *      it up as appropriate.
700          */
701         if (request->coa) request_coa_separate(request->coa);
702
703         /*
704          *      If we're the request, OR it isn't originating a CoA
705          *      request, check more things.
706          */
707         if (!request->proxy || (request->packet->code == request->proxy->code))
708 #endif
709         {
710                 rad_assert(request->listener != NULL);
711
712                 /*
713                  *      The socket was closed.  Tell the request that
714                  *      there is no point in continuing.
715                  */
716                 if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
717                         if ((request->master_state == REQUEST_ACTIVE) &&
718                             (request->child_state < REQUEST_REJECT_DELAY)) {
719                                 WDEBUG("Socket was closed while processing request %u: Stopping it.", request->number);
720                                 request->master_state = REQUEST_STOP_PROCESSING;
721                         }
722                 }
723         }
724
725         gettimeofday(&now, NULL);
726
727         /*
728          *      The request was forcibly stopped.
729          */
730         if (request->master_state == REQUEST_STOP_PROCESSING) {
731                 switch (request->child_state) {
732                 case REQUEST_QUEUED:
733                 case REQUEST_RUNNING:
734 #ifdef HAVE_PTHREAD_H
735                         rad_assert(spawn_flag == true);
736 #endif
737
738                 delay:
739                         /*
740                          *      Sleep for some more.  We HOPE that the
741                          *      child will become responsive at some
742                          *      point in the future.
743                          */
744                         when = now;
745                         tv_add(&when, request->delay);
746                         request->delay += request->delay >> 1;
747                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
748                         return;
749
750                         /*
751                          *      These should all be managed by the master thread
752                          */
753 #ifdef WITH_PROXY
754                 case REQUEST_PROXIED:
755 #endif
756                 case REQUEST_REJECT_DELAY:
757                 case REQUEST_CLEANUP_DELAY:
758                 case REQUEST_DONE:
759                 done:
760                         request_done(request, FR_ACTION_DONE);
761                         return;
762                 }
763         }
764
765         rad_assert(request->master_state == REQUEST_ACTIVE);
766
767         /*
768          *      It's still supposed to be running.
769          */
770         switch (request->child_state) {
771         case REQUEST_QUEUED:
772         case REQUEST_RUNNING:
773 #ifdef WITH_PROXY
774         case REQUEST_PROXIED:
775 #endif
776                 when = request->packet->timestamp;
777                 when.tv_sec += request->root->max_request_time;
778
779                 /*
780                  *      Taking too long: tell it to die.
781                  */
782                 if (timercmp(&now, &when, >=)) {
783 #ifdef HAVE_PTHREAD_H
784                         /*
785                          *      If there's a child thread processing it,
786                          *      complain.
787                          */
788                         if (spawn_flag &&
789                             (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
790                                 ERROR("Unresponsive child for request %u, in component %s module %s",
791                                       request->number,
792                                       request->component ? request->component : "<core>",
793                                       request->module ? request->module : "<core>");
794                                 exec_trigger(request, NULL, "server.thread.unresponsive", true);
795                         }
796 #endif
797                         request->master_state = REQUEST_STOP_PROCESSING;
798                 }
799
800 #ifdef WITH_PROXY
801                 /*
802                  *      We should wait for the proxy reply.
803                  */
804                 if (request->child_state == REQUEST_PROXIED) {
805                         if (request->proxy_reply) {
806                                 request->process = proxy_running;
807                         } else {
808                                 request->process = proxy_wait_for_reply;
809                         }
810                 }
811 #endif
812
813                 /*
814                  *      If the request has been told to die, we wait.
815                  *      Otherwise, we wait for the child thread to
816                  *      finish it's work.
817                  */
818                 goto delay;
819
820         case REQUEST_REJECT_DELAY:
821                 rad_assert(request->root->reject_delay > 0);
822 #ifdef WITH_COA
823                 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
824 #endif
825
826                 request->process = request_reject_delay;
827
828                 when = request->reply->timestamp;
829                 when.tv_sec += request->root->reject_delay;
830
831                 if (timercmp(&when, &now, >)) {
832 #ifdef DEBUG_STATE_MACHINE
833                         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_reject_delay");
834 #endif
835                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
836                         return;
837                 } /* else it's time to send the reject */
838
839                 RDEBUG2("Sending delayed reject");
840                 DEBUG_PACKET(request, request->reply, 1);
841                 request->listener->send(request->listener, request);
842                 request->child_state = REQUEST_CLEANUP_DELAY;
843                 /* FALL-THROUGH */
844
845         case REQUEST_CLEANUP_DELAY:
846                 rad_assert(request->root->cleanup_delay > 0);
847
848 #ifdef WITH_COA
849                 rad_assert(!request->proxy || (request->packet->code == request->proxy->code));
850 #endif
851
852                 request->process = request_cleanup_delay;
853
854                 when = request->reply->timestamp;
855                 when.tv_sec += request->root->cleanup_delay;
856
857                 if (timercmp(&when, &now, >)) {
858 #ifdef DEBUG_STATE_MACHINE
859                         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
860 #endif
861                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
862                         return;
863                 } /* else it's time to clean up */
864                 /* FALL-THROUGH */
865
866         case REQUEST_DONE:
867                 goto done;
868         }
869
870 }
871
872 static void request_queue_or_run(UNUSED REQUEST *request,
873                                  fr_request_process_t process)
874 {
875 #ifdef DEBUG_STATE_MACHINE
876         int action = FR_ACTION_TIMER;
877 #endif
878
879         TRACE_STATE_MACHINE;
880
881         /*
882          *      Do this here so that fewer other functions need to do
883          *      it.
884          */
885         if (request->master_state == REQUEST_STOP_PROCESSING) {
886 #ifdef DEBUG_STATE_MACHINE
887                 if (debug_flag) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
888                                        request->number, __FUNCTION__,
889                                        master_state_names[request->master_state],
890                                        child_state_names[request->child_state],
891                                        child_state_names[REQUEST_DONE]);
892 #endif
893                 request_done(request, FR_ACTION_DONE);
894                 return;
895         }
896
897         request->process = process;
898
899         if (we_are_master()) {
900                 struct timeval when;
901
902                 /*
903                  *      (re) set the initial delay.
904                  */
905                 request->delay = USEC / 3;
906                 gettimeofday(&when, NULL);
907                 tv_add(&when, request->delay);
908                 request->delay += request->delay >> 1;
909
910                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
911
912 #ifdef HAVE_PTHREAD_H
913                 if (spawn_flag) {
914                         /*
915                          *      A child thread will eventually pick it up.
916                          */
917                         if (request_enqueue(request)) return;
918
919                         /*
920                          *      Otherwise we're not going to do anything with
921                          *      it...
922                          */
923                         request_done(request, FR_ACTION_DONE);
924                         return;
925                 }
926 #endif
927         }
928
929         request->child_state = REQUEST_RUNNING;
930         request->process(request, FR_ACTION_RUN);
931
932 #ifdef WNOHANG
933         /*
934          *      Requests that care about child process exit
935          *      codes have already either called
936          *      rad_waitpid(), or they've given up.
937          */
938         while (waitpid(-1, NULL, WNOHANG) > 0);
939 #endif
940 }
941
942 STATE_MACHINE_DECL(request_common)
943 {
944 #ifdef WITH_PROXY
945         char buffer[128];
946 #endif
947
948         TRACE_STATE_MACHINE;
949         ASSERT_MASTER;
950
951         /*
952          *      Bail out as early as possible.
953          */
954         if (request->master_state == REQUEST_STOP_PROCESSING) {
955                 request_done(request, REQUEST_DONE);
956                 return;
957         }
958
959         switch (action) {
960         case FR_ACTION_DUP:
961 #ifdef WITH_PROXY
962                 /*
963                  *      We're still waiting for a proxy reply.
964                  */
965                 if (request->child_state == REQUEST_PROXIED) {
966                         proxy_wait_for_reply(request, action);
967                         return;
968                 }
969 #endif
970
971                 ERROR("(%u) Discarding duplicate request from "
972                        "client %s port %d - ID: %u due to unfinished request",
973                        request->number, request->client->shortname,
974                        request->packet->src_port,request->packet->id);
975                 break;
976
977         case FR_ACTION_CONFLICTING:
978                 /*
979                  *      We're in the master thread, ask the child to
980                  *      stop processing the request.
981                  */
982                 request_done(request, action);
983                 return;
984
985         case FR_ACTION_TIMER:
986                 request_process_timer(request);
987                 return;
988
989 #ifdef WITH_PROXY
990         case FR_ACTION_PROXY_REPLY:
991                 DEBUG2("Reply from home server %s port %d  - ID: %d arrived too late for request %u. Try increasing 'retry_delay' or 'max_request_time'",
992                        inet_ntop(request->proxy->src_ipaddr.af,
993                                  &request->proxy->src_ipaddr.ipaddr,
994                                  buffer, sizeof(buffer)),
995                        request->proxy->dst_port, request->proxy->id,
996                        request->number);
997                 return;
998 #endif
999
1000         default:
1001                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1002                 break;
1003         }
1004 }
1005
1006 STATE_MACHINE_DECL(request_cleanup_delay)
1007 {
1008         struct timeval when;
1009
1010         TRACE_STATE_MACHINE;
1011         ASSERT_MASTER;
1012
1013         switch (action) {
1014         case FR_ACTION_DUP:
1015                 if (request->reply->code != 0) {
1016                         request->listener->send(request->listener, request);
1017                 } else {
1018                         RDEBUG("No reply.  Ignoring retransmit.");
1019                 }
1020
1021                 /*
1022                  *      Double the cleanup_delay to catch retransmits.
1023                  */
1024                 when = request->reply->timestamp;
1025                 request->delay += request->delay ;
1026                 when.tv_sec += request->delay;
1027
1028                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
1029                 return;
1030
1031 #ifdef WITH_PROXY
1032         case FR_ACTION_PROXY_REPLY:
1033 #endif
1034         case FR_ACTION_CONFLICTING:
1035         case FR_ACTION_TIMER:
1036                 request_common(request, action);
1037                 return;
1038
1039         default:
1040                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1041                 break;
1042         }
1043 }
1044
1045 STATE_MACHINE_DECL(request_reject_delay)
1046 {
1047         TRACE_STATE_MACHINE;
1048         ASSERT_MASTER;
1049
1050         switch (action) {
1051         case FR_ACTION_DUP:
1052                 ERROR("(%u) Discarding duplicate request from "
1053                        "client %s port %d - ID: %u due to delayed reject",
1054                        request->number, request->client->shortname,
1055                        request->packet->src_port,request->packet->id);
1056                 return;
1057
1058 #ifdef WITH_PROXY
1059         case FR_ACTION_PROXY_REPLY:
1060 #endif
1061         case FR_ACTION_CONFLICTING:
1062         case FR_ACTION_TIMER:
1063                 request_common(request, action);
1064                 break;
1065
1066         default:
1067                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1068                 break;
1069         }
1070 }
1071
1072
1073 static int request_pre_handler(REQUEST *request, UNUSED int action)
1074 {
1075         TRACE_STATE_MACHINE;
1076
1077         int rcode;
1078
1079         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1080
1081         /*
1082          *      Don't decode the packet if it's an internal "fake"
1083          *      request.  Instead, just return so that the caller can
1084          *      process it.
1085          */
1086         if (request->packet->dst_port == 0) {
1087                 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1088                 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1089                 return 1;
1090         }
1091
1092 #ifdef WITH_PROXY
1093         /*
1094          *      Put the decoded packet into it's proper place.
1095          */
1096         if (request->proxy_reply != NULL) {
1097                 /*
1098                  *      There may be a proxy reply, but it may be too late.
1099                  */
1100                 if (!request->proxy_listener) return 0;
1101
1102                 rcode = request->proxy_listener->decode(request->proxy_listener, request);
1103                 DEBUG_PACKET(request, request->proxy_reply, 0);
1104
1105                 /*
1106                  *      Pro-actively remove it from the proxy hash.
1107                  *      This is later than in 2.1.x, but it means that
1108                  *      the replies are authenticated before being
1109                  *      removed from the hash.
1110                  */
1111                 if ((rcode == 0) &&
1112                     (request->num_proxied_requests <= request->num_proxied_responses)) {
1113                         remove_from_proxy_hash(request);
1114                 }
1115
1116         } else
1117 #endif
1118         if (request->packet->vps == NULL) {
1119                 rcode = request->listener->decode(request->listener, request);
1120
1121 #ifdef WITH_UNLANG
1122                 if (debug_condition) {
1123                         /*
1124                          *      Ignore parse errors.
1125                          */
1126                         if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1127                                 request->options = 2;
1128                                 request->radlog = vradlog_request;
1129                         }
1130                 }
1131 #endif
1132
1133                 DEBUG_PACKET(request, request->packet, 0);
1134         } else {
1135                 rcode = 0;
1136         }
1137
1138         if (rcode < 0) {
1139                 RDEBUG("Dropping packet without response because of error: %s", fr_strerror());
1140                 request->reply->offset = -2; /* bad authenticator */
1141                 return 0;
1142         }
1143
1144         if (!request->username) {
1145                 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1146         }
1147
1148 #ifdef WITH_PROXY
1149         if (action == FR_ACTION_PROXY_REPLY) {
1150                 return process_proxy_reply(request);
1151         }
1152 #endif
1153
1154         return 1;
1155 }
1156
1157 STATE_MACHINE_DECL(request_finish)
1158 {
1159         VALUE_PAIR *vp;
1160
1161         TRACE_STATE_MACHINE;
1162
1163         (void) action;  /* -Wunused */
1164
1165         if (request->master_state == REQUEST_STOP_PROCESSING) return;
1166
1167         /*
1168          *      Don't send replies if there are none to send.
1169          */
1170         if (!request->in_request_hash) {
1171 #ifdef WITH_TCP
1172                 if ((request->listener->type == RAD_LISTEN_AUTH)
1173 #ifdef WITH_ACCOUNTING
1174                     || (request->listener->type == RAD_LISTEN_ACCT)
1175 #endif
1176                         ) {
1177                         listen_socket_t *sock = request->listener->data;
1178
1179                         if (sock->proto == IPPROTO_UDP) return;
1180
1181                         /*
1182                          *      TCP packets aren't in the request
1183                          *      hash.
1184                          */
1185                 }
1186 #else
1187                 return;
1188 #endif
1189         }
1190
1191         /*
1192          *      Override the response code if a control:Response-Packet-Type attribute is present.
1193          */
1194         vp = pairfind(request->config_items, PW_RESPONSE_PACKET_TYPE, 0, TAG_ANY);
1195         if (vp) {
1196                 if (vp->vp_integer == 256) {
1197                         RDEBUG2("Not responding to request");
1198                         request->reply->code = 0;
1199                 } else {
1200                         request->reply->code = vp->vp_integer;
1201                 }
1202         }
1203         /*
1204          *      Catch Auth-Type := Reject BEFORE proxying the packet.
1205          */
1206         else if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1207                 if (request->reply->code == 0) {
1208                         vp = pairfind(request->config_items, PW_AUTH_TYPE, 0, TAG_ANY);
1209
1210                         if (!vp || (vp->vp_integer != PW_CODE_AUTHENTICATION_REJECT)) {
1211                                 RDEBUG2("There was no response configured: "
1212                                         "rejecting request");
1213                         }
1214
1215                         request->reply->code = PW_CODE_AUTHENTICATION_REJECT;
1216                 }
1217         }
1218
1219         /*
1220          *      Copy Proxy-State from the request to the reply.
1221          */
1222         vp = paircopy2(request->reply, request->packet->vps,
1223                        PW_PROXY_STATE, 0, TAG_ANY);
1224         if (vp) pairadd(&request->reply->vps, vp);
1225
1226         switch (request->reply->code) {
1227         case PW_CODE_AUTHENTICATION_ACK:
1228                 rad_postauth(request);
1229                 break;
1230         case PW_CODE_ACCESS_CHALLENGE:
1231                 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0,
1232                            TAG_ANY);
1233                 vp = pairmake_config("Post-Auth-Type", "Challenge", T_OP_SET);
1234                 if (vp) rad_postauth(request);
1235                 break;
1236         default:
1237                 break;
1238         }
1239
1240         /*
1241          *      Run rejected packets through
1242          *
1243          *      Post-Auth-Type = Reject
1244          *
1245          *      We do this separately so ACK and challenge can change the code
1246          *      to reject if a module returns reject.
1247          */
1248         if (request->reply->code == PW_CODE_AUTHENTICATION_REJECT) {
1249                 pairdelete(&request->config_items, PW_POST_AUTH_TYPE, 0, TAG_ANY);
1250                 vp = pairmake_config("Post-Auth-Type", "Reject", T_OP_SET);
1251                 if (vp) rad_postauth(request);
1252         }
1253
1254         /*
1255          *      Clean up.  These are no longer needed.
1256          */
1257         pairfree(&request->config_items);
1258
1259         pairfree(&request->packet->vps);
1260         request->username = NULL;
1261         request->password = NULL;
1262
1263 #ifdef WITH_PROXY
1264         if (request->proxy) {
1265                 pairfree(&request->proxy->vps);
1266         }
1267         if (request->proxy_reply) {
1268                 pairfree(&request->proxy_reply->vps);
1269         }
1270 #endif
1271
1272         gettimeofday(&request->reply->timestamp, NULL);
1273
1274         /*
1275          *      Send the reply.
1276          */
1277         if ((request->reply->code != PW_CODE_AUTHENTICATION_REJECT) ||
1278             (request->root->reject_delay == 0)) {
1279                 DEBUG_PACKET(request, request->reply, 1);
1280                 request->listener->send(request->listener,
1281                                         request);
1282                 pairfree(&request->reply->vps);
1283
1284                 RDEBUG2("Finished request %u.", request->number);
1285 #ifdef WITH_ACCOUNTING
1286                 if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1287                         NO_CHILD_THREAD;
1288                         request->child_state = REQUEST_DONE;
1289                 } else
1290 #endif
1291
1292                 if (request->root->cleanup_delay == 0) {
1293                         NO_CHILD_THREAD;
1294                         request->child_state = REQUEST_DONE;
1295                 } else {
1296                         NO_CHILD_THREAD;
1297                         request->child_state = REQUEST_CLEANUP_DELAY;
1298                 }
1299         } else {
1300                 RDEBUG2("Delaying reject of request %u for %d seconds",
1301                         request->number,
1302                         request->root->reject_delay);
1303                 NO_CHILD_THREAD;
1304                 request->child_state = REQUEST_REJECT_DELAY;
1305         }
1306 }
1307
1308 STATE_MACHINE_DECL(request_running)
1309 {
1310         TRACE_STATE_MACHINE;
1311
1312         switch (action) {
1313         case FR_ACTION_TIMER:
1314                 request_process_timer(request);
1315                 break;
1316
1317         case FR_ACTION_CONFLICTING:
1318         case FR_ACTION_DUP:
1319                 request_common(request, action);
1320                 return;
1321
1322 #ifdef WITH_PROXY
1323                 /*
1324                  *      This can happen due to a race condition where
1325                  *      we send a proxied request, and immediately get
1326                  *      another reply, before the timer has a chance
1327                  *      to update the various states.
1328                  */
1329         case FR_ACTION_PROXY_REPLY:
1330                 request->child_state = REQUEST_RUNNING;
1331                 request->process = proxy_running;
1332                 /* FALL-THROUGH */
1333 #endif
1334
1335         case FR_ACTION_RUN:
1336                 if (!request_pre_handler(request, action)) {
1337 #ifdef DEBUG_STATE_MACHINE
1338                         if (debug_flag) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1339                                                request->number, __FUNCTION__,
1340                                                child_state_names[request->child_state],
1341                                                child_state_names[REQUEST_DONE]);
1342 #endif
1343
1344                         NO_CHILD_THREAD;
1345                         request->child_state = REQUEST_DONE;
1346                         break;
1347                 }
1348
1349                 rad_assert(request->handle != NULL);
1350                 request->handle(request);
1351
1352 #ifdef WITH_PROXY
1353                 /*
1354                  *      We may need to send a proxied request.
1355                  */
1356                 if ((action == FR_ACTION_RUN) &&
1357                     request_will_proxy(request)) {
1358 #ifdef DEBUG_STATE_MACHINE
1359                         if (debug_flag) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1360 #endif
1361                         /*
1362                          *      If this fails, it
1363                          *      takes care of setting
1364                          *      up the post proxy fail
1365                          *      handler.
1366                          */
1367                         if (request_proxy(request, 0) < 0) goto finished;
1368                 } else
1369 #endif
1370                 {
1371 #ifdef DEBUG_STATE_MACHINE
1372                         if (debug_flag) printf("(%u) ********\tFinished\t********\n", request->number);
1373 #endif
1374
1375 #ifdef WITH_COA
1376                         /*
1377                          *      Maybe originate a CoA request.
1378                          */
1379                         if ((action == FR_ACTION_RUN) && request->coa) {
1380                                 request_coa_originate(request);
1381                         }
1382 #endif
1383
1384 #ifdef WITH_PROXY
1385                 finished:
1386 #endif
1387                         request_finish(request, action);
1388                 }
1389                 break;
1390
1391         default:
1392                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1393                 break;
1394         }
1395 }
1396
1397 int request_receive(rad_listen_t *listener, RADIUS_PACKET *packet,
1398                     RADCLIENT *client, RAD_REQUEST_FUNP fun)
1399 {
1400         int count;
1401         RADIUS_PACKET **packet_p;
1402         REQUEST *request = NULL;
1403         struct timeval now;
1404         listen_socket_t *sock = NULL;
1405
1406         /*
1407          *      Set the last packet received.
1408          */
1409         gettimeofday(&now, NULL);
1410
1411 #ifdef WITH_ACCOUNTING
1412         if (listener->type != RAD_LISTEN_DETAIL)
1413 #endif
1414         {
1415                 sock = listener->data;
1416                 sock->last_packet = now.tv_sec;
1417         }
1418         packet->timestamp = now;
1419
1420         /*
1421          *      Skip everything if required.
1422          */
1423         if (listener->nodup) goto skip_dup;
1424
1425         packet_p = fr_packet_list_find(pl, packet);
1426         if (packet_p) {
1427                 request = fr_packet2myptr(REQUEST, packet, packet_p);
1428                 rad_assert(request->in_request_hash);
1429
1430                 /*
1431                  *      Same src/dst ip/port, length, and
1432                  *      authentication vector: must be a duplicate.
1433                  */
1434                 if ((request->packet->data_len == packet->data_len) &&
1435                     (memcmp(request->packet->vector, packet->vector,
1436                             sizeof(packet->vector)) == 0)) {
1437
1438 #ifdef WITH_STATS
1439                         switch (packet->code) {
1440                         case PW_CODE_AUTHENTICATION_REQUEST:
1441                                 FR_STATS_INC(auth, total_dup_requests);
1442                                 break;
1443
1444 #ifdef WITH_ACCOUNTING
1445                         case PW_CODE_ACCOUNTING_REQUEST:
1446                                 FR_STATS_INC(acct, total_dup_requests);
1447                                 break;
1448 #endif
1449 #ifdef WITH_COA
1450                         case PW_CODE_COA_REQUEST:
1451                                 FR_STATS_INC(coa, total_dup_requests);
1452                                 break;
1453
1454                         case PW_CODE_DISCONNECT_REQUEST:
1455                                 FR_STATS_INC(dsc, total_dup_requests);
1456                                 break;
1457 #endif
1458
1459                         default:
1460                           break;
1461                         }
1462 #endif  /* WITH_STATS */
1463
1464                         request->process(request, FR_ACTION_DUP);
1465                         return 0;
1466                 }
1467
1468                 /*
1469                  *      Say we're ignoring the old one, and continue
1470                  *      to process the new one.
1471                  */
1472                 request->process(request, FR_ACTION_CONFLICTING);
1473                 request = NULL;
1474         }
1475
1476         /*
1477          *      Quench maximum number of outstanding requests.
1478          */
1479         if (mainconfig.max_requests &&
1480             ((count = fr_packet_list_num_elements(pl)) > mainconfig.max_requests)) {
1481                 static time_t last_complained = 0;
1482
1483                 if (last_complained == now.tv_sec) return 0;
1484
1485                 last_complained = now.tv_sec;
1486
1487                 ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1488                        client->shortname,
1489                        packet->src_port, packet->id);
1490                 WARN("Please check the configuration file.\n"
1491                      "\tThe value for 'max_requests' is probably set too low.\n");
1492
1493                 exec_trigger(NULL, NULL, "server.max_requests", true);
1494                 return 0;
1495         }
1496
1497 skip_dup:
1498         /*
1499          *      Rate-limit the incoming packets
1500          */
1501         if (sock && sock->max_rate) {
1502                 int pps;
1503
1504                 pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now,
1505                               &sock->rate_time, &now);
1506
1507                 if (pps > sock->max_rate) {
1508                         DEBUG("Dropping request due to rate limiting");
1509                         return 0;
1510                 }
1511                 sock->rate_pps_now++;
1512         }
1513
1514         request = request_setup(listener, packet, client, fun);
1515         if (!request) return 1;
1516
1517         /*
1518          *      Remember the request in the list.
1519          */
1520         if (!listener->nodup) {
1521                 if (!fr_packet_list_insert(pl, &request->packet)) {
1522                         RERROR("Failed to insert request in the list of live requests: discarding it");
1523                         request_done(request, FR_ACTION_DONE);
1524                         return 1;
1525                 }
1526
1527                 request->in_request_hash = true;
1528         }
1529
1530         /*
1531          *      Process it.  Send a response, and free it.
1532          */
1533         if (listener->synchronous) {
1534                 request->listener->decode(request->listener, request);
1535                 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1536                 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1537
1538                 fun(request);
1539                 request->listener->send(request->listener, request);
1540                 request_free(&request);
1541                 return 1;
1542         }
1543
1544         /*
1545          *      Otherwise, insert it into the state machine.
1546          *      The child threads will take care of processing it.
1547          */
1548         request_queue_or_run(request, request_running);
1549
1550         return 1;
1551 }
1552
1553
1554 static REQUEST *request_setup(rad_listen_t *listener, RADIUS_PACKET *packet,
1555                               RADCLIENT *client, RAD_REQUEST_FUNP fun)
1556 {
1557         REQUEST *request;
1558
1559         /*
1560          *      Create and initialize the new request.
1561          */
1562         request = request_alloc(NULL);
1563         request->reply = rad_alloc(request, 0);
1564         if (!request->reply) {
1565                 ERROR("No memory");
1566                 request_free(&request);
1567                 return NULL;
1568         }
1569
1570         request->listener = listener;
1571         request->client = client;
1572         request->packet = talloc_steal(request, packet);
1573         request->number = request_num_counter++;
1574         request->priority = listener->type;
1575         request->master_state = REQUEST_ACTIVE;
1576 #ifdef DEBUG_STATE_MACHINE
1577         if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1578                                request->number, __FUNCTION__,
1579                                child_state_names[request->child_state],
1580                                child_state_names[REQUEST_RUNNING]);
1581 #endif
1582         request->child_state = REQUEST_RUNNING;
1583         request->handle = fun;
1584         NO_CHILD_THREAD;
1585
1586 #ifdef WITH_STATS
1587         request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1588         if (packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
1589                 request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1590                 radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1591 #ifdef WITH_ACCOUNTING
1592         } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1593                 request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1594                 radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1595 #endif
1596         }
1597 #endif  /* WITH_STATS */
1598
1599         /*
1600          *      Status-Server packets go to the head of the queue.
1601          */
1602         if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1603
1604         /*
1605          *      Set virtual server identity
1606          */
1607         if (client->server) {
1608                 request->server = client->server;
1609         } else if (listener->server) {
1610                 request->server = listener->server;
1611         } else {
1612                 request->server = NULL;
1613         }
1614
1615         request->root = &mainconfig;
1616 #ifdef WITH_TCP
1617         request->listener->count++;
1618 #endif
1619
1620         /*
1621          *      The request passes many of our sanity checks.
1622          *      From here on in, if anything goes wrong, we
1623          *      send a reject message, instead of dropping the
1624          *      packet.
1625          */
1626
1627         /*
1628          *      Build the reply template from the request.
1629          */
1630
1631         request->reply->sockfd = request->packet->sockfd;
1632         request->reply->dst_ipaddr = request->packet->src_ipaddr;
1633         request->reply->src_ipaddr = request->packet->dst_ipaddr;
1634         request->reply->dst_port = request->packet->src_port;
1635         request->reply->src_port = request->packet->dst_port;
1636         request->reply->id = request->packet->id;
1637         request->reply->code = 0; /* UNKNOWN code */
1638         memcpy(request->reply->vector, request->packet->vector,
1639                sizeof(request->reply->vector));
1640         request->reply->vps = NULL;
1641         request->reply->data = NULL;
1642         request->reply->data_len = 0;
1643
1644         return request;
1645 }
1646
1647 #ifdef WITH_TCP
1648 /***********************************************************************
1649  *
1650  *      TCP Handlers.
1651  *
1652  ***********************************************************************/
1653
1654 /*
1655  *      Timer function for all TCP sockets.
1656  */
1657 static void tcp_socket_timer(void *ctx)
1658 {
1659         rad_listen_t *listener = ctx;
1660         listen_socket_t *sock = listener->data;
1661         struct timeval end, now;
1662         char buffer[256];
1663         fr_socket_limit_t *limit;
1664
1665         fr_event_now(el, &now);
1666
1667         if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1668
1669         switch (listener->type) {
1670 #ifdef WITH_PROXY
1671         case RAD_LISTEN_PROXY:
1672                 limit = &sock->home->limit;
1673                 break;
1674 #endif
1675
1676         case RAD_LISTEN_AUTH:
1677 #ifdef WITH_ACCOUNTING
1678         case RAD_LISTEN_ACCT:
1679 #endif
1680                 limit = &sock->limit;
1681                 break;
1682
1683         default:
1684                 return;
1685         }
1686
1687         /*
1688          *      If we enforce a lifetime, do it now.
1689          */
1690         if (limit->lifetime > 0) {
1691                 end.tv_sec = sock->opened + limit->lifetime;
1692                 end.tv_usec = 0;
1693
1694                 if (timercmp(&end, &now, <=)) {
1695                         listener->print(listener, buffer, sizeof(buffer));
1696                         DEBUG("Reached maximum lifetime on socket %s", buffer);
1697
1698                 do_close:
1699
1700                         listener->status = RAD_LISTEN_STATUS_EOL;
1701                         event_new_fd(listener);
1702                         return;
1703                 }
1704         } else {
1705                 end = now;
1706                 end.tv_sec += 3600;
1707         }
1708
1709         /*
1710          *      Enforce an idle timeout.
1711          */
1712         if (limit->idle_timeout > 0) {
1713                 struct timeval idle;
1714
1715                 rad_assert(sock->last_packet != 0);
1716                 idle.tv_sec = sock->last_packet + limit->idle_timeout;
1717                 idle.tv_usec = 0;
1718
1719                 if (timercmp(&idle, &now, <=)) {
1720                         listener->print(listener, buffer, sizeof(buffer));
1721                         DEBUG("Reached idle timeout on socket %s", buffer);
1722                         goto do_close;
1723                 }
1724
1725                 /*
1726                  *      Enforce the minimum of idle timeout or lifetime.
1727                  */
1728                 if (timercmp(&idle, &end, <)) {
1729                         end = idle;
1730                 }
1731         }
1732
1733         /*
1734          *      Wake up at t + 0.5s.  The code above checks if the timers
1735          *      are <= t.  This addition gives us a bit of leeway.
1736          */
1737         end.tv_usec = USEC / 2;
1738
1739         if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1740                 rad_panic("Failed to insert event");
1741         }
1742 }
1743
1744
1745 #ifdef WITH_PROXY
1746 /*
1747  *      Add +/- 2s of jitter, as suggested in RFC 3539
1748  *      and in RFC 5080.
1749  */
1750 static void add_jitter(struct timeval *when)
1751 {
1752         uint32_t jitter;
1753
1754         when->tv_sec -= 2;
1755
1756         jitter = fr_rand();
1757         jitter ^= (jitter >> 10);
1758         jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1759
1760         /*
1761          *      Add in ~ (4 * USEC) of jitter.
1762          */
1763         tv_add(when, jitter);
1764 }
1765
1766 /*
1767  *      Called by socket_del to remove requests with this socket
1768  */
1769 static int eol_proxy_listener(void *ctx, void *data)
1770 {
1771         rad_listen_t *this = ctx;
1772         RADIUS_PACKET **proxy_p = data;
1773         REQUEST *request;
1774
1775         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
1776         if (request->proxy_listener != this) return 0;
1777
1778         /*
1779          *      The normal "remove_from_proxy_hash" tries to grab the
1780          *      proxy mutex.  We already have it held, so grabbing it
1781          *      again will cause a deadlock.  Instead, call the "no
1782          *      lock" version of the function.
1783          */
1784         rad_assert(request->in_proxy_hash == true);
1785         remove_from_proxy_hash_nl(request, false);
1786
1787         /*
1788          *      Don't mark it as DONE.  The client can retransmit, and
1789          *      the packet SHOULD be re-proxied somewhere else.
1790          *
1791          *      Return "2" means that the rbtree code will remove it
1792          *      from the tree, and we don't need to do it ourselves.
1793          */
1794         return 2;
1795 }
1796 #endif  /* WITH_PROXY */
1797
1798 static int eol_listener(void *ctx, void *data)
1799 {
1800         rad_listen_t *this = ctx;
1801         RADIUS_PACKET **packet_p = data;
1802         REQUEST *request;
1803
1804         request = fr_packet2myptr(REQUEST, packet, packet_p);
1805         if (request->listener != this) return 0;
1806
1807         request->master_state = REQUEST_STOP_PROCESSING;
1808
1809         return 0;
1810 }
1811 #endif  /* WITH_TCP */
1812
1813 #ifdef WITH_PROXY
1814 /***********************************************************************
1815  *
1816  *      Proxy handlers for the state machine.
1817  *
1818  ***********************************************************************/
1819
1820 /*
1821  *      Called with the proxy mutex held
1822  */
1823 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
1824 {
1825         if (!request->in_proxy_hash) return;
1826
1827         fr_packet_list_id_free(proxy_list, request->proxy, yank);
1828         request->in_proxy_hash = false;
1829
1830         /*
1831          *      On the FIRST reply, decrement the count of outstanding
1832          *      requests.  Note that this is NOT the count of sent
1833          *      packets, but whether or not the home server has
1834          *      responded at all.
1835          */
1836         if (request->home_server &&
1837             request->home_server->currently_outstanding) {
1838                 request->home_server->currently_outstanding--;
1839
1840                 /*
1841                  *      If we're NOT sending it packets, then we don't know
1842                  *      if it's alive or dead.
1843                  */
1844                 if ((request->home_server->currently_outstanding == 0) &&
1845                     (request->home_server->state == HOME_STATE_ALIVE)) {
1846                         request->home_server->state = HOME_STATE_UNKNOWN;
1847                         request->home_server->last_packet_sent = 0;
1848                         request->home_server->last_packet_recv = 0;
1849                 }
1850         }
1851
1852 #ifdef WITH_TCP
1853         rad_assert(request->proxy_listener != NULL);
1854         request->proxy_listener->count--;
1855 #endif
1856         request->proxy_listener = NULL;
1857
1858         /*
1859          *      Got from YES in hash, to NO, not in hash while we hold
1860          *      the mutex.  This guarantees that when another thread
1861          *      grabs the mutex, the "not in hash" flag is correct.
1862          */
1863         RDEBUG3("proxy: request is no longer in proxy hash");
1864 }
1865
1866 static void remove_from_proxy_hash(REQUEST *request)
1867 {
1868         /*
1869          *      Check this without grabbing the mutex because it's a
1870          *      lot faster that way.
1871          */
1872         if (!request->in_proxy_hash) return;
1873
1874         /*
1875          *      The "not in hash" flag is definitive.  However, if the
1876          *      flag says that it IS in the hash, there might still be
1877          *      a race condition where it isn't.
1878          */
1879         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1880
1881         if (!request->in_proxy_hash) {
1882                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1883                 return;
1884         }
1885
1886         remove_from_proxy_hash_nl(request, true);
1887
1888         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1889 }
1890
1891 static int insert_into_proxy_hash(REQUEST *request)
1892 {
1893         char buf[128];
1894         int rcode, tries;
1895         void *proxy_listener;
1896
1897         rad_assert(request->proxy != NULL);
1898         rad_assert(request->home_server != NULL);
1899         rad_assert(proxy_list != NULL);
1900
1901
1902         PTHREAD_MUTEX_LOCK(&proxy_mutex);
1903         proxy_listener = NULL;
1904         request->num_proxied_requests = 1;
1905         request->num_proxied_responses = 0;
1906
1907         for (tries = 0; tries < 2; tries++) {
1908                 rad_listen_t *this;
1909
1910                 RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
1911                 rcode = fr_packet_list_id_alloc(proxy_list,
1912                                                 request->home_server->proto,
1913                                                 &request->proxy, &proxy_listener);
1914                 if ((debug_flag > 2) && (rcode == 0)) {
1915                         RDEBUG("proxy: Failed allocating ID: %s", fr_strerror());
1916                 }
1917                 if (rcode > 0) break;
1918                 if (tries > 0) continue; /* try opening new socket only once */
1919
1920 #ifdef HAVE_PTHREAD_H
1921                 if (proxy_no_new_sockets) break;
1922 #endif
1923
1924                 RDEBUG3("proxy: Trying to open a new listener to the home server");
1925                 this = proxy_new_listener(request->home_server, 0);
1926                 if (!this) {
1927                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1928                         goto fail;
1929                 }
1930
1931                 request->proxy->src_port = 0; /* Use any new socket */
1932                 proxy_listener = this;
1933
1934                 /*
1935                  *      Add it to the event loop (and to the packet list)
1936                  *      before we try to grab another Id.
1937                  */
1938                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1939                 if (!event_new_fd(this)) {
1940                         RDEBUG3("proxy: Failed inserting new socket into event loop");
1941                         listen_free(&this);
1942                         goto fail;
1943                 }
1944                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
1945         }
1946
1947         if (!proxy_listener || (rcode == 0)) {
1948                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1949                 REDEBUG2("proxy: Failed allocating Id for proxied request");
1950         fail:
1951                 request->proxy_listener = NULL;
1952                 request->in_proxy_hash = false;
1953                 return 0;
1954         }
1955
1956         rad_assert(request->proxy->id >= 0);
1957
1958         request->proxy_listener = proxy_listener;
1959         request->in_proxy_hash = true;
1960         RDEBUG3("proxy: request is now in proxy hash");
1961
1962         /*
1963          *      Keep track of maximum outstanding requests to a
1964          *      particular home server.  'max_outstanding' is
1965          *      enforced in home_server_ldb(), in realms.c.
1966          */
1967         request->home_server->currently_outstanding++;
1968
1969 #ifdef WITH_TCP
1970         request->proxy_listener->count++;
1971 #endif
1972
1973         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1974
1975         RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
1976                inet_ntop(request->proxy->dst_ipaddr.af,
1977                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
1978                request->proxy->dst_port,
1979                request->proxy->id);
1980
1981         return 1;
1982 }
1983
1984 static int process_proxy_reply(REQUEST *request)
1985 {
1986         int rcode;
1987         int post_proxy_type = 0;
1988         VALUE_PAIR *vp;
1989
1990         /*
1991          *      Delete any reply we had accumulated until now.
1992          */
1993         pairfree(&request->reply->vps);
1994
1995         /*
1996          *      Run the packet through the post-proxy stage,
1997          *      BEFORE playing games with the attributes.
1998          */
1999         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2000
2001         /*
2002          *      If we have a proxy_reply, and it was a reject, setup
2003          *      post-proxy-type Reject
2004          */
2005         if (!vp && request->proxy_reply &&
2006             request->proxy_reply->code == PW_CODE_AUTHENTICATION_REJECT) {
2007                 DICT_VALUE      *dval;
2008
2009                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Reject");
2010                 if (dval) {
2011                         vp = radius_paircreate(request, &request->config_items,
2012                                                PW_POST_PROXY_TYPE, 0);
2013
2014                         vp->vp_integer = dval->value;
2015                 }
2016         }
2017
2018         if (vp) {
2019                 post_proxy_type = vp->vp_integer;
2020
2021                 RDEBUG2("  Found Post-Proxy-Type %s",
2022                         dict_valnamebyattr(PW_POST_PROXY_TYPE, 0,
2023                                            post_proxy_type));
2024         }
2025
2026         if (request->home_pool && request->home_pool->virtual_server) {
2027                 char const *old_server = request->server;
2028
2029                 request->server = request->home_pool->virtual_server;
2030                 RDEBUG2(" server %s {", request->server);
2031                 rcode = process_post_proxy(post_proxy_type, request);
2032                 RDEBUG2(" }");
2033                 request->server = old_server;
2034         } else {
2035                 rcode = process_post_proxy(post_proxy_type, request);
2036         }
2037
2038 #ifdef WITH_COA
2039         if (request->packet->code == request->proxy->code)
2040           /*
2041            *    Don't run the next bit if we originated a CoA
2042            *    packet, after receiving an Access-Request or
2043            *    Accounting-Request.
2044            */
2045 #endif
2046
2047         /*
2048          *      There may NOT be a proxy reply, as we may be
2049          *      running Post-Proxy-Type = Fail.
2050          */
2051         if (request->proxy_reply) {
2052                 /*
2053                  *      Delete the Proxy-State Attributes from
2054                  *      the reply.  These include Proxy-State
2055                  *      attributes from us and remote server.
2056                  */
2057                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
2058
2059                 /*
2060                  *      Add the attributes left in the proxy
2061                  *      reply to the reply list.
2062                  */
2063                 pairfilter(request->reply, &request->reply->vps,
2064                           &request->proxy_reply->vps, 0, 0, TAG_ANY);
2065
2066                 /*
2067                  *      Free proxy request pairs.
2068                  */
2069                 pairfree(&request->proxy->vps);
2070         }
2071
2072         switch (rcode) {
2073         default:  /* Don't do anything */
2074                 break;
2075         case RLM_MODULE_FAIL:
2076                 return 0;
2077
2078         case RLM_MODULE_HANDLED:
2079                 return 0;
2080         }
2081
2082         return 1;
2083 }
2084
2085 int request_proxy_reply(RADIUS_PACKET *packet)
2086 {
2087         RADIUS_PACKET **proxy_p;
2088         REQUEST *request;
2089         struct timeval now;
2090         char buffer[128];
2091
2092         PTHREAD_MUTEX_LOCK(&proxy_mutex);
2093         proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2094
2095         if (!proxy_p) {
2096                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2097                 PROXY( "No outstanding request was found for reply from host %s port %d - ID %u",
2098                        inet_ntop(packet->src_ipaddr.af,
2099                                  &packet->src_ipaddr.ipaddr,
2100                                  buffer, sizeof(buffer)),
2101                        packet->src_port, packet->id);
2102                 return 0;
2103         }
2104
2105         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2106         request->num_proxied_responses++; /* needs to be protected by lock */
2107
2108         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2109
2110         /*
2111          *      No reply, BUT the current packet fails verification:
2112          *      ignore it.  This does the MD5 calculations in the
2113          *      server core, but I guess we can fix that later.
2114          */
2115         if (!request->proxy_reply &&
2116             (rad_verify(packet, request->proxy,
2117                         request->home_server->secret) != 0)) {
2118                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
2119                 return 0;
2120         }
2121
2122         /*
2123          *      The home server sent us a packet which doesn't match
2124          *      something we have: ignore it.  This is done only to
2125          *      catch the case of broken systems.
2126          */
2127         if (request->proxy_reply &&
2128             (memcmp(request->proxy_reply->vector,
2129                     packet->vector,
2130                     sizeof(request->proxy_reply->vector)) != 0)) {
2131                 RDEBUG2("Ignoring conflicting proxy reply");
2132                 return 0;
2133         }
2134
2135         gettimeofday(&now, NULL);
2136
2137         /*
2138          *      Status-Server packets don't count as real packets.
2139          */
2140         if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2141                 listen_socket_t *sock = request->proxy_listener->data;
2142
2143                 request->home_server->last_packet_recv = now.tv_sec;
2144                 sock->last_packet = now.tv_sec;
2145         }
2146
2147         /*
2148          *      If we have previously seen a reply, ignore the
2149          *      duplicate.
2150          */
2151         if (request->proxy_reply) {
2152                 RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d",
2153                         inet_ntop(packet->src_ipaddr.af,
2154                                   &packet->src_ipaddr.ipaddr,
2155                                   buffer, sizeof(buffer)),
2156                         packet->src_port, packet->id);
2157                 return 0;
2158         }
2159
2160         /*
2161          *      Call the state machine to do something useful with the
2162          *      request.
2163          */
2164         request->proxy_reply = packet;
2165         packet->timestamp = now;
2166         request->priority = RAD_LISTEN_PROXY;
2167
2168         /*
2169          *      We've received a reply.  If we hadn't been sending it
2170          *      packets for a while, just mark it alive.
2171          */
2172         if (request->home_server->state == HOME_STATE_UNKNOWN) {
2173                 request->home_server->state = HOME_STATE_ALIVE;
2174         }
2175
2176 #ifdef WITH_STATS
2177         request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2178         request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2179
2180         if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2181                 proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2182 #ifdef WITH_ACCOUNTING
2183         } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2184                 proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2185 #endif
2186         }
2187 #endif  /* WITH_STATS */
2188
2189 #ifdef WITH_COA
2190         /*
2191          *      When we originate CoA requests, we patch them in here
2192          *      so that they don't affect the rest of the state
2193          *      machine.
2194          */
2195         if (request->parent) {
2196                 rad_assert(request->parent->coa == request);
2197                 rad_assert((request->proxy->code == PW_CODE_COA_REQUEST) ||
2198                            (request->proxy->code == PW_CODE_DISCONNECT_REQUEST));
2199                 rad_assert(request->process != NULL);
2200                 request_coa_separate(request);
2201         }
2202 #endif
2203
2204         request->process(request, FR_ACTION_PROXY_REPLY);
2205
2206         return 1;
2207 }
2208
2209
2210 static int setup_post_proxy_fail(REQUEST *request)
2211 {
2212         DICT_VALUE const *dval = NULL;
2213         VALUE_PAIR *vp;
2214
2215         if (request->proxy->code == PW_CODE_AUTHENTICATION_REQUEST) {
2216                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2217                                       "Fail-Authentication");
2218
2219         } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2220                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0,
2221                                       "Fail-Accounting");
2222 #ifdef WITH_COA
2223         } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2224                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-CoA");
2225
2226         } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2227                 dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail-Disconnect");
2228 #endif
2229         } else {
2230                 WDEBUG("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2231                 return 0;
2232         }
2233
2234         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, 0, "Fail");
2235
2236         if (!dval) {
2237                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2238                 return 0;
2239         }
2240
2241         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE, 0, TAG_ANY);
2242         if (!vp) vp = radius_paircreate(request, &request->config_items,
2243                                         PW_POST_PROXY_TYPE, 0);
2244         vp->vp_integer = dval->value;
2245
2246         return 1;
2247 }
2248
2249 STATE_MACHINE_DECL(proxy_running)
2250 {
2251         TRACE_STATE_MACHINE;
2252
2253         switch (action) {
2254         case FR_ACTION_CONFLICTING:
2255         case FR_ACTION_DUP:
2256         case FR_ACTION_TIMER:
2257         case FR_ACTION_PROXY_REPLY:
2258                 request_common(request, action);
2259                 break;
2260
2261         case FR_ACTION_RUN:
2262                 request_running(request, action);
2263                 break;
2264
2265         default:
2266                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2267                 break;
2268         }
2269 }
2270
2271 STATE_MACHINE_DECL(request_virtual_server)
2272 {
2273         char const *old;
2274
2275         TRACE_STATE_MACHINE;
2276
2277         switch (action) {
2278         case FR_ACTION_CONFLICTING:
2279         case FR_ACTION_DUP:
2280         case FR_ACTION_TIMER:
2281         case FR_ACTION_PROXY_REPLY:
2282                 request_common(request, action);
2283                 break;
2284
2285         case FR_ACTION_RUN:
2286                 old = request->server;
2287                 request->server = request->home_server->server;
2288                 request_running(request, action);
2289                 request->server = old;
2290                 break;
2291
2292         default:
2293                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2294                 break;
2295         }
2296 }
2297
2298
2299 static int request_will_proxy(REQUEST *request)
2300 {
2301         int rcode, pre_proxy_type = 0;
2302         char const *realmname = NULL;
2303         VALUE_PAIR *vp, *strippedname;
2304         home_server_t *home;
2305         REALM *realm = NULL;
2306         home_pool_t *pool = NULL;
2307
2308         if (!request->root->proxy_requests) return 0;
2309         if (request->packet->dst_port == 0) return 0;
2310         if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2311         if (request->in_proxy_hash) return 0;
2312
2313         /*
2314          *      FIXME: for 3.0, allow this only for rejects?
2315          */
2316         if (request->reply->code != 0) return 0;
2317
2318         vp = pairfind(request->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
2319         if (vp) {
2320                 realm = realm_find2(vp->vp_strvalue);
2321                 if (!realm) {
2322                         REDEBUG2("Cannot proxy to unknown realm %s",
2323                                 vp->vp_strvalue);
2324                         return 0;
2325                 }
2326
2327                 realmname = vp->vp_strvalue;
2328
2329                 /*
2330                  *      Figure out which pool to use.
2331                  */
2332                 if (request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) {
2333                         pool = realm->auth_pool;
2334
2335 #ifdef WITH_ACCOUNTING
2336                 } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2337                         pool = realm->acct_pool;
2338 #endif
2339
2340 #ifdef WITH_COA
2341                 } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2342                            (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2343                         pool = realm->coa_pool;
2344 #endif
2345
2346                 } else {
2347                         return 0;
2348                 }
2349
2350         } else {
2351                 int pool_type;
2352
2353                 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL, 0, TAG_ANY);
2354                 if (!vp) return 0;
2355
2356                 switch (request->packet->code) {
2357                 case PW_CODE_AUTHENTICATION_REQUEST:
2358                         pool_type = HOME_TYPE_AUTH;
2359                         break;
2360
2361 #ifdef WITH_ACCOUNTING
2362                 case PW_CODE_ACCOUNTING_REQUEST:
2363                         pool_type = HOME_TYPE_ACCT;
2364                         break;
2365 #endif
2366
2367 #ifdef WITH_COA
2368                 case PW_CODE_COA_REQUEST:
2369                 case PW_CODE_DISCONNECT_REQUEST:
2370                         pool_type = HOME_TYPE_COA;
2371                         break;
2372 #endif
2373
2374                 default:
2375                         return 0;
2376                 }
2377
2378                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2379         }
2380
2381         if (!pool) {
2382                 RWDEBUG2("Cancelling proxy as no home pool exists");
2383                 return 0;
2384         }
2385
2386         if (request->listener->synchronous) {
2387                 WARN("Cannot proxy a request which is from a 'synchronous' socket");
2388                 return 0;
2389         }
2390
2391         request->home_pool = pool;
2392
2393         home = home_server_ldb(realmname, pool, request);
2394         if (!home) {
2395                 REDEBUG2("Failed to find live home server: Cancelling proxy");
2396                 return 0;
2397         }
2398         home_server_update_request(home, request);
2399
2400 #ifdef WITH_COA
2401         /*
2402          *      Once we've decided to proxy a request, we cannot send
2403          *      a CoA packet.  So we free up any CoA packet here.
2404          */
2405         if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2406 #endif
2407
2408         /*
2409          *      Remember that we sent the request to a Realm.
2410          */
2411         if (realmname) pairmake_packet("Realm", realmname, T_OP_EQ);
2412
2413         /*
2414          *      Strip the name, if told to.
2415          *
2416          *      Doing it here catches the case of proxied tunneled
2417          *      requests.
2418          */
2419         if (realm && (realm->striprealm == true) &&
2420            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY)) != NULL) {
2421                 /*
2422                  *      If there's a Stripped-User-Name attribute in
2423                  *      the request, then use THAT as the User-Name
2424                  *      for the proxied request, instead of the
2425                  *      original name.
2426                  *
2427                  *      This is done by making a copy of the
2428                  *      Stripped-User-Name attribute, turning it into
2429                  *      a User-Name attribute, deleting the
2430                  *      Stripped-User-Name and User-Name attributes
2431                  *      from the vps list, and making the new
2432                  *      User-Name the head of the vps list.
2433                  */
2434                 vp = pairfind(request->proxy->vps, PW_USER_NAME, 0, TAG_ANY);
2435                 if (!vp) {
2436                         vp_cursor_t cursor;
2437                         vp = radius_paircreate(request, NULL,
2438                                                PW_USER_NAME, 0);
2439                         rad_assert(vp != NULL); /* handled by above function */
2440                         /* Insert at the START of the list */
2441                         /* FIXME: Can't make assumptions about ordering */
2442                         fr_cursor_init(&cursor, &vp);
2443                         fr_cursor_insert(&cursor, request->proxy->vps);
2444                         request->proxy->vps = vp;
2445                 }
2446                 pairstrcpy(vp, strippedname->vp_strvalue);
2447
2448                 /*
2449                  *      Do NOT delete Stripped-User-Name.
2450                  */
2451         }
2452
2453         /*
2454          *      If there is no PW_CHAP_CHALLENGE attribute but
2455          *      there is a PW_CHAP_PASSWORD we need to add it
2456          *      since we can't use the request authenticator
2457          *      anymore - we changed it.
2458          */
2459         if ((request->packet->code == PW_CODE_AUTHENTICATION_REQUEST) &&
2460             pairfind(request->proxy->vps, PW_CHAP_PASSWORD, 0, TAG_ANY) &&
2461             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY) == NULL) {
2462                 vp = radius_paircreate(request, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2463                 pairmemcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2464         }
2465
2466         /*
2467          *      The RFC's say we have to do this, but FreeRADIUS
2468          *      doesn't need it.
2469          */
2470         vp = radius_paircreate(request, &request->proxy->vps, PW_PROXY_STATE, 0);
2471         pairsprintf(vp, "%u", request->packet->id);
2472
2473         /*
2474          *      Should be done BEFORE inserting into proxy hash, as
2475          *      pre-proxy may use this information, or change it.
2476          */
2477         request->proxy->code = request->packet->code;
2478
2479         /*
2480          *      Call the pre-proxy routines.
2481          */
2482         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
2483         if (vp) {
2484                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
2485                 /* Must be a validation issue */
2486                 rad_assert(dval);
2487                 RDEBUG2("  Found Pre-Proxy-Type %s", dval->name);
2488                 pre_proxy_type = vp->vp_integer;
2489         }
2490
2491         rad_assert(request->home_pool != NULL);
2492
2493         if (request->home_pool->virtual_server) {
2494                 char const *old_server = request->server;
2495
2496                 request->server = request->home_pool->virtual_server;
2497                 RDEBUG2(" server %s {", request->server);
2498                 rcode = process_pre_proxy(pre_proxy_type, request);
2499                 RDEBUG2(" }");
2500                         request->server = old_server;
2501         } else {
2502                 rcode = process_pre_proxy(pre_proxy_type, request);
2503         }
2504         switch (rcode) {
2505         case RLM_MODULE_FAIL:
2506         case RLM_MODULE_INVALID:
2507         case RLM_MODULE_NOTFOUND:
2508         case RLM_MODULE_USERLOCK:
2509         default:
2510                 /* FIXME: debug print failed stuff */
2511                 return -1;
2512
2513         case RLM_MODULE_REJECT:
2514         case RLM_MODULE_HANDLED:
2515                 return 0;
2516
2517         /*
2518          *      Only proxy the packet if the pre-proxy code succeeded.
2519          */
2520         case RLM_MODULE_NOOP:
2521         case RLM_MODULE_OK:
2522         case RLM_MODULE_UPDATED:
2523                 break;
2524         }
2525
2526         return 1;
2527 }
2528
2529 static int request_proxy(REQUEST *request, int retransmit)
2530 {
2531         char buffer[128];
2532
2533         rad_assert(request->parent == NULL);
2534         rad_assert(request->home_server != NULL);
2535
2536         if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
2537
2538 #ifdef WITH_COA
2539         if (request->coa) {
2540                 RWDEBUG("Cannot proxy and originate CoA packets at the same time.  Cancelling CoA request");
2541                 request_done(request->coa, FR_ACTION_DONE);
2542         }
2543 #endif
2544
2545         /*
2546          *      The request may be sent to a virtual server.  If we're
2547          *      in a child thread, just process it here. If we're the
2548          *      master, push it back onto the queue for later
2549          *      processing.
2550          */
2551         if (request->home_server->server) {
2552                 DEBUG("Proxying to virtual server %s",
2553                       request->home_server->server);
2554
2555                 if (!we_are_master()) {
2556                         request_virtual_server(request, FR_ACTION_RUN);
2557                         NO_CHILD_THREAD;
2558                         return 1;
2559                 }
2560
2561                 request_queue_or_run(request, request_virtual_server);
2562                 return 1;
2563         }
2564
2565         /*
2566          *      We're actually sending a proxied packet.  Do that now.
2567          */
2568         if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
2569                 EDEBUG("Failed to insert request into the proxy list.");
2570                 return -1;
2571         }
2572
2573         rad_assert(request->proxy->id >= 0);
2574
2575 #ifdef WITH_TLS
2576         if (request->home_server->tls) {
2577                 RDEBUG2("Proxying request to home server %s port %d (TLS)",
2578                         inet_ntop(request->proxy->dst_ipaddr.af,
2579                                   &request->proxy->dst_ipaddr.ipaddr,
2580                                   buffer, sizeof(buffer)),
2581                         request->proxy->dst_port);
2582         } else
2583 #endif
2584         RDEBUG2("Proxying request to home server %s port %d",
2585                inet_ntop(request->proxy->dst_ipaddr.af,
2586                          &request->proxy->dst_ipaddr.ipaddr,
2587                          buffer, sizeof(buffer)),
2588                 request->proxy->dst_port);
2589
2590         DEBUG_PACKET(request, request->proxy, 1);
2591
2592         gettimeofday(&request->proxy_retransmit, NULL);
2593         if (!retransmit) {
2594                 request->proxy->timestamp = request->proxy_retransmit;
2595                 request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
2596         }
2597
2598         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
2599         NO_CHILD_THREAD;
2600         request->child_state = REQUEST_PROXIED;
2601         request->proxy_listener->send(request->proxy_listener,
2602                                       request);
2603         return 1;
2604 }
2605
2606 /*
2607  *      Proxy the packet as if it was new.
2608  */
2609 static int request_proxy_anew(REQUEST *request)
2610 {
2611         home_server_t *home;
2612
2613         /*
2614          *      Delete the request from the proxy list.
2615          *
2616          *      The packet list code takes care of ensuring that IDs
2617          *      aren't reused until all 256 IDs have been used.  So
2618          *      there's a 1/256 chance of re-using the same ID when
2619          *      we're sending to the same home server.  Which is
2620          *      acceptable.
2621          */
2622         remove_from_proxy_hash(request);
2623
2624         /*
2625          *      Find a live home server for the request.
2626          */
2627         home = home_server_ldb(NULL, request->home_pool, request);
2628         if (!home) {
2629                 REDEBUG2("Failed to find live home server for request");
2630         post_proxy_fail:
2631                 if (setup_post_proxy_fail(request)) {
2632                         request_queue_or_run(request, proxy_running);
2633                 } else {
2634                         gettimeofday(&request->reply->timestamp, NULL);
2635                         request_cleanup_delay_init(request, NULL);
2636                 }
2637                 return 0;
2638         }
2639         home_server_update_request(home, request);
2640
2641         if (!insert_into_proxy_hash(request)) {
2642                 RPROXY("Failed to insert retransmission into the proxy list.");
2643                 goto post_proxy_fail;
2644         }
2645
2646         /*
2647          *      Free the old packet, to force re-encoding
2648          */
2649         talloc_free(request->proxy->data);
2650         request->proxy->data = NULL;
2651         request->proxy->data_len = 0;
2652
2653 #ifdef WITH_ACCOUNTING
2654         /*
2655          *      Update the Acct-Delay-Time attribute.
2656          */
2657         if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2658                 VALUE_PAIR *vp;
2659
2660                 vp = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY);
2661                 if (!vp) vp = radius_paircreate(request,
2662                                                 &request->proxy->vps,
2663                                                 PW_ACCT_DELAY_TIME, 0);
2664                 if (vp) {
2665                         struct timeval now;
2666
2667                         gettimeofday(&now, NULL);
2668                         vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
2669                 }
2670         }
2671 #endif
2672
2673         if (request_proxy(request, 1) != 1) goto post_proxy_fail;
2674
2675         return 1;
2676 }
2677
2678 STATE_MACHINE_DECL(request_ping)
2679 {
2680         home_server_t *home = request->home_server;
2681         char buffer[128];
2682
2683         TRACE_STATE_MACHINE;
2684         ASSERT_MASTER;
2685
2686         switch (action) {
2687         case FR_ACTION_TIMER:
2688                 ERROR("No response to status check %d for home server %s port %d",
2689                        request->number,
2690                        inet_ntop(request->proxy->dst_ipaddr.af,
2691                                  &request->proxy->dst_ipaddr.ipaddr,
2692                                  buffer, sizeof(buffer)),
2693                        request->proxy->dst_port);
2694                 break;
2695
2696         case FR_ACTION_PROXY_REPLY:
2697                 rad_assert(request->in_proxy_hash);
2698
2699                 request->home_server->num_received_pings++;
2700                 RPROXY("Received response to status check %d (%d in current sequence)",
2701                        request->number, home->num_received_pings);
2702
2703                 /*
2704                  *      Remove the request from any hashes
2705                  */
2706                 fr_event_delete(el, &request->ev);
2707                 remove_from_proxy_hash(request);
2708
2709                 /*
2710                  *      The control socket may have marked the home server as
2711                  *      alive.  OR, it may have suddenly started responding to
2712                  *      requests again.  If so, don't re-do the "make alive"
2713                  *      work.
2714                  */
2715                 if (home->state == HOME_STATE_ALIVE) break;
2716
2717                 /*
2718                  *      It's dead, and we haven't received enough ping
2719                  *      responses to mark it "alive".  Wait a bit.
2720                  *
2721                  *      If it's zombie, we mark it alive immediately.
2722                  */
2723                 if ((home->state == HOME_STATE_IS_DEAD) &&
2724                     (home->num_received_pings < home->num_pings_to_alive)) {
2725                         return;
2726                 }
2727
2728                 /*
2729                  *      Mark it alive and delete any outstanding
2730                  *      pings.
2731                  */
2732                 home->state = HOME_STATE_ALIVE;
2733                 exec_trigger(request, home->cs, "home_server.alive", false);
2734                 home->currently_outstanding = 0;
2735                 home->num_sent_pings = 0;
2736                 home->num_received_pings = 0;
2737                 gettimeofday(&home->revive_time, NULL);
2738
2739                 fr_event_delete(el, &home->ev);
2740
2741                 RPROXY("Marking home server %s port %d alive",
2742                        inet_ntop(request->proxy->dst_ipaddr.af,
2743                                  &request->proxy->dst_ipaddr.ipaddr,
2744                                  buffer, sizeof(buffer)),
2745                        request->proxy->dst_port);
2746                 break;
2747
2748         default:
2749                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2750                 break;
2751         }
2752
2753         rad_assert(!request->in_request_hash);
2754         rad_assert(request->ev == NULL);
2755         request_done(request, FR_ACTION_DONE);
2756 }
2757
2758 /*
2759  *      Called from start of zombie period, OR after control socket
2760  *      marks the home server dead.
2761  */
2762 static void ping_home_server(void *ctx)
2763 {
2764         home_server_t *home = ctx;
2765         REQUEST *request;
2766         VALUE_PAIR *vp;
2767         struct timeval when, now;
2768
2769         if ((home->state == HOME_STATE_ALIVE) ||
2770             (home->ping_check == HOME_PING_CHECK_NONE) ||
2771 #ifdef WITH_TCP
2772             (home->proto == IPPROTO_TCP) ||
2773 #endif
2774             (home->ev != NULL)) {
2775                 return;
2776         }
2777
2778         gettimeofday(&now, NULL);
2779
2780         if (home->state == HOME_STATE_ZOMBIE) {
2781                 when = home->zombie_period_start;
2782                 when.tv_sec += home->zombie_period;
2783
2784                 if (timercmp(&when, &now, <)) {
2785                         DEBUG("PING: Zombie period is over for home server %s",
2786                                 home->name);
2787                         mark_home_server_dead(home, &now);
2788                 }
2789         }
2790
2791         request = request_alloc(NULL);
2792         request->number = request_num_counter++;
2793         NO_CHILD_THREAD;
2794
2795         request->proxy = rad_alloc(request, 1);
2796         rad_assert(request->proxy != NULL);
2797
2798         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
2799                 request->proxy->code = PW_CODE_STATUS_SERVER;
2800
2801                 pairmake(request->proxy, &request->proxy->vps,
2802                          "Message-Authenticator", "0x00", T_OP_SET);
2803
2804         } else if (home->type == HOME_TYPE_AUTH) {
2805                 request->proxy->code = PW_CODE_AUTHENTICATION_REQUEST;
2806
2807                 pairmake(request->proxy, &request->proxy->vps,
2808                          "User-Name", home->ping_user_name, T_OP_SET);
2809                 pairmake(request->proxy, &request->proxy->vps,
2810                          "User-Password", home->ping_user_password, T_OP_SET);
2811                 pairmake(request->proxy, &request->proxy->vps,
2812                          "Service-Type", "Authenticate-Only", T_OP_SET);
2813                 pairmake(request->proxy, &request->proxy->vps,
2814                          "Message-Authenticator", "0x00", T_OP_SET);
2815
2816         } else {
2817 #ifdef WITH_ACCOUNTING
2818                 request->proxy->code = PW_CODE_ACCOUNTING_REQUEST;
2819
2820                 pairmake(request->proxy, &request->proxy->vps,
2821                          "User-Name", home->ping_user_name, T_OP_SET);
2822                 pairmake(request->proxy, &request->proxy->vps,
2823                          "Acct-Status-Type", "Stop", T_OP_SET);
2824                 pairmake(request->proxy, &request->proxy->vps,
2825                          "Acct-Session-Id", "00000000", T_OP_SET);
2826                 vp = pairmake(request->proxy, &request->proxy->vps,
2827                               "Event-Timestamp", "0", T_OP_SET);
2828                 vp->vp_date = now.tv_sec;
2829 #else
2830                 rad_assert("Internal sanity check failed");
2831 #endif
2832         }
2833
2834         vp = pairmake(request->proxy, &request->proxy->vps,
2835                       "NAS-Identifier", "", T_OP_SET);
2836         if (vp) {
2837                 pairsprintf(vp, "Status Check %u. Are you alive?",
2838                             home->num_sent_pings);
2839         }
2840
2841         request->proxy->src_ipaddr = home->src_ipaddr;
2842         request->proxy->dst_ipaddr = home->ipaddr;
2843         request->proxy->dst_port = home->port;
2844         request->home_server = home;
2845 #ifdef DEBUG_STATE_MACHINE
2846         if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
2847                                child_state_names[request->child_state],
2848                                child_state_names[REQUEST_DONE]);
2849         if (debug_flag) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
2850 #endif
2851 #ifdef HAVE_PTHREAD_H
2852         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
2853 #endif
2854         request->child_state = REQUEST_DONE;
2855         request->process = request_ping;
2856
2857         rad_assert(request->proxy_listener == NULL);
2858
2859         if (!insert_into_proxy_hash(request)) {
2860                 RPROXY("Failed to insert status check %d into proxy list.  Discarding it.",
2861                        request->number);
2862
2863                 rad_assert(!request->in_request_hash);
2864                 rad_assert(!request->in_proxy_hash);
2865                 rad_assert(request->ev == NULL);
2866                 request_free(&request);
2867                 return;
2868         }
2869
2870         /*
2871          *      Set up the timer callback.
2872          */
2873         when = now;
2874         when.tv_sec += home->ping_timeout;
2875
2876         DEBUG("PING: Waiting %u seconds for response to ping",
2877               home->ping_timeout);
2878
2879         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
2880         home->num_sent_pings++;
2881
2882         rad_assert(request->proxy_listener != NULL);
2883         request->proxy_listener->send(request->proxy_listener,
2884                                       request);
2885
2886         /*
2887          *      Add +/- 2s of jitter, as suggested in RFC 3539
2888          *      and in the Issues and Fixes draft.
2889          */
2890         home->when = now;
2891         home->when.tv_sec += home->ping_interval;
2892
2893         add_jitter(&home->when);
2894
2895         DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
2896         INSERT_EVENT(ping_home_server, home);
2897 }
2898
2899 static void home_trigger(home_server_t *home, char const *trigger)
2900 {
2901         REQUEST my_request;
2902         RADIUS_PACKET my_packet;
2903
2904         memset(&my_request, 0, sizeof(my_request));
2905         memset(&my_packet, 0, sizeof(my_packet));
2906         my_request.proxy = &my_packet;
2907         my_packet.dst_ipaddr = home->ipaddr;
2908         my_packet.src_ipaddr = home->src_ipaddr;
2909
2910         exec_trigger(&my_request, home->cs, trigger, false);
2911 }
2912
2913 static void mark_home_server_zombie(home_server_t *home, struct timeval *now)
2914 {
2915         time_t start;
2916         char buffer[128];
2917
2918         ASSERT_MASTER;
2919
2920         rad_assert((home->state == HOME_STATE_ALIVE) ||
2921                    (home->state == HOME_STATE_UNKNOWN));
2922
2923 #ifdef WITH_TCP
2924         if (home->proto == IPPROTO_TCP) {
2925                 WDEBUG("Not marking TCP server %s zombie", home->name);
2926                 return;
2927         }
2928 #endif
2929
2930         /*
2931          *      We've received a real packet recently.  Don't mark the
2932          *      server as zombie until we've received NO packets for a
2933          *      while.  The "1/4" of zombie period was chosen rather
2934          *      arbitrarily.  It's a balance between too short, which
2935          *      gives quick fail-over and fail-back, or too long,
2936          *      where the proxy still sends packets to an unresponsive
2937          *      home server.
2938          */
2939         start = now->tv_sec - ((home->zombie_period + 3) / 4);
2940         if (home->last_packet_recv >= start) {
2941                 DEBUG("Recieved reply from home server %d seconds ago.  Might not be zombie.",
2942                       (int) (now->tv_sec - home->last_packet_recv));
2943                 return;
2944         }
2945
2946         home->state = HOME_STATE_ZOMBIE;
2947         home_trigger(home, "home_server.zombie");
2948
2949         /*
2950          *      Set the home server to "zombie", as of the time
2951          *      calculated above.
2952          */
2953         home->zombie_period_start.tv_sec = start;
2954         home->zombie_period_start.tv_usec = USEC / 2;
2955
2956         fr_event_delete(el, &home->ev);
2957         home->num_sent_pings = 0;
2958         home->num_received_pings = 0;
2959
2960         PROXY( "Marking home server %s port %d as zombie (it has not responded in %d seconds).",
2961                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2962                          buffer, sizeof(buffer)),
2963                home->port, home->response_window);
2964
2965         ping_home_server(home);
2966 }
2967
2968
2969 void revive_home_server(void *ctx)
2970 {
2971         home_server_t *home = ctx;
2972         char buffer[128];
2973
2974 #ifdef WITH_TCP
2975         rad_assert(home->proto != IPPROTO_TCP);
2976 #endif
2977
2978         home->state = HOME_STATE_ALIVE;
2979         home_trigger(home, "home_server.alive");
2980         home->currently_outstanding = 0;
2981         gettimeofday(&home->revive_time, NULL);
2982
2983         /*
2984          *      Delete any outstanding events.
2985          */
2986         if (home->ev) fr_event_delete(el, &home->ev);
2987
2988         PROXY( "Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
2989                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
2990                          buffer, sizeof(buffer)),
2991                home->port);
2992 }
2993
2994 void mark_home_server_dead(home_server_t *home, struct timeval *when)
2995 {
2996         int previous_state = home->state;
2997         char buffer[128];
2998
2999 #ifdef WITH_TCP
3000         if (home->proto == IPPROTO_TCP) {
3001                 WDEBUG("Not marking TCP server dead");
3002                 return;
3003         }
3004 #endif
3005
3006         PROXY( "Marking home server %s port %d as dead.",
3007                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3008                          buffer, sizeof(buffer)),
3009                home->port);
3010
3011         home->state = HOME_STATE_IS_DEAD;
3012         home_trigger(home, "home_server.dead");
3013
3014         if (home->ping_check != HOME_PING_CHECK_NONE) {
3015                 /*
3016                  *      If the control socket marks us dead, start
3017                  *      pinging.  Otherwise, we already started
3018                  *      pinging when it was marked "zombie".
3019                  */
3020                 if (previous_state == HOME_STATE_ALIVE) {
3021                         ping_home_server(home);
3022                 } else {
3023                         DEBUG("PING: Already pinging home server %s",
3024                               home->name);
3025                 }
3026
3027         } else {
3028                 /*
3029                  *      Revive it after a fixed period of time.  This
3030                  *      is very, very, bad.
3031                  */
3032                 home->when = *when;
3033                 home->when.tv_sec += home->revive_interval;
3034
3035                 DEBUG("PING: Reviving home server %s in %u seconds",
3036                       home->name, home->revive_interval);
3037                 INSERT_EVENT(revive_home_server, home);
3038         }
3039 }
3040
3041 STATE_MACHINE_DECL(proxy_wait_for_reply)
3042 {
3043         struct timeval now, when;
3044         home_server_t *home = request->home_server;
3045         char buffer[128];
3046
3047         TRACE_STATE_MACHINE;
3048
3049         rad_assert(request->packet->code != PW_CODE_STATUS_SERVER);
3050         rad_assert(request->home_server != NULL);
3051
3052         if (request->master_state == REQUEST_STOP_PROCESSING) {
3053                 request->child_state = REQUEST_DONE;
3054                 return;
3055         }
3056
3057         gettimeofday(&now, NULL);
3058
3059         switch (action) {
3060         case FR_ACTION_DUP:
3061                 if (request->proxy_reply) return;
3062
3063                 if ((home->state == HOME_STATE_IS_DEAD) ||
3064                     !request->proxy_listener ||
3065                     (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3066                         request_proxy_anew(request);
3067                         return;
3068                 }
3069
3070 #ifdef WITH_TCP
3071                 if (home->proto == IPPROTO_TCP) {
3072                         DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3073                                inet_ntop(request->proxy->dst_ipaddr.af,
3074                                          &request->proxy->dst_ipaddr.ipaddr,
3075                                          buffer, sizeof(buffer)),
3076                                request->proxy->dst_port,
3077                                request->proxy->id);
3078                         return;
3079                 }
3080 #endif
3081
3082                 /*
3083                  *      More than one retransmit a second is stupid,
3084                  *      and should be suppressed by the proxy.
3085                  */
3086                 when = request->proxy_retransmit;
3087                 when.tv_sec++;
3088
3089                 if (timercmp(&now, &when, <)) {
3090                         DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3091                                inet_ntop(request->proxy->dst_ipaddr.af,
3092                                          &request->proxy->dst_ipaddr.ipaddr,
3093                                          buffer, sizeof(buffer)),
3094                                request->proxy->dst_port,
3095                                request->proxy->id);
3096                         return;
3097                 }
3098
3099 #ifdef WITH_ACCOUNTING
3100                 /*
3101                  *      If we update the Acct-Delay-Time, we need to
3102                  *      get a new ID.
3103                  */
3104                 if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3105                     pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME, 0, TAG_ANY)) {
3106                         request_proxy_anew(request);
3107                         return;
3108                 }
3109 #endif
3110
3111                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3112                         inet_ntop(request->proxy->dst_ipaddr.af,
3113                                   &request->proxy->dst_ipaddr.ipaddr,
3114                                   buffer, sizeof(buffer)),
3115                         request->proxy->dst_port,
3116                         request->proxy->id);
3117                 request->num_proxied_requests++;
3118
3119                 rad_assert(request->proxy_listener != NULL);;
3120                 DEBUG_PACKET(request, request->proxy, 1);
3121                 FR_STATS_TYPE_INC(home->stats.total_requests);
3122                 home->last_packet_sent = now.tv_sec;
3123                 request->proxy_retransmit = now;
3124                 request->proxy_listener->send(request->proxy_listener,
3125                                               request);
3126                 break;
3127
3128         case FR_ACTION_TIMER:
3129 #ifdef WITH_TCP
3130                 if (!request->proxy_listener ||
3131                     (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
3132                         remove_from_proxy_hash(request);
3133
3134                         when = request->packet->timestamp;
3135                         when.tv_sec += request->root->max_request_time;
3136
3137                         if (timercmp(&when, &now, >)) {
3138                                 RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3139                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3140                                 return;
3141                         }
3142                 } else
3143 #endif
3144                 {
3145                         /*
3146                          *      Wake up "response_window" time in the future.
3147                          *      i.e. when MY packet hasn't received a response.
3148                          *
3149                          *      Note that we DO NOT mark the home server as
3150                          *      zombie if it doesn't respond to us.  It may be
3151                          *      responding to other (better looking) packets.
3152                          */
3153                         when = request->proxy->timestamp;
3154                         when.tv_sec += home->response_window;
3155
3156                         /*
3157                          *      Not at the response window.  Set the timer for
3158                          *      that.
3159                          */
3160                         if (timercmp(&when, &now, >)) {
3161                                 RDEBUG("Expecting proxy response no later than %d seconds from now", home->response_window);
3162                                 STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3163                                 return;
3164                         }
3165                 }
3166
3167                 RDEBUG("No proxy response, giving up on request and marking it done");
3168
3169                 /*
3170                  *      If we haven't received any packets for
3171                  *      "response_window", then mark the home server
3172                  *      as zombie.
3173                  *
3174                  *      If the connection is TCP, then another
3175                  *      "watchdog timer" function takes care of pings,
3176                  *      etc.  So we don't need to do it here.
3177                  *
3178                  *      This check should really be part of a home
3179                  *      server state machine.
3180                  */
3181                 if (((home->state == HOME_STATE_ALIVE) ||
3182                      (home->state == HOME_STATE_UNKNOWN))
3183 #ifdef WITH_TCP
3184                     && (home->proto != IPPROTO_TCP)
3185 #endif
3186                         ) {
3187                         mark_home_server_zombie(home, &now);
3188                 }
3189
3190                 FR_STATS_TYPE_INC(home->stats.total_timeouts);
3191                 if (home->type == HOME_TYPE_AUTH) {
3192                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3193                         FR_STATS_TYPE_INC(proxy_auth_stats.total_timeouts);
3194                 }
3195 #ifdef WITH_ACCT
3196                 else if (home->type == HOME_TYPE_ACCT) {
3197                         if (request->proxy_listener) FR_STATS_TYPE_INC(request->proxy_listener->stats.total_timeouts);
3198                         FR_STATS_TYPE_INC(proxy_acct_stats.total_timeouts);
3199                 }
3200 #endif
3201
3202                 /*
3203                  *      There was no response within the window.  Stop
3204                  *      the request.  If the client retransmitted, it
3205                  *      may have failed over to another home server.
3206                  *      But that one may be dead, too.
3207                  */
3208                 RERROR("Failing request - proxy ID %u, due to lack of any response from home server %s port %d",
3209                        request->proxy->id,
3210                                inet_ntop(request->proxy->dst_ipaddr.af,
3211                                          &request->proxy->dst_ipaddr.ipaddr,
3212                                          buffer, sizeof(buffer)),
3213                                request->proxy->dst_port);
3214
3215                 if (!setup_post_proxy_fail(request)) {
3216                         gettimeofday(&request->reply->timestamp, NULL);
3217                         request_cleanup_delay_init(request, NULL);
3218                         return;
3219                 }
3220                 /* FALL-THROUGH */
3221
3222                 /*
3223                  *      Duplicate proxy replies have been quenched by
3224                  *      now.  This state is only called ONCE, when we
3225                  *      receive a new reply from the home server.
3226                  */
3227         case FR_ACTION_PROXY_REPLY:
3228                 request_queue_or_run(request, proxy_running);
3229                 break;
3230
3231         case FR_ACTION_CONFLICTING:
3232                 request_done(request, action);
3233                 return;
3234
3235         default:
3236                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3237                 break;
3238         }
3239 }
3240 #endif  /* WITH_PROXY */
3241
3242 /***********************************************************************
3243  *
3244  *  CoA code
3245  *
3246  ***********************************************************************/
3247 #ifdef WITH_COA
3248 static int null_handler(UNUSED REQUEST *request)
3249 {
3250         return 0;
3251 }
3252
3253 /*
3254  *      See if we need to originate a CoA request.
3255  */
3256 static void request_coa_originate(REQUEST *request)
3257 {
3258         int rcode, pre_proxy_type = 0;
3259         VALUE_PAIR *vp;
3260         REQUEST *coa;
3261         fr_ipaddr_t ipaddr;
3262         char buffer[256];
3263
3264         rad_assert(request != NULL);
3265         rad_assert(request->coa != NULL);
3266         rad_assert(request->proxy == NULL);
3267         rad_assert(!request->in_proxy_hash);
3268         rad_assert(request->proxy_reply == NULL);
3269
3270         /*
3271          *      Check whether we want to originate one, or cancel one.
3272          */
3273         vp = pairfind(request->config_items, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3274         if (!vp) {
3275                 vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST, 0, TAG_ANY);
3276         }
3277
3278         if (vp) {
3279                 if (vp->vp_integer == 0) {
3280                 fail:
3281                         request_free(&request->coa);
3282                         return;
3283                 }
3284         }
3285
3286         coa = request->coa;
3287
3288         /*
3289          *      src_ipaddr will be set up in proxy_encode.
3290          */
3291         memset(&ipaddr, 0, sizeof(ipaddr));
3292         vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS, 0, TAG_ANY);
3293         if (vp) {
3294                 ipaddr.af = AF_INET;
3295                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
3296
3297         } else if ((vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IPV6_ADDRESS, 0, TAG_ANY)) != NULL) {
3298                 ipaddr.af = AF_INET6;
3299                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
3300
3301         } else if ((vp = pairfind(coa->proxy->vps, PW_HOME_SERVER_POOL, 0, TAG_ANY)) != NULL) {
3302                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
3303                                                   HOME_TYPE_COA);
3304                 if (!coa->home_pool) {
3305                         RWDEBUG2("No such home_server_pool %s",
3306                                vp->vp_strvalue);
3307                         goto fail;
3308                 }
3309
3310                 /*
3311                  *      Prefer the pool to one server
3312                  */
3313         } else if (request->client->coa_pool) {
3314                 coa->home_pool = request->client->coa_pool;
3315
3316         } else if (request->client->coa_server) {
3317                 coa->home_server = request->client->coa_server;
3318
3319         } else {
3320                 /*
3321                  *      If all else fails, send it to the client that
3322                  *      originated this request.
3323                  */
3324                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
3325         }
3326
3327         /*
3328          *      Use the pool, if it exists.
3329          */
3330         if (coa->home_pool) {
3331                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
3332                 if (!coa->home_server) {
3333                         RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
3334                         goto fail;
3335                 }
3336                 home_server_update_request(coa->home_server, coa);
3337
3338         } else if (!coa->home_server) {
3339                 int port = PW_COA_UDP_PORT;
3340
3341                 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT, 0, TAG_ANY);
3342                 if (vp) port = vp->vp_integer;
3343
3344                 coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
3345                 if (!coa->home_server) {
3346                         RWDEBUG2("Unknown destination %s:%d for CoA request.",
3347                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
3348                                          buffer, sizeof(buffer)), port);
3349                         goto fail;
3350                 }
3351         }
3352
3353         vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE, 0, TAG_ANY);
3354         if (vp) {
3355                 switch (vp->vp_integer) {
3356                 case PW_CODE_COA_REQUEST:
3357                 case PW_CODE_DISCONNECT_REQUEST:
3358                         coa->proxy->code = vp->vp_integer;
3359                         break;
3360
3361                 default:
3362                         DEBUG("Cannot set CoA Packet-Type to code %d",
3363                               vp->vp_integer);
3364                         goto fail;
3365                 }
3366         }
3367
3368         if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
3369
3370         /*
3371          *      The rest of the server code assumes that
3372          *      request->packet && request->reply exist.  Copy them
3373          *      from the original request.
3374          */
3375         rad_assert(coa->packet != NULL);
3376         rad_assert(coa->packet->vps == NULL);
3377
3378         coa->packet = rad_copy_packet(coa, request->packet);
3379         coa->reply = rad_copy_packet(coa, request->reply);
3380
3381         coa->config_items = paircopy(coa, request->config_items);
3382         coa->num_coa_requests = 0;
3383         coa->handle = null_handler;
3384         coa->number = request->number; /* it's associated with the same request */
3385
3386         /*
3387          *      Call the pre-proxy routines.
3388          */
3389         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE, 0, TAG_ANY);
3390         if (vp) {
3391                 DICT_VALUE const *dval = dict_valbyattr(vp->da->attr, vp->da->vendor, vp->vp_integer);
3392                 /* Must be a validation issue */
3393                 rad_assert(dval);
3394                 RDEBUG2("  Found Pre-Proxy-Type %s", dval->name);
3395                 pre_proxy_type = vp->vp_integer;
3396         }
3397
3398         if (coa->home_pool && coa->home_pool->virtual_server) {
3399                 char const *old_server = coa->server;
3400
3401                 coa->server = coa->home_pool->virtual_server;
3402                 RDEBUG2(" server %s {", coa->server);
3403                 rcode = process_pre_proxy(pre_proxy_type, coa);
3404                 RDEBUG2(" }");
3405                 coa->server = old_server;
3406         } else {
3407                 rcode = process_pre_proxy(pre_proxy_type, coa);
3408         }
3409         switch (rcode) {
3410         default:
3411                 goto fail;
3412
3413         /*
3414          *      Only send the CoA packet if the pre-proxy code succeeded.
3415          */
3416         case RLM_MODULE_NOOP:
3417         case RLM_MODULE_OK:
3418         case RLM_MODULE_UPDATED:
3419                 break;
3420         }
3421
3422         /*
3423          *      Source IP / port is set when the proxy socket
3424          *      is chosen.
3425          */
3426         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
3427         coa->proxy->dst_port = coa->home_server->port;
3428
3429         if (!insert_into_proxy_hash(coa)) {
3430                 radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list.");
3431                 goto fail;
3432         }
3433
3434         /*
3435          *      We CANNOT divorce the CoA request from the parent
3436          *      request.  This function is running in a child thread,
3437          *      and we need access to the main event loop in order to
3438          *      to add the timers for the CoA packet.
3439          *
3440          *      Instead, we wait for the timer on the parent request
3441          *      to fire.
3442          */
3443         gettimeofday(&coa->proxy->timestamp, NULL);
3444         coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
3445         coa->delay = 0;         /* need to calculate a new delay */
3446
3447         DEBUG_PACKET(coa, coa->proxy, 1);
3448
3449         coa->process = coa_wait_for_reply;
3450 #ifdef DEBUG_STATE_MACHINE
3451         if (debug_flag) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3452                                child_state_names[request->child_state],
3453                                child_state_names[REQUEST_RUNNING]);
3454 #endif
3455         coa->child_state = REQUEST_PROXIED;
3456         rad_assert(coa->proxy_reply == NULL);
3457         FR_STATS_TYPE_INC(coa->home_server->stats.total_requests);
3458         coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
3459         coa->proxy_listener->send(coa->proxy_listener, coa);
3460 }
3461
3462
3463 static void coa_timer(REQUEST *request)
3464 {
3465         int delay, frac;
3466         struct timeval now, when, mrd;
3467
3468         rad_assert(request->parent == NULL);
3469
3470         if (request->proxy_reply) return request_process_timer(request);
3471
3472         gettimeofday(&now, NULL);
3473
3474         if (request->delay == 0) {
3475                 /*
3476                  *      Implement re-transmit algorithm as per RFC 5080
3477                  *      Section 2.2.1.
3478                  *
3479                  *      We want IRT + RAND*IRT
3480                  *      or 0.9 IRT + rand(0,.2) IRT
3481                  *
3482                  *      2^20 ~ USEC, and we want 2.
3483                  *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
3484                  */
3485                 delay = (fr_rand() & ((1 << 22) - 1)) / 10;
3486                 request->delay = delay * request->home_server->coa_irt;
3487                 delay = request->home_server->coa_irt * USEC;
3488                 delay -= delay / 10;
3489                 delay += request->delay;
3490                 request->delay = delay;
3491
3492                 when = request->proxy->timestamp;
3493                 tv_add(&when, delay);
3494
3495                 if (timercmp(&when, &now, >)) {
3496                         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3497                         return;
3498                 }
3499         }
3500
3501         /*
3502          *      Retransmit CoA request.
3503          */
3504
3505         /*
3506          *      Cap count at MRC, if it is non-zero.
3507          */
3508         if (request->home_server->coa_mrc &&
3509             (request->num_coa_requests >= request->home_server->coa_mrc)) {
3510                 if (!setup_post_proxy_fail(request)) {
3511                         return;
3512                 }
3513
3514                 request_queue_or_run(request, coa_running);
3515                 return;
3516         }
3517
3518         /*
3519          *      RFC 5080 Section 2.2.1
3520          *
3521          *      RT = 2*RTprev + RAND*RTprev
3522          *         = 1.9 * RTprev + rand(0,.2) * RTprev
3523          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
3524          */
3525         delay = fr_rand();
3526         delay ^= (delay >> 16);
3527         delay &= 0xffff;
3528         frac = request->delay / 5;
3529         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
3530
3531         delay += (2 * request->delay) - (request->delay / 10);
3532
3533         /*
3534          *      Cap delay at MRT, if MRT is non-zero.
3535          */
3536         if (request->home_server->coa_mrt &&
3537             (delay > (request->home_server->coa_mrt * USEC))) {
3538                 int mrt_usec = request->home_server->coa_mrt * USEC;
3539
3540                 /*
3541                  *      delay = MRT + RAND * MRT
3542                  *            = 0.9 MRT + rand(0,.2)  * MRT
3543                  */
3544                 delay = fr_rand();
3545                 delay ^= (delay >> 15);
3546                 delay &= 0x1ffff;
3547                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
3548                 delay += mrt_usec - (mrt_usec / 10);
3549         }
3550
3551         request->delay = delay;
3552         when = now;
3553         tv_add(&when, request->delay);
3554         mrd = request->proxy->timestamp;
3555         mrd.tv_sec += request->home_server->coa_mrd;
3556
3557         /*
3558          *      Cap duration at MRD.
3559          */
3560         if (timercmp(&mrd, &when, <)) {
3561                 when = mrd;
3562         }
3563         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3564
3565         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
3566
3567         FR_STATS_TYPE_INC(request->home_server->stats.total_requests);
3568
3569         /*
3570          *      Status servers don't count as real packets sent.
3571          */
3572         request->proxy_listener->send(request->proxy_listener,
3573                                       request);
3574 }
3575
3576 STATE_MACHINE_DECL(coa_wait_for_reply)
3577 {
3578         rad_assert(request->parent == NULL);
3579
3580         TRACE_STATE_MACHINE;
3581
3582         switch (action) {
3583         case FR_ACTION_TIMER:
3584                 /*
3585                  *      This is big enough to be in it's own function.
3586                  */
3587                 coa_timer(request);
3588                 break;
3589
3590         case FR_ACTION_PROXY_REPLY:
3591                 rad_assert(request->parent == NULL);
3592 #ifdef HAVE_PTHREAD_H
3593                 /*
3594                  *      Catch the case of a proxy reply when called
3595                  *      from the main worker thread.
3596                  */
3597                 if (we_are_master()) {
3598                         request_queue_or_run(request, coa_running);
3599                         return;
3600                 }
3601                 /* FALL-THROUGH */
3602 #endif
3603         case FR_ACTION_RUN:
3604                 request_running(request, action);
3605                 break;
3606
3607         default:
3608                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3609                 break;
3610         }
3611 }
3612
3613 static void request_coa_separate(REQUEST *request)
3614 {
3615 #ifdef DEBUG_STATE_MACHINE
3616         int action = FR_ACTION_TIMER;
3617 #endif
3618         TRACE_STATE_MACHINE;
3619
3620         rad_assert(request->parent != NULL);
3621         rad_assert(request->parent->coa == request);
3622         rad_assert(request->ev == NULL);
3623         rad_assert(!request->in_request_hash);
3624
3625         rad_assert(request->proxy_listener != NULL);
3626
3627         (void) talloc_steal(NULL, request);
3628         request->parent->coa = NULL;
3629         request->parent = NULL;
3630
3631         /*
3632          *      Should be coa_wait_for_reply()
3633          */
3634         request->process(request, FR_ACTION_TIMER);
3635 }
3636
3637 STATE_MACHINE_DECL(coa_running)
3638 {
3639         TRACE_STATE_MACHINE;
3640
3641         switch (action) {
3642         case FR_ACTION_TIMER:
3643                 request_process_timer(request);
3644                 break;
3645
3646         case FR_ACTION_PROXY_REPLY:
3647                 request_common(request, action);
3648                 break;
3649
3650         case FR_ACTION_RUN:
3651                 request_running(request, FR_ACTION_PROXY_REPLY);
3652                 break;
3653
3654         default:
3655                 RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3656                 break;
3657         }
3658 }
3659 #endif  /* WITH_COA */
3660
3661 /***********************************************************************
3662  *
3663  *  End of the State machine.  Start of additional helper code.
3664  *
3665  ***********************************************************************/
3666
3667 /***********************************************************************
3668  *
3669  *      Event handlers.
3670  *
3671  ***********************************************************************/
3672 static void event_socket_handler(UNUSED fr_event_list_t *xel, UNUSED int fd, void *ctx)
3673 {
3674         rad_listen_t *listener = ctx;
3675
3676         rad_assert(xel == el);
3677
3678         if (
3679 #ifdef WITH_DETAIL
3680             (listener->type != RAD_LISTEN_DETAIL) &&
3681 #endif
3682             (listener->fd < 0)) {
3683                 char buffer[256];
3684
3685                 listener->print(listener, buffer, sizeof(buffer));
3686                 ERROR("FATAL: Asked to read from closed socket: %s",
3687                        buffer);
3688
3689                 rad_panic("Socket was closed on us!");
3690                 fr_exit_now(1);
3691         }
3692
3693         listener->recv(listener);
3694 }
3695
3696 #ifdef WITH_DETAIL
3697 /*
3698  *      This function is called periodically to see if this detail
3699  *      file is available for reading.
3700  */
3701 static void event_poll_detail(void *ctx)
3702 {
3703         int delay;
3704         rad_listen_t *this = ctx;
3705         struct timeval when, now;
3706         listen_detail_t *detail = this->data;
3707
3708         rad_assert(this->type == RAD_LISTEN_DETAIL);
3709
3710  redo:
3711         event_socket_handler(el, this->fd, this);
3712
3713         fr_event_now(el, &now);
3714         when = now;
3715
3716         /*
3717          *      Backdoor API to get the delay until the next poll
3718          *      time.
3719          */
3720         delay = this->encode(this, NULL);
3721         if (delay == 0) goto redo;
3722
3723         tv_add(&when, delay);
3724
3725         if (!fr_event_insert(el, event_poll_detail, this,
3726                              &when, &detail->ev)) {
3727                 ERROR("Failed creating handler");
3728                 fr_exit(1);
3729         }
3730 }
3731 #endif
3732
3733 static void event_status(struct timeval *wake)
3734 {
3735 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3736         int argval;
3737 #endif
3738
3739         if (debug_flag == 0) {
3740                 if (just_started) {
3741                         INFO("Ready to process requests.");
3742                         just_started = false;
3743                 }
3744                 return;
3745         }
3746
3747         if (!wake) {
3748                 INFO("Ready to process requests.");
3749
3750         } else if ((wake->tv_sec != 0) ||
3751                    (wake->tv_usec >= 100000)) {
3752                 DEBUG("Waking up in %d.%01u seconds.",
3753                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3754         }
3755
3756
3757         /*
3758          *      FIXME: Put this somewhere else, where it isn't called
3759          *      all of the time...
3760          */
3761
3762 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3763         /*
3764          *      If there are no child threads, then there may
3765          *      be child processes.  In that case, wait for
3766          *      their exit status, and throw that exit status
3767          *      away.  This helps get rid of zxombie children.
3768          */
3769         while (waitpid(-1, &argval, WNOHANG) > 0) {
3770                 /* do nothing */
3771         }
3772 #endif
3773
3774 }
3775
3776 #ifdef WITH_TCP
3777 static void listener_free_cb(void *ctx)
3778 {
3779         rad_listen_t *this = ctx;
3780         char buffer[1024];
3781
3782         if (this->count > 0) {
3783                 struct timeval when;
3784                 listen_socket_t *sock = this->data;
3785
3786                 fr_event_now(el, &when);
3787                 when.tv_sec += 3;
3788
3789                 if (!fr_event_insert(el, listener_free_cb, this, &when,
3790                                      &(sock->ev))) {
3791                         rad_panic("Failed to insert event");
3792                 }
3793
3794                 return;
3795         }
3796
3797         /*
3798          *      It's all free, close the socket.
3799          */
3800
3801         this->print(this, buffer, sizeof(buffer));
3802         DEBUG("... cleaning up socket %s", buffer);
3803         listen_free(&this);
3804 }
3805 #endif
3806
3807 #ifdef WITH_PROXY
3808 static int proxy_eol_cb(void *ctx, void *data)
3809 {
3810         struct timeval when;
3811         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3812
3813         if (request->proxy_listener != ctx) return 0;
3814
3815         /*
3816          *      We don't care if it's being processed in a child thread.
3817          */
3818
3819 #ifdef WITH_ACCOUNTING
3820         /*
3821          *      Accounting packets should be deleted immediately.
3822          *      They will never be retransmitted by the client.
3823          */
3824         if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
3825                 RDEBUG("Stopping request due to failed connection to home server");
3826                 request->master_state = REQUEST_STOP_PROCESSING;
3827         }
3828 #endif
3829
3830         /*
3831          *      Reset the timer to be now, so that the request is
3832          *      quickly updated.  But spread the requests randomly
3833          *      over the next second, so that we don't overload the
3834          *      server.
3835          */
3836         fr_event_now(el, &when);
3837         tv_add(&when, fr_rand() % USEC);
3838         STATE_MACHINE_TIMER(FR_ACTION_TIMER);
3839
3840         /*
3841          *      Don't delete it from the list.
3842          */
3843         return 0;
3844 }
3845 #endif
3846
3847 int event_new_fd(rad_listen_t *this)
3848 {
3849         char buffer[1024];
3850
3851         if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
3852
3853         this->print(this, buffer, sizeof(buffer));
3854
3855         if (this->status == RAD_LISTEN_STATUS_INIT) {
3856                 listen_socket_t *sock = this->data;
3857
3858                 if (just_started) {
3859                         DEBUG("Listening on %s", buffer);
3860                 } else {
3861                         INFO(" ... adding new socket %s", buffer);
3862                 }
3863
3864 #ifdef WITH_PROXY
3865                 /*
3866                  *      Add it to the list of sockets we can use.
3867                  *      Server sockets (i.e. auth/acct) are never
3868                  *      added to the packet list.
3869                  */
3870                 if (this->type == RAD_LISTEN_PROXY) {
3871                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3872                         if (!fr_packet_list_socket_add(proxy_list, this->fd,
3873                                                        sock->proto,
3874                                                        &sock->other_ipaddr, sock->other_port,
3875                                                        this)) {
3876
3877 #ifdef HAVE_PTHREAD_H
3878                                 proxy_no_new_sockets = true;
3879 #endif
3880                                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3881
3882                                 /*
3883                                  *      This is bad.  However, the
3884                                  *      packet list now supports 256
3885                                  *      open sockets, which should
3886                                  *      minimize this problem.
3887                                  */
3888                                 ERROR("Failed adding proxy socket: %s",
3889                                        fr_strerror());
3890                                 return 0;
3891                         }
3892
3893                         if (sock->home) {
3894                                 sock->home->limit.num_connections++;
3895
3896 #ifdef HAVE_PTHREAD_H
3897                                 /*
3898                                  *      If necessary, add it to the list of
3899                                  *      new proxy listeners.
3900                                  */
3901                                 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3902                                         this->next = proxy_listener_list;
3903                                         proxy_listener_list = this;
3904                                 }
3905 #endif
3906                         }
3907                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3908
3909                         /*
3910                          *      Tell the main thread that we've added
3911                          *      a proxy listener, but only if we need
3912                          *      to update the event list.  Do this
3913                          *      with the mutex unlocked, to reduce
3914                          *      contention.
3915                          */
3916                         if (sock->home) {
3917                                 if (sock->home->limit.lifetime || sock->home->limit.idle_timeout) {
3918                                         radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3919                                 }
3920                         }
3921                 }
3922 #endif
3923
3924 #ifdef WITH_DETAIL
3925                 /*
3926                  *      Detail files are always known, and aren't
3927                  *      put into the socket event loop.
3928                  */
3929                 if (this->type == RAD_LISTEN_DETAIL) {
3930                         this->status = RAD_LISTEN_STATUS_KNOWN;
3931
3932                         /*
3933                          *      Set up the first poll interval.
3934                          */
3935                         event_poll_detail(this);
3936                         return 1;
3937                 }
3938 #endif
3939
3940 #ifdef WITH_TCP
3941                 /*
3942                  *      Add timers to child sockets, if necessary.
3943                  */
3944                 if (sock->proto == IPPROTO_TCP && sock->opened &&
3945                     (sock->limit.lifetime || sock->limit.idle_timeout)) {
3946                         struct timeval when;
3947
3948                         ASSERT_MASTER;
3949
3950                         when.tv_sec = sock->opened + 1;
3951                         when.tv_usec = 0;
3952
3953                         if (!fr_event_insert(el, tcp_socket_timer, this, &when,
3954                                              &(sock->ev))) {
3955                                 rad_panic("Failed to insert event");
3956                         }
3957                 }
3958 #endif
3959
3960                 FD_MUTEX_LOCK(&fd_mutex);
3961                 if (!fr_event_fd_insert(el, 0, this->fd,
3962                                         event_socket_handler, this)) {
3963                         ERROR("Failed adding event handler for socket!");
3964                         fr_exit(1);
3965                 }
3966                 FD_MUTEX_UNLOCK(&fd_mutex);
3967
3968                 this->status = RAD_LISTEN_STATUS_KNOWN;
3969                 return 1;
3970         } /* end of INIT */
3971
3972 #ifdef WITH_TCP
3973         /*
3974          *      Stop using this socket, if at all possible.
3975          */
3976         if (this->status == RAD_LISTEN_STATUS_EOL) {
3977                 /*
3978                  *      Remove it from the list of live FD's.
3979                  */
3980                 FD_MUTEX_LOCK(&fd_mutex);
3981                 fr_event_fd_delete(el, 0, this->fd);
3982                 FD_MUTEX_UNLOCK(&fd_mutex);
3983
3984 #ifdef WITH_PROXY
3985                 /*
3986                  *      Proxy sockets get frozen, so that we don't use
3987                  *      them for new requests.  But we do keep them
3988                  *      open to listen for replies to requests we had
3989                  *      previously sent.
3990                  */
3991                 if (this->type == RAD_LISTEN_PROXY) {
3992                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3993                         if (!fr_packet_list_socket_freeze(proxy_list,
3994                                                           this->fd)) {
3995                                 ERROR("Fatal error freezing socket: %s", fr_strerror());
3996                                 fr_exit(1);
3997                         }
3998
3999                         fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4000                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4001                 }
4002 #endif
4003
4004                 /*
4005                  *      Requests are still using the socket.  Wait for
4006                  *      them to finish.
4007                  */
4008                 if (this->count > 0) {
4009                         struct timeval when;
4010                         listen_socket_t *sock = this->data;
4011
4012                         /*
4013                          *      Try again to clean up the socket in 30
4014                          *      seconds.
4015                          */
4016                         gettimeofday(&when, NULL);
4017                         when.tv_sec += 30;
4018
4019                         if (!fr_event_insert(el,
4020                                              (fr_event_callback_t) event_new_fd,
4021                                              this, &when, &sock->ev)) {
4022                                 rad_panic("Failed to insert event");
4023                         }
4024
4025                         return 1;
4026                 }
4027
4028                 /*
4029                  *      No one is using the socket.  We can remove it now.
4030                  */
4031                 this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4032         } /* socket is at EOL */
4033 #endif
4034
4035         /*
4036          *      Nuke the socket.
4037          */
4038         if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4039                 int devnull;
4040 #ifdef WITH_TCP
4041                 listen_socket_t *sock = this->data;
4042 #endif
4043                 struct timeval when;
4044
4045                 /*
4046                  *      Re-open the socket, pointing it to /dev/null.
4047                  *      This means that all writes proceed without
4048                  *      blocking, and all reads return "no data".
4049                  *
4050                  *      This leaves the socket active, so any child
4051                  *      threads won't go insane.  But it means that
4052                  *      they cannot send or receive any packets.
4053                  *
4054                  *      This is EXTRA work in the normal case, when
4055                  *      sockets are closed without error.  But it lets
4056                  *      us have one simple processing method for all
4057                  *      sockets.
4058                  */
4059                 devnull = open("/dev/null", O_RDWR);
4060                 if (devnull < 0) {
4061                         ERROR("FATAL failure opening /dev/null: %s",
4062                                fr_syserror(errno));
4063                         fr_exit(1);
4064                 }
4065                 if (dup2(devnull, this->fd) < 0) {
4066                         ERROR("FATAL failure closing socket: %s",
4067                                fr_syserror(errno));
4068                         fr_exit(1);
4069                 }
4070                 close(devnull);
4071
4072 #ifdef WITH_DETAIL
4073                 rad_assert(this->type != RAD_LISTEN_DETAIL);
4074 #endif
4075
4076 #ifdef WITH_TCP
4077                 INFO(" ... shutting down socket %s", buffer);
4078
4079 #ifdef WITH_PROXY
4080                 /*
4081                  *      The socket is dead.  Force all proxied packets
4082                  *      to stop using it.  And then remove it from the
4083                  *      list of outgoing sockets.
4084                  */
4085                 if (this->type == RAD_LISTEN_PROXY) {
4086                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
4087                         fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4088
4089                         if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4090                                 ERROR("Fatal error removing socket %s: %s",
4091                                       buffer, fr_strerror());
4092                                 fr_exit(1);
4093                         }
4094                         if (sock->home &&  sock->home->limit.num_connections) {
4095                                 sock->home->limit.num_connections--;
4096                         }
4097                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4098                 } else
4099 #endif
4100                 {
4101                         /*
4102                          *      EOL all requests using this socket.
4103                          */
4104                         fr_packet_list_walk(pl, this, eol_listener);
4105                 }
4106
4107                 /*
4108                  *      No child threads, clean it up now.
4109                  */
4110                 if (!spawn_flag) {
4111                         if (sock->ev) fr_event_delete(el, &sock->ev);
4112                         listen_free(&this);
4113                         return 1;
4114                 }
4115
4116                 /*
4117                  *      Wait until all requests using this socket are done.
4118                  */
4119                 gettimeofday(&when, NULL);
4120                 when.tv_sec += 3;
4121
4122                 if (!fr_event_insert(el, listener_free_cb, this, &when,
4123                                      &(sock->ev))) {
4124                         rad_panic("Failed to insert event");
4125                 }
4126         }
4127 #endif  /* WITH_TCP */
4128
4129         return 1;
4130 }
4131
4132 /***********************************************************************
4133  *
4134  *      Signal handlers.
4135  *
4136  ***********************************************************************/
4137
4138 static void handle_signal_self(int flag)
4139 {
4140         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
4141                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
4142                         INFO("Signalled to exit");
4143                         fr_event_loop_exit(el, 1);
4144                 } else {
4145                         INFO("Signalled to terminate");
4146                         exec_trigger(NULL, NULL, "server.signal.term", true);
4147                         fr_event_loop_exit(el, 2);
4148                 }
4149
4150                 return;
4151         } /* else exit/term flags weren't set */
4152
4153         /*
4154          *      Tell the even loop to stop processing.
4155          */
4156         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
4157                 time_t when;
4158                 static time_t last_hup = 0;
4159
4160                 when = time(NULL);
4161                 if ((int) (when - last_hup) < 5) {
4162                         INFO("Ignoring HUP (less than 5s since last one)");
4163                         return;
4164                 }
4165
4166                 INFO("Received HUP signal.");
4167
4168                 last_hup = when;
4169
4170                 exec_trigger(NULL, NULL, "server.signal.hup", true);
4171                 fr_event_loop_exit(el, 0x80);
4172         }
4173
4174 #ifdef WITH_DETAIL
4175         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
4176                 rad_listen_t *this;
4177
4178                 /*
4179                  *      FIXME: O(N) loops suck.
4180                  */
4181                 for (this = mainconfig.listen;
4182                      this != NULL;
4183                      this = this->next) {
4184                         if (this->type != RAD_LISTEN_DETAIL) continue;
4185
4186                         /*
4187                          *      This one didn't send the signal, skip
4188                          *      it.
4189                          */
4190                         if (!this->decode(this, NULL)) continue;
4191
4192                         /*
4193                          *      Go service the interrupt.
4194                          */
4195                         event_poll_detail(this);
4196                 }
4197         }
4198 #endif
4199
4200 #ifdef WITH_TCP
4201 #ifdef WITH_PROXY
4202 #ifdef HAVE_PTHREAD_H
4203         /*
4204          *      Add event handlers for idle timeouts && maximum lifetime.
4205          */
4206         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
4207                 struct timeval when, now;
4208
4209                 fr_event_now(el, &now);
4210
4211                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4212
4213                 while (proxy_listener_list) {
4214                         rad_listen_t *this = proxy_listener_list;
4215                         listen_socket_t *sock = this->data;
4216
4217                         rad_assert(sock->proto == IPPROTO_TCP);
4218                         proxy_listener_list = this->next;
4219                         this->next = NULL;
4220
4221                         if (!sock->home) continue; /* skip UDP sockets */
4222
4223                         when = now;
4224
4225                         /*
4226                          *      Sockets should only be added to the
4227                          *      proxy_listener_list if they have limits.
4228                          *
4229                          */
4230                         rad_assert(sock->home->limit.lifetime || sock->home->limit.idle_timeout);
4231
4232                         if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4233                                              &(sock->ev))) {
4234                                 rad_panic("Failed to insert event");
4235                         }
4236                 }
4237
4238                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4239         }
4240 #endif  /* HAVE_PTHREAD_H */
4241 #endif  /* WITH_PROXY */
4242 #endif  /* WITH_TCP */
4243 }
4244
4245 #ifndef WITH_SELF_PIPE
4246 void radius_signal_self(int flag)
4247 {
4248         handle_signal_self(flag);
4249 }
4250 #else
4251 /*
4252  *      Inform ourselves that we received a signal.
4253  */
4254 void radius_signal_self(int flag)
4255 {
4256         ssize_t rcode;
4257         uint8_t buffer[16];
4258
4259         /*
4260          *      The read MUST be non-blocking for this to work.
4261          */
4262         rcode = read(self_pipe[0], buffer, sizeof(buffer));
4263         if (rcode > 0) {
4264                 ssize_t i;
4265
4266                 for (i = 0; i < rcode; i++) {
4267                         buffer[0] |= buffer[i];
4268                 }
4269         } else {
4270                 buffer[0] = 0;
4271         }
4272
4273         buffer[0] |= flag;
4274
4275         write(self_pipe[1], buffer, 1);
4276 }
4277
4278
4279 static void event_signal_handler(UNUSED fr_event_list_t *xel,
4280                                  UNUSED int fd, UNUSED void *ctx)
4281 {
4282         ssize_t i, rcode;
4283         uint8_t buffer[32];
4284
4285         rcode = read(self_pipe[0], buffer, sizeof(buffer));
4286         if (rcode <= 0) return;
4287
4288         /*
4289          *      Merge pending signals.
4290          */
4291         for (i = 0; i < rcode; i++) {
4292                 buffer[0] |= buffer[i];
4293         }
4294
4295         handle_signal_self(buffer[0]);
4296 }
4297 #endif
4298
4299 /***********************************************************************
4300  *
4301  *      Bootstrapping code.
4302  *
4303  ***********************************************************************/
4304
4305 /*
4306  *      Externally-visibly functions.
4307  */
4308 int radius_event_init(TALLOC_CTX *ctx) {
4309         el = fr_event_list_create(ctx, event_status);
4310         if (!el) return 0;
4311
4312         return 1;
4313 }
4314
4315 int radius_event_start(CONF_SECTION *cs, bool have_children)
4316 {
4317         rad_listen_t *head = NULL;
4318
4319         if (fr_start_time != (time_t)-1) return 0;
4320
4321         time(&fr_start_time);
4322
4323         /*
4324          *  radius_event_init() must be called first
4325          */
4326         rad_assert(el);
4327         if (fr_start_time == (time_t)-1) return 0;
4328
4329         pl = fr_packet_list_create(0);
4330         if (!pl) return 0;      /* leak el */
4331
4332         request_num_counter = 0;
4333
4334 #ifdef WITH_PROXY
4335         if (mainconfig.proxy_requests) {
4336                 /*
4337                  *      Create the tree for managing proxied requests and
4338                  *      responses.
4339                  */
4340                 proxy_list = fr_packet_list_create(1);
4341                 if (!proxy_list) return 0;
4342
4343 #ifdef HAVE_PTHREAD_H
4344                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
4345                         ERROR("FATAL: Failed to initialize proxy mutex: %s",
4346                                fr_syserror(errno));
4347                         fr_exit(1);
4348                 }
4349 #endif
4350         }
4351 #endif
4352
4353         /*
4354          *      Move all of the thread calls to this file?
4355          *
4356          *      It may be best for the mutexes to be in this file...
4357          */
4358         spawn_flag = have_children;
4359
4360 #ifdef HAVE_PTHREAD_H
4361         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
4362
4363         /*
4364          *      Initialize the threads ONLY if we're spawning, AND
4365          *      we're running normally.
4366          */
4367         if (have_children && !check_config &&
4368             (thread_pool_init(cs, &spawn_flag) < 0)) {
4369                 fr_exit(1);
4370         }
4371 #endif
4372
4373         if (check_config) {
4374                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
4375                        mainconfig.name);
4376                 if (listen_init(cs, &head, spawn_flag) < 0) {
4377                         fflush(NULL);
4378                         fr_exit(1);
4379                 }
4380                 return 1;
4381         }
4382
4383 #ifdef WITH_SELF_PIPE
4384         /*
4385          *      Child threads need a pipe to signal us, as do the
4386          *      signal handlers.
4387          */
4388         if (pipe(self_pipe) < 0) {
4389                 ERROR("radiusd: Error opening internal pipe: %s",
4390                        fr_syserror(errno));
4391                 fr_exit(1);
4392         }
4393         if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
4394             (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
4395                 ERROR("radiusd: Error setting internal flags: %s",
4396                        fr_syserror(errno));
4397                 fr_exit(1);
4398         }
4399         if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
4400             (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
4401                 ERROR("radiusd: Error setting internal flags: %s",
4402                        fr_syserror(errno));
4403                 fr_exit(1);
4404         }
4405
4406         if (!fr_event_fd_insert(el, 0, self_pipe[0],
4407                                   event_signal_handler, el)) {
4408                 ERROR("Failed creating handler for signals");
4409                 fr_exit(1);
4410         }
4411 #endif  /* WITH_SELF_PIPE */
4412
4413        DEBUG("%s: #### Opening IP addresses and Ports ####",
4414                mainconfig.name);
4415
4416        /*
4417         *       The server temporarily switches to an unprivileged
4418         *       user very early in the bootstrapping process.
4419         *       However, some sockets MAY require privileged access
4420         *       (bind to device, or to port < 1024, or to raw
4421         *       sockets).  Those sockets need to call suid up/down
4422         *       themselves around the functions that need a privileged
4423         *       uid.
4424         */
4425        if (listen_init(cs, &head, spawn_flag) < 0) {
4426                 fr_exit_now(1);
4427         }
4428
4429         mainconfig.listen = head;
4430
4431         /*
4432          *      At this point, no one has any business *ever* going
4433          *      back to root uid.
4434          */
4435         fr_suid_down_permanent();
4436
4437         return 1;
4438 }
4439
4440
4441 #ifdef WITH_PROXY
4442 static int proxy_delete_cb(UNUSED void *ctx, void *data)
4443 {
4444         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4445
4446         request->master_state = REQUEST_STOP_PROCESSING;
4447
4448         /*
4449          *      Not done, or the child thread is still processing it.
4450          */
4451         if (request->child_state != REQUEST_DONE) return 0; /* continue */
4452
4453 #ifdef HAVE_PTHREAD_H
4454         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4455 #endif
4456
4457         request->in_proxy_hash = false;
4458
4459         /*
4460          *      Delete it from the list.
4461          */
4462         return 2;
4463 }
4464 #endif
4465
4466
4467 static int request_delete_cb(UNUSED void *ctx, void *data)
4468 {
4469         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4470
4471         request->master_state = REQUEST_STOP_PROCESSING;
4472
4473         /*
4474          *      Not done, or the child thread is still processing it.
4475          */
4476         if (request->child_state < REQUEST_REJECT_DELAY) return 0; /* continue */
4477
4478 #ifdef HAVE_PTHREAD_H
4479         if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
4480 #endif
4481
4482 #ifdef WITH_PROXY
4483         rad_assert(request->in_proxy_hash == false);
4484 #endif
4485
4486         request->in_request_hash = false;
4487         if (request->ev) fr_event_delete(el, &request->ev);
4488
4489         if (mainconfig.memory_report) {
4490                 RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
4491                         request->packet->id,
4492                         (unsigned int) (request->timestamp - fr_start_time));
4493         }
4494
4495         request_free(&request);
4496
4497         /*
4498          *      Delete it from the list, and continue;
4499          */
4500         return 2;
4501 }
4502
4503
4504 void radius_event_free(void)
4505 {
4506         ASSERT_MASTER;
4507
4508 #ifdef WITH_PROXY
4509         /*
4510          *      There are requests in the proxy hash that aren't
4511          *      referenced from anywhere else.  Remove them first.
4512          */
4513         if (proxy_list) {
4514                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4515         }
4516 #endif
4517
4518         fr_packet_list_walk(pl, NULL, request_delete_cb);
4519
4520         if (spawn_flag) {
4521                 /*
4522                  *      Now that all requests have been marked "please stop",
4523                  *      ensure that all of the threads have exited.
4524                  */
4525 #ifdef HAVE_PTHREAD_H
4526                 thread_pool_stop();
4527 #endif
4528
4529                 /*
4530                  *      Walk the lists again, ensuring that all
4531                  *      requests are done.
4532                  */
4533                 if (mainconfig.memory_report) {
4534                         int num;
4535
4536 #ifdef WITH_PROXY
4537                         if (proxy_list) {
4538                                 fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
4539                                 num = fr_packet_list_num_elements(proxy_list);
4540                                 if (num > 0) {
4541                                         ERROR("Proxy list has %d requests still in it.", num);
4542                                 }
4543                         }
4544 #endif
4545
4546                         fr_packet_list_walk(pl, NULL, request_delete_cb);
4547                         num = fr_packet_list_num_elements(pl);
4548                         if (num > 0) {
4549                                 ERROR("Request list has %d requests still in it.", num);
4550                         }
4551                 }
4552         }
4553
4554         fr_packet_list_free(pl);
4555         pl = NULL;
4556
4557 #ifdef WITH_PROXY
4558         fr_packet_list_free(proxy_list);
4559         proxy_list = NULL;
4560 #endif
4561
4562         TALLOC_FREE(el);
4563
4564         if (debug_condition) talloc_free(debug_condition);
4565 }
4566
4567 int radius_event_process(void)
4568 {
4569         if (!el) return 0;
4570
4571         return fr_event_loop(el);
4572 }