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