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