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