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