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