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