Track the number of outstanding packets on a TCP connection.
[freeradius.git] / src / main / event.c
1 /*
2  * event.c      Server event handling
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/detail.h>
31
32 #include <freeradius-devel/rad_assert.h>
33
34 #include <signal.h>
35 #include <fcntl.h>
36
37 #ifdef HAVE_SYS_WAIT_H
38 #       include <sys/wait.h>
39 #endif
40
41 #define USEC (1000000)
42
43 extern pid_t radius_pid;
44 extern int dont_fork;
45 extern int check_config;
46 extern void force_log_reopen(void);
47 extern char *debug_condition;
48
49 /*
50  *      Ridiculous amounts of local state.
51  */
52 static fr_event_list_t  *el = NULL;
53 static fr_packet_list_t *pl = NULL;
54 static int                      request_num_counter = 0;
55 static struct timeval           now;
56 time_t                          fr_start_time;
57 static int                      have_children;
58 static int                      just_started = TRUE;
59
60 #ifndef __MINGW32__
61 #ifdef HAVE_PTHREAD_H
62 #define WITH_SELF_PIPE (1)
63 #endif
64 #endif
65
66 #ifdef WITH_SELF_PIPE
67 static int self_pipe[2];
68 #endif
69
70 #ifdef HAVE_PTHREAD_H
71 #ifdef WITH_PROXY
72 static pthread_mutex_t  proxy_mutex;
73 #endif
74
75 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
76 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
77
78 static pthread_t NO_SUCH_CHILD_PID;
79 #else
80 /*
81  *      This is easier than ifdef's throughout the code.
82  */
83 #define PTHREAD_MUTEX_LOCK(_x)
84 #define PTHREAD_MUTEX_UNLOCK(_x)
85 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
86 {
87         radius_handle_request(request, fun);
88         return 1;
89 }
90 #endif
91
92 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
93
94 #ifdef WITH_PROXY
95 static fr_packet_list_t *proxy_list = NULL;
96
97 /*
98  *      We keep the proxy FD's here.  The RADIUS Id's are marked
99  *      "allocated" per Id, via a bit per proxy FD.
100  */
101 static int              proxy_fds[32];
102 static rad_listen_t     *proxy_listeners[32];
103 #else
104 #define remove_from_proxy_hash(foo)
105 #endif
106
107 static void request_post_handler(REQUEST *request);
108 static void wait_a_bit(void *ctx);
109 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
110 #ifdef WITH_DETAIL
111 static void event_poll_detail(void *ctx);
112 #endif
113
114 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
115                                     const char *msg)
116 {
117         radlog(L_ERR, "[%s:%d] %s", file, line, msg);
118         _exit(1);
119 }
120
121 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
122
123
124 static void tv_add(struct timeval *tv, int usec_delay)
125 {
126         if (usec_delay > USEC) {
127                 tv->tv_sec += usec_delay / USEC;
128                 usec_delay %= USEC;
129         }
130         tv->tv_usec += usec_delay;
131
132         if (tv->tv_usec > USEC) {
133                 tv->tv_usec -= USEC;
134                 tv->tv_sec++;
135         }
136 }
137
138 static void remove_from_request_hash(REQUEST *request)
139 {
140         if (!request->in_request_hash) return;
141
142         fr_packet_list_yank(pl, request->packet);
143         request->in_request_hash = FALSE;
144
145         request_stats_final(request);
146
147 #ifdef WITH_TCP
148         request->listener->count--;
149
150         /*
151          *      The TCP socket was closed, but we've got to
152          *      hang around until done.
153          */
154         if ((request->listener->status == RAD_LISTEN_STATUS_FINISH) &&
155             (request->listener->count == 0)) {
156                 listen_free(&request->listener);
157         }
158 #endif
159 }
160
161
162 #ifdef WITH_PROXY
163 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
164 {
165         RADIUS_PACKET **proxy_p;
166         REQUEST *request;
167
168         PTHREAD_MUTEX_LOCK(&proxy_mutex);
169         proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
170
171         if (!proxy_p) {
172                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
173                 return NULL;
174         }
175
176         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
177
178         if (!request) {
179                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
180                 return NULL;
181         }
182
183         request->num_proxied_responses++;
184
185         /*
186          *      Catch the most common case of everything working
187          *      correctly.
188          */
189         if (request->num_proxied_requests == request->num_proxied_responses) {
190                 fr_packet_list_yank(proxy_list, request->proxy);
191                 fr_packet_list_id_free(proxy_list, request->proxy);
192                 request->in_proxy_hash = FALSE;
193         }
194
195         /*
196          *      On the FIRST reply, decrement the count of outstanding
197          *      requests.  Note that this is NOT the count of sent
198          *      packets, but whether or not the home server has
199          *      responded at all.
200          */
201         if (!request->proxy_reply &&
202             request->home_server &&
203             request->home_server->currently_outstanding) {
204                 request->home_server->currently_outstanding--;
205         }
206
207         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
208
209         return request;
210 }
211
212
213 static void remove_from_proxy_hash(REQUEST *request)
214 {
215         /*
216          *      Check this without grabbing the mutex because it's a
217          *      lot faster that way.
218          */
219         if (!request->in_proxy_hash) return;
220
221         /*
222          *      The "not in hash" flag is definitive.  However, if the
223          *      flag says that it IS in the hash, there might still be
224          *      a race condition where it isn't.
225          */
226         PTHREAD_MUTEX_LOCK(&proxy_mutex);
227
228         if (!request->in_proxy_hash) {
229                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
230                 return;
231         }
232
233         fr_packet_list_yank(proxy_list, request->proxy);
234         fr_packet_list_id_free(proxy_list, request->proxy);
235
236         /*
237          *      The home server hasn't replied, but we've given up on
238          *      this request.  Don't count this request against the
239          *      home server.
240          */
241         if (!request->proxy_reply &&
242             request->home_server &&
243             request->home_server->currently_outstanding) {
244                 request->home_server->currently_outstanding--;
245         }
246
247         /*
248          *      Got from YES in hash, to NO, not in hash while we hold
249          *      the mutex.  This guarantees that when another thread
250          *      grans the mutex, the "not in hash" flag is correct.
251          */
252         request->in_proxy_hash = FALSE;
253
254         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
255 }
256
257 static void ev_request_free(REQUEST **prequest)
258 {
259         REQUEST *request;
260         
261         if (!prequest || !*prequest) return;
262
263         request = *prequest;
264
265 #ifdef WITH_COA
266         if (request->coa) {
267                 /*
268                  *      Divorce the child from the parent first,
269                  *      then clean up the child.
270                  */
271                 request->coa->parent = NULL;
272                 ev_request_free(&request->coa);
273         }
274
275         /*
276          *      Divorce the parent from the child, and leave the
277          *      parent still alive.
278          */
279         if (request->parent && (request->parent->coa == request)) {
280                 request->parent->coa = NULL;
281         }
282 #endif
283
284         if (request->ev) fr_event_delete(el, &request->ev);
285         if (request->in_proxy_hash) remove_from_proxy_hash(request);
286         if (request->in_request_hash) remove_from_request_hash(request);
287
288         request_free(prequest);
289 }
290
291 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
292 {
293         int i, proxy, found;
294         rad_listen_t *proxy_listener;
295
296         if (fr_packet_list_id_alloc(proxy_list, packet)) return 1;
297
298         /*
299          *      Allocate a new proxy fd.  This function adds
300          *      it to the tail of the list of listeners.  With
301          *      some care, this can be thread-safe.
302          */
303         proxy_listener = proxy_new_listener(&packet->src_ipaddr, FALSE);
304         if (!proxy_listener) {
305                 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
306                 return 0;
307         }
308         
309         /*
310          *      Cache it locally.
311          */
312         found = -1;
313         proxy = proxy_listener->fd;
314         for (i = 0; i < 32; i++) {
315                 /*
316                  *      Found a free entry.  Save the socket,
317                  *      and remember where we saved it.
318                  */
319                 if (proxy_fds[(proxy + i) & 0x1f] == -1) {
320                         found = (proxy + i) & 0x1f;
321                         proxy_fds[found] = proxy;
322                         proxy_listeners[found] = proxy_listener;
323                         break;
324                 }
325         }
326         rad_assert(found >= 0);
327         
328         if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
329                         RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
330                 return 0;
331                 
332         }
333         
334         if (!fr_packet_list_id_alloc(proxy_list, packet)) {
335                         RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
336                 return 0;
337         }
338         
339         /*
340          *      Signal the main thread to add the new FD to the list
341          *      of listening FD's.
342          */
343         radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
344         return 1;
345 }
346
347
348 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
349 {
350         int i, proxy;
351         char buf[128];
352
353         rad_assert(request->proxy != NULL);
354         rad_assert(proxy_list != NULL);
355
356         PTHREAD_MUTEX_LOCK(&proxy_mutex);
357
358         /*
359          *      Keep track of maximum outstanding requests to a
360          *      particular home server.  'max_outstanding' is
361          *      enforced in home_server_ldb(), in realms.c.
362          */
363         if (request->home_server) {
364                 request->home_server->currently_outstanding++;
365         }
366
367         if (retransmit) {
368                 RADIUS_PACKET packet;
369
370                 packet = *request->proxy;
371
372                 if (!proxy_id_alloc(request, &packet)) {
373                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
374                         return 0;
375                 }
376
377                 /*
378                  *      Yank the request, free the old Id, and
379                  *      remember the new Id.
380                  */
381                 fr_packet_list_yank(proxy_list, request->proxy);
382                 fr_packet_list_id_free(proxy_list, request->proxy);
383                 *request->proxy = packet;
384
385         } else if (!proxy_id_alloc(request, request->proxy)) {
386                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
387                 return 0;
388         }
389
390         rad_assert(request->proxy->sockfd >= 0);
391
392         /*
393          *      FIXME: Hack until we get rid of rad_listen_t, and put
394          *      the information into the packet_list.
395          */
396         proxy = -1;
397         for (i = 0; i < 32; i++) {
398                 if (proxy_fds[i] == request->proxy->sockfd) {
399                         proxy = i;
400                         break;
401                 }
402         }
403
404         if (proxy < 0) {
405                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
406                 RDEBUG2("ERROR: All sockets are full.");
407                 return 0;
408         }
409
410         rad_assert(proxy_fds[proxy] != -1);
411         rad_assert(proxy_listeners[proxy] != NULL);
412         request->proxy_listener = proxy_listeners[proxy];
413
414         if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
415                 fr_packet_list_id_free(proxy_list, request->proxy);
416                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
417                 RDEBUG2("ERROR: Failed to insert entry into proxy list");
418                 return 0;
419         }
420
421         request->in_proxy_hash = TRUE;
422
423         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
424
425         RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
426                inet_ntop(request->proxy->dst_ipaddr.af,
427                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
428                request->proxy->dst_port,
429                request->proxy->id);
430
431         return 1;
432 }
433
434
435 /*
436  *      Called as BOTH an event, and in-line from other functions.
437  */
438 static void wait_for_proxy_id_to_expire(void *ctx)
439 {
440         REQUEST *request = ctx;
441
442         rad_assert(request->magic == REQUEST_MAGIC);
443         rad_assert(request->proxy != NULL);
444
445         if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
446         request->when = request->proxy_when;
447
448 #ifdef WITH_COA
449         if (((request->proxy->code == PW_COA_REQUEST) ||
450              (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
451             (request->packet->code != request->proxy->code)) {
452                 request->when.tv_sec += request->home_server->coa_mrd;
453         } else
454 #endif
455         request->when.tv_sec += request->home_server->response_window;
456
457         if ((request->num_proxied_requests == request->num_proxied_responses) ||
458             timercmp(&now, &request->when, >)) {
459                 if (request->packet) {
460                         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
461                                request->number, request->packet->id,
462                                (unsigned int) (request->timestamp - fr_start_time));
463                 } else {
464                         RDEBUG2("Cleaning up request %d with timestamp +%d",
465                                request->number,
466                                (unsigned int) (request->timestamp - fr_start_time));
467                 }
468
469                 ev_request_free(&request);
470                 return;
471         }
472
473         INSERT_EVENT(wait_for_proxy_id_to_expire, request);
474 }
475 #endif
476
477 #ifdef HAVE_PTHREAD_H
478 static void wait_for_child_to_die(void *ctx)
479 {
480         REQUEST *request = ctx;
481
482         rad_assert(request->magic == REQUEST_MAGIC);
483
484         if ((request->child_state == REQUEST_QUEUED) |
485             (request->child_state == REQUEST_RUNNING)) {
486                 request->delay += (request->delay >> 1);
487                 tv_add(&request->when, request->delay);
488
489                 RDEBUG2("Child is still stuck for request %d", request->number);
490
491                 INSERT_EVENT(wait_for_child_to_die, request);
492                 return;
493         }
494
495         RDEBUG2("Child is finally responsive for request %d", request->number);
496         remove_from_request_hash(request);
497
498 #ifdef WITH_PROXY
499         if (request->proxy) {
500                 wait_for_proxy_id_to_expire(request);
501                 return;
502         }
503 #endif
504
505         ev_request_free(&request);
506 }
507 #endif
508
509 static void cleanup_delay(void *ctx)
510 {
511         REQUEST *request = ctx;
512
513         rad_assert(request->magic == REQUEST_MAGIC);
514         rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
515                    (request->child_state == REQUEST_DONE));
516
517         remove_from_request_hash(request);
518
519 #ifdef WITH_PROXY
520         if (request->proxy && request->in_proxy_hash) {
521                 wait_for_proxy_id_to_expire(request);
522                 return;
523         }
524 #endif
525
526         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
527                request->number, request->packet->id,
528                (unsigned int) (request->timestamp - fr_start_time));
529
530         ev_request_free(&request);
531 }
532
533
534 /*
535  *      In daemon mode, AND this request has debug flags set.
536  */
537 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
538
539 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
540 {
541         VALUE_PAIR *vp;
542         char buffer[1024];
543         const char *received, *from;
544         const fr_ipaddr_t *ip;
545         int port;
546
547         if (!packet) return;
548
549         rad_assert(request->radlog != NULL);
550
551         if (direction == 0) {
552                 received = "Received";
553                 from = "from";  /* what else? */
554                 ip = &packet->src_ipaddr;
555                 port = packet->src_port;
556
557         } else {
558                 received = "Sending";
559                 from = "to";    /* hah! */
560                 ip = &packet->dst_ipaddr;
561                 port = packet->dst_port;
562         }
563         
564         /*
565          *      Client-specific debugging re-prints the input
566          *      packet into the client log.
567          *
568          *      This really belongs in a utility library
569          */
570         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
571                 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
572                        received, fr_packet_codes[packet->code], from,
573                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
574                        port, packet->id, packet->data_len);
575         } else {
576                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
577                        received, from,
578                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
579                        port,
580                        packet->code, packet->id, packet->data_len);
581         }
582
583         for (vp = packet->vps; vp != NULL; vp = vp->next) {
584                 vp_prints(buffer, sizeof(buffer), vp);
585                 request->radlog(L_DBG, 0, request, "\t%s", buffer);
586         }
587 }
588
589 static void reject_delay(void *ctx)
590 {
591         REQUEST *request = ctx;
592
593         rad_assert(request->magic == REQUEST_MAGIC);
594         rad_assert(request->child_state == REQUEST_REJECT_DELAY);
595
596         RDEBUG2("Sending delayed reject for request %d", request->number);
597
598         DEBUG_PACKET(request, request->reply, 1);
599
600         request->listener->send(request->listener, request);
601
602         request->when.tv_sec += request->root->cleanup_delay;
603         request->child_state = REQUEST_CLEANUP_DELAY;
604
605         INSERT_EVENT(cleanup_delay, request);
606 }
607
608
609 #ifdef WITH_PROXY
610 void revive_home_server(void *ctx)
611 {
612         home_server *home = ctx;
613         char buffer[128];
614
615         home->state = HOME_STATE_ALIVE;
616         home->currently_outstanding = 0;
617         home->revive_time = now;
618
619         /*
620          *      Delete any outstanding events.
621          */
622         if (home->ev) fr_event_delete(el, &home->ev);
623
624         radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
625                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
626                          buffer, sizeof(buffer)),
627                home->port);
628
629 }
630
631
632 static void no_response_to_ping(void *ctx)
633 {
634         REQUEST *request = ctx;
635         home_server *home;
636         char buffer[128];
637
638         rad_assert(request->home_server != NULL);
639
640         home = request->home_server;
641         home->num_received_pings = 0;
642
643         RDEBUG2("No response to status check %d from home server %s port %d",
644                request->number,
645                inet_ntop(request->proxy->dst_ipaddr.af,
646                          &request->proxy->dst_ipaddr.ipaddr,
647                          buffer, sizeof(buffer)),
648                request->proxy->dst_port);
649
650         wait_for_proxy_id_to_expire(request);
651 }
652
653
654 static void received_response_to_ping(REQUEST *request)
655 {
656         home_server *home;
657         char buffer[128];
658
659         rad_assert(request->home_server != NULL);
660
661         home = request->home_server;
662         home->num_received_pings++;
663
664         RDEBUG2("Received response to status check %d (%d in current sequence)",
665                request->number, home->num_received_pings);
666
667         /*
668          *      Remove the request from any hashes
669          */
670         fr_event_delete(el, &request->ev);
671         remove_from_proxy_hash(request);
672         rad_assert(request->in_request_hash == FALSE);
673
674         /*
675          *      The control socket may have marked the home server as
676          *      alive.  OR, it may have suddenly started responding to
677          *      requests again.  If so, don't re-do the "make alive"
678          *      work.
679          */
680         if (home->state == HOME_STATE_ALIVE) return;
681
682         /*
683          *      We haven't received enough ping responses to mark it
684          *      "alive".  Wait a bit.
685          */
686         if (home->num_received_pings < home->num_pings_to_alive) {
687                 return;
688         }
689
690         home->state = HOME_STATE_ALIVE;
691         home->currently_outstanding = 0;
692         home->revive_time = now;
693
694         if (!fr_event_delete(el, &home->ev)) {
695                 RDEBUG2("Hmm... no event for home server.  Oh well.");
696         }
697
698         radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
699                inet_ntop(request->proxy->dst_ipaddr.af,
700                          &request->proxy->dst_ipaddr.ipaddr,
701                          buffer, sizeof(buffer)),
702                request->proxy->dst_port);
703 }
704
705
706 /*
707  *      Called from start of zombie period, OR after control socket
708  *      marks the home server dead.
709  */
710 static void ping_home_server(void *ctx)
711 {
712         uint32_t jitter;
713         home_server *home = ctx;
714         REQUEST *request;
715         VALUE_PAIR *vp;
716
717         if ((home->state == HOME_STATE_ALIVE) ||
718             (home->ping_check == HOME_PING_CHECK_NONE) ||
719             (home->ev != NULL)) {
720                 return;
721         }
722
723         request = request_alloc();
724         request->number = request_num_counter++;
725
726         request->proxy = rad_alloc(1);
727         rad_assert(request->proxy != NULL);
728
729         fr_event_now(el, &request->when);
730         home->when = request->when;
731
732         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
733                 request->proxy->code = PW_STATUS_SERVER;
734
735                 radius_pairmake(request, &request->proxy->vps,
736                                 "Message-Authenticator", "0x00", T_OP_SET);
737
738         } else if (home->type == HOME_TYPE_AUTH) {
739                 request->proxy->code = PW_AUTHENTICATION_REQUEST;
740
741                 radius_pairmake(request, &request->proxy->vps,
742                                 "User-Name", home->ping_user_name, T_OP_SET);
743                 radius_pairmake(request, &request->proxy->vps,
744                                 "User-Password", home->ping_user_password, T_OP_SET);
745                 radius_pairmake(request, &request->proxy->vps,
746                                 "Service-Type", "Authenticate-Only", T_OP_SET);
747                 radius_pairmake(request, &request->proxy->vps,
748                                 "Message-Authenticator", "0x00", T_OP_SET);
749
750         } else {
751 #ifdef WITH_ACCOUNTING
752                 request->proxy->code = PW_ACCOUNTING_REQUEST;
753                 
754                 radius_pairmake(request, &request->proxy->vps,
755                                 "User-Name", home->ping_user_name, T_OP_SET);
756                 radius_pairmake(request, &request->proxy->vps,
757                                 "Acct-Status-Type", "Stop", T_OP_SET);
758                 radius_pairmake(request, &request->proxy->vps,
759                                 "Acct-Session-Id", "00000000", T_OP_SET);
760                 vp = radius_pairmake(request, &request->proxy->vps,
761                                      "Event-Timestamp", "0", T_OP_SET);
762                 vp->vp_date = now.tv_sec;
763 #else
764                 rad_assert("Internal sanity check failed");
765 #endif
766         }
767
768         radius_pairmake(request, &request->proxy->vps,
769                         "NAS-Identifier", "Status Check. Are you alive?",
770                         T_OP_SET);
771
772         request->proxy->dst_ipaddr = home->ipaddr;
773         request->proxy->dst_port = home->port;
774         request->home_server = home;
775
776         rad_assert(request->proxy_listener == NULL);
777
778         if (!insert_into_proxy_hash(request, FALSE)) {
779                 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash.  Discarding it.",
780                        request->number);
781                 ev_request_free(&request);
782                 return;
783         }
784         rad_assert(request->proxy_listener != NULL);
785         request->proxy_listener->send(request->proxy_listener,
786                                       request);
787
788         request->next_callback = NULL;
789         request->child_state = REQUEST_PROXIED;
790         request->when.tv_sec += home->ping_timeout;;
791
792         INSERT_EVENT(no_response_to_ping, request);
793
794         /*
795          *      Add +/- 2s of jitter, as suggested in RFC 3539
796          *      and in the Issues and Fixes draft.
797          */
798         home->when.tv_sec += home->ping_interval - 2;
799
800         jitter = fr_rand();
801         jitter ^= (jitter >> 10);
802         jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
803
804         tv_add(&home->when, jitter);
805
806         INSERT_EVENT(ping_home_server, home);
807 }
808
809
810 void mark_home_server_dead(home_server *home, struct timeval *when)
811 {
812         int previous_state = home->state;
813         char buffer[128];
814
815         radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
816                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
817                          buffer, sizeof(buffer)),
818                home->port);
819
820         home->state = HOME_STATE_IS_DEAD;
821         home->num_received_pings = 0;
822
823         if (home->ping_check != HOME_PING_CHECK_NONE) {
824                 /*
825                  *      If the control socket marks us dead, start
826                  *      pinging.  Otherwise, we already started
827                  *      pinging when it was marked "zombie".
828                  */
829                 if (previous_state == HOME_STATE_ALIVE) {
830                         ping_home_server(home);
831                 }
832
833         } else {
834                 /*
835                  *      Revive it after a fixed period of time.  This
836                  *      is very, very, bad.
837                  */
838                 home->when = *when;
839                 home->when.tv_sec += home->revive_interval;
840
841                 INSERT_EVENT(revive_home_server, home);
842         }
843 }
844
845 static void check_for_zombie_home_server(REQUEST *request)
846 {
847         home_server *home;
848         struct timeval when;
849
850         home = request->home_server;
851
852         if (home->state != HOME_STATE_ZOMBIE) return;
853
854         when = home->zombie_period_start;
855         when.tv_sec += home->zombie_period;
856
857         fr_event_now(el, &now);
858         if (timercmp(&now, &when, <)) {
859                 return;
860         }
861
862         mark_home_server_dead(home, &request->when);
863 }
864
865 static int proxy_to_virtual_server(REQUEST *request);
866
867 static int virtual_server_handler(UNUSED REQUEST *request)
868 {
869         proxy_to_virtual_server(request);
870         return 0;
871 }
872
873 static void proxy_fallback_handler(REQUEST *request)
874 {
875         /*
876          *      A proper time is required for wait_a_bit.
877          */
878         request->delay = USEC / 10;
879         gettimeofday(&now, NULL);
880         request->next_when = now;
881         tv_add(&request->next_when, request->delay);
882         request->next_callback = wait_a_bit;
883
884         /*
885          *      Re-queue the request.
886          */
887         request->child_state = REQUEST_QUEUED;
888         
889         rad_assert(request->proxy != NULL);
890         if (!thread_pool_addrequest(request, virtual_server_handler)) {
891                 request->child_state = REQUEST_DONE;
892         }
893
894 #ifdef HAVE_PTHREAD_H
895         /*
896          *      MAY free the request if we're over max_request_time,
897          *      AND we're not in threaded mode!
898          *
899          *      Note that we call this ONLY if we're threaded, as
900          *      if we're NOT threaded, request_post_handler() calls
901          *      wait_a_bit(), which means that "request" may not
902          *      exist any more...
903          */
904         if (have_children) wait_a_bit(request);
905 #endif
906 }
907
908
909 static int setup_post_proxy_fail(REQUEST *request)
910 {
911         DICT_VALUE *dval = NULL;
912         VALUE_PAIR *vp;
913
914         request->child_state = REQUEST_RUNNING;
915
916         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
917                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
918
919         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
920                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
921
922 #ifdef WITH_COA
923                 /*
924                  *      See no_response_to_coa_request
925                  */
926         } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
927                 request->packet->code &= 0xff; /* restore it */
928
929                 if (request->proxy->code == PW_COA_REQUEST) {
930                         dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
931
932                 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
933                         dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
934                 } else {
935                         return 0;
936                 }
937
938 #endif
939         } else {
940                 return 0;
941         }
942
943         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
944
945         if (!dval) {
946                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
947                 return 0;
948         }
949
950         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
951         if (!vp) vp = radius_paircreate(request, &request->config_items,
952                                         PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
953         vp->vp_integer = dval->value;
954
955         rad_assert(request->proxy_reply == NULL);
956
957         return 1;
958 }
959
960
961 static int null_handler(UNUSED REQUEST *request)
962 {
963         return 0;
964 }
965
966 static void post_proxy_fail_handler(REQUEST *request)
967 {
968         /*
969          *      A proper time is required for wait_a_bit.
970          */
971         request->delay = USEC / 10;
972         gettimeofday(&now, NULL);
973
974         /*
975          *      Not set up to run Post-Proxy-Type = Fail.
976          *
977          *      Mark the request as still running, and figure out what
978          *      to do next.
979          */
980         if (!setup_post_proxy_fail(request)) {
981                 request_post_handler(request);
982
983         } else {
984                 /*
985                  *      Re-queue the request.
986                  */
987                 request->child_state = REQUEST_QUEUED;
988
989                 /*
990                  *      There is a post-proxy-type of fail.  We run
991                  *      the request through the pre/post proxy
992                  *      handlers, just like it was a real proxied
993                  *      request.  However, we set the per-request
994                  *      handler to NULL, as we don't want to do
995                  *      anything else.
996                  *
997                  *      Note that when we're not threaded, this will
998                  *      process the request even if it's greater than
999                  *      max_request_time.  That's not fatal.
1000                  */
1001                 request->priority = 0;
1002                 rad_assert(request->proxy != NULL);
1003                 thread_pool_addrequest(request, null_handler);
1004         }
1005
1006         /*
1007          *      MAY free the request if we're over max_request_time,
1008          *      AND we're not in threaded mode!
1009          *
1010          *      Note that we call this ONLY if we're threaded, as
1011          *      if we're NOT threaded, request_post_handler() calls
1012          *      wait_a_bit(), which means that "request" may not
1013          *      exist any more...
1014          */
1015         if (have_children) wait_a_bit(request);
1016 }
1017
1018
1019 /* maybe check this against wait_for_proxy_id_to_expire? */
1020 static void no_response_to_proxied_request(void *ctx)
1021 {
1022         REQUEST *request = ctx;
1023         home_server *home;
1024         char buffer[128];
1025
1026         rad_assert(request->magic == REQUEST_MAGIC);
1027         rad_assert(request->child_state == REQUEST_PROXIED);
1028
1029         /*
1030          *      If we've failed over to an internal home server,
1031          *      replace the callback with the correct one.  This
1032          *      is due to locking issues with child threads...
1033          */
1034         if (request->home_server->server) {
1035                 wait_a_bit(request);
1036                 return;
1037         }
1038
1039         check_for_zombie_home_server(request);
1040
1041         home = request->home_server;
1042
1043         /*
1044          *      The default as of 2.1.7 is to allow requests to
1045          *      fail-over to a backup home server when this one does
1046          *      not respond.  The old behavior can be configured as
1047          *      well.
1048          */
1049         if (home->no_response_fail) {
1050                 radlog(L_ERR, "Rejecting request %d (proxy Id %d) due to lack of any response from home server %s port %d",
1051                        request->number, request->proxy->id,
1052                        inet_ntop(request->proxy->dst_ipaddr.af,
1053                                  &request->proxy->dst_ipaddr.ipaddr,
1054                                  buffer, sizeof(buffer)),
1055                        request->proxy->dst_port);
1056
1057                 post_proxy_fail_handler(request);
1058         }
1059
1060         /*
1061          *      Don't touch request due to race conditions
1062          */
1063         if (home->state == HOME_STATE_IS_DEAD) {
1064                 rad_assert(home->ev != NULL); /* or it will never wake up */
1065                 return;
1066         }
1067
1068         /*
1069          *      Enable the zombie period when we notice that the home
1070          *      server hasn't responded.  We do NOT back-date the start
1071          *      of the zombie period.
1072          */
1073         if (home->state == HOME_STATE_ALIVE) {
1074                 home->state = HOME_STATE_ZOMBIE;
1075                 home->zombie_period_start = now;        
1076
1077                 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1078                        inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1079                                  buffer, sizeof(buffer)),
1080                        home->port);
1081
1082                 /*
1083                  *      Start pinging the home server.
1084                  */
1085                 ping_home_server(home);
1086         }
1087 }
1088 #endif
1089
1090 static void wait_a_bit(void *ctx)
1091 {
1092         struct timeval when;
1093         REQUEST *request = ctx;
1094         fr_event_callback_t callback = NULL;
1095
1096         rad_assert(request->magic == REQUEST_MAGIC);
1097
1098         /*
1099          *      The socket was closed.  Tell the request that
1100          *      there is no point in continuing.
1101          */
1102         if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
1103                 goto stop_processing;
1104         }
1105
1106 #ifdef WITH_COA
1107         /*
1108          *      The CoA request is a new (internally generated)
1109          *      request, created in a child thread.  We therefore need
1110          *      some way to tie its events back into the main event
1111          *      handler.
1112          */
1113         if (request->coa && !request->coa->proxy_reply &&
1114             request->coa->next_callback) {
1115                 request->coa->when = request->coa->next_when;
1116                 INSERT_EVENT(request->coa->next_callback, request->coa);
1117                 request->coa->next_callback = NULL;
1118                 request->coa->parent = NULL;
1119                 request->coa = NULL;
1120         }
1121 #endif
1122
1123         switch (request->child_state) {
1124         case REQUEST_QUEUED:
1125         case REQUEST_RUNNING:
1126                 when = request->received;
1127                 when.tv_sec += request->root->max_request_time;
1128
1129                 /*
1130                  *      Normally called from the event loop with the
1131                  *      proper event loop time.  Otherwise, called from
1132                  *      post proxy fail handler, which sets "now", and
1133                  *      this call won't re-set it, because we're not
1134                  *      in the event loop.
1135                  */
1136                 fr_event_now(el, &now);
1137
1138                 /*
1139                  *      Request still has more time.  Continue
1140                  *      waiting.
1141                  */
1142                 if (timercmp(&now, &when, <) ||
1143                     ((request->listener->type == RAD_LISTEN_DETAIL) &&
1144                      (request->child_state == REQUEST_QUEUED))) {
1145                         if (request->delay < (USEC / 10)) {
1146                                 request->delay = USEC / 10;
1147                         }
1148                         request->delay += request->delay >> 1;
1149
1150 #ifdef WITH_DETAIL
1151                         /*
1152                          *      Cap wait at some sane value for detail
1153                          *      files.
1154                          */
1155                         if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1156                             (request->delay > (request->root->max_request_time * USEC))) {
1157                                 request->delay = request->root->max_request_time * USEC;
1158                         }
1159 #endif
1160
1161                         request->when = now;
1162                         tv_add(&request->when, request->delay);
1163                         callback = wait_a_bit;
1164                         break;
1165                 }
1166
1167 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1168                 /*
1169                  *      A child thread MAY still be running on the
1170                  *      request.  Ask the thread to stop working on
1171                  *      the request.
1172                  */
1173                 if (have_children) {
1174                         /* FIXME: kill unresponsive children? */
1175
1176                         /*
1177                          *      Print this error message ONLY if
1178                          *      there's a child currently processing
1179                          *      the request.  As we don't have thread
1180                          *      locks here, there may be race
1181                          *      conditions on this check.  But it's
1182                          *      just an error message, so that's OK.
1183                          */
1184                         if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1185                                 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1186                                        request->number,
1187                                        request->module ? request->module : "<server core>",
1188                                        request->component ? request->component : "<server core>");
1189                         }
1190
1191                 stop_processing:
1192                         request->master_state = REQUEST_STOP_PROCESSING;
1193                         
1194                         request->delay = USEC / 4;
1195                         tv_add(&request->when, request->delay);
1196                         callback = wait_for_child_to_die;
1197                         break;
1198                 }
1199 #else  /* no child threads */
1200         stop_processing:
1201 #endif
1202
1203                 /*
1204                  *      Else there are no child threads.  We probably
1205                  *      should have just marked the request as 'done'
1206                  *      elsewhere, like in the post-proxy-fail
1207                  *      handler.  But doing that would involve
1208                  *      checking for max_request_time in multiple
1209                  *      places, so this may be simplest.
1210                  */
1211                 request->child_state = REQUEST_DONE;
1212                 /* FALL-THROUGH */
1213
1214                 /*
1215                  *      Mark the request as no longer running,
1216                  *      and clean it up.
1217                  */
1218         case REQUEST_DONE:
1219 #ifdef HAVE_PTHREAD_H
1220                 request->child_pid = NO_SUCH_CHILD_PID;
1221 #endif
1222
1223 #ifdef WTH_COA
1224                 /*
1225                  *      This is a CoA request.  It's been divorced
1226                  *      from everything else, so we clean it up now.
1227                  */
1228                 if (!request->in_request_hash &&
1229                     request->proxy &&
1230                     (request->packet->code != request->proxy->code) &&
1231                     ((request->proxy->code == PW_COA_REQUEST) ||
1232                      (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1233                         /*
1234                          *      FIXME: Do CoA MIBs
1235                          */
1236                         ev_request_free(&request);
1237                         return;
1238                 }
1239 #endif
1240                 request_stats_final(request);
1241                 cleanup_delay(request);
1242                 return;
1243
1244         case REQUEST_REJECT_DELAY:
1245         case REQUEST_CLEANUP_DELAY:
1246 #ifdef HAVE_PTHREAD_H
1247                 request->child_pid = NO_SUCH_CHILD_PID;
1248 #endif
1249                 request_stats_final(request);
1250
1251         case REQUEST_PROXIED:
1252                 rad_assert(request->next_callback != NULL);
1253                 rad_assert(request->next_callback != wait_a_bit);
1254
1255                 request->when = request->next_when;
1256                 callback = request->next_callback;
1257                 request->next_callback = NULL;
1258                 break;
1259
1260         default:
1261                 rad_panic("Internal sanity check failure");
1262                 return;
1263         }
1264
1265         /*
1266          *      Something major went wrong.  Discard the request, and
1267          *      keep running.
1268          *
1269          *      FIXME: No idea why this happens or how to fix it...
1270          *      It seems to happen *only* when requests are proxied,
1271          *      and where the home server doesn't respond.  So it looks
1272          *      like a race condition above, but it happens in debug
1273          *      mode, with no threads...
1274          */
1275         if (!callback) {
1276                 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1277                 ev_request_free(&request);
1278                 return;
1279         }
1280
1281         INSERT_EVENT(callback, request);
1282 }
1283
1284 #ifdef WITH_COA
1285 static void no_response_to_coa_request(void *ctx)
1286 {
1287         REQUEST *request = ctx;
1288         char buffer[128];
1289
1290         rad_assert(request->magic == REQUEST_MAGIC);
1291         rad_assert(request->child_state == REQUEST_PROXIED);
1292         rad_assert(request->home_server != NULL);
1293         rad_assert(!request->in_request_hash);
1294
1295         radlog(L_ERR, "No response to CoA request sent to %s",
1296                inet_ntop(request->proxy->dst_ipaddr.af,
1297                          &request->proxy->dst_ipaddr.ipaddr,
1298                          buffer, sizeof(buffer)));
1299
1300         /*
1301          *      Hack.
1302          */
1303         request->packet->code |= (PW_COA_REQUEST << 8);
1304         post_proxy_fail_handler(request);
1305 }
1306
1307
1308 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1309 {
1310         VALUE_PAIR *vp;
1311
1312         vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1313         if (!vp) return 0;
1314
1315         vp->vp_date = when;
1316
1317         if (packet->data) {
1318                 free(packet->data);
1319                 packet->data = NULL;
1320                 packet->data_len = 0;
1321         }
1322
1323         return 1;               /* time stamp updated */
1324 }
1325
1326
1327 /*
1328  *      Called when we haven't received a response to a CoA request.
1329  */
1330 static void retransmit_coa_request(void *ctx)
1331 {
1332         int delay, frac;
1333         struct timeval mrd;
1334         REQUEST *request = ctx;
1335
1336         rad_assert(request->magic == REQUEST_MAGIC);
1337         rad_assert(request->child_state == REQUEST_PROXIED);
1338         rad_assert(request->home_server != NULL);
1339         rad_assert(!request->in_request_hash);
1340         rad_assert(request->parent == NULL);
1341         
1342         fr_event_now(el, &now);
1343
1344         /*
1345          *      Cap count at MRC, if it is non-zero.
1346          */
1347         if (request->home_server->coa_mrc &&
1348             (request->num_coa_requests >= request->home_server->coa_mrc)) {
1349                 no_response_to_coa_request(request);
1350                 return;
1351         }
1352
1353         /*
1354          *      RFC 5080 Section 2.2.1
1355          *
1356          *      RT = 2*RTprev + RAND*RTprev
1357          *         = 1.9 * RTprev + rand(0,.2) * RTprev
1358          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1359          */
1360         delay = fr_rand();
1361         delay ^= (delay >> 16);
1362         delay &= 0xffff;
1363         frac = request->delay / 5;
1364         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1365
1366         delay += (2 * request->delay) - (request->delay / 10);
1367
1368         /*
1369          *      Cap delay at MRT, if MRT is non-zero.
1370          */
1371         if (request->home_server->coa_mrt &&
1372             (delay > (request->home_server->coa_mrt * USEC))) {
1373                 int mrt_usec = request->home_server->coa_mrt * USEC;
1374
1375                 /*
1376                  *      delay = MRT + RAND * MRT
1377                  *            = 0.9 MRT + rand(0,.2)  * MRT
1378                  */
1379                 delay = fr_rand();
1380                 delay ^= (delay >> 15);
1381                 delay &= 0x1ffff;
1382                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1383                 delay += mrt_usec - (mrt_usec / 10);
1384         }
1385
1386         request->delay = delay;
1387         request->when = now;
1388         tv_add(&request->when, request->delay);
1389         mrd = request->proxy_when;
1390         mrd.tv_sec += request->home_server->coa_mrd;
1391
1392         /*
1393          *      Cap duration at MRD.
1394          */
1395         if (timercmp(&mrd, &request->when, <)) {
1396                 request->when = mrd;
1397                 INSERT_EVENT(no_response_to_coa_request, request);
1398
1399         } else {
1400                 INSERT_EVENT(retransmit_coa_request, request);
1401         }
1402         
1403         if (update_event_timestamp(request->proxy, now.tv_sec)) {
1404                 if (!insert_into_proxy_hash(request, TRUE)) {
1405                         DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1406                         return;
1407                 }
1408
1409                 request->num_proxied_requests = 0;
1410                 request->num_proxied_responses = 0;
1411         }
1412
1413         request->num_proxied_requests++;
1414         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1415
1416         request->proxy_listener->send(request->proxy_listener,
1417                                       request);
1418 }
1419
1420
1421 /*
1422  *      The original request is either DONE, or in CLEANUP_DELAY.
1423  */
1424 static int originated_coa_request(REQUEST *request)
1425 {
1426         int delay, rcode, pre_proxy_type = 0;
1427         VALUE_PAIR *vp;
1428         REQUEST *coa;
1429         fr_ipaddr_t ipaddr;
1430         char buffer[256];
1431
1432         rad_assert(request->proxy == NULL);
1433         rad_assert(!request->in_proxy_hash);
1434         rad_assert(request->proxy_reply == NULL);
1435
1436         vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1437         if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1438         if (vp) {
1439                 if (vp->vp_integer == 0) {
1440                         ev_request_free(&request->coa);
1441                         return 1;       /* success */
1442                 }
1443
1444                 if (!request->coa) request_alloc_coa(request);
1445                 if (!request->coa) return 0;
1446         }
1447
1448         coa = request->coa;
1449
1450         /*
1451          *      src_ipaddr will be set up in proxy_encode.
1452          */
1453         memset(&ipaddr, 0, sizeof(ipaddr));
1454         vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1455         if (vp) {
1456                 ipaddr.af = AF_INET;
1457                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1458
1459         } else if ((vp = pairfind(coa->proxy->vps,
1460                                   PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1461                 ipaddr.af = AF_INET6;
1462                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1463                 
1464         } else if ((vp = pairfind(coa->proxy->vps,
1465                                   PW_HOME_SERVER_POOL)) != NULL) {
1466                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1467                                                   HOME_TYPE_COA);
1468                 if (!coa->home_pool) {
1469                         RDEBUG2("WARNING: No such home_server_pool %s",
1470                                vp->vp_strvalue);
1471         fail:
1472                         ev_request_free(&request->coa);
1473                         return 0;
1474                 }
1475
1476                 /*
1477                  *      Prefer
1478                  */
1479         } else if (request->client->coa_pool) {
1480                 coa->home_pool = request->client->coa_pool;
1481
1482         } else if (request->client->coa_server) {
1483                 coa->home_server = request->client->coa_server;
1484
1485         } else {
1486                 /*
1487                  *      If all else fails, send it to the client that
1488                  *      originated this request.
1489                  */
1490                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1491         }
1492
1493         /*
1494          *      Use the pool, if it exists.
1495          */
1496         if (coa->home_pool) {
1497                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1498                 if (!coa->home_server) {
1499                         RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1500                         goto fail;
1501                 }
1502
1503         } else if (!coa->home_server) {
1504                 int port = PW_COA_UDP_PORT;
1505
1506                 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1507                 if (vp) port = vp->vp_integer;
1508
1509                 coa->home_server = home_server_find(&ipaddr, port);
1510                 if (!coa->home_server) {
1511                         RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1512                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1513                                          buffer, sizeof(buffer)), port);
1514                         goto fail;
1515                 }
1516         }
1517
1518         vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1519         if (vp) {
1520                 switch (vp->vp_integer) {
1521                 case PW_COA_REQUEST:
1522                 case PW_DISCONNECT_REQUEST:
1523                         coa->proxy->code = vp->vp_integer;
1524                         break;
1525                         
1526                 default:
1527                         DEBUG("Cannot set CoA Packet-Type to code %d",
1528                               vp->vp_integer);
1529                         goto fail;
1530                 }
1531         }
1532
1533         if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1534
1535         /*
1536          *      The rest of the server code assumes that
1537          *      request->packet && request->reply exist.  Copy them
1538          *      from the original request.
1539          */
1540         rad_assert(coa->packet != NULL);
1541         rad_assert(coa->packet->vps == NULL);
1542         memcpy(coa->packet, request->packet, sizeof(*request->packet));
1543         coa->packet->vps = paircopy(request->packet->vps);
1544         coa->packet->data = NULL;
1545         rad_assert(coa->reply != NULL);
1546         rad_assert(coa->reply->vps == NULL);
1547         memcpy(coa->reply, request->reply, sizeof(*request->reply));
1548         coa->reply->vps = paircopy(request->reply->vps);
1549         coa->reply->data = NULL;
1550         coa->config_items = paircopy(request->config_items);
1551
1552         /*
1553          *      Call the pre-proxy routines.
1554          */
1555         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1556         if (vp) {
1557                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
1558                 pre_proxy_type = vp->vp_integer;
1559         }
1560
1561         if (coa->home_pool && coa->home_pool->virtual_server) {
1562                 const char *old_server = coa->server;
1563                 
1564                 coa->server = coa->home_pool->virtual_server;
1565                 RDEBUG2(" server %s {", coa->server);
1566                 rcode = module_pre_proxy(pre_proxy_type, coa);
1567                 RDEBUG2(" }");
1568                 coa->server = old_server;
1569         } else {
1570                 rcode = module_pre_proxy(pre_proxy_type, coa);
1571         }
1572         switch (rcode) {
1573         default:
1574                 goto fail;
1575
1576         /*
1577          *      Only send the CoA packet if the pre-proxy code succeeded.
1578          */
1579         case RLM_MODULE_NOOP:
1580         case RLM_MODULE_OK:
1581         case RLM_MODULE_UPDATED:
1582                 break;
1583         }
1584
1585         /*
1586          *      Source IP / port is set when the proxy socket
1587          *      is chosen.
1588          */
1589         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1590         coa->proxy->dst_port = coa->home_server->port;
1591
1592         if (!insert_into_proxy_hash(coa, FALSE)) {
1593                 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1594                 goto fail;
1595         }
1596
1597         /*
1598          *      We CANNOT divorce the CoA request from the parent
1599          *      request.  This function is running in a child thread,
1600          *      and we need access to the main event loop in order to
1601          *      to add the timers for the CoA packet.  See
1602          *      wait_a_bit().
1603          */
1604
1605         /*
1606          *      Forget about the original request completely at this
1607          *      point.
1608          */
1609         request = coa;
1610
1611         gettimeofday(&request->proxy_when, NULL);       
1612         request->received = request->next_when = request->proxy_when;
1613         rad_assert(request->proxy_reply == NULL);
1614
1615         /*
1616          *      Implement re-transmit algorithm as per RFC 5080
1617          *      Section 2.2.1.
1618          *
1619          *      We want IRT + RAND*IRT
1620          *      or 0.9 IRT + rand(0,.2) IRT
1621          *
1622          *      2^20 ~ USEC, and we want 2.
1623          *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1624          */
1625         delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1626         request->delay = delay * request->home_server->coa_irt;
1627         delay = request->home_server->coa_irt * USEC;
1628         delay -= delay / 10;
1629         delay += request->delay;
1630      
1631         request->delay = delay;
1632         tv_add(&request->next_when, delay);
1633         request->next_callback = retransmit_coa_request;
1634         
1635         /*
1636          *      Note that we set proxied BEFORE sending the packet.
1637          *
1638          *      Once we send it, the request is tainted, as
1639          *      another thread may have picked it up.  Don't
1640          *      touch it!
1641          */
1642         request->num_proxied_requests = 1;
1643         request->num_proxied_responses = 0;
1644         request->child_pid = NO_SUCH_CHILD_PID;
1645
1646         update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1647
1648         request->child_state = REQUEST_PROXIED;
1649
1650         DEBUG_PACKET(request, request->proxy, 1);
1651
1652         request->proxy_listener->send(request->proxy_listener,
1653                                       request);
1654         return 1;
1655 }
1656 #endif  /* WITH_COA */
1657
1658 #ifdef WITH_PROXY
1659 static int process_proxy_reply(REQUEST *request)
1660 {
1661         int rcode;
1662         int post_proxy_type = 0;
1663         VALUE_PAIR *vp;
1664         
1665         /*
1666          *      Delete any reply we had accumulated until now.
1667          */
1668         pairfree(&request->reply->vps);
1669         
1670         /*
1671          *      Run the packet through the post-proxy stage,
1672          *      BEFORE playing games with the attributes.
1673          */
1674         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1675         if (vp) {
1676                 RDEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1677                 post_proxy_type = vp->vp_integer;
1678         }
1679         
1680         if (request->home_pool && request->home_pool->virtual_server) {
1681                 const char *old_server = request->server;
1682                 
1683                 request->server = request->home_pool->virtual_server;
1684                 RDEBUG2(" server %s {", request->server);
1685                 rcode = module_post_proxy(post_proxy_type, request);
1686                 RDEBUG2(" }");
1687                 request->server = old_server;
1688         } else {
1689                 rcode = module_post_proxy(post_proxy_type, request);
1690         }
1691
1692 #ifdef WITH_COA
1693         if (request->packet->code == request->proxy->code)
1694           /*
1695            *    Don't run the next bit if we originated a CoA
1696            *    packet, after receiving an Access-Request or
1697            *    Accounting-Request.
1698            */
1699 #endif
1700         
1701         /*
1702          *      There may NOT be a proxy reply, as we may be
1703          *      running Post-Proxy-Type = Fail.
1704          */
1705         if (request->proxy_reply) {
1706                 /*
1707                  *      Delete the Proxy-State Attributes from
1708                  *      the reply.  These include Proxy-State
1709                  *      attributes from us and remote server.
1710                  */
1711                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1712                 
1713                 /*
1714                  *      Add the attributes left in the proxy
1715                  *      reply to the reply list.
1716                  */
1717                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1718                 request->proxy_reply->vps = NULL;
1719                 
1720                 /*
1721                  *      Free proxy request pairs.
1722                  */
1723                 pairfree(&request->proxy->vps);
1724         }
1725         
1726         switch (rcode) {
1727         default:  /* Don't do anything */
1728                 break;
1729         case RLM_MODULE_FAIL:
1730                 /* FIXME: debug print stuff */
1731                 request->child_state = REQUEST_DONE;
1732                 return 0;
1733                 
1734         case RLM_MODULE_HANDLED:
1735                 /* FIXME: debug print stuff */
1736                 request->child_state = REQUEST_DONE;
1737                 return 0;
1738         }
1739
1740         return 1;
1741 }
1742 #endif
1743
1744 static int request_pre_handler(REQUEST *request)
1745 {
1746         int rcode;
1747
1748         rad_assert(request->magic == REQUEST_MAGIC);
1749         rad_assert(request->packet != NULL);
1750
1751         request->child_state = REQUEST_RUNNING;
1752
1753         /*
1754          *      Don't decode the packet if it's an internal "fake"
1755          *      request.  Instead, just return so that the caller can
1756          *      process it.
1757          */
1758         if (request->packet->dst_port == 0) {
1759                 request->username = pairfind(request->packet->vps,
1760                                              PW_USER_NAME);
1761                 request->password = pairfind(request->packet->vps,
1762                                              PW_USER_PASSWORD);
1763                 return 1;
1764         }
1765
1766 #ifdef WITH_PROXY
1767         /*
1768          *      Put the decoded packet into it's proper place.
1769          */
1770         if (request->proxy_reply != NULL) {
1771                 rcode = request->proxy_listener->decode(request->proxy_listener,
1772                                                         request);
1773                 DEBUG_PACKET(request, request->proxy_reply, 0);
1774         } else
1775 #endif
1776         if (request->packet->vps == NULL) {
1777                 rcode = request->listener->decode(request->listener, request);
1778                 
1779                 if (debug_condition) {
1780                         int result = FALSE;
1781                         const char *my_debug = debug_condition;
1782
1783                         /*
1784                          *      Ignore parse errors.
1785                          */
1786                         radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1787                                                   &my_debug, 1,
1788                                                   &result);
1789                         if (result) {
1790                                 request->options = 2;
1791                                 request->radlog = radlog_request;
1792                         }
1793                 }
1794                 
1795                 DEBUG_PACKET(request, request->packet, 0);
1796         } else {
1797                 rcode = 0;
1798         }
1799
1800         if (rcode < 0) {
1801                 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1802                 request->child_state = REQUEST_DONE;
1803                 return 0;
1804         }
1805
1806         if (!request->username) {
1807                 request->username = pairfind(request->packet->vps,
1808                                              PW_USER_NAME);
1809         }
1810
1811 #ifdef WITH_PROXY
1812         if (request->proxy) {
1813                 return process_proxy_reply(request);
1814 #endif
1815         }
1816
1817         return 1;
1818 }
1819
1820
1821 #ifdef WITH_PROXY
1822 /*
1823  *      Do state handling when we proxy a request.
1824  */
1825 static int proxy_request(REQUEST *request)
1826 {
1827         struct timeval when;
1828         char buffer[128];
1829
1830         if (request->home_server->server) {
1831                 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1832                 return 0;
1833         }
1834
1835         if (!insert_into_proxy_hash(request, FALSE)) {
1836                 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1837                 return 0;
1838         }
1839
1840         request->proxy_listener->encode(request->proxy_listener, request);
1841
1842         when = request->received;
1843         when.tv_sec += request->root->max_request_time;
1844
1845         gettimeofday(&request->proxy_when, NULL);
1846
1847         request->next_when = request->proxy_when;
1848         request->next_when.tv_sec += request->home_server->response_window;
1849
1850         rad_assert(request->home_server->response_window > 0);
1851
1852         if (timercmp(&when, &request->next_when, <)) {
1853                 request->next_when = when;
1854         }
1855         request->next_callback = no_response_to_proxied_request;
1856
1857         RDEBUG2("Proxying request %d to home server %s port %d",
1858                request->number,
1859                inet_ntop(request->proxy->dst_ipaddr.af,
1860                          &request->proxy->dst_ipaddr.ipaddr,
1861                          buffer, sizeof(buffer)),
1862                request->proxy->dst_port);
1863
1864         /*
1865          *      Note that we set proxied BEFORE sending the packet.
1866          *
1867          *      Once we send it, the request is tainted, as
1868          *      another thread may have picked it up.  Don't
1869          *      touch it!
1870          */
1871         request->num_proxied_requests = 1;
1872         request->num_proxied_responses = 0;
1873 #ifdef HAVE_PTHREAD_H
1874         request->child_pid = NO_SUCH_CHILD_PID;
1875 #endif
1876         request->child_state = REQUEST_PROXIED;
1877
1878         DEBUG_PACKET(request, request->proxy, 1);
1879
1880         request->proxy_listener->send(request->proxy_listener,
1881                                       request);
1882         return 1;
1883 }
1884
1885
1886 /*
1887  *      "Proxy" the request by sending it to a new virtual server.
1888  */
1889 static int proxy_to_virtual_server(REQUEST *request)
1890 {
1891         REQUEST *fake;
1892         RAD_REQUEST_FUNP fun;
1893
1894         if (!request->home_server || !request->home_server->server) return 0;
1895
1896         if (request->parent) {
1897                 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1898                 return 0;
1899         }
1900
1901         fake = request_alloc_fake(request);
1902         if (!fake) {
1903                 RDEBUG2("WARNING: Out of memory");
1904                 return 0;
1905         }
1906
1907         fake->packet->vps = paircopy(request->proxy->vps);
1908         fake->server = request->home_server->server;
1909
1910         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1911                 fun = rad_authenticate;
1912
1913 #ifdef WITH_ACCOUNTING
1914         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1915                 fun = rad_accounting;
1916 #endif
1917
1918         } else {
1919                 RDEBUG2("Unknown packet type %d", request->proxy->code);
1920                 ev_request_free(&fake);
1921                 return 0;
1922         }
1923
1924         RDEBUG2(">>> Sending proxied request internally to virtual server.");
1925         radius_handle_request(fake, fun);
1926         RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
1927
1928         if (fake->reply->code != 0) {
1929                 request->proxy_reply = fake->reply;
1930                 fake->reply = NULL;
1931         } else {
1932                 /*
1933                  *      There was no response
1934                  */
1935                 setup_post_proxy_fail(request);
1936         }
1937
1938         ev_request_free(&fake);
1939
1940         process_proxy_reply(request);
1941
1942         /*
1943          *      Process it through the normal section again, but ONLY
1944          *      if we received a proxy reply..
1945          */
1946         if (request->proxy_reply) {
1947                 if (request->server) RDEBUG("server %s {",
1948                                             request->server != NULL ?
1949                                             request->server : ""); 
1950                 fun(request);
1951                 
1952                 if (request->server) RDEBUG("} # server %s",
1953                                             request->server != NULL ?
1954                                             request->server : "");
1955         }
1956
1957         return 2;               /* success, but NOT '1' !*/
1958 }
1959
1960 /*
1961  *      Return 1 if we did proxy it, or the proxy attempt failed
1962  *      completely.  Either way, the caller doesn't touch the request
1963  *      any more if we return 1.
1964  */
1965 static int successfully_proxied_request(REQUEST *request)
1966 {
1967         int rcode;
1968         int pre_proxy_type = 0;
1969         VALUE_PAIR *realmpair;
1970         VALUE_PAIR *strippedname;
1971         VALUE_PAIR *vp;
1972         char *realmname = NULL;
1973         home_server *home;
1974         REALM *realm = NULL;
1975         home_pool_t *pool;
1976
1977         /*
1978          *      If it was already proxied, do nothing.
1979          *
1980          *      FIXME: This should really be a serious error.
1981          */
1982         if (request->in_proxy_hash ||
1983             (request->proxy_reply && (request->proxy_reply->code != 0))) {
1984                 return 0;
1985         }
1986
1987         realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1988         if (!realmpair || (realmpair->length == 0)) {
1989                 int pool_type;
1990
1991                 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
1992                 if (!vp) return 0;
1993
1994                 switch (request->packet->code) {
1995                 case PW_AUTHENTICATION_REQUEST:
1996                         pool_type = HOME_TYPE_AUTH;
1997                         break;
1998
1999 #ifdef WITH_ACCOUNTING
2000                 case PW_ACCOUNTING_REQUEST:
2001                         pool_type = HOME_TYPE_ACCT;
2002                         break;
2003 #endif
2004
2005 #ifdef WITH_COA
2006                 case PW_COA_REQUEST:
2007                 case PW_DISCONNECT_REQUEST:
2008                         pool_type = HOME_TYPE_COA;
2009                         break;
2010 #endif
2011
2012                 default:
2013                         return 0;
2014                 }
2015
2016                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2017                 if (!pool) {
2018                         RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2019                                 vp->vp_strvalue);
2020                         return 0;
2021                 }
2022
2023                 realmname = NULL; /* no realms */
2024                 realm = NULL;
2025                 goto found_pool;
2026         }
2027
2028         realmname = (char *) realmpair->vp_strvalue;
2029
2030         realm = realm_find2(realmname);
2031         if (!realm) {
2032                 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2033                 return 0;
2034         }
2035
2036         /*
2037          *      Figure out which pool to use.
2038          */
2039         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2040                 pool = realm->auth_pool;
2041
2042 #ifdef WITH_ACCOUNTING
2043         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2044                 pool = realm->acct_pool;
2045 #endif
2046
2047 #ifdef WITH_COA
2048         } else if ((request->packet->code == PW_COA_REQUEST) ||
2049                    (request->packet->code == PW_DISCONNECT_REQUEST)) {
2050                 pool = realm->acct_pool;
2051 #endif
2052
2053         } else {
2054                 rad_panic("Internal sanity check failed");
2055         }
2056
2057         if (!pool) {
2058                 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2059                        realmname);
2060                 return 0;
2061         }
2062
2063 found_pool:
2064         home = home_server_ldb(realmname, pool, request);
2065         if (!home) {
2066                 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2067                        realmname);
2068                 return -1;
2069         }
2070         request->home_pool = pool;
2071
2072 #ifdef WITH_COA
2073         /*
2074          *      Once we've decided to proxy a request, we cannot send
2075          *      a CoA packet.  So we free up any CoA packet here.
2076          */
2077         ev_request_free(&request->coa);
2078 #endif
2079         /*
2080          *      Remember that we sent the request to a Realm.
2081          */
2082         if (realmname) pairadd(&request->packet->vps,
2083                                pairmake("Realm", realmname, T_OP_EQ));
2084
2085         /*
2086          *      Strip the name, if told to.
2087          *
2088          *      Doing it here catches the case of proxied tunneled
2089          *      requests.
2090          */
2091         if (realm && (realm->striprealm == TRUE) &&
2092            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2093                 /*
2094                  *      If there's a Stripped-User-Name attribute in
2095                  *      the request, then use THAT as the User-Name
2096                  *      for the proxied request, instead of the
2097                  *      original name.
2098                  *
2099                  *      This is done by making a copy of the
2100                  *      Stripped-User-Name attribute, turning it into
2101                  *      a User-Name attribute, deleting the
2102                  *      Stripped-User-Name and User-Name attributes
2103                  *      from the vps list, and making the new
2104                  *      User-Name the head of the vps list.
2105                  */
2106                 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2107                 if (!vp) {
2108                         vp = radius_paircreate(request, NULL,
2109                                                PW_USER_NAME, PW_TYPE_STRING);
2110                         rad_assert(vp != NULL); /* handled by above function */
2111                         /* Insert at the START of the list */
2112                         vp->next = request->proxy->vps;
2113                         request->proxy->vps = vp;
2114                 }
2115                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2116                        sizeof(vp->vp_strvalue));
2117                 vp->length = strippedname->length;
2118
2119                 /*
2120                  *      Do NOT delete Stripped-User-Name.
2121                  */
2122         }
2123
2124         /*
2125          *      If there is no PW_CHAP_CHALLENGE attribute but
2126          *      there is a PW_CHAP_PASSWORD we need to add it
2127          *      since we can't use the request authenticator
2128          *      anymore - we changed it.
2129          */
2130         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2131             pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2132             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2133                 vp = radius_paircreate(request, &request->proxy->vps,
2134                                        PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2135                 vp->length = AUTH_VECTOR_LEN;
2136                 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2137         }
2138
2139         /*
2140          *      The RFC's say we have to do this, but FreeRADIUS
2141          *      doesn't need it.
2142          */
2143         vp = radius_paircreate(request, &request->proxy->vps,
2144                                PW_PROXY_STATE, PW_TYPE_OCTETS);
2145         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2146                  request->packet->id);
2147         vp->length = strlen(vp->vp_strvalue);
2148
2149         /*
2150          *      Should be done BEFORE inserting into proxy hash, as
2151          *      pre-proxy may use this information, or change it.
2152          */
2153         request->proxy->code = request->packet->code;
2154
2155         /*
2156          *      Call the pre-proxy routines.
2157          */
2158         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2159         if (vp) {
2160                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
2161                 pre_proxy_type = vp->vp_integer;
2162         }
2163
2164         rad_assert(request->home_pool != NULL);
2165
2166         if (request->home_pool->virtual_server) {
2167                 const char *old_server = request->server;
2168                 
2169                 request->server = request->home_pool->virtual_server;
2170                 RDEBUG2(" server %s {", request->server);
2171                 rcode = module_pre_proxy(pre_proxy_type, request);
2172                 RDEBUG2(" }");
2173                         request->server = old_server;
2174         } else {
2175                 rcode = module_pre_proxy(pre_proxy_type, request);
2176         }
2177         switch (rcode) {
2178         case RLM_MODULE_FAIL:
2179         case RLM_MODULE_INVALID:
2180         case RLM_MODULE_NOTFOUND:
2181         case RLM_MODULE_USERLOCK:
2182         default:
2183                 /* FIXME: debug print failed stuff */
2184                 return -1;
2185
2186         case RLM_MODULE_REJECT:
2187         case RLM_MODULE_HANDLED:
2188                 return 0;
2189
2190         /*
2191          *      Only proxy the packet if the pre-proxy code succeeded.
2192          */
2193         case RLM_MODULE_NOOP:
2194         case RLM_MODULE_OK:
2195         case RLM_MODULE_UPDATED:
2196                 break;
2197         }
2198
2199         /*
2200          *      If it's a fake request, don't send the proxy
2201          *      packet.  The outer tunnel session will take
2202          *      care of doing that.
2203          */
2204         if (request->packet->dst_port == 0) {
2205                 request->home_server = NULL;
2206                 return 1;
2207         }
2208
2209         if (request->home_server->server) {
2210                 return proxy_to_virtual_server(request);
2211         }
2212
2213         if (!proxy_request(request)) {
2214                 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2215                 return -1;
2216         }
2217         
2218         return 1;
2219 }
2220 #endif
2221
2222 static void request_post_handler(REQUEST *request)
2223 {
2224         int child_state = -1;
2225         struct timeval when;
2226         VALUE_PAIR *vp;
2227
2228         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2229             (request->parent &&
2230              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2231                 RDEBUG2("Request %d was cancelled.", request->number);
2232 #ifdef HAVE_PTHREAD_H
2233                 request->child_pid = NO_SUCH_CHILD_PID;
2234 #endif
2235                 child_state = REQUEST_DONE;
2236                 goto cleanup;
2237         }
2238
2239         if (request->child_state != REQUEST_RUNNING) {
2240                 rad_panic("Internal sanity check failed");
2241         }
2242
2243 #ifdef WITH_COA
2244         /*
2245          *      If it's not in the request hash, it's a CoA request.
2246          *      We hope.
2247          */
2248         if (!request->in_request_hash &&
2249             request->proxy &&
2250             ((request->proxy->code == PW_COA_REQUEST) ||
2251              (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2252                 request->next_callback = NULL;
2253                 child_state = REQUEST_DONE;
2254                 goto cleanup;
2255         }
2256 #endif
2257
2258         /*
2259          *      Catch Auth-Type := Reject BEFORE proxying the packet.
2260          */
2261         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2262             (request->reply->code == 0) &&
2263             ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2264             (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2265                 request->reply->code = PW_AUTHENTICATION_REJECT;
2266         }
2267
2268 #ifdef WITH_PROXY
2269         if (request->root->proxy_requests &&
2270             !request->in_proxy_hash &&
2271             (request->reply->code == 0) &&
2272             (request->packet->dst_port != 0) &&
2273             (request->packet->code != PW_STATUS_SERVER)) {
2274                 int rcode = successfully_proxied_request(request);
2275
2276                 if (rcode == 1) return; /* request is invalid */
2277
2278                 /*
2279                  *      Failed proxying it (dead home servers, etc.)
2280                  *      Run it through Post-Proxy-Type = Fail, and
2281                  *      respond to the request.
2282                  *
2283                  *      Note that we're in a child thread here, so we
2284                  *      do NOT re-schedule the request.  Instead, we
2285                  *      do what we would have done, which is run the
2286                  *      pre-handler, a NULL request handler, and then
2287                  *      the post handler.
2288                  */
2289                 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2290                         request_pre_handler(request);
2291                 }
2292
2293                 /*
2294                  *      Else we weren't supposed to proxy it,
2295                  *      OR we proxied it internally to a virutal server.
2296                  */
2297         }
2298 #endif
2299
2300         /*
2301          *      Fake requests don't get encoded or signed.  The caller
2302          *      also requires the reply VP's, so we don't free them
2303          *      here!
2304          */
2305         if (request->packet->dst_port == 0) {
2306                 /* FIXME: RDEBUG going to the next request */
2307 #ifdef HAVE_PTHREAD_H
2308                 request->child_pid = NO_SUCH_CHILD_PID;
2309 #endif
2310                 request->child_state = REQUEST_DONE;
2311                 return;
2312         }
2313
2314 #ifdef WITH_PROXY
2315         /*
2316          *      Copy Proxy-State from the request to the reply.
2317          */
2318         vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2319         if (vp) pairadd(&request->reply->vps, vp);
2320 #endif
2321
2322         /*
2323          *      Access-Requests get delayed or cached.
2324          */
2325         switch (request->packet->code) {
2326         case PW_AUTHENTICATION_REQUEST:
2327                 gettimeofday(&request->next_when, NULL);
2328
2329                 if (request->reply->code == 0) {
2330                         /*
2331                          *      Check if the lack of response is intentional.
2332                          */
2333                         vp = pairfind(request->config_items,
2334                                       PW_RESPONSE_PACKET_TYPE);
2335                         if (!vp) {
2336                                 RDEBUG2("There was no response configured: rejecting request %d",
2337                                        request->number);
2338                                 request->reply->code = PW_AUTHENTICATION_REJECT;
2339
2340                         } else if (vp->vp_integer == 256) {
2341                                 RDEBUG2("Not responding to request %d",
2342                                        request->number);
2343
2344                                 /*
2345                                  *      Force cleanup after a long
2346                                  *      time, so that we don't
2347                                  *      re-process the packet.
2348                                  */
2349                                 request->next_when.tv_sec += request->root->max_request_time;
2350                                 request->next_callback = cleanup_delay;
2351                                 child_state = REQUEST_CLEANUP_DELAY;
2352                                 break;
2353                         } else {
2354                                 request->reply->code = vp->vp_integer;
2355
2356                         }
2357                 }
2358
2359                 /*
2360                  *      Run rejected packets through
2361                  *
2362                  *      Post-Auth-Type = Reject
2363                  */
2364                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2365                         pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2366                         vp = radius_pairmake(request, &request->config_items,
2367                                              "Post-Auth-Type", "Reject",
2368                                              T_OP_SET);
2369                         if (vp) rad_postauth(request);
2370
2371                         /*
2372                          *      If configured, delay Access-Reject packets.
2373                          *
2374                          *      If request->root->reject_delay = 0, we discover
2375                          *      that we have to send the packet now.
2376                          */
2377                         when = request->received;
2378                         when.tv_sec += request->root->reject_delay;
2379
2380                         if (timercmp(&when, &request->next_when, >)) {
2381                                 RDEBUG2("Delaying reject of request %d for %d seconds",
2382                                        request->number,
2383                                        request->root->reject_delay);
2384                                 request->next_when = when;
2385                                 request->next_callback = reject_delay;
2386 #ifdef HAVE_PTHREAD_H
2387                                 request->child_pid = NO_SUCH_CHILD_PID;
2388 #endif
2389                                 request->child_state = REQUEST_REJECT_DELAY;
2390                                 return;
2391                         }
2392                 }
2393
2394 #ifdef WITH_COA
2395         case PW_COA_REQUEST:
2396         case PW_DISCONNECT_REQUEST:
2397 #endif
2398                 request->next_when.tv_sec += request->root->cleanup_delay;
2399                 request->next_callback = cleanup_delay;
2400                 child_state = REQUEST_CLEANUP_DELAY;
2401                 break;
2402
2403         case PW_ACCOUNTING_REQUEST:
2404                 request->next_callback = NULL; /* just to be safe */
2405                 child_state = REQUEST_DONE;
2406                 break;
2407
2408                 /*
2409                  *      FIXME: Status-Server should probably not be
2410                  *      handled here...
2411                  */
2412         case PW_STATUS_SERVER:
2413                 request->next_callback = NULL;
2414                 child_state = REQUEST_DONE;
2415                 break;
2416
2417         default:
2418                 /*
2419                  *      DHCP, VMPS, etc.
2420                  */
2421                 request->next_callback = NULL;
2422                 child_state = REQUEST_DONE;
2423                 break;
2424         }
2425
2426         /*
2427          *      Suppress "no reply" packets here, unless we're reading
2428          *      from the "detail" file.  In that case, we've got to
2429          *      tell the detail file handler that the request is dead,
2430          *      and it should re-send it.
2431          *      If configured, encode, sign, and send.
2432          */
2433         if ((request->reply->code != 0) ||
2434             (request->listener->type == RAD_LISTEN_DETAIL)) {
2435                 DEBUG_PACKET(request, request->reply, 1);
2436                 request->listener->send(request->listener, request);
2437         }
2438
2439 #ifdef WITH_COA
2440         /*
2441          *      Now that we've completely processed the request,
2442          *      see if we need to originate a CoA request.
2443          */
2444         if (request->coa ||
2445             (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2446                 if (!originated_coa_request(request)) {
2447                         RDEBUG2("Do CoA Fail handler here");
2448                 }
2449                 /* request->coa is stil set, so we can update events */
2450         }
2451 #endif
2452
2453  cleanup:
2454         /*
2455          *      Clean up.  These are no longer needed.
2456          */
2457         pairfree(&request->config_items);
2458
2459         pairfree(&request->packet->vps);
2460         request->username = NULL;
2461         request->password = NULL;
2462
2463         pairfree(&request->reply->vps);
2464
2465 #ifdef WITH_PROXY
2466         if (request->proxy) {
2467                 pairfree(&request->proxy->vps);
2468
2469                 if (request->proxy_reply) {
2470                         pairfree(&request->proxy_reply->vps);
2471                 }
2472
2473 #if 0
2474                 /*
2475                  *      We're not tracking responses from the home
2476                  *      server, we can therefore free this memory in
2477                  *      the child thread.
2478                  */
2479                 if (!request->in_proxy_hash) {
2480                         rad_free(&request->proxy);
2481                         rad_free(&request->proxy_reply);
2482                         request->home_server = NULL;
2483                 }
2484 #endif
2485         }
2486 #endif
2487
2488         RDEBUG2("Finished request %d.", request->number);
2489         rad_assert(child_state >= 0);
2490         request->child_state = child_state;
2491
2492         /*
2493          *      Single threaded mode: update timers now.
2494          */
2495         if (!have_children) wait_a_bit(request);
2496 }
2497
2498
2499 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2500 {
2501 #ifdef WITH_PROXY
2502         char buffer[128];
2503 #endif
2504
2505         RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2506         RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2507         
2508         switch (request->child_state) {
2509         case REQUEST_QUEUED:
2510         case REQUEST_RUNNING:
2511 #ifdef WITH_PROXY
2512         discard:
2513 #endif
2514                 radlog(L_ERR, "Discarding duplicate request from "
2515                        "client %s port %d - ID: %d due to unfinished request %d",
2516                        client->shortname,
2517                        request->packet->src_port,request->packet->id,
2518                        request->number);
2519                 break;
2520
2521 #ifdef WITH_PROXY
2522         case REQUEST_PROXIED:
2523                 /*
2524                  *      We're not supposed to have duplicate
2525                  *      accounting packets.  The other states handle
2526                  *      duplicates fine (discard, or send duplicate
2527                  *      reply).  But we do NOT want to retransmit an
2528                  *      accounting request here, because that would
2529                  *      involve updating the Acct-Delay-Time, and
2530                  *      therefore changing the packet Id, etc.
2531                  *
2532                  *      Instead, we just discard the packet.  We may
2533                  *      eventually respond, or the client will send a
2534                  *      new accounting packet.            
2535                  *
2536                  *      The same comments go for Status-Server, and
2537                  *      other packet types.
2538                  *
2539                  *      FIXME: coa: when we proxy CoA && Disconnect
2540                  *      packets, this logic has to be fixed.
2541                  */
2542                 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2543                         goto discard;
2544                 }
2545
2546                 check_for_zombie_home_server(request);
2547
2548                 /*
2549                  *      If we've just discovered that the home server
2550                  *      is dead, OR the socket has been closed, look for
2551                  *      another connection to a home server.
2552                  */
2553                 if (((request->packet->dst_port != 0) &&
2554                      (request->home_server->state == HOME_STATE_IS_DEAD)) ||
2555                     (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
2556                         home_server *home;
2557
2558                         remove_from_proxy_hash(request);
2559
2560                         home = home_server_ldb(NULL, request->home_pool, request);
2561                         if (!home) {
2562                                 RDEBUG2("Failed to find live home server for request %d", request->number);
2563                         no_home_servers:
2564                                 /*
2565                                  *      Do post-request processing,
2566                                  *      and any insertion of necessary
2567                                  *      events.
2568                                  */
2569                                 post_proxy_fail_handler(request);
2570                                 return;
2571                         }
2572
2573                         request->proxy->code = request->packet->code;
2574
2575                         /*
2576                          *      Free the old packet, to force re-encoding
2577                          */
2578                         free(request->proxy->data);
2579                         request->proxy->data = NULL;
2580                         request->proxy->data_len = 0;
2581
2582                         /*
2583                          *      This request failed over to a virtual
2584                          *      server.  Push it back onto the queue
2585                          *      to be processed.
2586                          */
2587                         if (request->home_server->server) {
2588                                 proxy_fallback_handler(request);
2589                                 return;
2590                         }
2591
2592                         /*
2593                          *      Try to proxy the request.
2594                          */
2595                         if (!proxy_request(request)) {
2596                                 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2597                                 goto no_home_servers;
2598                         }
2599
2600                         /*
2601                          *      This code executes in the main server
2602                          *      thread, so there's no need for locking.
2603                          */
2604                         rad_assert(request->next_callback != NULL);
2605                         INSERT_EVENT(request->next_callback, request);
2606                         request->next_callback = NULL;
2607                         return;
2608                 } /* else the home server is still alive */
2609
2610                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2611                        inet_ntop(request->proxy->dst_ipaddr.af,
2612                                  &request->proxy->dst_ipaddr.ipaddr,
2613                                  buffer, sizeof(buffer)),
2614                        request->proxy->dst_port,
2615                        request->proxy->id);
2616                 request->num_proxied_requests++;
2617
2618                 DEBUG_PACKET(request, request->proxy, 1);
2619                 request->proxy_listener->send(request->proxy_listener,
2620                                               request);
2621                 break;
2622 #endif
2623
2624         case REQUEST_REJECT_DELAY:
2625                 RDEBUG2("Waiting to send Access-Reject "
2626                        "to client %s port %d - ID: %d",
2627                        client->shortname,
2628                        request->packet->src_port, request->packet->id);
2629                 break;
2630
2631         case REQUEST_CLEANUP_DELAY:
2632         case REQUEST_DONE:
2633                 if (request->reply->code == 0) {
2634                         RDEBUG2("Ignoring retransmit from client %s port %d "
2635                                 "- ID: %d, no reply was configured",
2636                                 client->shortname,
2637                                 request->packet->src_port, request->packet->id);
2638                         return;
2639                 }
2640
2641                 /*
2642                  *      FIXME: This sends duplicate replies to
2643                  *      accounting requests, even if Acct-Delay-Time
2644                  *      or Event-Timestamp is in the packet.  In those
2645                  *      cases, the Id should be changed, and the packet
2646                  *      re-calculated.
2647                  */
2648                 RDEBUG2("Sending duplicate reply "
2649                        "to client %s port %d - ID: %d",
2650                        client->shortname,
2651                        request->packet->src_port, request->packet->id);
2652                 DEBUG_PACKET(request, request->reply, 1);
2653                 request->listener->send(request->listener, request);
2654                 break;
2655         }
2656 }
2657
2658
2659 static void received_conflicting_request(REQUEST *request,
2660                                          const RADCLIENT *client)
2661 {
2662         radlog(L_ERR, "Received conflicting packet from "
2663                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
2664                client->shortname,
2665                request->packet->src_port, request->packet->id,
2666                request->number);
2667
2668         /*
2669          *      Nuke it from the request hash, so we can receive new
2670          *      packets.
2671          */
2672         remove_from_request_hash(request);
2673
2674         switch (request->child_state) {
2675 #ifdef HAVE_PTHREAD_H
2676                 /*
2677                  *      It's queued or running.  Tell it to stop, and
2678                  *      wait for it to do so.
2679                  */
2680         case REQUEST_QUEUED:
2681         case REQUEST_RUNNING:
2682                 request->master_state = REQUEST_STOP_PROCESSING;
2683                 request->delay += request->delay >> 1;
2684
2685                 tv_add(&request->when, request->delay);
2686
2687                 INSERT_EVENT(wait_for_child_to_die, request);
2688                 return;
2689 #endif
2690
2691                 /*
2692                  *      Catch race conditions.  It may have switched
2693                  *      from running to done while this code is being
2694                  *      executed.
2695                  */
2696         case REQUEST_REJECT_DELAY:
2697         case REQUEST_CLEANUP_DELAY:
2698         case REQUEST_DONE:
2699                 break;
2700
2701                 /*
2702                  *      It's in some other state, and therefore also
2703                  *      in the event queue.  At some point, the
2704                  *      child will notice, and we can then delete it.
2705                  */
2706         case REQUEST_PROXIED:
2707         default:
2708                 rad_assert(request->ev != NULL);
2709                 break;
2710         }
2711 }
2712
2713
2714 static int can_handle_new_request(RADIUS_PACKET *packet,
2715                                   RADCLIENT *client,
2716                                   struct main_config_t *root)
2717 {
2718         /*
2719          *      Count the total number of requests, to see if
2720          *      there are too many.  If so, return with an
2721          *      error.
2722          */
2723         if (root->max_requests) {
2724                 int request_count = fr_packet_list_num_elements(pl);
2725
2726                 /*
2727                  *      This is a new request.  Let's see if
2728                  *      it makes us go over our configured
2729                  *      bounds.
2730                  */
2731                 if (request_count > root->max_requests) {
2732                         radlog(L_ERR, "Dropping request (%d is too many): "
2733                                "from client %s port %d - ID: %d", request_count,
2734                                client->shortname,
2735                                packet->src_port, packet->id);
2736                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2737                                "\tThe value for 'max_requests' is probably set too low.\n");
2738                         return 0;
2739                 } /* else there were a small number of requests */
2740         } /* else there was no configured limit for requests */
2741
2742         /*
2743          *      FIXME: Add per-client checks.  If one client is sending
2744          *      too many packets, start discarding them.
2745          *
2746          *      We increment the counters here, and decrement them
2747          *      when the response is sent... somewhere in this file.
2748          */
2749
2750         /*
2751          *      FUTURE: Add checks for system load.  If the system is
2752          *      busy, start dropping requests...
2753          *
2754          *      We can probably keep some statistics ourselves...  if
2755          *      there are more requests coming in than we can handle,
2756          *      start dropping some.
2757          */
2758
2759         return 1;
2760 }
2761
2762
2763 int received_request(rad_listen_t *listener,
2764                      RADIUS_PACKET *packet, REQUEST **prequest,
2765                      RADCLIENT *client)
2766 {
2767         RADIUS_PACKET **packet_p;
2768         REQUEST *request = NULL;
2769         struct main_config_t *root = &mainconfig;
2770
2771         packet_p = fr_packet_list_find(pl, packet);
2772         if (packet_p) {
2773                 request = fr_packet2myptr(REQUEST, packet, packet_p);
2774                 rad_assert(request->in_request_hash);
2775
2776                 if ((request->packet->data_len == packet->data_len) &&
2777                     (memcmp(request->packet->vector, packet->vector,
2778                             sizeof(packet->vector)) == 0)) {
2779                         received_retransmit(request, client);
2780                         return 0;
2781                 }
2782
2783                 /*
2784                  *      The new request is different from the old one,
2785                  *      but maybe the old is finished.  If so, delete
2786                  *      the old one.
2787                  */
2788                 switch (request->child_state) {
2789                         struct timeval when;
2790
2791                 default:
2792                         /*
2793                          *      Special hacks for race conditions.
2794                          *      The reply is encoded, and therefore
2795                          *      likely sent.  We received a *new*
2796                          *      packet from the client, likely before
2797                          *      the next line or two of code which
2798                          *      updated the child state.  In this
2799                          *      case, just accept the new request.
2800                          */
2801                         if ((request->reply->code != 0) &&
2802                             request->reply->data) {
2803                                 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2804                                        client->shortname,
2805                                        packet->src_port, packet->id,
2806                                        request->number);
2807                                 remove_from_request_hash(request);
2808                                 request = NULL;
2809                                 break;
2810                         }
2811
2812                         gettimeofday(&when, NULL);
2813                         when.tv_sec -= 1;
2814
2815                         /*
2816                          *      If the cached request was received
2817                          *      within the last second, then we
2818                          *      discard the NEW request instead of the
2819                          *      old one.  This will happen ONLY when
2820                          *      the client is severely broken, and is
2821                          *      sending conflicting packets very
2822                          *      quickly.
2823                          */
2824                         if (timercmp(&when, &request->received, <)) {
2825                                 radlog(L_ERR, "Discarding conflicting packet from "
2826                                        "client %s port %d - ID: %d due to recent request %d.",
2827                                        client->shortname,
2828                                        packet->src_port, packet->id,
2829                                        request->number);
2830                                 return 0;
2831                         }
2832
2833                         received_conflicting_request(request, client);
2834                         request = NULL;
2835                         break;
2836
2837                 case REQUEST_REJECT_DELAY:
2838                 case REQUEST_CLEANUP_DELAY:
2839                         request->child_state = REQUEST_DONE;
2840                 case REQUEST_DONE:
2841                         cleanup_delay(request);
2842                         request = NULL;
2843                         break;
2844                 }
2845         }
2846
2847         /*
2848          *      We may want to quench the new request.
2849          */
2850         if ((listener->type != RAD_LISTEN_DETAIL) &&
2851             !can_handle_new_request(packet, client, root)) {
2852                 return 0;
2853         }
2854
2855         /*
2856          *      Create and initialize the new request.
2857          */
2858         request = request_alloc(); /* never fails */
2859
2860         if ((request->reply = rad_alloc(0)) == NULL) {
2861                 radlog(L_ERR, "No memory");
2862                 exit(1);
2863         }
2864
2865         request->listener = listener;
2866         request->client = client;
2867         request->packet = packet;
2868         request->packet->timestamp = request->timestamp;
2869         request->number = request_num_counter++;
2870         request->priority = listener->type;
2871 #ifdef HAVE_PTHREAD_H
2872         request->child_pid = NO_SUCH_CHILD_PID;
2873 #endif
2874
2875         /*
2876          *      Status-Server packets go to the head of the queue.
2877          */
2878         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2879
2880         /*
2881          *      Set virtual server identity
2882          */
2883         if (client->server) {
2884                 request->server = client->server;
2885         } else if (listener->server) {
2886                 request->server = listener->server;
2887         } else {
2888                 request->server = NULL;
2889         }
2890
2891         /*
2892          *      Remember the request in the list.
2893          */
2894         if (!fr_packet_list_insert(pl, &request->packet)) {
2895                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2896                 ev_request_free(&request);
2897                 return 0;
2898         }
2899
2900         request->in_request_hash = TRUE;
2901         request->root = root;
2902         root->refcount++;
2903 #ifdef WITH_TCP
2904         request->listener->count++;
2905 #endif
2906
2907         /*
2908          *      The request passes many of our sanity checks.
2909          *      From here on in, if anything goes wrong, we
2910          *      send a reject message, instead of dropping the
2911          *      packet.
2912          */
2913
2914         /*
2915          *      Build the reply template from the request.
2916          */
2917
2918         request->reply->sockfd = request->packet->sockfd;
2919         request->reply->dst_ipaddr = request->packet->src_ipaddr;
2920         request->reply->src_ipaddr = request->packet->dst_ipaddr;
2921         request->reply->dst_port = request->packet->src_port;
2922         request->reply->src_port = request->packet->dst_port;
2923         request->reply->id = request->packet->id;
2924         request->reply->code = 0; /* UNKNOWN code */
2925         memcpy(request->reply->vector, request->packet->vector,
2926                sizeof(request->reply->vector));
2927         request->reply->vps = NULL;
2928         request->reply->data = NULL;
2929         request->reply->data_len = 0;
2930
2931         request->master_state = REQUEST_ACTIVE;
2932         request->child_state = REQUEST_QUEUED;
2933         request->next_callback = NULL;
2934
2935         gettimeofday(&request->received, NULL);
2936         request->timestamp = request->received.tv_sec;
2937         request->when = request->received;
2938
2939         request->delay = USEC;
2940
2941         tv_add(&request->when, request->delay);
2942
2943         INSERT_EVENT(wait_a_bit, request);
2944
2945         *prequest = request;
2946         return 1;
2947 }
2948
2949
2950 #ifdef WITH_PROXY
2951 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2952 {
2953         char            buffer[128];
2954         REQUEST         *request;
2955
2956         /*
2957          *      Also removes from the proxy hash if responses == requests
2958          */
2959         request = lookup_in_proxy_hash(packet);
2960
2961         if (!request) {
2962                 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2963                        inet_ntop(packet->src_ipaddr.af,
2964                                  &packet->src_ipaddr.ipaddr,
2965                                  buffer, sizeof(buffer)),
2966                        packet->src_port, packet->id);
2967                 return NULL;
2968         }
2969
2970         /*
2971          *      We haven't replied to the NAS, but we have seen an
2972          *      earlier reply from the home server.  Ignore this packet,
2973          *      as we're likely still processing the previous reply.
2974          */
2975         if (request->proxy_reply) {
2976                 if (memcmp(request->proxy_reply->vector,
2977                            packet->vector,
2978                            sizeof(request->proxy_reply->vector)) == 0) {
2979                         RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d for request %d",
2980                                inet_ntop(packet->src_ipaddr.af,
2981                                          &packet->src_ipaddr.ipaddr,
2982                                          buffer, sizeof(buffer)),
2983                                packet->src_port, packet->id,
2984                                request->number);
2985                 } else {
2986                         /*
2987                          *      ? The home server gave us a new proxy
2988                          *      reply which doesn't match the old
2989                          *      one.  Delete it.
2990                          */
2991                         RDEBUG2("Ignoring conflicting proxy reply");
2992                 }
2993                 
2994                 /* assert that there's an event queued for request? */
2995                 return NULL;
2996         }
2997
2998         /*
2999          *      Verify the packet before doing ANYTHING with it.  This
3000          *      means we're doing more MD5 checks in the server core.
3001          *      However, we can fix that by moving to multiple threads
3002          *      listening on sockets.
3003          *
3004          *      We do this AFTER looking the request up in the hash,
3005          *      and AFTER vhecking if we saw a previous request.  This
3006          *      helps minimize the DoS effect of people attacking us
3007          *      with spoofed packets.
3008          */
3009         if (rad_verify(packet, request->proxy,
3010                        request->home_server->secret) != 0) {
3011                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
3012                 return NULL;
3013         }
3014
3015         gettimeofday(&now, NULL);
3016
3017         /*
3018          *      Maybe move this earlier in the decision process?
3019          *      Having it here means that late or duplicate proxy
3020          *      replies no longer get the home server marked as
3021          *      "alive".  This might be good for stability, though.
3022          *
3023          *      FIXME: Do we really want to do this whenever we
3024          *      receive a packet?  Setting this here means that we
3025          *      mark it alive on *any* packet, even if it's lost all
3026          *      of the *other* packets in the last 10s.
3027          */
3028         request->home_server->state = HOME_STATE_ALIVE;
3029         
3030 #ifdef WITH_COA
3031         /*
3032          *      When originating CoA, the "proxy" reply is the reply
3033          *      to the CoA request that we originated.  At this point,
3034          *      the original request is finished, and it has a reply.
3035          *
3036          *      However, if we haven't separated the two requests, do
3037          *      so now.  This is done so that cleaning up the original
3038          *      request won't cause the CoA request to be free'd.  See
3039          *      util.c, request_free()
3040          */
3041         if (request->parent && (request->parent->coa == request)) {
3042                 request->parent->coa = NULL;
3043                 request->parent = NULL;
3044
3045         } else
3046                 /*
3047                  *      Skip the next set of checks, as the original
3048                  *      reply is cached.  We want to be able to still
3049                  *      process the CoA reply, AND to reference the
3050                  *      original request/reply.
3051                  *
3052                  *      This is getting to be really quite a bit of a
3053                  *      hack.
3054                  */
3055 #endif
3056
3057         /*
3058          *      If there's a reply to the NAS, ignore everything
3059          *      related to proxy responses
3060          */
3061         if (request->reply && request->reply->code != 0) {
3062                 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3063                 return NULL;
3064         }
3065         
3066 #ifdef WITH_STATS
3067         /*
3068          *      The average includes our time to receive packets and
3069          *      look them up in the hashes, which should be the same
3070          *      for all packets.
3071          *
3072          *      We update the response time only for the FIRST packet
3073          *      we receive.
3074          */
3075         if (request->home_server->ema.window > 0) {
3076                 radius_stats_ema(&request->home_server->ema,
3077                                  &now, &request->proxy_when);
3078         }
3079 #endif
3080
3081         switch (request->child_state) {
3082         case REQUEST_QUEUED:
3083         case REQUEST_RUNNING:
3084                 radlog(L_ERR, "Internal sanity check failed for child state");
3085                 /* FALL-THROUGH */
3086
3087         case REQUEST_REJECT_DELAY:
3088         case REQUEST_CLEANUP_DELAY:
3089         case REQUEST_DONE:
3090                 radlog(L_ERR, "Reply from home server %s port %d  - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
3091                        inet_ntop(packet->src_ipaddr.af,
3092                                  &packet->src_ipaddr.ipaddr,
3093                                  buffer, sizeof(buffer)),
3094                        packet->src_port, packet->id,
3095                        request->number);
3096                 /* assert that there's an event queued for request? */
3097                 return NULL;
3098
3099         case REQUEST_PROXIED:
3100                 break;
3101         }
3102
3103         request->proxy_reply = packet;
3104
3105 #if 0
3106         /*
3107          *      Perform RTT calculations, as per RFC 2988 (for TCP).
3108          *      Note that we only do so on the first response.
3109          */
3110         if ((request->num_proxied_responses == 1)
3111                 int rtt;
3112                 home_server *home = request->home_server;
3113
3114                 rtt = now.tv_sec - request->proxy_when.tv_sec;
3115                 rtt *= USEC;
3116                 rtt += now.tv_usec;
3117                 rtt -= request->proxy_when.tv_usec;
3118
3119                 if (!home->has_rtt) {
3120                         home->has_rtt = TRUE;
3121
3122                         home->srtt = rtt;
3123                         home->rttvar = rtt / 2;
3124
3125                 } else {
3126                         home->rttvar -= home->rttvar >> 2;
3127                         home->rttvar += (home->srtt - rtt);
3128                         home->srtt -= home->srtt >> 3;
3129                         home->srtt += rtt >> 3;
3130                 }
3131
3132                 home->rto = home->srtt;
3133                 if (home->rttvar > (USEC / 4)) {
3134                         home->rto += home->rttvar * 4;
3135                 } else {
3136                         home->rto += USEC;
3137                 }
3138         }
3139 #endif
3140
3141         /*
3142          *      There's no incoming request, so it's a proxied packet
3143          *      we originated.
3144          */
3145         if (!request->packet) {
3146                 received_response_to_ping(request);
3147                 request->proxy_reply = NULL; /* caller will free it */
3148                 ev_request_free(&request);
3149                 return NULL;
3150         }
3151
3152         request->child_state = REQUEST_QUEUED;
3153         request->when = now;
3154         request->delay = USEC;
3155         request->priority = RAD_LISTEN_PROXY;
3156         tv_add(&request->when, request->delay);
3157
3158         /*
3159          *      Wait a bit will take care of max_request_time
3160          */
3161         INSERT_EVENT(wait_a_bit, request);
3162
3163         return request;
3164 }
3165 #endif
3166
3167 void event_new_fd(rad_listen_t *this)
3168 {
3169         char buffer[1024];
3170
3171         if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3172         
3173         this->print(this, buffer, sizeof(buffer));
3174         
3175         if (this->status == RAD_LISTEN_STATUS_INIT) {
3176                 if (just_started) {
3177                         DEBUG("Listening on %s", buffer);
3178                 } else {
3179                         DEBUG2(" ... adding new socket %s", buffer);
3180                 }
3181                 if (!fr_event_fd_insert(el, 0, this->fd,
3182                                         event_socket_handler, this)) {
3183                         radlog(L_ERR, "Failed remembering handle for proxy socket!");
3184                         exit(1);
3185                 }
3186                 
3187                 this->status = RAD_LISTEN_STATUS_KNOWN;
3188                 return;
3189         }
3190         
3191         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3192                 DEBUG2(" ... closing socket %s", buffer);
3193                 
3194                 fr_event_fd_delete(el, 0, this->fd);
3195                 this->status = RAD_LISTEN_STATUS_FINISH;
3196                 
3197                 /*
3198                  *      Close the fd AFTER fixing up the requests and
3199                  *      listeners, so that they don't send/recv on the
3200                  *      wrong socket (if someone manages to open
3201                  *      another one).
3202                  */
3203                 close(this->fd);
3204                 this->fd = -1;
3205         }
3206 }
3207
3208 static void handle_signal_self(int flag)
3209 {
3210         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3211                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3212                         fr_event_loop_exit(el, 1);
3213                 } else {
3214                         fr_event_loop_exit(el, 2);
3215                 }
3216
3217                 return;
3218         } /* else exit/term flags weren't set */
3219
3220         /*
3221          *      Tell the even loop to stop processing.
3222          */
3223         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3224                 time_t when;
3225                 static time_t last_hup = 0;
3226
3227                 DEBUG("Received HUP signal.");
3228
3229                 when = time(NULL);
3230                 if ((int) (when - last_hup) < 5) {
3231                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3232                         return;
3233                 }
3234                 last_hup = when;
3235
3236                 fr_event_loop_exit(el, 0x80);
3237         }
3238
3239 #ifdef WITH_DETAIL
3240         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3241                 rad_listen_t *this;
3242                 
3243                 /*
3244                  *      FIXME: O(N) loops suck.
3245                  */
3246                 for (this = mainconfig.listen;
3247                      this != NULL;
3248                      this = this->next) {
3249                         if (this->type != RAD_LISTEN_DETAIL) continue;
3250
3251                         /*
3252                          *      This one didn't send the signal, skip
3253                          *      it.
3254                          */
3255                         if (!this->decode(this, NULL)) continue;
3256
3257                         /*
3258                          *      Go service the interrupt.
3259                          */
3260                         event_poll_detail(this);
3261                 }
3262         }
3263 #endif
3264
3265         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3266                 rad_listen_t *this;
3267                 
3268                 for (this = mainconfig.listen;
3269                      this != NULL;
3270                      this = this->next) {
3271                         event_new_fd(this);
3272                 }
3273         }
3274 }
3275
3276 #ifndef WITH_SELF_PIPE
3277 void radius_signal_self(int flag)
3278 {
3279         handle_signal_self(flag);
3280 }
3281 #else
3282 /*
3283  *      Inform ourselves that we received a signal.
3284  */
3285 void radius_signal_self(int flag)
3286 {
3287         ssize_t rcode;
3288         uint8_t buffer[16];
3289
3290         /*
3291          *      The read MUST be non-blocking for this to work.
3292          */
3293         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3294         if (rcode > 0) {
3295                 ssize_t i;
3296
3297                 for (i = 0; i < rcode; i++) {
3298                         buffer[0] |= buffer[i];
3299                 }
3300         } else {
3301                 buffer[0] = 0;
3302         }
3303
3304         buffer[0] |= flag;
3305
3306         write(self_pipe[1], buffer, 1);
3307 }
3308
3309
3310 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3311                                  UNUSED int fd, UNUSED void *ctx)
3312 {
3313         ssize_t i, rcode;
3314         uint8_t buffer[32];
3315
3316         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3317         if (rcode <= 0) return;
3318
3319         /*
3320          *      Merge pending signals.
3321          */
3322         for (i = 0; i < rcode; i++) {
3323                 buffer[0] |= buffer[i];
3324         }
3325
3326         handle_signal_self(buffer[0]);
3327 }
3328 #endif
3329
3330
3331 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3332                                  void *ctx)
3333 {
3334         rad_listen_t *listener = ctx;
3335         RAD_REQUEST_FUNP fun;
3336         REQUEST *request;
3337
3338         rad_assert(xel == el);
3339
3340         xel = xel;
3341
3342         if (listener->fd < 0) rad_panic("Socket was closed on us!");
3343         
3344         if (!listener->recv(listener, &fun, &request)) return;
3345
3346         if (!thread_pool_addrequest(request, fun)) {
3347                 request->child_state = REQUEST_DONE;
3348         }
3349 }
3350
3351 typedef struct listen_detail_t {
3352         fr_event_t      *ev;
3353 } listen_detail_t;
3354
3355 /*
3356  *      This function is called periodically to see if this detail
3357  *      file is available for reading.
3358  */
3359 static void event_poll_detail(void *ctx)
3360 {
3361         int rcode, delay;
3362         RAD_REQUEST_FUNP fun;
3363         REQUEST *request;
3364         rad_listen_t *this = ctx;
3365         struct timeval when;
3366         listen_detail_t *detail = this->data;
3367
3368         rad_assert(this->type == RAD_LISTEN_DETAIL);
3369
3370         /*
3371          *      Try to read something.
3372          *
3373          *      FIXME: This does poll AND receive.
3374          */
3375         rcode = this->recv(this, &fun, &request);
3376         if (rcode != 0) {
3377                 rad_assert(fun != NULL);
3378                 rad_assert(request != NULL);
3379                 
3380                 if (!thread_pool_addrequest(request, fun)) {
3381                         request->child_state = REQUEST_DONE;
3382                 }
3383         }
3384
3385         if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3386         when = now;
3387
3388         /*
3389          *      Backdoor API to get the delay until the next poll
3390          *      time.
3391          */
3392         delay = this->encode(this, NULL);
3393         tv_add(&when, delay);
3394
3395         if (!fr_event_insert(el, event_poll_detail, this,
3396                              &when, &detail->ev)) {
3397                 radlog(L_ERR, "Failed creating handler");
3398                 exit(1);
3399         }
3400 }
3401
3402
3403 static void event_status(struct timeval *wake)
3404 {
3405 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3406         int argval;
3407 #endif
3408
3409         if (debug_flag == 0) {
3410                 if (just_started) {
3411                         radlog(L_INFO, "Ready to process requests.");
3412                         just_started = FALSE;
3413                 }
3414                 return;
3415         }
3416
3417         if (!wake) {
3418                 DEBUG("Ready to process requests.");
3419
3420         } else if ((wake->tv_sec != 0) ||
3421                    (wake->tv_usec >= 100000)) {
3422                 DEBUG("Waking up in %d.%01u seconds.",
3423                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3424         }
3425
3426
3427         /*
3428          *      FIXME: Put this somewhere else, where it isn't called
3429          *      all of the time...
3430          */
3431
3432 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3433         /*
3434          *      If there are no child threads, then there may
3435          *      be child processes.  In that case, wait for
3436          *      their exit status, and throw that exit status
3437          *      away.  This helps get rid of zxombie children.
3438          */
3439         while (waitpid(-1, &argval, WNOHANG) > 0) {
3440                 /* do nothing */
3441         }
3442 #endif
3443
3444 }
3445
3446 /*
3447  *      Externally-visibly functions.
3448  */
3449 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3450 {
3451         rad_listen_t *this, *head = NULL;
3452
3453         if (el) return 0;
3454
3455         time(&fr_start_time);
3456
3457         el = fr_event_list_create(event_status);
3458         if (!el) return 0;
3459
3460         pl = fr_packet_list_create(0);
3461         if (!pl) return 0;      /* leak el */
3462
3463         request_num_counter = 0;
3464
3465 #ifdef WITH_PROXY
3466         if (mainconfig.proxy_requests) {
3467                 pthread_mutexattr_t attr;
3468
3469                 /*
3470                  *      Create the tree for managing proxied requests and
3471                  *      responses.
3472                  */
3473                 proxy_list = fr_packet_list_create(1);
3474                 if (!proxy_list) return 0;
3475
3476 #ifdef HAVE_PTHREAD_H
3477                 pthread_mutexattr_init(&attr);
3478
3479 #ifdef PTHREAD_MUTEX_RECURSIVE
3480                 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) < 0) {
3481                         radlog(L_ERR, "FATAL: Failed to set type for proxy mutex: %s",
3482                                strerror(errno));
3483                         exit(1);
3484                 }
3485 #endif
3486
3487                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3488                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3489                                strerror(errno));
3490                         exit(1);
3491                 }
3492
3493                 pthread_mutexattr_destroy(&attr);
3494 #endif
3495         }
3496 #endif
3497
3498         /*
3499          *      Just before we spawn the child threads, force the log
3500          *      subsystem to re-open the log file for every write.
3501          */
3502         if (spawn_flag) force_log_reopen();
3503
3504 #ifdef HAVE_PTHREAD_H
3505 #ifndef __MINGW32__
3506         NO_SUCH_CHILD_PID = (pthread_t ) (0);
3507 #else
3508         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3509 #endif
3510         /*
3511          *      Initialize the threads ONLY if we're spawning, AND
3512          *      we're running normally.
3513          */
3514         if (spawn_flag && !check_config &&
3515             (thread_pool_init(cs, &spawn_flag) < 0)) {
3516                 exit(1);
3517         }
3518 #endif
3519
3520         /*
3521          *      Move all of the thread calls to this file?
3522          *
3523          *      It may be best for the mutexes to be in this file...
3524          */
3525         have_children = spawn_flag;
3526
3527         if (check_config) {
3528                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3529                        mainconfig.name);
3530                 return 1;
3531         }
3532
3533 #ifdef WITH_SELF_PIPE
3534         /*
3535          *      Child threads need a pipe to signal us, as do the
3536          *      signal handlers.
3537          */
3538         if (pipe(self_pipe) < 0) {
3539                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3540                        strerror(errno));
3541                 exit(1);
3542         }
3543         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3544                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3545                        strerror(errno));
3546                 exit(1);
3547         }
3548         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3549                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3550                        strerror(errno));
3551                 exit(1);
3552         }
3553
3554         if (!fr_event_fd_insert(el, 0, self_pipe[0],
3555                                   event_signal_handler, el)) {
3556                 radlog(L_ERR, "Failed creating handler for signals");
3557                 exit(1);
3558         }
3559 #endif  /* WITH_SELF_PIPE */
3560
3561 #ifdef WITH_PROXY
3562         /*
3563          *      Mark the proxy Fd's as unused.
3564          */
3565         {
3566                 int i;
3567
3568                 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3569         }
3570 #endif
3571
3572        DEBUG("%s: #### Opening IP addresses and Ports ####",
3573                mainconfig.name);
3574
3575        /*
3576         *       The server temporarily switches to an unprivileged
3577         *       user very early in the bootstrapping process.
3578         *       However, some sockets MAY require privileged access
3579         *       (bind to device, or to port < 1024, or to raw
3580         *       sockets).  Those sockets need to call suid up/down
3581         *       themselves around the functions that need a privileged
3582         *       uid.
3583         */
3584         if (listen_init(cs, &head) < 0) {
3585                 _exit(1);
3586         }
3587         
3588         /*
3589          *      At this point, no one has any business *ever* going
3590          *      back to root uid.
3591          */
3592         fr_suid_down_permanent();
3593
3594         /*
3595          *      Add all of the sockets to the event loop.
3596          */
3597         for (this = head;
3598              this != NULL;
3599              this = this->next) {
3600                 char buffer[256];
3601
3602                 this->print(this, buffer, sizeof(buffer));
3603
3604                 switch (this->type) {
3605 #ifdef WITH_DETAIL
3606                 case RAD_LISTEN_DETAIL:
3607                         DEBUG("Listening on %s", buffer);
3608
3609                         /*
3610                          *      Detail files are always known, and aren't
3611                          *      put into the socket event loop.
3612                          */
3613                         this->status = RAD_LISTEN_STATUS_KNOWN;
3614
3615                         /*
3616                          *      Set up the first poll interval.
3617                          */
3618                         event_poll_detail(this);
3619                         break;
3620 #endif
3621
3622 #ifdef WITH_PROXY
3623                 case RAD_LISTEN_PROXY:
3624                         rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3625                         rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3626                         
3627                         proxy_fds[this->fd & 0x1f] = this->fd;
3628                         proxy_listeners[this->fd & 0x1f] = this;
3629                         if (!fr_packet_list_socket_add(proxy_list,
3630                                                          this->fd)) {
3631                                 rad_assert(0 == 1);
3632                         }
3633                         /* FALL-THROUGH */
3634 #endif
3635
3636                 default:
3637                         break;
3638                 }
3639
3640                 event_new_fd(this);
3641
3642                 this->status = RAD_LISTEN_STATUS_KNOWN;
3643         }
3644
3645         mainconfig.listen = head;
3646
3647         return 1;
3648 }
3649
3650
3651 static int request_hash_cb(UNUSED void *ctx, void *data)
3652 {
3653         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3654
3655 #ifdef WITH_PROXY
3656         rad_assert(request->in_proxy_hash == FALSE);
3657 #endif
3658
3659         ev_request_free(&request);
3660
3661         return 0;
3662 }
3663
3664
3665 #ifdef WITH_PROXY
3666 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3667 {
3668         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3669
3670         ev_request_free(&request);
3671
3672         return 0;
3673 }
3674 #endif
3675
3676 void radius_event_free(void)
3677 {
3678         /*
3679          *      FIXME: Stop all threads, or at least check that
3680          *      they're all waiting on the semaphore, and the queues
3681          *      are empty.
3682          */
3683
3684 #ifdef WITH_PROXY
3685         /*
3686          *      There are requests in the proxy hash that aren't
3687          *      referenced from anywhere else.  Remove them first.
3688          */
3689         if (proxy_list) {
3690                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3691                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3692                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3693                 fr_packet_list_free(proxy_list);
3694                 proxy_list = NULL;
3695         }
3696 #endif
3697
3698         fr_packet_list_walk(pl, NULL, request_hash_cb);
3699
3700         fr_packet_list_free(pl);
3701         pl = NULL;
3702
3703         fr_event_list_free(el);
3704 }
3705
3706 int radius_event_process(void)
3707 {
3708         if (!el) return 0;
3709
3710         return fr_event_loop(el);
3711 }
3712
3713 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3714 {
3715         request->options = RAD_REQUEST_OPTION_DEBUG2;
3716
3717         if (request_pre_handler(request)) {
3718                 rad_assert(fun != NULL);
3719                 rad_assert(request != NULL);
3720                 
3721                 if (request->server) RDEBUG("server %s {",
3722                                             request->server != NULL ?
3723                                             request->server : ""); 
3724                 fun(request);
3725
3726                 if (request->server) RDEBUG("} # server %s",
3727                                              request->server != NULL ?
3728                                             request->server : "");
3729
3730                 request_post_handler(request);
3731         }
3732
3733         DEBUG2("Going to the next request");
3734         return;
3735 }