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