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