f7b7027139e43ebe6171511121f98c46c6de93b6
[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          *      We CANNOT divorce the CoA request from the parent
1578          *      request.  This function is running in a child thread,
1579          *      and we need access to the main event loop in order to
1580          *      to add the timers for the CoA packet.  See
1581          *      wait_a_bit().
1582          */
1583
1584         /*
1585          *      Forget about the original request completely at this
1586          *      point.
1587          */
1588         request = coa;
1589
1590         gettimeofday(&request->proxy_when, NULL);       
1591         request->received = request->next_when = request->proxy_when;
1592         rad_assert(request->proxy_reply == NULL);
1593
1594         /*
1595          *      Implement re-transmit algorithm as per RFC 5080
1596          *      Section 2.2.1.
1597          *
1598          *      We want IRT + RAND*IRT
1599          *      or 0.9 IRT + rand(0,.2) IRT
1600          *
1601          *      2^20 ~ USEC, and we want 2.
1602          *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1603          */
1604         delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1605         request->delay = delay * request->home_server->coa_irt;
1606         delay = request->home_server->coa_irt * USEC;
1607         delay -= delay / 10;
1608         delay += request->delay;
1609      
1610         request->delay = delay;
1611         tv_add(&request->next_when, delay);
1612         request->next_callback = retransmit_coa_request;
1613         
1614         /*
1615          *      Note that we set proxied BEFORE sending the packet.
1616          *
1617          *      Once we send it, the request is tainted, as
1618          *      another thread may have picked it up.  Don't
1619          *      touch it!
1620          */
1621         request->num_proxied_requests = 1;
1622         request->num_proxied_responses = 0;
1623         request->child_pid = NO_SUCH_CHILD_PID;
1624
1625         update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1626
1627         request->child_state = REQUEST_PROXIED;
1628
1629         DEBUG_PACKET(request, request->proxy, 1);
1630
1631         request->proxy_listener->send(request->proxy_listener,
1632                                       request);
1633         return 1;
1634 }
1635 #endif  /* WITH_COA */
1636
1637 #ifdef WITH_PROXY
1638 static int process_proxy_reply(REQUEST *request)
1639 {
1640         int rcode;
1641         int post_proxy_type = 0;
1642         VALUE_PAIR *vp;
1643         
1644         /*
1645          *      Delete any reply we had accumulated until now.
1646          */
1647         pairfree(&request->reply->vps);
1648         
1649         /*
1650          *      Run the packet through the post-proxy stage,
1651          *      BEFORE playing games with the attributes.
1652          */
1653         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1654         if (vp) {
1655                 RDEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1656                 post_proxy_type = vp->vp_integer;
1657         }
1658         
1659         if (request->home_pool && request->home_pool->virtual_server) {
1660                 const char *old_server = request->server;
1661                 
1662                 request->server = request->home_pool->virtual_server;
1663                 RDEBUG2(" server %s {", request->server);
1664                 rcode = module_post_proxy(post_proxy_type, request);
1665                 RDEBUG2(" }");
1666                 request->server = old_server;
1667         } else {
1668                 rcode = module_post_proxy(post_proxy_type, request);
1669         }
1670
1671 #ifdef WITH_COA
1672         if (request->packet->code == request->proxy->code)
1673           /*
1674            *    Don't run the next bit if we originated a CoA
1675            *    packet, after receiving an Access-Request or
1676            *    Accounting-Request.
1677            */
1678 #endif
1679         
1680         /*
1681          *      There may NOT be a proxy reply, as we may be
1682          *      running Post-Proxy-Type = Fail.
1683          */
1684         if (request->proxy_reply) {
1685                 /*
1686                  *      Delete the Proxy-State Attributes from
1687                  *      the reply.  These include Proxy-State
1688                  *      attributes from us and remote server.
1689                  */
1690                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1691                 
1692                 /*
1693                  *      Add the attributes left in the proxy
1694                  *      reply to the reply list.
1695                  */
1696                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1697                 request->proxy_reply->vps = NULL;
1698                 
1699                 /*
1700                  *      Free proxy request pairs.
1701                  */
1702                 pairfree(&request->proxy->vps);
1703         }
1704         
1705         switch (rcode) {
1706         default:  /* Don't do anything */
1707                 break;
1708         case RLM_MODULE_FAIL:
1709                 /* FIXME: debug print stuff */
1710                 request->child_state = REQUEST_DONE;
1711                 return 0;
1712                 
1713         case RLM_MODULE_HANDLED:
1714                 /* FIXME: debug print stuff */
1715                 request->child_state = REQUEST_DONE;
1716                 return 0;
1717         }
1718
1719         return 1;
1720 }
1721 #endif
1722
1723 static int request_pre_handler(REQUEST *request)
1724 {
1725         int rcode;
1726
1727         rad_assert(request->magic == REQUEST_MAGIC);
1728         rad_assert(request->packet != NULL);
1729
1730         request->child_state = REQUEST_RUNNING;
1731
1732         /*
1733          *      Don't decode the packet if it's an internal "fake"
1734          *      request.  Instead, just return so that the caller can
1735          *      process it.
1736          */
1737         if (request->packet->dst_port == 0) {
1738                 request->username = pairfind(request->packet->vps,
1739                                              PW_USER_NAME);
1740                 request->password = pairfind(request->packet->vps,
1741                                              PW_USER_PASSWORD);
1742                 return 1;
1743         }
1744
1745 #ifdef WITH_PROXY
1746         /*
1747          *      Put the decoded packet into it's proper place.
1748          */
1749         if (request->proxy_reply != NULL) {
1750                 rcode = request->proxy_listener->decode(request->proxy_listener,
1751                                                         request);
1752                 DEBUG_PACKET(request, request->proxy_reply, 0);
1753         } else
1754 #endif
1755         if (request->packet->vps == NULL) {
1756                 rcode = request->listener->decode(request->listener, request);
1757                 
1758                 if (debug_condition) {
1759                         int result = FALSE;
1760                         const char *my_debug = debug_condition;
1761
1762                         /*
1763                          *      Ignore parse errors.
1764                          */
1765                         radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1766                                                   &my_debug, 1,
1767                                                   &result);
1768                         if (result) {
1769                                 request->options = 2;
1770                                 request->radlog = radlog_request;
1771                         }
1772                 }
1773                 
1774                 DEBUG_PACKET(request, request->packet, 0);
1775         } else {
1776                 rcode = 0;
1777         }
1778
1779         if (rcode < 0) {
1780                 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1781                 request->child_state = REQUEST_DONE;
1782                 return 0;
1783         }
1784
1785         if (!request->username) {
1786                 request->username = pairfind(request->packet->vps,
1787                                              PW_USER_NAME);
1788         }
1789
1790 #ifdef WITH_PROXY
1791         if (request->proxy) {
1792                 return process_proxy_reply(request);
1793 #endif
1794         }
1795
1796         return 1;
1797 }
1798
1799
1800 #ifdef WITH_PROXY
1801 /*
1802  *      Do state handling when we proxy a request.
1803  */
1804 static int proxy_request(REQUEST *request)
1805 {
1806         struct timeval when;
1807         char buffer[128];
1808
1809         if (request->home_server->server) {
1810                 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1811                 return 0;
1812         }
1813
1814         if (!insert_into_proxy_hash(request, FALSE)) {
1815                 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1816                 return 0;
1817         }
1818
1819         request->proxy_listener->encode(request->proxy_listener, request);
1820
1821         when = request->received;
1822         when.tv_sec += request->root->max_request_time;
1823
1824         gettimeofday(&request->proxy_when, NULL);
1825
1826         request->next_when = request->proxy_when;
1827         request->next_when.tv_sec += request->home_server->response_window;
1828
1829         rad_assert(request->home_server->response_window > 0);
1830
1831         if (timercmp(&when, &request->next_when, <)) {
1832                 request->next_when = when;
1833         }
1834         request->next_callback = no_response_to_proxied_request;
1835
1836         RDEBUG2("Proxying request %d to home server %s port %d",
1837                request->number,
1838                inet_ntop(request->proxy->dst_ipaddr.af,
1839                          &request->proxy->dst_ipaddr.ipaddr,
1840                          buffer, sizeof(buffer)),
1841                request->proxy->dst_port);
1842
1843         /*
1844          *      Note that we set proxied BEFORE sending the packet.
1845          *
1846          *      Once we send it, the request is tainted, as
1847          *      another thread may have picked it up.  Don't
1848          *      touch it!
1849          */
1850         request->num_proxied_requests = 1;
1851         request->num_proxied_responses = 0;
1852 #ifdef HAVE_PTHREAD_H
1853         request->child_pid = NO_SUCH_CHILD_PID;
1854 #endif
1855         request->child_state = REQUEST_PROXIED;
1856
1857         DEBUG_PACKET(request, request->proxy, 1);
1858
1859         request->proxy_listener->send(request->proxy_listener,
1860                                       request);
1861         return 1;
1862 }
1863
1864
1865 /*
1866  *      "Proxy" the request by sending it to a new virtual server.
1867  */
1868 static int proxy_to_virtual_server(REQUEST *request)
1869 {
1870         REQUEST *fake;
1871         RAD_REQUEST_FUNP fun;
1872
1873         if (!request->home_server || !request->home_server->server) return 0;
1874
1875         if (request->parent) {
1876                 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1877                 return 0;
1878         }
1879
1880         fake = request_alloc_fake(request);
1881         if (!fake) {
1882                 RDEBUG2("WARNING: Out of memory");
1883                 return 0;
1884         }
1885
1886         fake->packet->vps = paircopy(request->proxy->vps);
1887         fake->server = request->home_server->server;
1888
1889         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1890                 fun = rad_authenticate;
1891
1892 #ifdef WITH_ACCOUNTING
1893         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1894                 fun = rad_accounting;
1895 #endif
1896
1897         } else {
1898                 RDEBUG2("Unknown packet type %d", request->proxy->code);
1899                 request_free(&fake);
1900                 return 0;
1901         }
1902
1903         RDEBUG2(">>> Sending proxied request internally to virtual server.");
1904         radius_handle_request(fake, fun);
1905         RDEBUG2("<<< Received proxied response from internal virtual server.");
1906
1907         request->proxy_reply = fake->reply;
1908         fake->reply = NULL;
1909
1910         request_free(&fake);
1911
1912         process_proxy_reply(request);
1913         fun(request);
1914
1915         return 2;               /* success, but NOT '1' !*/
1916 }
1917
1918 /*
1919  *      Return 1 if we did proxy it, or the proxy attempt failed
1920  *      completely.  Either way, the caller doesn't touch the request
1921  *      any more if we return 1.
1922  */
1923 static int successfully_proxied_request(REQUEST *request)
1924 {
1925         int rcode;
1926         int pre_proxy_type = 0;
1927         VALUE_PAIR *realmpair;
1928         VALUE_PAIR *strippedname;
1929         VALUE_PAIR *vp;
1930         char *realmname = NULL;
1931         home_server *home;
1932         REALM *realm = NULL;
1933         home_pool_t *pool;
1934
1935         /*
1936          *      If it was already proxied, do nothing.
1937          *
1938          *      FIXME: This should really be a serious error.
1939          */
1940         if (request->in_proxy_hash) {
1941                 return 0;
1942         }
1943
1944         realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1945         if (!realmpair || (realmpair->length == 0)) {
1946                 return 0;
1947         }
1948
1949         realmname = (char *) realmpair->vp_strvalue;
1950
1951         realm = realm_find2(realmname);
1952         if (!realm) {
1953                 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1954                 return 0;
1955         }
1956
1957         /*
1958          *      Figure out which pool to use.
1959          */
1960         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1961                 pool = realm->auth_pool;
1962
1963 #ifdef WITH_ACCOUNTING
1964         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1965                 pool = realm->acct_pool;
1966 #endif
1967
1968         } else {
1969                 rad_panic("Internal sanity check failed");
1970         }
1971
1972         if (!pool) {
1973                 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1974                        realmname);
1975                 return 0;
1976         }
1977
1978         home = home_server_ldb(realmname, pool, request);
1979         if (!home) {
1980                 RDEBUG2("ERROR: Failed to find live home server for realm %s",
1981                        realmname);
1982                 return -1;
1983         }
1984         request->home_pool = pool;
1985
1986         /*
1987          *      Remember that we sent the request to a Realm.
1988          */
1989         pairadd(&request->packet->vps,
1990                 pairmake("Realm", realmname, T_OP_EQ));
1991
1992         /*
1993          *      Strip the name, if told to.
1994          *
1995          *      Doing it here catches the case of proxied tunneled
1996          *      requests.
1997          */
1998         if (realm->striprealm == TRUE &&
1999            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2000                 /*
2001                  *      If there's a Stripped-User-Name attribute in
2002                  *      the request, then use THAT as the User-Name
2003                  *      for the proxied request, instead of the
2004                  *      original name.
2005                  *
2006                  *      This is done by making a copy of the
2007                  *      Stripped-User-Name attribute, turning it into
2008                  *      a User-Name attribute, deleting the
2009                  *      Stripped-User-Name and User-Name attributes
2010                  *      from the vps list, and making the new
2011                  *      User-Name the head of the vps list.
2012                  */
2013                 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2014                 if (!vp) {
2015                         vp = radius_paircreate(request, NULL,
2016                                                PW_USER_NAME, PW_TYPE_STRING);
2017                         rad_assert(vp != NULL); /* handled by above function */
2018                         /* Insert at the START of the list */
2019                         vp->next = request->proxy->vps;
2020                         request->proxy->vps = vp;
2021                 }
2022                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2023                        sizeof(vp->vp_strvalue));
2024                 vp->length = strippedname->length;
2025
2026                 /*
2027                  *      Do NOT delete Stripped-User-Name.
2028                  */
2029         }
2030
2031         /*
2032          *      If there is no PW_CHAP_CHALLENGE attribute but
2033          *      there is a PW_CHAP_PASSWORD we need to add it
2034          *      since we can't use the request authenticator
2035          *      anymore - we changed it.
2036          */
2037         if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2038             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2039                 vp = radius_paircreate(request, &request->proxy->vps,
2040                                        PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2041                 vp->length = AUTH_VECTOR_LEN;
2042                 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2043         }
2044
2045         /*
2046          *      The RFC's say we have to do this, but FreeRADIUS
2047          *      doesn't need it.
2048          */
2049         vp = radius_paircreate(request, &request->proxy->vps,
2050                                PW_PROXY_STATE, PW_TYPE_OCTETS);
2051         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2052                  request->packet->id);
2053         vp->length = strlen(vp->vp_strvalue);
2054
2055         /*
2056          *      Should be done BEFORE inserting into proxy hash, as
2057          *      pre-proxy may use this information, or change it.
2058          */
2059         request->proxy->code = request->packet->code;
2060
2061         /*
2062          *      Call the pre-proxy routines.
2063          */
2064         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2065         if (vp) {
2066                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
2067                 pre_proxy_type = vp->vp_integer;
2068         }
2069
2070         rad_assert(request->home_pool != NULL);
2071
2072         if (request->home_pool->virtual_server) {
2073                 const char *old_server = request->server;
2074                 
2075                 request->server = request->home_pool->virtual_server;
2076                 RDEBUG2(" server %s {", request->server);
2077                 rcode = module_pre_proxy(pre_proxy_type, request);
2078                 RDEBUG2(" }");
2079                         request->server = old_server;
2080         } else {
2081                 rcode = module_pre_proxy(pre_proxy_type, request);
2082         }
2083         switch (rcode) {
2084         case RLM_MODULE_FAIL:
2085         case RLM_MODULE_INVALID:
2086         case RLM_MODULE_NOTFOUND:
2087         case RLM_MODULE_USERLOCK:
2088         default:
2089                 /* FIXME: debug print failed stuff */
2090                 return -1;
2091
2092         case RLM_MODULE_REJECT:
2093         case RLM_MODULE_HANDLED:
2094                 return 0;
2095
2096         /*
2097          *      Only proxy the packet if the pre-proxy code succeeded.
2098          */
2099         case RLM_MODULE_NOOP:
2100         case RLM_MODULE_OK:
2101         case RLM_MODULE_UPDATED:
2102                 break;
2103         }
2104
2105         /*
2106          *      If it's a fake request, don't send the proxy
2107          *      packet.  The outer tunnel session will take
2108          *      care of doing that.
2109          */
2110         if (request->packet->dst_port == 0) {
2111                 request->home_server = NULL;
2112                 return 1;
2113         }
2114
2115         if (request->home_server->server) {
2116                 return proxy_to_virtual_server(request);
2117         }
2118
2119         if (!proxy_request(request)) {
2120                 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2121                 return -1;
2122         }
2123         
2124         return 1;
2125 }
2126 #endif
2127
2128 static void request_post_handler(REQUEST *request)
2129 {
2130         int child_state = -1;
2131         struct timeval when;
2132         VALUE_PAIR *vp;
2133
2134         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2135             (request->parent &&
2136              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2137                 RDEBUG2("Request %d was cancelled.", request->number);
2138 #ifdef HAVE_PTHREAD_H
2139                 request->child_pid = NO_SUCH_CHILD_PID;
2140 #endif
2141                 child_state = REQUEST_DONE;
2142                 goto cleanup;
2143         }
2144
2145         if (request->child_state != REQUEST_RUNNING) {
2146                 rad_panic("Internal sanity check failed");
2147         }
2148
2149 #ifdef WITH_COA
2150         /*
2151          *      If it's not in the request hash, it's a CoA request.
2152          *      We hope.
2153          */
2154         if (!request->in_request_hash &&
2155             request->proxy &&
2156             ((request->proxy->code == PW_COA_REQUEST) ||
2157              (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2158                 request->next_callback = NULL;
2159                 child_state = REQUEST_DONE;
2160                 goto cleanup;
2161         }
2162 #endif
2163
2164         if ((request->reply->code == 0) &&
2165             ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2166             (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2167                 request->reply->code = PW_AUTHENTICATION_REJECT;
2168         }
2169
2170 #ifdef WITH_PROXY
2171         if (request->root->proxy_requests &&
2172             !request->in_proxy_hash &&
2173             (request->reply->code == 0) &&
2174             (request->packet->dst_port != 0) &&
2175             (request->packet->code != PW_STATUS_SERVER)) {
2176                 int rcode = successfully_proxied_request(request);
2177
2178 #ifdef WITH_COA
2179                 /*
2180                  *      If we proxy it, we CANNOT originate a CoA
2181                  *      request at the same time.
2182                  */
2183                 if (rcode != 0) request_free(&request->coa);
2184 #endif
2185
2186                 if (rcode == 1) return;
2187
2188                 /*
2189                  *      Failed proxying it (dead home servers, etc.)
2190                  *      Run it through Post-Proxy-Type = Fail, and
2191                  *      respond to the request.
2192                  *
2193                  *      Note that we're in a child thread here, so we
2194                  *      do NOT re-schedule the request.  Instead, we
2195                  *      do what we would have done, which is run the
2196                  *      pre-handler, a NULL request handler, and then
2197                  *      the post handler.
2198                  */
2199                 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2200                         request_pre_handler(request);
2201                 }
2202
2203                 /*
2204                  *      Else we weren't supposed to proxy it,
2205                  *      OR we proxied it internally to a virutal server.
2206                  */
2207         }
2208 #endif
2209
2210         /*
2211          *      Fake requests don't get encoded or signed.  The caller
2212          *      also requires the reply VP's, so we don't free them
2213          *      here!
2214          */
2215         if (request->packet->dst_port == 0) {
2216                 /* FIXME: RDEBUG going to the next request */
2217 #ifdef HAVE_PTHREAD_H
2218                 request->child_pid = NO_SUCH_CHILD_PID;
2219 #endif
2220                 request->child_state = REQUEST_DONE;
2221                 return;
2222         }
2223
2224 #ifdef WITH_PROXY
2225         /*
2226          *      Copy Proxy-State from the request to the reply.
2227          */
2228         vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2229         if (vp) pairadd(&request->reply->vps, vp);
2230 #endif
2231
2232         /*
2233          *      Access-Requests get delayed or cached.
2234          */
2235         switch (request->packet->code) {
2236         case PW_AUTHENTICATION_REQUEST:
2237                 gettimeofday(&request->next_when, NULL);
2238
2239                 if (request->reply->code == 0) {
2240                         /*
2241                          *      Check if the lack of response is intentional.
2242                          */
2243                         vp = pairfind(request->config_items,
2244                                       PW_RESPONSE_PACKET_TYPE);
2245                         if (!vp) {
2246                                 RDEBUG2("There was no response configured: rejecting request %d",
2247                                        request->number);
2248                                 request->reply->code = PW_AUTHENTICATION_REJECT;
2249                         } else if (vp->vp_integer == 256) {
2250                                 RDEBUG2("Not responding to request %d",
2251                                        request->number);
2252
2253                         } else {
2254                                 request->reply->code = vp->vp_integer;
2255
2256                         }
2257                 }
2258
2259                 /*
2260                  *      Run rejected packets through
2261                  *
2262                  *      Post-Auth-Type = Reject
2263                  */
2264                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2265                         pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2266                         vp = radius_pairmake(request, &request->config_items,
2267                                              "Post-Auth-Type", "Reject",
2268                                              T_OP_SET);
2269                         if (vp) rad_postauth(request);
2270
2271                         /*
2272                          *      If configured, delay Access-Reject packets.
2273                          *
2274                          *      If request->root->reject_delay = 0, we discover
2275                          *      that we have to send the packet now.
2276                          */
2277                         when = request->received;
2278                         when.tv_sec += request->root->reject_delay;
2279
2280                         if (timercmp(&when, &request->next_when, >)) {
2281                                 RDEBUG2("Delaying reject of request %d for %d seconds",
2282                                        request->number,
2283                                        request->root->reject_delay);
2284                                 request->next_when = when;
2285                                 request->next_callback = reject_delay;
2286 #ifdef HAVE_PTHREAD_H
2287                                 request->child_pid = NO_SUCH_CHILD_PID;
2288 #endif
2289                                 request->child_state = REQUEST_REJECT_DELAY;
2290                                 return;
2291                         }
2292                 }
2293
2294                 request->next_when.tv_sec += request->root->cleanup_delay;
2295                 request->next_callback = cleanup_delay;
2296                 child_state = REQUEST_CLEANUP_DELAY;
2297                 break;
2298
2299         case PW_ACCOUNTING_REQUEST:
2300                 request->next_callback = NULL; /* just to be safe */
2301                 child_state = REQUEST_DONE;
2302                 break;
2303
2304                 /*
2305                  *      FIXME: Status-Server should probably not be
2306                  *      handled here...
2307                  */
2308         case PW_STATUS_SERVER:
2309                 request->next_callback = NULL;
2310                 child_state = REQUEST_DONE;
2311                 break;
2312
2313         default:
2314                 if ((request->packet->code > 1024) &&
2315                     (request->packet->code < (1024 + 254 + 1))) {
2316                         request->next_callback = NULL;
2317                         child_state = REQUEST_DONE;
2318                         break;
2319                 }
2320
2321                 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
2322                 request->next_callback = NULL;
2323                 child_state = REQUEST_DONE;
2324                 break;
2325         }
2326
2327         /*
2328          *      Suppress "no reply" packets here, unless we're reading
2329          *      from the "detail" file.  In that case, we've got to
2330          *      tell the detail file handler that the request is dead,
2331          *      and it should re-send it.
2332          *      If configured, encode, sign, and send.
2333          */
2334         if ((request->reply->code != 0) ||
2335             (request->listener->type == RAD_LISTEN_DETAIL)) {
2336                 DEBUG_PACKET(request, request->reply, 1);
2337                 request->listener->send(request->listener, request);
2338         }
2339
2340 #ifdef WITH_COA
2341         /*
2342          *      Now that we've completely processed the request,
2343          *      see if we need to originate a CoA request.
2344          */
2345         if (request->coa ||
2346             (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2347                 if (!originated_coa_request(request)) {
2348                         RDEBUG2("Do CoA Fail handler here");
2349                 }
2350                 /* request->coa is stil set, so we can update events */
2351         }
2352 #endif
2353
2354  cleanup:
2355         /*
2356          *      Clean up.  These are no longer needed.
2357          */
2358         pairfree(&request->config_items);
2359
2360         pairfree(&request->packet->vps);
2361         request->username = NULL;
2362         request->password = NULL;
2363
2364         pairfree(&request->reply->vps);
2365
2366 #ifdef WITH_PROXY
2367         if (request->proxy) {
2368                 pairfree(&request->proxy->vps);
2369
2370                 if (request->proxy_reply) {
2371                         pairfree(&request->proxy_reply->vps);
2372                 }
2373
2374 #if 0
2375                 /*
2376                  *      We're not tracking responses from the home
2377                  *      server, we can therefore free this memory in
2378                  *      the child thread.
2379                  */
2380                 if (!request->in_proxy_hash) {
2381                         rad_free(&request->proxy);
2382                         rad_free(&request->proxy_reply);
2383                         request->home_server = NULL;
2384                 }
2385 #endif
2386         }
2387 #endif
2388
2389         RDEBUG2("Finished request %d.", request->number);
2390         rad_assert(child_state >= 0);
2391         request->child_state = child_state;
2392
2393         /*
2394          *      Single threaded mode: update timers now.
2395          */
2396         if (!have_children) wait_a_bit(request);
2397 }
2398
2399
2400 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2401 {
2402 #ifdef WITH_PROXY
2403         char buffer[128];
2404 #endif
2405
2406         RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2407         RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2408         
2409         switch (request->child_state) {
2410         case REQUEST_QUEUED:
2411         case REQUEST_RUNNING:
2412 #ifdef WITH_PROXY
2413         discard:
2414 #endif
2415                 radlog(L_ERR, "Discarding duplicate request from "
2416                        "client %s port %d - ID: %d due to unfinished request %d",
2417                        client->shortname,
2418                        request->packet->src_port,request->packet->id,
2419                        request->number);
2420                 break;
2421
2422 #ifdef WITH_PROXY
2423         case REQUEST_PROXIED:
2424                 /*
2425                  *      We're not supposed to have duplicate
2426                  *      accounting packets.  The other states handle
2427                  *      duplicates fine (discard, or send duplicate
2428                  *      reply).  But we do NOT want to retransmit an
2429                  *      accounting request here, because that would
2430                  *      involve updating the Acct-Delay-Time, and
2431                  *      therefore changing the packet Id, etc.
2432                  *
2433                  *      Instead, we just discard the packet.  We may
2434                  *      eventually respond, or the client will send a
2435                  *      new accounting packet.            
2436                  *
2437                  *      The same comments go for Status-Server, and
2438                  *      other packet types.
2439                  *
2440                  *      FIXME: coa: when we proxy CoA && Disconnect
2441                  *      packets, this logic has to be fixed.
2442                  */
2443                 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2444                         goto discard;
2445                 }
2446
2447                 check_for_zombie_home_server(request);
2448
2449                 /*
2450                  *      If we've just discovered that the home server is
2451                  *      dead, send the packet to another one.
2452                  */
2453                 if ((request->packet->dst_port != 0) &&
2454                     (request->home_server->state == HOME_STATE_IS_DEAD)) {
2455                         home_server *home;
2456
2457                         remove_from_proxy_hash(request);
2458
2459                         home = home_server_ldb(NULL, request->home_pool, request);
2460                         if (!home) {
2461                                 RDEBUG2("Failed to find live home server for request %d", request->number);
2462                         no_home_servers:
2463                                 /*
2464                                  *      Do post-request processing,
2465                                  *      and any insertion of necessary
2466                                  *      events.
2467                                  */
2468                                 post_proxy_fail_handler(request);
2469                                 return;
2470                         }
2471
2472                         request->proxy->code = request->packet->code;
2473
2474                         /*
2475                          *      Free the old packet, to force re-encoding
2476                          */
2477                         free(request->proxy->data);
2478                         request->proxy->data = NULL;
2479                         request->proxy->data_len = 0;
2480
2481                         /*
2482                          *      This request failed over to a virtual
2483                          *      server.  Push it back onto the queue
2484                          *      to be processed.
2485                          */
2486                         if (request->home_server->server) {
2487                                 proxy_fallback_handler(request);
2488                                 return;
2489                         }
2490
2491                         /*
2492                          *      Try to proxy the request.
2493                          */
2494                         if (!proxy_request(request)) {
2495                                 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2496                                 goto no_home_servers;
2497                         }
2498
2499                         /*
2500                          *      This code executes in the main server
2501                          *      thread, so there's no need for locking.
2502                          */
2503                         rad_assert(request->next_callback != NULL);
2504                         INSERT_EVENT(request->next_callback, request);
2505                         request->next_callback = NULL;
2506                         return;
2507                 } /* else the home server is still alive */
2508
2509                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2510                        inet_ntop(request->proxy->dst_ipaddr.af,
2511                                  &request->proxy->dst_ipaddr.ipaddr,
2512                                  buffer, sizeof(buffer)),
2513                        request->proxy->dst_port,
2514                        request->proxy->id);
2515                 request->num_proxied_requests++;
2516
2517                 DEBUG_PACKET(request, request->proxy, 1);
2518                 request->proxy_listener->send(request->proxy_listener,
2519                                               request);
2520                 break;
2521 #endif
2522
2523         case REQUEST_REJECT_DELAY:
2524                 RDEBUG2("Waiting to send Access-Reject "
2525                        "to client %s port %d - ID: %d",
2526                        client->shortname,
2527                        request->packet->src_port, request->packet->id);
2528                 break;
2529
2530         case REQUEST_CLEANUP_DELAY:
2531         case REQUEST_DONE:
2532                 /*
2533                  *      FIXME: This sends duplicate replies to
2534                  *      accounting requests, even if Acct-Delay-Time
2535                  *      or Event-Timestamp is in the packet.  In those
2536                  *      cases, the Id should be changed, and the packet
2537                  *      re-calculated.
2538                  */
2539                 RDEBUG2("Sending duplicate reply "
2540                        "to client %s port %d - ID: %d",
2541                        client->shortname,
2542                        request->packet->src_port, request->packet->id);
2543                 DEBUG_PACKET(request, request->reply, 1);
2544                 request->listener->send(request->listener, request);
2545                 break;
2546         }
2547 }
2548
2549
2550 static void received_conflicting_request(REQUEST *request,
2551                                          const RADCLIENT *client)
2552 {
2553         radlog(L_ERR, "Received conflicting packet from "
2554                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
2555                client->shortname,
2556                request->packet->src_port, request->packet->id,
2557                request->number);
2558
2559         /*
2560          *      Nuke it from the request hash, so we can receive new
2561          *      packets.
2562          */
2563         remove_from_request_hash(request);
2564
2565         switch (request->child_state) {
2566 #ifdef HAVE_PTHREAD_H
2567                 /*
2568                  *      It's queued or running.  Tell it to stop, and
2569                  *      wait for it to do so.
2570                  */
2571         case REQUEST_QUEUED:
2572         case REQUEST_RUNNING:
2573                 request->master_state = REQUEST_STOP_PROCESSING;
2574                 request->delay += request->delay >> 1;
2575
2576                 tv_add(&request->when, request->delay);
2577
2578                 INSERT_EVENT(wait_for_child_to_die, request);
2579                 return;
2580 #endif
2581
2582                 /*
2583                  *      It's in some other state, and therefore also
2584                  *      in the event queue.  At some point, the
2585                  *      child will notice, and we can then delete it.
2586                  */
2587         default:
2588                 rad_assert(request->ev != NULL);
2589                 break;
2590         }
2591 }
2592
2593
2594 static int can_handle_new_request(RADIUS_PACKET *packet,
2595                                   RADCLIENT *client,
2596                                   struct main_config_t *root)
2597 {
2598         /*
2599          *      Count the total number of requests, to see if
2600          *      there are too many.  If so, return with an
2601          *      error.
2602          */
2603         if (root->max_requests) {
2604                 int request_count = fr_packet_list_num_elements(pl);
2605
2606                 /*
2607                  *      This is a new request.  Let's see if
2608                  *      it makes us go over our configured
2609                  *      bounds.
2610                  */
2611                 if (request_count > root->max_requests) {
2612                         radlog(L_ERR, "Dropping request (%d is too many): "
2613                                "from client %s port %d - ID: %d", request_count,
2614                                client->shortname,
2615                                packet->src_port, packet->id);
2616                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2617                                "\tThe value for 'max_requests' is probably set too low.\n");
2618                         return 0;
2619                 } /* else there were a small number of requests */
2620         } /* else there was no configured limit for requests */
2621
2622         /*
2623          *      FIXME: Add per-client checks.  If one client is sending
2624          *      too many packets, start discarding them.
2625          *
2626          *      We increment the counters here, and decrement them
2627          *      when the response is sent... somewhere in this file.
2628          */
2629
2630         /*
2631          *      FUTURE: Add checks for system load.  If the system is
2632          *      busy, start dropping requests...
2633          *
2634          *      We can probably keep some statistics ourselves...  if
2635          *      there are more requests coming in than we can handle,
2636          *      start dropping some.
2637          */
2638
2639         return 1;
2640 }
2641
2642
2643 int received_request(rad_listen_t *listener,
2644                      RADIUS_PACKET *packet, REQUEST **prequest,
2645                      RADCLIENT *client)
2646 {
2647         RADIUS_PACKET **packet_p;
2648         REQUEST *request = NULL;
2649         struct main_config_t *root = &mainconfig;
2650
2651         packet_p = fr_packet_list_find(pl, packet);
2652         if (packet_p) {
2653                 request = fr_packet2myptr(REQUEST, packet, packet_p);
2654                 rad_assert(request->in_request_hash);
2655
2656                 if ((request->packet->data_len == packet->data_len) &&
2657                     (memcmp(request->packet->vector, packet->vector,
2658                             sizeof(packet->vector)) == 0)) {
2659                         received_retransmit(request, client);
2660                         return 0;
2661                 }
2662
2663                 /*
2664                  *      The new request is different from the old one,
2665                  *      but maybe the old is finished.  If so, delete
2666                  *      the old one.
2667                  */
2668                 switch (request->child_state) {
2669                         struct timeval when;
2670
2671                 default:
2672                         gettimeofday(&when, NULL);
2673                         when.tv_sec -= 1;
2674
2675                         /*
2676                          *      If the cached request was received
2677                          *      within the last second, then we
2678                          *      discard the NEW request instead of the
2679                          *      old one.  This will happen ONLY when
2680                          *      the client is severely broken, and is
2681                          *      sending conflicting packets very
2682                          *      quickly.
2683                          */
2684                         if (timercmp(&when, &request->received, <)) {
2685                                 radlog(L_ERR, "Discarding conflicting packet from "
2686                                        "client %s port %d - ID: %d due to recent request %d.",
2687                                        client->shortname,
2688                                        packet->src_port, packet->id,
2689                                        request->number);
2690                                 return 0;
2691                         }
2692
2693                         received_conflicting_request(request, client);
2694                         request = NULL;
2695                         break;
2696
2697                 case REQUEST_REJECT_DELAY:
2698                 case REQUEST_CLEANUP_DELAY:
2699                         request->child_state = REQUEST_DONE;
2700                 case REQUEST_DONE:
2701                         cleanup_delay(request);
2702                         request = NULL;
2703                         break;
2704                 }
2705         }
2706
2707         /*
2708          *      We may want to quench the new request.
2709          */
2710         if ((listener->type != RAD_LISTEN_DETAIL) &&
2711             !can_handle_new_request(packet, client, root)) {
2712                 return 0;
2713         }
2714
2715         /*
2716          *      Create and initialize the new request.
2717          */
2718         request = request_alloc(); /* never fails */
2719
2720         if ((request->reply = rad_alloc(0)) == NULL) {
2721                 radlog(L_ERR, "No memory");
2722                 exit(1);
2723         }
2724
2725         request->listener = listener;
2726         request->client = client;
2727         request->packet = packet;
2728         request->packet->timestamp = request->timestamp;
2729         request->number = request_num_counter++;
2730         request->priority = listener->type;
2731 #ifdef HAVE_PTHREAD_H
2732         request->child_pid = NO_SUCH_CHILD_PID;
2733 #endif
2734
2735         /*
2736          *      Status-Server packets go to the head of the queue.
2737          */
2738         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2739
2740         /*
2741          *      Set virtual server identity
2742          */
2743         if (client->server) {
2744                 request->server = client->server;
2745         } else if (listener->server) {
2746                 request->server = listener->server;
2747         } else {
2748                 request->server = NULL;
2749         }
2750
2751         /*
2752          *      Remember the request in the list.
2753          */
2754         if (!fr_packet_list_insert(pl, &request->packet)) {
2755                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2756                 request_free(&request);
2757                 return 0;
2758         }
2759
2760         request->in_request_hash = TRUE;
2761         request->root = root;
2762         root->refcount++;
2763
2764         /*
2765          *      The request passes many of our sanity checks.
2766          *      From here on in, if anything goes wrong, we
2767          *      send a reject message, instead of dropping the
2768          *      packet.
2769          */
2770
2771         /*
2772          *      Build the reply template from the request.
2773          */
2774
2775         request->reply->sockfd = request->packet->sockfd;
2776         request->reply->dst_ipaddr = request->packet->src_ipaddr;
2777         request->reply->src_ipaddr = request->packet->dst_ipaddr;
2778         request->reply->dst_port = request->packet->src_port;
2779         request->reply->src_port = request->packet->dst_port;
2780         request->reply->id = request->packet->id;
2781         request->reply->code = 0; /* UNKNOWN code */
2782         memcpy(request->reply->vector, request->packet->vector,
2783                sizeof(request->reply->vector));
2784         request->reply->vps = NULL;
2785         request->reply->data = NULL;
2786         request->reply->data_len = 0;
2787
2788         request->master_state = REQUEST_ACTIVE;
2789         request->child_state = REQUEST_QUEUED;
2790         request->next_callback = NULL;
2791
2792         gettimeofday(&request->received, NULL);
2793         request->timestamp = request->received.tv_sec;
2794         request->when = request->received;
2795
2796         request->delay = USEC;
2797
2798         tv_add(&request->when, request->delay);
2799
2800         INSERT_EVENT(wait_a_bit, request);
2801
2802         *prequest = request;
2803         return 1;
2804 }
2805
2806
2807 #ifdef WITH_PROXY
2808 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2809 {
2810         char            buffer[128];
2811         REQUEST         *request;
2812
2813         /*
2814          *      Also removes from the proxy hash if responses == requests
2815          */
2816         request = lookup_in_proxy_hash(packet);
2817
2818         if (!request) {
2819                 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
2820                        inet_ntop(packet->src_ipaddr.af,
2821                                  &packet->src_ipaddr.ipaddr,
2822                                  buffer, sizeof(buffer)),
2823                        packet->src_port, packet->id);
2824                 return NULL;
2825         }
2826
2827         /*
2828          *      We haven't replied to the NAS, but we have seen an
2829          *      earlier reply from the home server.  Ignore this packet,
2830          *      as we're likely still processing the previous reply.
2831          */
2832         if (request->proxy_reply) {
2833                 if (memcmp(request->proxy_reply->vector,
2834                            packet->vector,
2835                            sizeof(request->proxy_reply->vector)) == 0) {
2836                         RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d for request %d",
2837                                inet_ntop(packet->src_ipaddr.af,
2838                                          &packet->src_ipaddr.ipaddr,
2839                                          buffer, sizeof(buffer)),
2840                                packet->src_port, packet->id,
2841                                request->number);
2842                 } else {
2843                         /*
2844                          *      ? The home server gave us a new proxy
2845                          *      reply which doesn't match the old
2846                          *      one.  Delete it.
2847                          */
2848                         RDEBUG2("Ignoring conflicting proxy reply");
2849                 }
2850                 
2851                 /* assert that there's an event queued for request? */
2852                 return NULL;
2853         }
2854
2855         gettimeofday(&now, NULL);
2856
2857         /*
2858          *      Maybe move this earlier in the decision process?
2859          *      Having it here means that late or duplicate proxy
2860          *      replies no longer get the home server marked as
2861          *      "alive".  This might be good for stability, though.
2862          */
2863         request->home_server->state = HOME_STATE_ALIVE;
2864         
2865 #ifdef WITH_COA
2866         /*
2867          *      When originating CoA, the "proxy" reply is the reply
2868          *      to the CoA request that we originated.  At this point,
2869          *      the original request is finished, and it has a reply.
2870          *
2871          *      However, if we haven't separated the two requests, do
2872          *      so now.  This is done so that cleaning up the original
2873          *      request won't cause the CoA request to be free'd.  See
2874          *      util.c, request_free()
2875          */
2876         if (request->parent && (request->parent->coa == request)) {
2877                 request->parent->coa = NULL;
2878                 request->parent = NULL;
2879
2880         } else
2881                 /*
2882                  *      Skip the next set of checks, as the original
2883                  *      reply is cached.  We want to be able to still
2884                  *      process the CoA reply, AND to reference the
2885                  *      original request/reply.
2886                  *
2887                  *      This is getting to be really quite a bit of a
2888                  *      hack.
2889                  */
2890 #endif
2891
2892         /*
2893          *      If there's a reply to the NAS, ignore everything
2894          *      related to proxy responses
2895          */
2896         if (request->reply && request->reply->code != 0) {
2897                 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
2898                 return NULL;
2899         }
2900         
2901 #ifdef WITH_STATS
2902         /*
2903          *      The average includes our time to receive packets and
2904          *      look them up in the hashes, which should be the same
2905          *      for all packets.
2906          *
2907          *      We update the response time only for the FIRST packet
2908          *      we receive.
2909          */
2910         if (request->home_server->ema.window > 0) {
2911                 radius_stats_ema(&request->home_server->ema,
2912                                  &now, &request->proxy_when);
2913         }
2914 #endif
2915
2916         switch (request->child_state) {
2917         case REQUEST_QUEUED:
2918         case REQUEST_RUNNING:
2919                 radlog(L_ERR, "Internal sanity check failed for child state");
2920                 /* FALL-THROUGH */
2921
2922         case REQUEST_REJECT_DELAY:
2923         case REQUEST_CLEANUP_DELAY:
2924         case REQUEST_DONE:
2925                 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'",
2926                        inet_ntop(packet->src_ipaddr.af,
2927                                  &packet->src_ipaddr.ipaddr,
2928                                  buffer, sizeof(buffer)),
2929                        packet->src_port, packet->id,
2930                        request->number);
2931                 /* assert that there's an event queued for request? */
2932                 return NULL;
2933
2934         case REQUEST_PROXIED:
2935                 break;
2936         }
2937
2938         request->proxy_reply = packet;
2939
2940 #if 0
2941         /*
2942          *      Perform RTT calculations, as per RFC 2988 (for TCP).
2943          *      Note that we only do so on the first response.
2944          */
2945         if ((request->num_proxied_responses == 1)
2946                 int rtt;
2947                 home_server *home = request->home_server;
2948
2949                 rtt = now.tv_sec - request->proxy_when.tv_sec;
2950                 rtt *= USEC;
2951                 rtt += now.tv_usec;
2952                 rtt -= request->proxy_when.tv_usec;
2953
2954                 if (!home->has_rtt) {
2955                         home->has_rtt = TRUE;
2956
2957                         home->srtt = rtt;
2958                         home->rttvar = rtt / 2;
2959
2960                 } else {
2961                         home->rttvar -= home->rttvar >> 2;
2962                         home->rttvar += (home->srtt - rtt);
2963                         home->srtt -= home->srtt >> 3;
2964                         home->srtt += rtt >> 3;
2965                 }
2966
2967                 home->rto = home->srtt;
2968                 if (home->rttvar > (USEC / 4)) {
2969                         home->rto += home->rttvar * 4;
2970                 } else {
2971                         home->rto += USEC;
2972                 }
2973         }
2974 #endif
2975
2976         /*
2977          *      There's no incoming request, so it's a proxied packet
2978          *      we originated.
2979          */
2980         if (!request->packet) {
2981                 received_response_to_ping(request);
2982                 return NULL;
2983         }
2984
2985         request->child_state = REQUEST_QUEUED;
2986         request->when = now;
2987         request->delay = USEC;
2988         request->priority = RAD_LISTEN_PROXY;
2989         tv_add(&request->when, request->delay);
2990
2991         /*
2992          *      Wait a bit will take care of max_request_time
2993          */
2994         INSERT_EVENT(wait_a_bit, request);
2995
2996         return request;
2997 }
2998 #endif
2999
3000 void event_new_fd(rad_listen_t *this)
3001 {
3002         char buffer[1024];
3003         
3004         this->print(this, buffer, sizeof(buffer));
3005         
3006         if (this->status == RAD_LISTEN_STATUS_INIT) {
3007                 if (just_started) {
3008                         DEBUG("Listening on %s", buffer);
3009                 } else {
3010                         DEBUG2(" ... adding new socket %s", buffer);
3011                 }
3012                 if (!fr_event_fd_insert(el, 0, this->fd,
3013                                         event_socket_handler, this)) {
3014                         radlog(L_ERR, "Failed remembering handle for proxy socket!");
3015                         exit(1);
3016                 }
3017                 
3018                 this->status = RAD_LISTEN_STATUS_KNOWN;
3019                 return;
3020         }
3021         
3022         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3023                 DEBUG2(" ... closing socket %s", buffer);
3024                 
3025                 fr_event_fd_delete(el, 0, this->fd);
3026                 this->status = RAD_LISTEN_STATUS_FINISH;
3027                 
3028                 /*
3029                  *      Close the fd AFTER fixing up the requests and
3030                  *      listeners, so that they don't send/recv on the
3031                  *      wrong socket (if someone manages to open
3032                  *      another one).
3033                  */
3034                 close(this->fd);
3035                 this->fd = -1;
3036         }
3037 }
3038
3039 static void handle_signal_self(int flag)
3040 {
3041         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3042                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3043                         fr_event_loop_exit(el, 1);
3044                 } else {
3045                         fr_event_loop_exit(el, 2);
3046                 }
3047
3048                 return;
3049         } /* else exit/term flags weren't set */
3050
3051         /*
3052          *      Tell the even loop to stop processing.
3053          */
3054         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3055                 time_t when;
3056                 static time_t last_hup = 0;
3057
3058                 DEBUG("Received HUP signal.");
3059
3060                 when = time(NULL);
3061                 if ((int) (when - last_hup) < 5) {
3062                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3063                         return;
3064                 }
3065                 last_hup = when;
3066
3067                 fr_event_loop_exit(el, 0x80);
3068         }
3069
3070 #ifdef WITH_DETAIL
3071         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3072                 rad_listen_t *this;
3073                 
3074                 /*
3075                  *      FIXME: O(N) loops suck.
3076                  */
3077                 for (this = mainconfig.listen;
3078                      this != NULL;
3079                      this = this->next) {
3080                         int delay;
3081                         struct timeval when;
3082
3083                         if (this->type != RAD_LISTEN_DETAIL) continue;
3084                         
3085                         delay = detail_delay(this);
3086                         if (!delay) continue;
3087
3088                         fr_event_now(el, &now);
3089                         when = now;
3090                         tv_add(&when, delay);
3091
3092                         if (delay > (USEC / 10)) {
3093                                 DEBUG("Delaying next detail event for %d.%01u seconds.",
3094                                        delay / USEC, (delay % USEC) / 100000);
3095                         }
3096
3097                         /*
3098                          *      Reset the detail timer.
3099                          */
3100                         if (!fr_event_insert(el, event_poll_detail, this,
3101                                              &when, NULL)) {
3102                                 radlog(L_ERR, "Failed remembering detail timer");
3103                                 exit(1);
3104                         }
3105                 }
3106         }
3107 #endif
3108
3109         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3110                 rad_listen_t *this;
3111                 
3112                 for (this = mainconfig.listen;
3113                      this != NULL;
3114                      this = this->next) {
3115                         if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
3116
3117                         event_new_fd(this);
3118                 }
3119         }
3120 }
3121
3122 #ifndef WITH_SELF_PIPE
3123 void radius_signal_self(int flag)
3124 {
3125         handle_signal_self(flag);
3126 }
3127 #else
3128 /*
3129  *      Inform ourselves that we received a signal.
3130  */
3131 void radius_signal_self(int flag)
3132 {
3133         ssize_t rcode;
3134         uint8_t buffer[16];
3135
3136         /*
3137          *      The read MUST be non-blocking for this to work.
3138          */
3139         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3140         if (rcode > 0) {
3141                 ssize_t i;
3142
3143                 for (i = 0; i < rcode; i++) {
3144                         buffer[0] |= buffer[i];
3145                 }
3146         } else {
3147                 buffer[0] = 0;
3148         }
3149
3150         buffer[0] |= flag;
3151
3152         write(self_pipe[1], buffer, 1);
3153 }
3154
3155
3156 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3157                                  UNUSED int fd, UNUSED void *ctx)
3158 {
3159         ssize_t i, rcode;
3160         uint8_t buffer[32];
3161
3162         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3163         if (rcode <= 0) return;
3164
3165         /*
3166          *      Merge pending signals.
3167          */
3168         for (i = 0; i < rcode; i++) {
3169                 buffer[0] |= buffer[i];
3170         }
3171
3172         handle_signal_self(buffer[0]);
3173 }
3174 #endif
3175
3176
3177 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3178                                  void *ctx)
3179 {
3180         rad_listen_t *listener = ctx;
3181         RAD_REQUEST_FUNP fun;
3182         REQUEST *request;
3183
3184         rad_assert(xel == el);
3185
3186         xel = xel;
3187
3188         if (listener->fd < 0) rad_panic("Socket was closed on us!");
3189         
3190         if (!listener->recv(listener, &fun, &request)) return;
3191
3192         if (!thread_pool_addrequest(request, fun)) {
3193                 request->child_state = REQUEST_DONE;
3194         }
3195 }
3196
3197
3198 /*
3199  *      This function is called periodically to see if this detail
3200  *      file is available for reading.
3201  */
3202 static void event_poll_detail(void *ctx)
3203 {
3204         int rcode;
3205         RAD_REQUEST_FUNP fun;
3206         REQUEST *request;
3207         rad_listen_t *this = ctx;
3208         struct timeval when;
3209
3210         fr_event_now(el, &now);
3211         when = now;
3212
3213         rad_assert(this->type == RAD_LISTEN_DETAIL);
3214
3215         /*
3216          *      Set the next poll time to be X +/- 0.5s, to help
3217          *      spread the load a bit over time.
3218          */
3219         when.tv_sec += detail_poll_interval(this);
3220         when.tv_usec += fr_rand() % (USEC / 2);
3221
3222         /*
3223          *      Try to read something.
3224          *
3225          *      FIXME: This does poll AND receive.
3226          */
3227         rcode = this->recv(this, &fun, &request);
3228         if (rcode != 0) {
3229                 rad_assert(fun != NULL);
3230                 rad_assert(request != NULL);
3231                 
3232                 if (!thread_pool_addrequest(request, fun)) {
3233                         request->child_state = REQUEST_DONE;
3234                 }
3235         }
3236
3237         /*
3238          *      Reset the poll to fire one second from now.  If the
3239          *      detail reader DOES read a packet, it will send us a
3240          *      signal when it's done, and the signal handler will
3241          *      reset the timer to a more appropriate (i.e. shorter)
3242          *      value.
3243          */
3244         if (!fr_event_insert(el, event_poll_detail, this,
3245                              &when, NULL)) {
3246                 radlog(L_ERR, "Failed creating handler");
3247                 exit(1);
3248         }
3249 }
3250
3251
3252 static void event_status(struct timeval *wake)
3253 {
3254 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3255         int argval;
3256 #endif
3257
3258         if (debug_flag == 0) {
3259                 if (just_started) {
3260                         radlog(L_INFO, "Ready to process requests.");
3261                         just_started = FALSE;
3262                 }
3263                 return;
3264         }
3265
3266         if (!wake) {
3267                 DEBUG("Ready to process requests.");
3268
3269         } else if ((wake->tv_sec != 0) ||
3270                    (wake->tv_usec >= 100000)) {
3271                 DEBUG("Waking up in %d.%01u seconds.",
3272                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3273         }
3274
3275
3276         /*
3277          *      FIXME: Put this somewhere else, where it isn't called
3278          *      all of the time...
3279          */
3280
3281 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3282         /*
3283          *      If there are no child threads, then there may
3284          *      be child processes.  In that case, wait for
3285          *      their exit status, and throw that exit status
3286          *      away.  This helps get rid of zxombie children.
3287          */
3288         while (waitpid(-1, &argval, WNOHANG) > 0) {
3289                 /* do nothing */
3290         }
3291 #endif
3292
3293 }
3294
3295 /*
3296  *      Externally-visibly functions.
3297  */
3298 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3299 {
3300         rad_listen_t *this, *head = NULL;
3301
3302         if (el) return 0;
3303
3304         time(&fr_start_time);
3305
3306         el = fr_event_list_create(event_status);
3307         if (!el) return 0;
3308
3309         pl = fr_packet_list_create(0);
3310         if (!pl) return 0;      /* leak el */
3311
3312         request_num_counter = 0;
3313
3314         /*
3315          *      Move all of the thread calls to this file?
3316          *
3317          *      It may be best for the mutexes to be in this file...
3318          */
3319         have_children = spawn_flag;
3320
3321 #ifdef WITH_PROXY
3322         if (mainconfig.proxy_requests) {
3323                 /*
3324                  *      Create the tree for managing proxied requests and
3325                  *      responses.
3326                  */
3327                 proxy_list = fr_packet_list_create(1);
3328                 if (!proxy_list) return 0;
3329
3330 #ifdef HAVE_PTHREAD_H
3331                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3332                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3333                                strerror(errno));
3334                         exit(1);
3335                 }
3336 #endif
3337         }
3338 #endif
3339
3340         /*
3341          *      Just before we spawn the child threads, force the log
3342          *      subsystem to re-open the log file for every write.
3343          */
3344         if (spawn_flag) force_log_reopen();
3345
3346 #ifdef HAVE_PTHREAD_H
3347 #ifndef __MINGW32__
3348         NO_SUCH_CHILD_PID = (pthread_t ) (0);
3349 #else
3350         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3351 #endif
3352         if (thread_pool_init(cs, spawn_flag) < 0) {
3353                 exit(1);
3354         }
3355 #endif
3356
3357         if (check_config) {
3358                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3359                        mainconfig.name);
3360                 return 1;
3361         }
3362
3363 #ifdef WITH_SELF_PIPE
3364         /*
3365          *      Child threads need a pipe to signal us, as do the
3366          *      signal handlers.
3367          */
3368         if (pipe(self_pipe) < 0) {
3369                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3370                        strerror(errno));
3371                 exit(1);
3372         }
3373         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3374                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3375                        strerror(errno));
3376                 exit(1);
3377         }
3378         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3379                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3380                        strerror(errno));
3381                 exit(1);
3382         }
3383
3384         if (!fr_event_fd_insert(el, 0, self_pipe[0],
3385                                   event_signal_handler, el)) {
3386                 radlog(L_ERR, "Failed creating handler for signals");
3387                 exit(1);
3388         }
3389 #endif  /* WITH_SELF_PIPE */
3390
3391 #ifdef WITH_PROXY
3392         /*
3393          *      Mark the proxy Fd's as unused.
3394          */
3395         {
3396                 int i;
3397
3398                 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
3399         }
3400 #endif
3401
3402        DEBUG("%s: #### Opening IP addresses and Ports ####",
3403                mainconfig.name);
3404
3405        /*
3406         *       The server temporarily switches to an unprivileged
3407         *       user very early in the bootstrapping process.
3408         *       However, some sockets MAY require privileged access
3409         *       (bind to device, or to port < 1024, or to raw
3410         *       sockets).  Those sockets need to call suid up/down
3411         *       themselves around the functions that need a privileged
3412         *       uid.
3413         */
3414         if (listen_init(cs, &head) < 0) {
3415                 _exit(1);
3416         }
3417         
3418         /*
3419          *      At this point, no one has any business *ever* going
3420          *      back to root uid.
3421          */
3422         fr_suid_down_permanent();
3423
3424         /*
3425          *      Add all of the sockets to the event loop.
3426          */
3427         for (this = head;
3428              this != NULL;
3429              this = this->next) {
3430                 char buffer[256];
3431
3432                 this->print(this, buffer, sizeof(buffer));
3433
3434                 switch (this->type) {
3435 #ifdef WITH_DETAIL
3436                         struct timeval when;
3437
3438                 case RAD_LISTEN_DETAIL:
3439                         DEBUG("Listening on %s", buffer);
3440
3441                         /*
3442                          *      Add some initial jitter to help spread
3443                          *      the load a bit.
3444                          */
3445                         when.tv_sec = fr_start_time + 1;
3446                         when.tv_usec = fr_rand() % USEC;
3447
3448                         if (!fr_event_insert(el, event_poll_detail, this,
3449                                              &when, NULL)) {
3450                                 radlog(L_ERR, "Failed creating detail poll timer");
3451                                 exit(1);
3452                         }
3453                         break;
3454 #endif
3455
3456 #ifdef WITH_PROXY
3457                 case RAD_LISTEN_PROXY:
3458                         rad_assert(proxy_fds[this->fd & 0x1f] == -1);
3459                         rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
3460                         
3461                         proxy_fds[this->fd & 0x1f] = this->fd;
3462                         proxy_listeners[this->fd & 0x1f] = this;
3463                         if (!fr_packet_list_socket_add(proxy_list,
3464                                                          this->fd)) {
3465                                 rad_assert(0 == 1);
3466                         }
3467                         /* FALL-THROUGH */
3468 #endif
3469
3470                 default:
3471                         break;
3472                 }
3473
3474                 /*
3475                  *      The file descriptor isn't ready.  Poll for
3476                  *      when it will become ready.  This is for the
3477                  *      detail file fd's.
3478                  */
3479                 if (this->fd < 0) {
3480                         continue;
3481                 }
3482
3483                 event_new_fd(this);
3484         }
3485
3486         mainconfig.listen = head;
3487
3488         return 1;
3489 }
3490
3491
3492 static int request_hash_cb(UNUSED void *ctx, void *data)
3493 {
3494         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
3495
3496 #ifdef WITH_PROXY
3497         rad_assert(request->in_proxy_hash == FALSE);
3498 #endif
3499
3500         fr_event_delete(el, &request->ev);
3501         remove_from_request_hash(request);
3502         request_free(&request);
3503
3504         return 0;
3505 }
3506
3507
3508 #ifdef WITH_PROXY
3509 static int proxy_hash_cb(UNUSED void *ctx, void *data)
3510 {
3511         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
3512
3513         fr_packet_list_yank(proxy_list, request->proxy);
3514         request->in_proxy_hash = FALSE;
3515
3516         if (!request->in_request_hash) {
3517                 fr_event_delete(el, &request->ev);
3518                 request_free(&request);
3519         }
3520
3521         return 0;
3522 }
3523 #endif
3524
3525 void radius_event_free(void)
3526 {
3527         /*
3528          *      FIXME: Stop all threads, or at least check that
3529          *      they're all waiting on the semaphore, and the queues
3530          *      are empty.
3531          */
3532
3533 #ifdef WITH_PROXY
3534         /*
3535          *      There are requests in the proxy hash that aren't
3536          *      referenced from anywhere else.  Remove them first.
3537          */
3538         if (proxy_list) {
3539                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3540                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
3541                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3542                 fr_packet_list_free(proxy_list);
3543                 proxy_list = NULL;
3544         }
3545 #endif
3546
3547         fr_packet_list_walk(pl, NULL, request_hash_cb);
3548
3549         fr_packet_list_free(pl);
3550         pl = NULL;
3551
3552         fr_event_list_free(el);
3553 }
3554
3555 int radius_event_process(void)
3556 {
3557         if (!el) return 0;
3558
3559         return fr_event_loop(el);
3560 }
3561
3562 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3563 {
3564         request->options = RAD_REQUEST_OPTION_DEBUG2;
3565
3566         if (request_pre_handler(request)) {
3567                 rad_assert(fun != NULL);
3568                 rad_assert(request != NULL);
3569                 
3570                 if (request->server) RDEBUG("server %s {",
3571                                              request->server); 
3572                 fun(request);
3573
3574                 if (request->server) RDEBUG("} # server %s",
3575                                              request->server);
3576
3577                 request_post_handler(request);
3578         }
3579
3580         DEBUG2("Going to the next request");
3581         return;
3582 }