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