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