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