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