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