Removed need for global NO_SUCH_CHILD_PID
[freeradius.git] / src / main / event.c
1 /*
2  * event.c      Server event handling
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/detail.h>
31
32 #include <freeradius-devel/rad_assert.h>
33
34 #include <signal.h>
35 #include <fcntl.h>
36
37 #ifdef HAVE_SYS_WAIT_H
38 #       include <sys/wait.h>
39 #endif
40
41 #define USEC (1000000)
42
43 extern pid_t radius_pid;
44 extern int dont_fork;
45 extern int check_config;
46 extern void force_log_reopen(void);
47 extern char *debug_condition;
48
49 /*
50  *      Ridiculous amounts of local state.
51  */
52 static fr_event_list_t  *el = NULL;
53 static fr_packet_list_t *pl = NULL;
54 static int                      request_num_counter = 0;
55 static struct timeval           now;
56 time_t                          fr_start_time;
57 static int                      have_children;
58 static int                      has_detail_listener = FALSE;
59 static int                      just_started = TRUE;
60
61 #ifndef __MINGW32__
62 static int self_pipe[2];
63 #endif
64
65 #ifdef HAVE_PTHREAD_H
66 #ifdef WITH_PROXY
67 static pthread_mutex_t  proxy_mutex;
68 #endif
69
70 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
71 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
72
73 static pthread_t NO_SUCH_CHILD_PID;
74 #else
75 /*
76  *      This is easier than ifdef's throughout the code.
77  */
78 #define PTHREAD_MUTEX_LOCK(_x)
79 #define PTHREAD_MUTEX_UNLOCK(_x)
80 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
81 {
82         radius_handle_request(request, fun);
83         return 1;
84 }
85 #endif
86
87 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
88
89 #ifdef WITH_PROXY
90 static fr_packet_list_t *proxy_list = NULL;
91
92 /*
93  *      We keep the proxy FD's here.  The RADIUS Id's are marked
94  *      "allocated" per Id, via a bit per proxy FD.
95  */
96 static int              proxy_fds[32];
97 static rad_listen_t     *proxy_listeners[32];
98 #else
99 #define remove_from_proxy_hash(foo)
100 #endif
101
102 static void request_post_handler(REQUEST *request);
103 static void wait_a_bit(void *ctx);
104 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
105
106 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
107                                     const char *msg)
108 {
109         radlog(L_ERR, "[%s:%d] %s", file, line, msg);
110         _exit(1);
111 }
112
113 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
114
115
116 static void tv_add(struct timeval *tv, int usec_delay)
117 {
118         if (usec_delay > USEC) {
119                 tv->tv_sec += usec_delay / USEC;
120                 usec_delay %= USEC;
121         }
122         tv->tv_usec += usec_delay;
123
124         if (tv->tv_usec > USEC) {
125                 tv->tv_usec -= USEC;
126                 tv->tv_sec++;
127         }
128 }
129
130 static void remove_from_request_hash(REQUEST *request)
131 {
132         if (!request->in_request_hash) return;
133
134         fr_packet_list_yank(pl, request->packet);
135         request->in_request_hash = FALSE;
136
137         request_stats_final(request);
138 }
139
140
141 #ifdef WITH_PROXY
142 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
143 {
144         RADIUS_PACKET **proxy_p;
145         REQUEST *request;
146
147         PTHREAD_MUTEX_LOCK(&proxy_mutex);
148         proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
149
150         if (!proxy_p) {
151                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
152                 return NULL;
153         }
154
155         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
156
157         if (!request) {
158                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
159                 return NULL;
160         }
161
162         request->num_proxied_responses++;
163
164         /*
165          *      Catch the most common case of everything working
166          *      correctly.
167          */
168         if (request->num_proxied_requests == request->num_proxied_responses) {
169                 fr_packet_list_yank(proxy_list, request->proxy);
170                 fr_packet_list_id_free(proxy_list, request->proxy);
171                 request->in_proxy_hash = FALSE;
172         }
173
174         /*
175          *      On the FIRST reply, decrement the count of outstanding
176          *      requests.  Note that this is NOT the count of sent
177          *      packets, but whether or not the home server has
178          *      responded at all.
179          */
180         if (!request->proxy_reply &&
181             request->home_server->currently_outstanding) {
182                 request->home_server->currently_outstanding--;
183         }
184
185         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
186
187         return request;
188 }
189
190
191 static void remove_from_proxy_hash(REQUEST *request)
192 {
193         if (!request->in_proxy_hash) return;
194
195         PTHREAD_MUTEX_LOCK(&proxy_mutex);
196         fr_packet_list_yank(proxy_list, request->proxy);
197         fr_packet_list_id_free(proxy_list, request->proxy);
198
199         /*
200          *      The home server hasn't replied, but we've given up on
201          *      this request.  Don't count this request against the
202          *      home server.
203          */
204         if (!request->proxy_reply &&
205             request->home_server->currently_outstanding) {
206                 request->home_server->currently_outstanding--;
207         }
208
209         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
210
211         request->in_proxy_hash = FALSE;
212 }
213
214
215 static int insert_into_proxy_hash(REQUEST *request)
216 {
217         int i, proxy;
218         char buf[128];
219
220         rad_assert(request->proxy != NULL);
221         rad_assert(proxy_list != NULL);
222
223         request->proxy->sockfd = -1;
224
225         PTHREAD_MUTEX_LOCK(&proxy_mutex);
226
227         request->home_server->currently_outstanding++;
228
229         if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
230                 int found;
231                 rad_listen_t *proxy_listener;
232
233                 /*
234                  *      Allocate a new proxy fd.  This function adds
235                  *      it to the tail of the list of listeners.  With
236                  *      some care, this can be thread-safe.
237                  */
238                 proxy_listener = proxy_new_listener();
239                 if (!proxy_listener) {
240                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
241                         RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
242                         return 0;
243                 }
244
245                 /*
246                  *      Cache it locally.
247                  */
248                 found = -1;
249                 proxy = proxy_listener->fd;
250                 for (i = 0; i < 32; i++) {
251                         /*
252                          *      Found a free entry.  Save the socket,
253                          *      and remember where we saved it.
254                          */
255                         if (proxy_fds[(proxy + i) & 0x1f] == -1) {
256                                 found = (proxy + i) & 0x1f;
257                                 proxy_fds[found] = proxy;
258                                 proxy_listeners[found] = proxy_listener;
259                                 break;
260                         }
261                 }
262                 rad_assert(found >= 0);
263
264                 if (!fr_packet_list_socket_add(proxy_list, proxy_listener->fd)) {
265                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
266                         RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
267                         return 0;
268
269                 }
270
271                 if (!fr_packet_list_id_alloc(proxy_list, request->proxy)) {
272                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
273                         RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
274                         return 0;
275                 }
276
277                 /*
278                  *      Signal the main thread to add the new FD to the list
279                  *      of listening FD's.
280                  */
281                 radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
282         }
283         rad_assert(request->proxy->sockfd >= 0);
284
285         /*
286          *      FIXME: Hack until we get rid of rad_listen_t, and put
287          *      the information into the packet_list.
288          */
289         proxy = -1;
290         for (i = 0; i < 32; i++) {
291                 if (proxy_fds[i] == request->proxy->sockfd) {
292                         proxy = i;
293                         break;
294                 }
295         }
296
297         if (proxy < 0) {
298                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
299                 RDEBUG2("ERROR: All sockets are full.");
300                 return 0;
301         }
302
303         rad_assert(proxy_fds[proxy] != -1);
304         rad_assert(proxy_listeners[proxy] != NULL);
305         request->proxy_listener = proxy_listeners[proxy];
306
307         if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
308                 fr_packet_list_id_free(proxy_list, request->proxy);
309                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
310                 RDEBUG2("ERROR: Failed to insert entry into proxy list");
311                 return 0;
312         }
313
314         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
315
316         RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
317                inet_ntop(request->proxy->dst_ipaddr.af,
318                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
319                request->proxy->dst_port,
320                request->proxy->id);
321
322         request->in_proxy_hash = TRUE;
323
324         return 1;
325 }
326
327
328 /*
329  *      Called as BOTH an event, and in-line from other functions.
330  */
331 static void wait_for_proxy_id_to_expire(void *ctx)
332 {
333         REQUEST *request = ctx;
334         home_server *home = request->home_server;
335
336         rad_assert(request->magic == REQUEST_MAGIC);
337         rad_assert(request->proxy != NULL);
338
339         if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
340         request->when = request->proxy_when;
341         request->when.tv_sec += home->response_window;
342
343         if ((request->num_proxied_requests == request->num_proxied_responses) ||
344             timercmp(&now, &request->when, >)) {
345                 if (request->packet) {
346                         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
347                                request->number, request->packet->id,
348                                (unsigned int) (request->timestamp - fr_start_time));
349                 } else {
350                         RDEBUG2("Cleaning up request %d with timestamp +%d",
351                                request->number,
352                                (unsigned int) (request->timestamp - fr_start_time));
353                 }
354                 fr_event_delete(el, &request->ev);
355                 remove_from_proxy_hash(request);
356                 remove_from_request_hash(request);
357                 request_free(&request);
358                 return;
359         }
360
361         INSERT_EVENT(wait_for_proxy_id_to_expire, request);
362 }
363 #endif
364
365 #ifdef HAVE_PTHREAD_H
366 static void wait_for_child_to_die(void *ctx)
367 {
368         REQUEST *request = ctx;
369
370         rad_assert(request->magic == REQUEST_MAGIC);
371
372         if ((request->child_state == REQUEST_QUEUED) |
373             (request->child_state == REQUEST_RUNNING)) {
374                 request->delay += (request->delay >> 1);
375                 tv_add(&request->when, request->delay);
376
377                 RDEBUG2("Child is still stuck for request %d", request->number);
378
379                 INSERT_EVENT(wait_for_child_to_die, request);
380                 return;
381         }
382
383         RDEBUG2("Child is finally responsive for request %d", request->number);
384         remove_from_request_hash(request);
385
386 #ifdef WITH_PROXY
387         if (request->proxy) {
388                 wait_for_proxy_id_to_expire(request);
389                 return;
390         }
391 #endif
392
393         request_free(&request);
394 }
395 #endif
396
397 static void cleanup_delay(void *ctx)
398 {
399         REQUEST *request = ctx;
400
401         rad_assert(request->magic == REQUEST_MAGIC);
402         rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
403                    (request->child_state == REQUEST_DONE));
404
405         remove_from_request_hash(request);
406
407 #ifdef WITH_PROXY
408         if (request->proxy && request->in_proxy_hash) {
409                 wait_for_proxy_id_to_expire(request);
410                 return;
411         }
412 #endif
413
414         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
415                request->number, request->packet->id,
416                (unsigned int) (request->timestamp - fr_start_time));
417
418         fr_event_delete(el, &request->ev);
419         request_free(&request);
420 }
421
422
423 /*
424  *      FIXME: Put into a libradius function.
425  */
426 #define MAX_PACKET_CODE (52)
427 static const char *packet_codes[] = {
428   "",
429   "Access-Request",
430   "Access-Accept",
431   "Access-Reject",
432   "Accounting-Request",
433   "Accounting-Response",
434   "Accounting-Status",
435   "Password-Request",
436   "Password-Accept",
437   "Password-Reject",
438   "Accounting-Message",
439   "Access-Challenge",
440   "Status-Server",
441   "Status-Client",
442   "14",
443   "15",
444   "16",
445   "17",
446   "18",
447   "19",
448   "20",
449   "Resource-Free-Request",
450   "Resource-Free-Response",
451   "Resource-Query-Request",
452   "Resource-Query-Response",
453   "Alternate-Resource-Reclaim-Request",
454   "NAS-Reboot-Request",
455   "NAS-Reboot-Response",
456   "28",
457   "Next-Passcode",
458   "New-Pin",
459   "Terminate-Session",
460   "Password-Expired",
461   "Event-Request",
462   "Event-Response",
463   "35",
464   "36",
465   "37",
466   "38",
467   "39",
468   "Disconnect-Request",
469   "Disconnect-ACK",
470   "Disconnect-NAK",
471   "CoA-Request",
472   "CoA-ACK",
473   "CoA-NAK",
474   "46",
475   "47",
476   "48",
477   "49",
478   "IP-Address-Allocate",
479   "IP-Address-Release"
480 };
481
482
483 /*
484  *      In daemon mode, AND this request has debug flags set.
485  */
486 #define DEBUG_PACKET if (!debug_flag && request->options) debug_packet
487
488 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
489 {
490         VALUE_PAIR *vp;
491         char buffer[1024];
492         const char *received, *from;
493         const fr_ipaddr_t *ip;
494         int port;
495
496         if (!packet) return;
497
498         if (direction == 0) {
499                 received = "Received";
500                 from = "from";  /* what else? */
501                 ip = &packet->src_ipaddr;
502                 port = packet->src_port;
503
504         } else {
505                 received = "Sending";
506                 from = "to";    /* hah! */
507                 ip = &packet->dst_ipaddr;
508                 port = packet->dst_port;
509         }
510         
511         /*
512          *      Client-specific debugging re-prints the input
513          *      packet into the client log.
514          *
515          *      This really belongs in a utility library
516          */
517         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
518                 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
519                        received, packet_codes[packet->code], from,
520                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
521                        port, packet->id, packet->data_len);
522         } else {
523                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
524                        received, from,
525                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
526                        port,
527                        packet->code, packet->id, packet->data_len);
528         }
529
530         for (vp = packet->vps; vp != NULL; vp = vp->next) {
531                 vp_prints(buffer, sizeof(buffer), vp);
532                 request->radlog(L_DBG, 0, request, "\t%s", buffer);
533         }
534 }
535
536 static void reject_delay(void *ctx)
537 {
538         REQUEST *request = ctx;
539
540         rad_assert(request->magic == REQUEST_MAGIC);
541         rad_assert(request->child_state == REQUEST_REJECT_DELAY);
542
543         RDEBUG2("Sending delayed reject for request %d", request->number);
544
545         if (!debug_flag && request->options) {
546                 debug_packet(request, request->reply, 1);
547         }
548         request->listener->send(request->listener, request);
549
550         request->when.tv_sec += request->root->cleanup_delay;
551         request->child_state = REQUEST_CLEANUP_DELAY;
552
553         INSERT_EVENT(cleanup_delay, request);
554 }
555
556
557 #ifdef WITH_PROXY
558 static void revive_home_server(void *ctx)
559 {
560         home_server *home = ctx;
561         char buffer[128];
562
563         home->state = HOME_STATE_ALIVE;
564         radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
565                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
566                          buffer, sizeof(buffer)),
567                home->port);
568         home->currently_outstanding = 0;
569         home->revive_time = now;
570 }
571
572
573 static void no_response_to_ping(void *ctx)
574 {
575         REQUEST *request = ctx;
576         home_server *home = request->home_server;
577         char buffer[128];
578
579         home->num_received_pings = 0;
580
581         RDEBUG2("No response to status check %d from home server %s port %d",
582                request->number,
583                inet_ntop(request->proxy->dst_ipaddr.af,
584                          &request->proxy->dst_ipaddr.ipaddr,
585                          buffer, sizeof(buffer)),
586                request->proxy->dst_port);
587
588         wait_for_proxy_id_to_expire(request);
589 }
590
591
592 static void received_response_to_ping(REQUEST *request)
593 {
594         home_server *home = request->home_server;
595         char buffer[128];
596
597         home->num_received_pings++;
598
599         RDEBUG2("Received response to status check %d (%d in current sequence)",
600                request->number, home->num_received_pings);
601
602         if (home->num_received_pings < home->num_pings_to_alive) {
603                 wait_for_proxy_id_to_expire(request);
604                 return;
605         }
606
607         radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
608                inet_ntop(request->proxy->dst_ipaddr.af,
609                          &request->proxy->dst_ipaddr.ipaddr,
610                          buffer, sizeof(buffer)),
611                request->proxy->dst_port);
612
613         if (!fr_event_delete(el, &home->ev)) {
614                 RDEBUG2("Hmm... no event for home server, WTF?");
615         }
616
617         if (!fr_event_delete(el, &request->ev)) {
618                 RDEBUG2("Hmm... no event for request, WTF?");
619         }
620
621         wait_for_proxy_id_to_expire(request);
622
623         home->state = HOME_STATE_ALIVE;
624         home->currently_outstanding = 0;
625         home->revive_time = now;
626 }
627
628
629 static void ping_home_server(void *ctx)
630 {
631         uint32_t jitter;
632         home_server *home = ctx;
633         REQUEST *request;
634         VALUE_PAIR *vp;
635
636         if (home->state == HOME_STATE_ALIVE) {
637                 radlog(L_INFO, "Suspicious proxy state... continuing");
638                 return;
639         }
640
641         request = request_alloc();
642         request->number = request_num_counter++;
643
644         request->proxy = rad_alloc(1);
645         rad_assert(request->proxy != NULL);
646
647         fr_event_now(el, &request->when);
648         home->when = request->when;
649
650         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
651                 request->proxy->code = PW_STATUS_SERVER;
652
653                 radius_pairmake(request, &request->proxy->vps,
654                                 "Message-Authenticator", "0x00", T_OP_SET);
655
656         } else if (home->type == HOME_TYPE_AUTH) {
657                 request->proxy->code = PW_AUTHENTICATION_REQUEST;
658
659                 radius_pairmake(request, &request->proxy->vps,
660                                 "User-Name", home->ping_user_name, T_OP_SET);
661                 radius_pairmake(request, &request->proxy->vps,
662                                 "User-Password", home->ping_user_password, T_OP_SET);
663                 radius_pairmake(request, &request->proxy->vps,
664                                 "Service-Type", "Authenticate-Only", T_OP_SET);
665                 radius_pairmake(request, &request->proxy->vps,
666                                 "Message-Authenticator", "0x00", T_OP_SET);
667
668         } else {
669 #ifdef WITH_ACCOUNTING
670                 request->proxy->code = PW_ACCOUNTING_REQUEST;
671                 
672                 radius_pairmake(request, &request->proxy->vps,
673                                 "User-Name", home->ping_user_name, T_OP_SET);
674                 radius_pairmake(request, &request->proxy->vps,
675                                 "Acct-Status-Type", "Stop", T_OP_SET);
676                 radius_pairmake(request, &request->proxy->vps,
677                                 "Acct-Session-Id", "00000000", T_OP_SET);
678                 vp = radius_pairmake(request, &request->proxy->vps,
679                                      "Event-Timestamp", "0", T_OP_SET);
680                 vp->vp_date = now.tv_sec;
681 #else
682                 rad_assert("Internal sanity check failed");
683 #endif
684         }
685
686         radius_pairmake(request, &request->proxy->vps,
687                         "NAS-Identifier", "Status Check. Are you alive?",
688                         T_OP_SET);
689
690         request->proxy->dst_ipaddr = home->ipaddr;
691         request->proxy->dst_port = home->port;
692         request->home_server = home;
693
694         rad_assert(request->proxy_listener == NULL);
695
696         if (!insert_into_proxy_hash(request)) {
697                 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash.  Discarding it.",
698                        request->number);
699                 request_free(&request);
700                 return;
701         }
702         rad_assert(request->proxy_listener != NULL);
703         request->proxy_listener->send(request->proxy_listener,
704                                       request);
705
706         request->next_callback = NULL;
707         request->child_state = REQUEST_PROXIED;
708         request->when.tv_sec += home->ping_timeout;;
709
710         INSERT_EVENT(no_response_to_ping, request);
711
712         /*
713          *      Add +/- 2s of jitter, as suggested in RFC 3539
714          *      and in the Issues and Fixes draft.
715          */
716         home->when.tv_sec += home->ping_interval - 2;
717
718         jitter = fr_rand();
719         jitter ^= (jitter >> 10);
720         jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
721
722         tv_add(&home->when, jitter);
723
724
725         INSERT_EVENT(ping_home_server, home);
726 }
727
728
729 static void check_for_zombie_home_server(REQUEST *request)
730 {
731         home_server *home;
732         struct timeval when;
733         char buffer[128];
734
735         home = request->home_server;
736
737         if (home->state != HOME_STATE_ZOMBIE) return;
738
739         when = home->zombie_period_start;
740         when.tv_sec += home->zombie_period;
741
742         fr_event_now(el, &now);
743         if (timercmp(&now, &when, <)) {
744                 return;
745         }
746
747         /*
748          *      It's been a zombie for too long, mark it as
749          *      dead.
750          */
751         radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
752                inet_ntop(request->proxy->dst_ipaddr.af,
753                          &request->proxy->dst_ipaddr.ipaddr,
754                          buffer, sizeof(buffer)),
755                request->proxy->dst_port);
756         home->state = HOME_STATE_IS_DEAD;
757         home->num_received_pings = 0;
758         home->when = request->when;
759
760         if (home->ping_check != HOME_PING_CHECK_NONE) {
761                 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
762                            (home->ping_user_name != NULL));
763                 home->when.tv_sec += home->ping_interval;
764
765                 INSERT_EVENT(ping_home_server, home);
766         } else {
767                 home->when.tv_sec += home->revive_interval;
768
769                 INSERT_EVENT(revive_home_server, home);
770         }
771 }
772
773 static int proxy_to_virtual_server(REQUEST *request);
774
775 static int virtual_server_handler(UNUSED REQUEST *request)
776 {
777         proxy_to_virtual_server(request);
778         return 0;
779 }
780
781 static void proxy_fallback_handler(REQUEST *request)
782 {
783         /*
784          *      A proper time is required for wait_a_bit.
785          */
786         request->delay = USEC / 10;
787         gettimeofday(&now, NULL);
788         request->next_when = now;
789         tv_add(&request->next_when, request->delay);
790         request->next_callback = wait_a_bit;
791
792         /*
793          *      Re-queue the request.
794          */
795         request->child_state = REQUEST_QUEUED;
796         
797         rad_assert(request->proxy != NULL);
798         if (!thread_pool_addrequest(request, virtual_server_handler)) {
799                 request->child_state = REQUEST_DONE;
800         }
801
802 #ifdef HAVE_PTHREAD_H
803         /*
804          *      MAY free the request if we're over max_request_time,
805          *      AND we're not in threaded mode!
806          *
807          *      Note that we call this ONLY if we're threaded, as
808          *      if we're NOT threaded, request_post_handler() calls
809          *      wait_a_bit(), which means that "request" may not
810          *      exist any more...
811          */
812         if (have_children) wait_a_bit(request);
813 #endif
814 }
815
816
817 static int setup_post_proxy_fail(REQUEST *request)
818 {
819         DICT_VALUE *dval = NULL;
820         VALUE_PAIR *vp;
821
822         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
823                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
824
825         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
826                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
827
828         } else {
829                 return 0;
830         }
831
832         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
833
834         if (!dval) {
835                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
836                 return 0;
837         }
838
839         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
840         if (!vp) vp = radius_paircreate(request, &request->config_items,
841                                         PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
842         vp->vp_integer = dval->value;
843
844         rad_assert(request->proxy_reply == NULL);
845
846         return 1;
847 }
848
849
850 static int null_handler(UNUSED REQUEST *request)
851 {
852         return 0;
853 }
854
855 static void post_proxy_fail_handler(REQUEST *request)
856 {
857         /*
858          *      A proper time is required for wait_a_bit.
859          */
860         request->delay = USEC / 10;
861         gettimeofday(&now, NULL);
862
863         /*
864          *      Not set up to run Post-Proxy-Type = Fail.
865          *
866          *      Mark the request as still running, and figure out what
867          *      to do next.
868          */
869         if (!setup_post_proxy_fail(request)) {
870                 request->child_state = REQUEST_RUNNING;
871                 request_post_handler(request);
872
873         } else {
874                 /*
875                  *      Re-queue the request.
876                  */
877                 request->child_state = REQUEST_QUEUED;
878
879                 /*
880                  *      There is a post-proxy-type of fail.  We run
881                  *      the request through the pre/post proxy
882                  *      handlers, just like it was a real proxied
883                  *      request.  However, we set the per-request
884                  *      handler to NULL, as we don't want to do
885                  *      anything else.
886                  *
887                  *      Note that when we're not threaded, this will
888                  *      process the request even if it's greater than
889                  *      max_request_time.  That's not fatal.
890                  */
891                 request->priority = 0;
892                 rad_assert(request->proxy != NULL);
893                 thread_pool_addrequest(request, null_handler);
894         }
895
896         /*
897          *      MAY free the request if we're over max_request_time,
898          *      AND we're not in threaded mode!
899          *
900          *      Note that we call this ONLY if we're threaded, as
901          *      if we're NOT threaded, request_post_handler() calls
902          *      wait_a_bit(), which means that "request" may not
903          *      exist any more...
904          */
905         if (have_children) wait_a_bit(request);
906 }
907
908
909 /* maybe check this against wait_for_proxy_id_to_expire? */
910 static void no_response_to_proxied_request(void *ctx)
911 {
912         REQUEST *request = ctx;
913         home_server *home;
914         char buffer[128];
915
916         rad_assert(request->magic == REQUEST_MAGIC);
917         rad_assert(request->child_state == REQUEST_PROXIED);
918
919         /*
920          *      If we've failed over to an internal home server,
921          *      replace the callback with the correct one.  This
922          *      is due to locking issues with child threads...
923          */
924         if (request->home_server->server) {
925                 wait_a_bit(request);
926                 return;
927         }
928
929         radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
930                request->number,
931                inet_ntop(request->proxy->dst_ipaddr.af,
932                          &request->proxy->dst_ipaddr.ipaddr,
933                          buffer, sizeof(buffer)),
934                request->proxy->dst_port);
935
936         check_for_zombie_home_server(request);
937
938         home = request->home_server;
939
940         post_proxy_fail_handler(request);
941
942         /*
943          *      Don't touch request due to race conditions
944          */
945         if (home->state == HOME_STATE_IS_DEAD) {
946                 rad_assert(home->ev != NULL); /* or it will never wake up */
947                 return;
948         }
949
950         /*
951          *      Enable the zombie period when we notice that the home
952          *      server hasn't responded.  We also back-date the start
953          *      of the zombie period to when the proxied request was
954          *      sent.
955          */
956         if (home->state == HOME_STATE_ALIVE) {
957                 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
958                        inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
959                                  buffer, sizeof(buffer)),
960                        home->port);
961                 home->state = HOME_STATE_ZOMBIE;
962                 home->zombie_period_start = now;
963                 home->zombie_period_start.tv_sec -= home->response_window;
964                 return;
965         }
966 }
967 #endif
968
969 static void wait_a_bit(void *ctx)
970 {
971         struct timeval when;
972         REQUEST *request = ctx;
973         fr_event_callback_t callback = NULL;
974
975         rad_assert(request->magic == REQUEST_MAGIC);
976
977         switch (request->child_state) {
978         case REQUEST_QUEUED:
979         case REQUEST_RUNNING:
980                 when = request->received;
981                 when.tv_sec += request->root->max_request_time;
982
983                 /*
984                  *      Normally called from the event loop with the
985                  *      proper event loop time.  Otherwise, called from
986                  *      post proxy fail handler, which sets "now", and
987                  *      this call won't re-set it, because we're not
988                  *      in the event loop.
989                  */
990                 fr_event_now(el, &now);
991
992                 /*
993                  *      Request still has more time.  Continue
994                  *      waiting.
995                  */
996                 if (timercmp(&now, &when, <) ||
997                     ((request->listener->type == RAD_LISTEN_DETAIL) &&
998                      (request->child_state == REQUEST_QUEUED))) {
999                         if (request->delay < (USEC / 10)) {
1000                                 request->delay = USEC / 10;
1001                         }
1002                         request->delay += request->delay >> 1;
1003
1004 #ifdef WITH_DETAIL
1005                         /*
1006                          *      Cap wait at some sane value for detail
1007                          *      files.
1008                          */
1009                         if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1010                             (request->delay > (request->root->max_request_time * USEC))) {
1011                                 request->delay = request->root->max_request_time * USEC;
1012                         }
1013 #endif
1014
1015                         request->when = now;
1016                         tv_add(&request->when, request->delay);
1017                         callback = wait_a_bit;
1018                         break;
1019                 }
1020
1021 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1022                 /*
1023                  *      A child thread MAY still be running on the
1024                  *      request.  Ask the thread to stop working on
1025                  *      the request.
1026                  */
1027                 if (have_children) {
1028                         /* FIXME: kill unresponsive children? */
1029
1030                         /*
1031                          *      Print this error message ONLY if
1032                          *      there's a child currently processing
1033                          *      the request.  As we don't have thread
1034                          *      locks here, there may be race
1035                          *      conditions on this check.  But it's
1036                          *      just an error message, so that's OK.
1037                          */
1038                         if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1039                                 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1040                                        request->number,
1041                                        request->module ? request->module : "<server core>",
1042                                        request->component ? request->component : "<server core>");
1043                         }
1044
1045                         request->master_state = REQUEST_STOP_PROCESSING;
1046                         
1047                         request->delay = USEC / 4;
1048                         tv_add(&request->when, request->delay);
1049                         callback = wait_for_child_to_die;
1050                         break;
1051                 }
1052 #endif
1053
1054                 /*
1055                  *      Else there are no child threads.  We probably
1056                  *      should have just marked the request as 'done'
1057                  *      elsewhere, like in the post-proxy-fail
1058                  *      handler.  But doing that would involve
1059                  *      checking for max_request_time in multiple
1060                  *      places, so this may be simplest.
1061                  */
1062                 request->child_state = REQUEST_DONE;
1063                 /* FALL-THROUGH */
1064
1065                 /*
1066                  *      Mark the request as no longer running,
1067                  *      and clean it up.
1068                  */
1069         case REQUEST_DONE:
1070 #ifdef HAVE_PTHREAD_H
1071                 request->child_pid = NO_SUCH_CHILD_PID;
1072 #endif
1073                 request_stats_final(request);
1074                 cleanup_delay(request);
1075                 return;
1076
1077         case REQUEST_REJECT_DELAY:
1078         case REQUEST_CLEANUP_DELAY:
1079 #ifdef HAVE_PTHREAD_H
1080                 request->child_pid = NO_SUCH_CHILD_PID;
1081 #endif
1082                 request_stats_final(request);
1083
1084         case REQUEST_PROXIED:
1085                 rad_assert(request->next_callback != NULL);
1086                 rad_assert(request->next_callback != wait_a_bit);
1087
1088                 request->when = request->next_when;
1089                 callback = request->next_callback;
1090                 request->next_callback = NULL;
1091                 break;
1092
1093         default:
1094                 rad_panic("Internal sanity check failure");
1095                 return;
1096         }
1097
1098         /*
1099          *      Something major went wrong.  Discard the request, and
1100          *      keep running.
1101          *
1102          *      FIXME: No idea why this happens or how to fix it...
1103          *      It seems to happen *only* when requests are proxied,
1104          *      and where the home server doesn't respond.  So it looks
1105          *      like a race condition above, but it happens in debug
1106          *      mode, with no threads...
1107          */
1108         if (!callback) {
1109                 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1110                 fr_event_delete(el, &request->ev);
1111                 remove_from_proxy_hash(request);
1112                 remove_from_request_hash(request);
1113                 request_free(&request);
1114                 return;
1115         }
1116
1117         INSERT_EVENT(callback, request);
1118 }
1119
1120
1121 #ifdef WITH_PROXY
1122 static int process_proxy_reply(REQUEST *request)
1123 {
1124         int rcode;
1125         int post_proxy_type = 0;
1126         VALUE_PAIR *vp;
1127         
1128         /*
1129          *      Delete any reply we had accumulated until now.
1130          */
1131         pairfree(&request->reply->vps);
1132         
1133         /*
1134          *      Run the packet through the post-proxy stage,
1135          *      BEFORE playing games with the attributes.
1136          */
1137         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1138         if (vp) {
1139                 RDEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1140                 post_proxy_type = vp->vp_integer;
1141         }
1142         
1143         rad_assert(request->home_pool != NULL);
1144         
1145         if (request->home_pool->virtual_server) {
1146                 const char *old_server = request->server;
1147                 
1148                 request->server = request->home_pool->virtual_server;
1149                 RDEBUG2(" server %s {", request->server);
1150                 rcode = module_post_proxy(post_proxy_type, request);
1151                 RDEBUG2(" }");
1152                 request->server = old_server;
1153         } else {
1154                 rcode = module_post_proxy(post_proxy_type, request);
1155         }
1156         
1157         /*
1158          *      There may NOT be a proxy reply, as we may be
1159          *      running Post-Proxy-Type = Fail.
1160          */
1161         if (request->proxy_reply) {
1162                 /*
1163                  *      Delete the Proxy-State Attributes from
1164                  *      the reply.  These include Proxy-State
1165                  *      attributes from us and remote server.
1166                  */
1167                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1168                 
1169                 /*
1170                  *      Add the attributes left in the proxy
1171                  *      reply to the reply list.
1172                  */
1173                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1174                 request->proxy_reply->vps = NULL;
1175                 
1176                 /*
1177                  *      Free proxy request pairs.
1178                  */
1179                 pairfree(&request->proxy->vps);
1180         }
1181         
1182         switch (rcode) {
1183         default:  /* Don't do anything */
1184                 break;
1185         case RLM_MODULE_FAIL:
1186                 /* FIXME: debug print stuff */
1187                 request->child_state = REQUEST_DONE;
1188                 return 0;
1189                 
1190         case RLM_MODULE_HANDLED:
1191                 /* FIXME: debug print stuff */
1192                 request->child_state = REQUEST_DONE;
1193                 return 0;
1194         }
1195
1196         return 1;
1197 }
1198 #endif
1199
1200 static int request_pre_handler(REQUEST *request)
1201 {
1202         int rcode;
1203
1204         rad_assert(request->magic == REQUEST_MAGIC);
1205         rad_assert(request->packet != NULL);
1206
1207         request->child_state = REQUEST_RUNNING;
1208
1209         /*
1210          *      Don't decode the packet if it's an internal "fake"
1211          *      request.  Instead, just return so that the caller can
1212          *      process it.
1213          */
1214         if (request->packet->dst_port == 0) {
1215                 request->username = pairfind(request->packet->vps,
1216                                              PW_USER_NAME);
1217                 request->password = pairfind(request->packet->vps,
1218                                              PW_USER_PASSWORD);
1219                 return 1;
1220         }
1221
1222 #ifdef WITH_PROXY
1223         /*
1224          *      Put the decoded packet into it's proper place.
1225          */
1226         if (request->proxy_reply != NULL) {
1227                 rcode = request->proxy_listener->decode(request->proxy_listener,
1228                                                         request);
1229                 DEBUG_PACKET(request, request->proxy_reply, 0);
1230         } else
1231 #endif
1232         if (request->packet->vps == NULL) {
1233                 rcode = request->listener->decode(request->listener, request);
1234                 
1235                 if (debug_condition) {
1236                         int result = FALSE;
1237                         
1238                         /*
1239                          *      Ignore parse errors.
1240                          */
1241                         radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1242                                                   &debug_condition, 1,
1243                                                   &result);
1244                         if (result) {
1245                                 request->priority = 2;
1246                                 request->radlog = radlog_request;
1247                         }
1248                 }
1249                 
1250                 DEBUG_PACKET(request, request->packet, 0);
1251         } else {
1252                 rcode = 0;
1253         }
1254
1255         if (rcode < 0) {
1256                 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1257                 request->child_state = REQUEST_DONE;
1258                 return 0;
1259         }
1260
1261 #ifdef WITH_PROXY
1262         if (!request->proxy)
1263 #endif
1264           {
1265                   request->username = pairfind(request->packet->vps,
1266                                              PW_USER_NAME);
1267
1268 #ifdef WITH_PROXY
1269         } else {
1270                 return process_proxy_reply(request);
1271 #endif
1272         }
1273
1274         return 1;
1275 }
1276
1277
1278 #ifdef WITH_PROXY
1279 /*
1280  *      Do state handling when we proxy a request.
1281  */
1282 static int proxy_request(REQUEST *request)
1283 {
1284         struct timeval when;
1285         char buffer[128];
1286
1287         if (request->home_server->server) {
1288                 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1289                 return 0;
1290         }
1291
1292         if (!insert_into_proxy_hash(request)) {
1293                 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1294                 return 0;
1295         }
1296
1297         request->proxy_listener->encode(request->proxy_listener, request);
1298
1299         when = request->received;
1300         when.tv_sec += request->root->max_request_time;
1301
1302         gettimeofday(&request->proxy_when, NULL);
1303
1304         request->next_when = request->proxy_when;
1305         request->next_when.tv_sec += request->home_server->response_window;
1306
1307         rad_assert(request->home_server->response_window > 0);
1308
1309         if (timercmp(&when, &request->next_when, <)) {
1310                 request->next_when = when;
1311         }
1312         request->next_callback = no_response_to_proxied_request;
1313
1314         RDEBUG2("Proxying request %d to home server %s port %d",
1315                request->number,
1316                inet_ntop(request->proxy->dst_ipaddr.af,
1317                          &request->proxy->dst_ipaddr.ipaddr,
1318                          buffer, sizeof(buffer)),
1319                request->proxy->dst_port);
1320
1321         /*
1322          *      Note that we set proxied BEFORE sending the packet.
1323          *
1324          *      Once we send it, the request is tainted, as
1325          *      another thread may have picked it up.  Don't
1326          *      touch it!
1327          */
1328         request->num_proxied_requests = 1;
1329         request->num_proxied_responses = 0;
1330 #ifdef HAVE_PTHREAD_H
1331         request->child_pid = NO_SUCH_CHILD_PID;
1332 #endif
1333         request->child_state = REQUEST_PROXIED;
1334
1335         if (!debug_flag && request->options) {
1336                 debug_packet(request, request->proxy, 1);
1337         }
1338
1339         request->proxy_listener->send(request->proxy_listener,
1340                                       request);
1341         return 1;
1342 }
1343
1344
1345 /*
1346  *      "Proxy" the request by sending it to a new virtual server.
1347  */
1348 static int proxy_to_virtual_server(REQUEST *request)
1349 {
1350         REQUEST *fake;
1351         RAD_REQUEST_FUNP fun;
1352
1353         if (!request->home_server || !request->home_server->server) return 0;
1354
1355         if (request->parent) {
1356                 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1357                 return 0;
1358         }
1359
1360         fake = request_alloc_fake(request);
1361         if (!fake) {
1362                 RDEBUG2("WARNING: Out of memory");
1363                 return 0;
1364         }
1365
1366         fake->packet->vps = paircopy(request->proxy->vps);
1367         fake->server = request->home_server->server;
1368
1369         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1370                 fun = rad_authenticate;
1371
1372 #ifdef WITH_ACCOUNTING
1373         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1374                 fun = rad_accounting;
1375 #endif
1376
1377         } else {
1378                 RDEBUG2("Unknown packet type %d", request->proxy->code);
1379                 return 0;
1380         }
1381
1382         RDEBUG2(">>> Sending proxied request internally to virtual server.");
1383         radius_handle_request(fake, fun);
1384         RDEBUG2("<<< Received proxied response from internal virtual server.");
1385
1386         request->proxy_reply = fake->reply;
1387         fake->reply = NULL;
1388
1389         request_free(&fake);
1390
1391         process_proxy_reply(request);
1392         fun(request);
1393
1394         return 2;               /* success, but NOT '1' !*/
1395 }
1396
1397
1398 /*
1399  *      Return 1 if we did proxy it, or the proxy attempt failed
1400  *      completely.  Either way, the caller doesn't touch the request
1401  *      any more if we return 1.
1402  */
1403 static int successfully_proxied_request(REQUEST *request)
1404 {
1405         int rcode;
1406         int pre_proxy_type = 0;
1407         VALUE_PAIR *realmpair;
1408         VALUE_PAIR *strippedname;
1409         VALUE_PAIR *vp;
1410         char *realmname;
1411         home_server *home;
1412         REALM *realm = NULL;
1413         home_pool_t *pool;
1414
1415         /*
1416          *      If it was already proxied, do nothing.
1417          *
1418          *      FIXME: This should really be a serious error.
1419          */
1420         if (request->in_proxy_hash) {
1421                 return 0;
1422         }
1423
1424         realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1425         if (!realmpair || (realmpair->length == 0)) {
1426                 return 0;
1427         }
1428
1429         realmname = (char *) realmpair->vp_strvalue;
1430
1431         realm = realm_find2(realmname);
1432         if (!realm) {
1433                 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1434                 return 0;
1435         }
1436
1437         /*
1438          *      Figure out which pool to use.
1439          */
1440         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1441                 pool = realm->auth_pool;
1442
1443 #ifdef WITH_ACCOUNTING
1444         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1445                 pool = realm->acct_pool;
1446 #endif
1447
1448         } else {
1449                 rad_panic("Internal sanity check failed");
1450         }
1451
1452         if (!pool) {
1453                 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1454                        realmname);
1455                 return 0;
1456         }
1457
1458         home = home_server_ldb(realmname, pool, request);
1459         if (!home) {
1460                 RDEBUG2("ERROR: Failed to find live home server for realm %s",
1461                        realmname);
1462                 return -1;
1463         }
1464         request->home_pool = pool;
1465
1466         /*
1467          *      Remember that we sent the request to a Realm.
1468          */
1469         pairadd(&request->packet->vps,
1470                 pairmake("Realm", realmname, T_OP_EQ));
1471
1472 #ifdef WITH_DETAIL
1473         /*
1474          *      We read the packet from a detail file, AND it came from
1475          *      the server we're about to send it to.  Don't do that.
1476          */
1477         if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1478             (request->listener->type == RAD_LISTEN_DETAIL) &&
1479             (home->ipaddr.af == AF_INET) &&
1480             (request->packet->src_ipaddr.af == AF_INET) &&
1481             (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1482                 RDEBUG2("    rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1483                 return 0;
1484         }
1485 #endif
1486
1487         /*
1488          *      Allocate the proxy packet, only if it wasn't already
1489          *      allocated by a module.  This check is mainly to support
1490          *      the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1491          *
1492          *      In those cases, the EAP module creates a "fake"
1493          *      request, and recursively passes it through the
1494          *      authentication stage of the server.  The module then
1495          *      checks if the request was supposed to be proxied, and
1496          *      if so, creates a proxy packet from the TUNNELED request,
1497          *      and not from the EAP request outside of the tunnel.
1498          *
1499          *      The proxy then works like normal, except that the response
1500          *      packet is "eaten" by the EAP module, and encapsulated into
1501          *      an EAP packet.
1502          */
1503         if (!request->proxy) {
1504                 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1505                         radlog(L_ERR|L_CONS, "no memory");
1506                         exit(1);
1507                 }
1508
1509                 /*
1510                  *      Copy the request, then look up name and
1511                  *      plain-text password in the copy.
1512                  *
1513                  *      Note that the User-Name attribute is the
1514                  *      *original* as sent over by the client.  The
1515                  *      Stripped-User-Name attribute is the one hacked
1516                  *      through the 'hints' file.
1517                  */
1518                 request->proxy->vps =  paircopy(request->packet->vps);
1519         }
1520
1521         /*
1522          *      Strip the name, if told to.
1523          *
1524          *      Doing it here catches the case of proxied tunneled
1525          *      requests.
1526          */
1527         if (realm->striprealm == TRUE &&
1528            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1529                 /*
1530                  *      If there's a Stripped-User-Name attribute in
1531                  *      the request, then use THAT as the User-Name
1532                  *      for the proxied request, instead of the
1533                  *      original name.
1534                  *
1535                  *      This is done by making a copy of the
1536                  *      Stripped-User-Name attribute, turning it into
1537                  *      a User-Name attribute, deleting the
1538                  *      Stripped-User-Name and User-Name attributes
1539                  *      from the vps list, and making the new
1540                  *      User-Name the head of the vps list.
1541                  */
1542                 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1543                 if (!vp) {
1544                         vp = radius_paircreate(request, NULL,
1545                                                PW_USER_NAME, PW_TYPE_STRING);
1546                         rad_assert(vp != NULL); /* handled by above function */
1547                         /* Insert at the START of the list */
1548                         vp->next = request->proxy->vps;
1549                         request->proxy->vps = vp;
1550                 }
1551                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1552                        sizeof(vp->vp_strvalue));
1553                 vp->length = strippedname->length;
1554
1555                 /*
1556                  *      Do NOT delete Stripped-User-Name.
1557                  */
1558         }
1559
1560         /*
1561          *      If there is no PW_CHAP_CHALLENGE attribute but
1562          *      there is a PW_CHAP_PASSWORD we need to add it
1563          *      since we can't use the request authenticator
1564          *      anymore - we changed it.
1565          */
1566         if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1567             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1568                 vp = radius_paircreate(request, &request->proxy->vps,
1569                                        PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1570                 vp->length = AUTH_VECTOR_LEN;
1571                 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1572         }
1573
1574         /*
1575          *      The RFC's say we have to do this, but FreeRADIUS
1576          *      doesn't need it.
1577          */
1578         vp = radius_paircreate(request, &request->proxy->vps,
1579                                PW_PROXY_STATE, PW_TYPE_OCTETS);
1580         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
1581                  request->packet->id);
1582         vp->length = strlen(vp->vp_strvalue);
1583
1584         /*
1585          *      Should be done BEFORE inserting into proxy hash, as
1586          *      pre-proxy may use this information, or change it.
1587          */
1588         request->proxy->code = request->packet->code;
1589         request->proxy->dst_ipaddr = home->ipaddr;
1590         request->proxy->dst_port = home->port;
1591         request->home_server = home;
1592
1593         /*
1594          *      Call the pre-proxy routines.
1595          */
1596         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1597         if (vp) {
1598                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
1599                 pre_proxy_type = vp->vp_integer;
1600         }
1601
1602         rad_assert(request->home_pool != NULL);
1603
1604         if (request->home_pool->virtual_server) {
1605                 const char *old_server = request->server;
1606                 
1607                 request->server = request->home_pool->virtual_server;
1608                 RDEBUG2(" server %s {", request->server);
1609                 rcode = module_pre_proxy(pre_proxy_type, request);
1610                 RDEBUG2(" }");
1611                         request->server = old_server;
1612         } else {
1613                 rcode = module_pre_proxy(pre_proxy_type, request);
1614         }
1615         switch (rcode) {
1616         case RLM_MODULE_FAIL:
1617         case RLM_MODULE_INVALID:
1618         case RLM_MODULE_NOTFOUND:
1619         case RLM_MODULE_USERLOCK:
1620         default:
1621                 /* FIXME: debug print failed stuff */
1622                 return -1;
1623
1624         case RLM_MODULE_REJECT:
1625         case RLM_MODULE_HANDLED:
1626                 return 0;
1627
1628         /*
1629          *      Only proxy the packet if the pre-proxy code succeeded.
1630          */
1631         case RLM_MODULE_NOOP:
1632         case RLM_MODULE_OK:
1633         case RLM_MODULE_UPDATED:
1634                 break;
1635         }
1636
1637         /*
1638          *      If it's a fake request, don't send the proxy
1639          *      packet.  The outer tunnel session will take
1640          *      care of doing that.
1641          */
1642         if (request->packet->dst_port == 0) {
1643                 request->home_server = NULL;
1644                 return 1;
1645         }
1646
1647         if (request->home_server->server) {
1648                 return proxy_to_virtual_server(request);
1649         }
1650
1651         if (!proxy_request(request)) {
1652                 RDEBUG("ERROR: Failed to proxy request %d", request->number);
1653                 return -1;
1654         }
1655         
1656         return 1;
1657 }
1658 #endif
1659
1660
1661 static void request_post_handler(REQUEST *request)
1662 {
1663         int child_state = -1;
1664         struct timeval when;
1665         VALUE_PAIR *vp;
1666
1667         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1668             (request->parent &&
1669              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1670                 RDEBUG2("Request %d was cancelled.", request->number);
1671 #ifdef HAVE_PTHREAD_H
1672                 request->child_pid = NO_SUCH_CHILD_PID;
1673 #endif
1674                 request->child_state = REQUEST_DONE;
1675                 return;
1676         }
1677
1678         if (request->child_state != REQUEST_RUNNING) {
1679                 rad_panic("Internal sanity check failed");
1680         }
1681
1682         if ((request->reply->code == 0) &&
1683             ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1684             (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1685                 request->reply->code = PW_AUTHENTICATION_REJECT;
1686         }
1687
1688 #ifdef WITH_PROXY
1689         if (request->root->proxy_requests &&
1690             !request->in_proxy_hash &&
1691             (request->reply->code == 0) &&
1692             (request->packet->dst_port != 0) &&
1693             (request->packet->code != PW_STATUS_SERVER)) {
1694                 int rcode = successfully_proxied_request(request);
1695
1696                 if (rcode == 1) return;
1697
1698                 /*
1699                  *      Failed proxying it (dead home servers, etc.)
1700                  *      Run it through Post-Proxy-Type = Fail, and
1701                  *      respond to the request.
1702                  *
1703                  *      Note that we're in a child thread here, so we
1704                  *      do NOT re-schedule the request.  Instead, we
1705                  *      do what we would have done, which is run the
1706                  *      pre-handler, a NULL request handler, and then
1707                  *      the post handler.
1708                  */
1709                 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1710                         request_pre_handler(request);
1711                 }
1712
1713                 /*
1714                  *      Else we weren't supposed to proxy it,
1715                  *      OR we proxied it internally to a virutal server.
1716                  */
1717         }
1718 #endif
1719
1720         /*
1721          *      Fake requests don't get encoded or signed.  The caller
1722          *      also requires the reply VP's, so we don't free them
1723          *      here!
1724          */
1725         if (request->packet->dst_port == 0) {
1726                 /* FIXME: RDEBUG going to the next request */
1727 #ifdef HAVE_PTHREAD_H
1728                 request->child_pid = NO_SUCH_CHILD_PID;
1729 #endif
1730                 request->child_state = REQUEST_DONE;
1731                 return;
1732         }
1733
1734 #ifdef WITH_PROXY
1735         /*
1736          *      Copy Proxy-State from the request to the reply.
1737          */
1738         vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1739         if (vp) pairadd(&request->reply->vps, vp);
1740 #endif
1741
1742         /*
1743          *      Access-Requests get delayed or cached.
1744          */
1745         switch (request->packet->code) {
1746         case PW_AUTHENTICATION_REQUEST:
1747                 gettimeofday(&request->next_when, NULL);
1748
1749                 if (request->reply->code == 0) {
1750                         /*
1751                          *      Check if the lack of response is intentional.
1752                          */
1753                         vp = pairfind(request->config_items,
1754                                       PW_RESPONSE_PACKET_TYPE);
1755                         if (!vp) {
1756                                 RDEBUG2("There was no response configured: rejecting request %d",
1757                                        request->number);
1758                                 request->reply->code = PW_AUTHENTICATION_REJECT;
1759                         } else if (vp->vp_integer == 256) {
1760                                 RDEBUG2("Not responding to request %d",
1761                                        request->number);
1762
1763                         } else {
1764                                 request->reply->code = vp->vp_integer;
1765
1766                         }
1767                 }
1768
1769                 /*
1770                  *      Run rejected packets through
1771                  *
1772                  *      Post-Auth-Type = Reject
1773                  */
1774                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1775                         pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1776                         vp = radius_pairmake(request, &request->config_items,
1777                                              "Post-Auth-Type", "Reject",
1778                                              T_OP_SET);
1779                         if (vp) rad_postauth(request);
1780
1781                         /*
1782                          *      If configured, delay Access-Reject packets.
1783                          *
1784                          *      If request->root->reject_delay = 0, we discover
1785                          *      that we have to send the packet now.
1786                          */
1787                         when = request->received;
1788                         when.tv_sec += request->root->reject_delay;
1789
1790                         if (timercmp(&when, &request->next_when, >)) {
1791                                 RDEBUG2("Delaying reject of request %d for %d seconds",
1792                                        request->number,
1793                                        request->root->reject_delay);
1794                                 request->next_when = when;
1795                                 request->next_callback = reject_delay;
1796 #ifdef HAVE_PTHREAD_H
1797                                 request->child_pid = NO_SUCH_CHILD_PID;
1798 #endif
1799                                 request->child_state = REQUEST_REJECT_DELAY;
1800                                 return;
1801                         }
1802                 }
1803
1804                 request->next_when.tv_sec += request->root->cleanup_delay;
1805                 request->next_callback = cleanup_delay;
1806                 child_state = REQUEST_CLEANUP_DELAY;
1807                 break;
1808
1809         case PW_ACCOUNTING_REQUEST:
1810                 request->next_callback = NULL; /* just to be safe */
1811                 child_state = REQUEST_DONE;
1812                 break;
1813
1814                 /*
1815                  *      FIXME: Status-Server should probably not be
1816                  *      handled here...
1817                  */
1818         case PW_STATUS_SERVER:
1819                 request->next_callback = NULL;
1820                 child_state = REQUEST_DONE;
1821                 break;
1822
1823         default:
1824                 if ((request->packet->code > 1024) &&
1825                     (request->packet->code < (1024 + 254 + 1))) {
1826                         request->next_callback = NULL;
1827                         child_state = REQUEST_DONE;
1828                         break;
1829                 }
1830
1831                 radlog(L_ERR, "Unknown packet type %d", request->packet->code);
1832                 rad_panic("Unknown packet type");
1833                 break;
1834         }
1835
1836         /*
1837          *      Suppress "no reply" packets here, unless we're reading
1838          *      from the "detail" file.  In that case, we've got to
1839          *      tell the detail file handler that the request is dead,
1840          *      and it should re-send it.
1841          *      If configured, encode, sign, and send.
1842          */
1843         if ((request->reply->code != 0) ||
1844             (request->listener->type == RAD_LISTEN_DETAIL)) {
1845                 DEBUG_PACKET(request, request->reply, 1);
1846                 request->listener->send(request->listener, request);
1847         }
1848
1849         /*
1850          *      Clean up.  These are no longer needed.
1851          */
1852         pairfree(&request->config_items);
1853
1854         pairfree(&request->packet->vps);
1855         request->username = NULL;
1856         request->password = NULL;
1857
1858         pairfree(&request->reply->vps);
1859
1860 #ifdef WITH_PROXY
1861         if (request->proxy) {
1862                 pairfree(&request->proxy->vps);
1863
1864                 if (request->proxy_reply) {
1865                         pairfree(&request->proxy_reply->vps);
1866                 }
1867
1868 #if 0
1869                 /*
1870                  *      We're not tracking responses from the home
1871                  *      server, we can therefore free this memory in
1872                  *      the child thread.
1873                  */
1874                 if (!request->in_proxy_hash) {
1875                         rad_free(&request->proxy);
1876                         rad_free(&request->proxy_reply);
1877                         request->home_server = NULL;
1878                 }
1879 #endif
1880         }
1881 #endif
1882
1883         RDEBUG2("Finished request %d.", request->number);
1884
1885         request->child_state = child_state;
1886
1887         /*
1888          *      Single threaded mode: update timers now.
1889          */
1890         if (!have_children) wait_a_bit(request);
1891 }
1892
1893
1894 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1895 {
1896 #ifdef WITH_PROXY
1897         char buffer[128];
1898 #endif
1899
1900         RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
1901         RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
1902
1903         switch (request->child_state) {
1904         case REQUEST_QUEUED:
1905         case REQUEST_RUNNING:
1906 #ifdef WITH_PROXY
1907         discard:
1908 #endif
1909                 radlog(L_ERR, "Discarding duplicate request from "
1910                        "client %s port %d - ID: %d due to unfinished request %d",
1911                        client->shortname,
1912                        request->packet->src_port,request->packet->id,
1913                        request->number);
1914                 break;
1915
1916 #ifdef WITH_PROXY
1917         case REQUEST_PROXIED:
1918                 /*
1919                  *      We're not supposed to have duplicate
1920                  *      accounting packets.  The other states handle
1921                  *      duplicates fine (discard, or send duplicate
1922                  *      reply).  But we do NOT want to retransmit an
1923                  *      accounting request here, because that would
1924                  *      involve updating the Acct-Delay-Time, and
1925                  *      therefore changing the packet Id, etc.
1926                  *
1927                  *      Instead, we just discard the packet.  We may
1928                  *      eventually respond, or the client will send a
1929                  *      new accounting packet.
1930                  */
1931                 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1932                         goto discard;
1933                 }
1934
1935                 check_for_zombie_home_server(request);
1936
1937                 /*
1938                  *      If we've just discovered that the home server is
1939                  *      dead, send the packet to another one.
1940                  */
1941                 if ((request->packet->dst_port != 0) &&
1942                     (request->home_server->state == HOME_STATE_IS_DEAD)) {
1943                         home_server *home;
1944
1945                         remove_from_proxy_hash(request);
1946
1947                         home = home_server_ldb(NULL, request->home_pool, request);
1948                         if (!home) {
1949                                 RDEBUG2("Failed to find live home server for request %d", request->number);
1950                         no_home_servers:
1951                                 /*
1952                                  *      Do post-request processing,
1953                                  *      and any insertion of necessary
1954                                  *      events.
1955                                  */
1956                                 post_proxy_fail_handler(request);
1957                                 return;
1958                         }
1959
1960                         request->proxy->code = request->packet->code;
1961                         request->proxy->dst_ipaddr = home->ipaddr;
1962                         request->proxy->dst_port = home->port;
1963                         request->home_server = home;
1964
1965                         /*
1966                          *      Free the old packet, to force re-encoding
1967                          */
1968                         free(request->proxy->data);
1969                         request->proxy->data = NULL;
1970                         request->proxy->data_len = 0;
1971
1972                         /*
1973                          *      This request failed over to a virtual
1974                          *      server.  Push it back onto the queue
1975                          *      to be processed.
1976                          */
1977                         if (request->home_server->server) {
1978                                 proxy_fallback_handler(request);
1979                                 return;
1980                         }
1981
1982                         /*
1983                          *      Try to proxy the request.
1984                          */
1985                         if (!proxy_request(request)) {
1986                                 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
1987                                 goto no_home_servers;
1988                         }
1989
1990                         /*
1991                          *      This code executes in the main server
1992                          *      thread, so there's no need for locking.
1993                          */
1994                         rad_assert(request->next_callback != NULL);
1995                         INSERT_EVENT(request->next_callback, request);
1996                         request->next_callback = NULL;
1997                         return;
1998                 } /* else the home server is still alive */
1999
2000                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2001                        inet_ntop(request->proxy->dst_ipaddr.af,
2002                                  &request->proxy->dst_ipaddr.ipaddr,
2003                                  buffer, sizeof(buffer)),
2004                        request->proxy->dst_port,
2005                        request->proxy->id);
2006                 request->num_proxied_requests++;
2007
2008                 DEBUG_PACKET(request, request->proxy, 1);
2009                 request->proxy_listener->send(request->proxy_listener,
2010                                               request);
2011                 break;
2012 #endif
2013
2014         case REQUEST_REJECT_DELAY:
2015                 RDEBUG2("Waiting to send Access-Reject "
2016                        "to client %s port %d - ID: %d",
2017                        client->shortname,
2018                        request->packet->src_port, request->packet->id);
2019                 break;
2020
2021         case REQUEST_CLEANUP_DELAY:
2022         case REQUEST_DONE:
2023                 RDEBUG2("Sending duplicate reply "
2024                        "to client %s port %d - ID: %d",
2025                        client->shortname,
2026                        request->packet->src_port, request->packet->id);
2027                 DEBUG_PACKET(request, request->reply, 1);
2028                 request->listener->send(request->listener, request);
2029                 break;
2030         }
2031 }
2032
2033
2034 static void received_conflicting_request(REQUEST *request,
2035                                          const RADCLIENT *client)
2036 {
2037         radlog(L_ERR, "Received conflicting packet from "
2038                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
2039                client->shortname,
2040                request->packet->src_port, request->packet->id,
2041                request->number);
2042
2043         /*
2044          *      Nuke it from the request hash, so we can receive new
2045          *      packets.
2046          */
2047         remove_from_request_hash(request);
2048
2049         switch (request->child_state) {
2050 #ifdef HAVE_PTHREAD_H
2051                 /*
2052                  *      It's queued or running.  Tell it to stop, and
2053                  *      wait for it to do so.
2054                  */
2055         case REQUEST_QUEUED:
2056         case REQUEST_RUNNING:
2057                 request->master_state = REQUEST_STOP_PROCESSING;
2058                 request->delay += request->delay >> 1;
2059
2060                 tv_add(&request->when, request->delay);
2061
2062                 INSERT_EVENT(wait_for_child_to_die, request);
2063                 return;
2064 #endif
2065
2066                 /*
2067                  *      It's in some other state, and therefore also
2068                  *      in the event queue.  At some point, the
2069                  *      child will notice, and we can then delete it.
2070                  */
2071         default:
2072                 rad_assert(request->ev != NULL);
2073                 break;
2074         }
2075 }
2076
2077
2078 static int can_handle_new_request(RADIUS_PACKET *packet,
2079                                   RADCLIENT *client,
2080                                   struct main_config_t *root)
2081 {
2082         /*
2083          *      Count the total number of requests, to see if
2084          *      there are too many.  If so, return with an
2085          *      error.
2086          */
2087         if (root->max_requests) {
2088                 int request_count = fr_packet_list_num_elements(pl);
2089
2090                 /*
2091                  *      This is a new request.  Let's see if
2092                  *      it makes us go over our configured
2093                  *      bounds.
2094                  */
2095                 if (request_count > root->max_requests) {
2096                         radlog(L_ERR, "Dropping request (%d is too many): "
2097                                "from client %s port %d - ID: %d", request_count,
2098                                client->shortname,
2099                                packet->src_port, packet->id);
2100                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2101                                "\tThe value for 'max_requests' is probably set too low.\n");
2102                         return 0;
2103                 } /* else there were a small number of requests */
2104         } /* else there was no configured limit for requests */
2105
2106         /*
2107          *      FIXME: Add per-client checks.  If one client is sending
2108          *      too many packets, start discarding them.
2109          *
2110          *      We increment the counters here, and decrement them
2111          *      when the response is sent... somewhere in this file.
2112          */
2113
2114         /*
2115          *      FUTURE: Add checks for system load.  If the system is
2116          *      busy, start dropping requests...
2117          *
2118          *      We can probably keep some statistics ourselves...  if
2119          *      there are more requests coming in than we can handle,
2120          *      start dropping some.
2121          */
2122
2123         return 1;
2124 }
2125
2126
2127 int received_request(rad_listen_t *listener,
2128                      RADIUS_PACKET *packet, REQUEST **prequest,
2129                      RADCLIENT *client)
2130 {
2131         RADIUS_PACKET **packet_p;
2132         REQUEST *request = NULL;
2133         struct main_config_t *root = &mainconfig;
2134
2135         packet_p = fr_packet_list_find(pl, packet);
2136         if (packet_p) {
2137                 request = fr_packet2myptr(REQUEST, packet, packet_p);
2138                 rad_assert(request->in_request_hash);
2139
2140                 if ((request->packet->data_len == packet->data_len) &&
2141                     (memcmp(request->packet->vector, packet->vector,
2142                             sizeof(packet->vector)) == 0)) {
2143                         received_retransmit(request, client);
2144                         return 0;
2145                 }
2146
2147                 /*
2148                  *      The new request is different from the old one,
2149                  *      but maybe the old is finished.  If so, delete
2150                  *      the old one.
2151                  */
2152                 switch (request->child_state) {
2153                         struct timeval when;
2154
2155                 default:
2156                         gettimeofday(&when, NULL);
2157                         when.tv_sec -= 1;
2158
2159                         /*
2160                          *      If the cached request was received
2161                          *      within the last second, then we
2162                          *      discard the NEW request instead of the
2163                          *      old one.  This will happen ONLY when
2164                          *      the client is severely broken, and is
2165                          *      sending conflicting packets very
2166                          *      quickly.
2167                          */
2168                         if (timercmp(&when, &request->received, <)) {
2169                                 radlog(L_ERR, "Discarding conflicting packet from "
2170                                        "client %s port %d - ID: %d due to recent request %d.",
2171                                        client->shortname,
2172                                        packet->src_port, packet->id,
2173                                        request->number);
2174                                 return 0;
2175                         }
2176
2177                         received_conflicting_request(request, client);
2178                         request = NULL;
2179                         break;
2180
2181                 case REQUEST_REJECT_DELAY:
2182                 case REQUEST_CLEANUP_DELAY:
2183                         request->child_state = REQUEST_DONE;
2184                 case REQUEST_DONE:
2185                         cleanup_delay(request);
2186                         request = NULL;
2187                         break;
2188                 }
2189         }
2190
2191         /*
2192          *      We may want to quench the new request.
2193          */
2194         if ((listener->type != RAD_LISTEN_DETAIL) &&
2195             !can_handle_new_request(packet, client, root)) {
2196                 return 0;
2197         }
2198
2199         /*
2200          *      Create and initialize the new request.
2201          */
2202         request = request_alloc(); /* never fails */
2203
2204         if ((request->reply = rad_alloc(0)) == NULL) {
2205                 radlog(L_ERR, "No memory");
2206                 exit(1);
2207         }
2208
2209         request->listener = listener;
2210         request->client = client;
2211         request->packet = packet;
2212         request->packet->timestamp = request->timestamp;
2213         request->number = request_num_counter++;
2214         request->priority = listener->type;
2215 #ifdef HAVE_PTHREAD_H
2216         request->child_pid = NO_SUCH_CHILD_PID;
2217 #endif
2218
2219         /*
2220          *      Status-Server packets go to the head of the queue.
2221          */
2222         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2223
2224         /*
2225          *      Set virtual server identity
2226          */
2227         if (client->server) {
2228                 request->server = client->server;
2229         } else if (listener->server) {
2230                 request->server = listener->server;
2231         } else {
2232                 request->server = NULL;
2233         }
2234
2235         /*
2236          *      Remember the request in the list.
2237          */
2238         if (!fr_packet_list_insert(pl, &request->packet)) {
2239                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2240                 request_free(&request);
2241                 return 0;
2242         }
2243
2244         request->in_request_hash = TRUE;
2245         request->root = root;
2246         root->refcount++;
2247
2248         /*
2249          *      The request passes many of our sanity checks.
2250          *      From here on in, if anything goes wrong, we
2251          *      send a reject message, instead of dropping the
2252          *      packet.
2253          */
2254
2255         /*
2256          *      Build the reply template from the request.
2257          */
2258
2259         request->reply->sockfd = request->packet->sockfd;
2260         request->reply->dst_ipaddr = request->packet->src_ipaddr;
2261         request->reply->src_ipaddr = request->packet->dst_ipaddr;
2262         request->reply->dst_port = request->packet->src_port;
2263         request->reply->src_port = request->packet->dst_port;
2264         request->reply->id = request->packet->id;
2265         request->reply->code = 0; /* UNKNOWN code */
2266         memcpy(request->reply->vector, request->packet->vector,
2267                sizeof(request->reply->vector));
2268         request->reply->vps = NULL;
2269         request->reply->data = NULL;
2270         request->reply->data_len = 0;
2271
2272         request->master_state = REQUEST_ACTIVE;
2273         request->child_state = REQUEST_QUEUED;
2274         request->next_callback = NULL;
2275
2276         gettimeofday(&request->received, NULL);
2277         request->timestamp = request->received.tv_sec;
2278         request->when = request->received;
2279
2280         request->delay = USEC;
2281
2282         tv_add(&request->when, request->delay);
2283
2284         INSERT_EVENT(wait_a_bit, request);
2285
2286         *prequest = request;
2287         return 1;
2288 }
2289
2290
2291 #ifdef WITH_PROXY
2292 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2293 {
2294         char            buffer[128];
2295         home_server     *home;
2296         REQUEST         *request;
2297
2298         if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
2299                 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
2300                        inet_ntop(packet->src_ipaddr.af,
2301                                  &packet->src_ipaddr.ipaddr,
2302                                  buffer, sizeof(buffer)),
2303                                packet->src_port);
2304                 rad_free(&packet);
2305                 return NULL;
2306         }
2307
2308         /*
2309          *      Also removes from the proxy hash if responses == requests
2310          */
2311         request = lookup_in_proxy_hash(packet);
2312
2313         if (!request) {
2314                 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
2315                        inet_ntop(packet->src_ipaddr.af,
2316                                  &packet->src_ipaddr.ipaddr,
2317                                  buffer, sizeof(buffer)),
2318                        packet->src_port, packet->id);
2319                 rad_free(&packet);
2320                 return NULL;
2321         }
2322
2323         home = request->home_server;
2324
2325         gettimeofday(&now, NULL);
2326
2327         home->state = HOME_STATE_ALIVE;
2328
2329         if (request->reply && request->reply->code != 0) {
2330                 RDEBUG2("We already replied to this request.  Discarding response from home server.");
2331                 rad_free(&packet);
2332                 return NULL;
2333         }
2334
2335         /*
2336          *      We had previously received a reply, so we don't need
2337          *      to do anything here.
2338          */
2339         if (request->proxy_reply) {
2340                 if (memcmp(request->proxy_reply->vector,
2341                            packet->vector,
2342                            sizeof(request->proxy_reply->vector)) == 0) {
2343                         RDEBUG2("Discarding duplicate reply from home server %s port %d  - ID: %d for request %d",
2344                                inet_ntop(packet->src_ipaddr.af,
2345                                          &packet->src_ipaddr.ipaddr,
2346                                          buffer, sizeof(buffer)),
2347                                packet->src_port, packet->id,
2348                                request->number);
2349                 } else {
2350                         /*
2351                          *      ? The home server gave us a new proxy
2352                          *      reply, which doesn't match the old
2353                          *      one.  Delete it.
2354                          */
2355                         RDEBUG2("Ignoring conflicting proxy reply");
2356                 }
2357
2358                 /* assert that there's an event queued for request? */
2359                 rad_free(&packet);
2360                 return NULL;
2361         }
2362 #ifdef WITH_STATS
2363         /*
2364          *      The average includes our time to receive packets and
2365          *      look them up in the hashes, which should be the same
2366          *      for all packets.
2367          *
2368          *      We update the response time only for the FIRST packet
2369          *      we receive.
2370          */
2371         else if (home->ema.window > 0) {
2372                 radius_stats_ema(&home->ema, &now, &request->proxy_when);
2373         }
2374 #endif
2375
2376
2377         switch (request->child_state) {
2378         case REQUEST_QUEUED:
2379         case REQUEST_RUNNING:
2380                 rad_panic("Internal sanity check failed for child state");
2381                 break;
2382
2383         case REQUEST_REJECT_DELAY:
2384         case REQUEST_CLEANUP_DELAY:
2385         case REQUEST_DONE:
2386                 radlog(L_ERR, "Reply from home server %s port %d  - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
2387                        inet_ntop(packet->src_ipaddr.af,
2388                                  &packet->src_ipaddr.ipaddr,
2389                                  buffer, sizeof(buffer)),
2390                        packet->src_port, packet->id,
2391                        request->number);
2392                 /* assert that there's an event queued for request? */
2393                 rad_free(&packet);
2394                 return NULL;
2395
2396         case REQUEST_PROXIED:
2397                 break;
2398         }
2399
2400         request->proxy_reply = packet;
2401
2402 #if 0
2403         /*
2404          *      Perform RTT calculations, as per RFC 2988 (for TCP).
2405          *      Note that we do so only if we sent one request, and
2406          *      received one response.  If we sent two requests, we
2407          *      have no idea if the response is for the first, or for
2408          *      the second request/
2409          */
2410         if (request->num_proxied_requests == 1) {
2411                 int rtt;
2412                 home_server *home = request->home_server;
2413
2414                 rtt = now.tv_sec - request->proxy_when.tv_sec;
2415                 rtt *= USEC;
2416                 rtt += now.tv_usec;
2417                 rtt -= request->proxy_when.tv_usec;
2418
2419                 if (!home->has_rtt) {
2420                         home->has_rtt = TRUE;
2421
2422                         home->srtt = rtt;
2423                         home->rttvar = rtt / 2;
2424
2425                 } else {
2426                         home->rttvar -= home->rttvar >> 2;
2427                         home->rttvar += (home->srtt - rtt);
2428                         home->srtt -= home->srtt >> 3;
2429                         home->srtt += rtt >> 3;
2430                 }
2431
2432                 home->rto = home->srtt;
2433                 if (home->rttvar > (USEC / 4)) {
2434                         home->rto += home->rttvar * 4;
2435                 } else {
2436                         home->rto += USEC;
2437                 }
2438         }
2439 #endif
2440
2441         /*
2442          *      There's no incoming request, so it's a proxied packet
2443          *      we originated.
2444          */
2445         if (!request->packet) {
2446                 received_response_to_ping(request);
2447                 return NULL;
2448         }
2449
2450         request->child_state = REQUEST_QUEUED;
2451         request->when = now;
2452         request->delay = USEC;
2453         request->priority = RAD_LISTEN_PROXY;
2454         tv_add(&request->when, request->delay);
2455
2456         /*
2457          *      Wait a bit will take care of max_request_time
2458          */
2459         INSERT_EVENT(wait_a_bit, request);
2460
2461         return request;
2462 }
2463 #endif
2464
2465 void event_new_fd(rad_listen_t *this)
2466 {
2467         char buffer[1024];
2468         
2469         this->print(this, buffer, sizeof(buffer));
2470         
2471         if (this->status == RAD_LISTEN_STATUS_INIT) {
2472                 if (just_started) {
2473                         DEBUG("Listening on %s", buffer);
2474                 } else {
2475                         DEBUG2(" ... adding new socket %s", buffer);
2476                 }
2477                 if (!fr_event_fd_insert(el, 0, this->fd,
2478                                         event_socket_handler, this)) {
2479                         radlog(L_ERR, "Failed remembering handle for proxy socket!");
2480                         exit(1);
2481                 }
2482                 
2483                 this->status = RAD_LISTEN_STATUS_KNOWN;
2484                 return;
2485         }
2486         
2487         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
2488                 DEBUG2(" ... closing socket %s", buffer);
2489                 
2490                 fr_event_fd_delete(el, 0, this->fd);
2491                 this->status = RAD_LISTEN_STATUS_FINISH;
2492                 
2493                 /*
2494                  *      Close the fd AFTER fixing up the requests and
2495                  *      listeners, so that they don't send/recv on the
2496                  *      wrong socket (if someone manages to open
2497                  *      another one).
2498                  */
2499                 close(this->fd);
2500                 this->fd = -1;
2501         }
2502 }
2503
2504 #ifdef WITH_DETAIL
2505 static void event_detail_timer(void *ctx)
2506 {
2507         rad_listen_t *listener = ctx;
2508         RAD_REQUEST_FUNP fun;
2509         REQUEST *request;
2510
2511         if (listener->recv(listener, &fun, &request)) {
2512                 if (!thread_pool_addrequest(request, fun)) {
2513                         request->child_state = REQUEST_DONE;
2514                 }
2515         }
2516 }
2517 #endif
2518
2519 static void handle_signal_self(int flag)
2520 {
2521         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2522                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2523                         fr_event_loop_exit(el, 1);
2524                 } else {
2525                         fr_event_loop_exit(el, 2);
2526                 }
2527
2528                 return;
2529         } /* else exit/term flags weren't set */
2530
2531         /*
2532          *      Tell the even loop to stop processing.
2533          */
2534         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2535                 time_t when;
2536                 static time_t last_hup = 0;
2537
2538                 DEBUG("Received HUP signal.");
2539
2540                 when = time(NULL);
2541                 if ((int) (when - last_hup) < 5) {
2542                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2543                         return;
2544                 }
2545                 last_hup = when;
2546
2547                 fr_event_loop_exit(el, 0x80);
2548         }
2549
2550 #ifdef WITH_DETAIL
2551         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2552                 rad_listen_t *this;
2553                 
2554                 for (this = mainconfig.listen;
2555                      this != NULL;
2556                      this = this->next) {
2557                         int delay;
2558                         struct timeval when;
2559
2560                         if (this->type != RAD_LISTEN_DETAIL) continue;
2561                         
2562                         delay = detail_delay(this);
2563                         if (!delay) continue;
2564
2565                         fr_event_now(el, &now);
2566                         when = now;
2567                         tv_add(&when, delay);
2568
2569                         if (delay > 100000) {
2570                                 DEBUG("Delaying next detail event for %d.%01u seconds.",
2571                                        delay / USEC, (delay % USEC) / 100000);
2572                         }
2573
2574                         if (!fr_event_insert(el, event_detail_timer, this,
2575                                              &when, NULL)) {
2576                                 radlog(L_ERR, "Failed remembering timer");
2577                                 exit(1);
2578                         }
2579                 }
2580         }
2581 #endif
2582
2583         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2584                 rad_listen_t *this;
2585                 
2586                 for (this = mainconfig.listen;
2587                      this != NULL;
2588                      this = this->next) {
2589                         if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
2590
2591                         event_new_fd(this);
2592                 }
2593         }
2594 }
2595
2596 #ifdef __MINGW32__
2597 void radius_signal_self(int flag)
2598 {
2599         handle_signal_self(flag);
2600 }
2601 #else
2602 /*
2603  *      Inform ourselves that we received a signal.
2604  */
2605 void radius_signal_self(int flag)
2606 {
2607         ssize_t rcode;
2608         uint8_t buffer[16];
2609
2610         /*
2611          *      The read MUST be non-blocking for this to work.
2612          */
2613         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2614         if (rcode > 0) {
2615                 ssize_t i;
2616
2617                 for (i = 0; i < rcode; i++) {
2618                         buffer[0] |= buffer[i];
2619                 }
2620         } else {
2621                 buffer[0] = 0;
2622         }
2623
2624         buffer[0] |= flag;
2625
2626         write(self_pipe[1], buffer, 1);
2627 }
2628
2629
2630 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2631                                  UNUSED int fd, UNUSED void *ctx)
2632 {
2633         ssize_t i, rcode;
2634         uint8_t buffer[32];
2635
2636         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2637         if (rcode <= 0) return;
2638
2639         /*
2640          *      Merge pending signals.
2641          */
2642         for (i = 0; i < rcode; i++) {
2643                 buffer[0] |= buffer[i];
2644         }
2645
2646         handle_signal_self(buffer[0]);
2647 }
2648 #endif
2649
2650
2651 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
2652                                  void *ctx)
2653 {
2654         rad_listen_t *listener = ctx;
2655         RAD_REQUEST_FUNP fun;
2656         REQUEST *request;
2657
2658         rad_assert(xel == el);
2659
2660         xel = xel;
2661
2662         if (listener->fd < 0) rad_panic("Socket was closed on us!");
2663         
2664         if (!listener->recv(listener, &fun, &request)) return;
2665
2666         if (!thread_pool_addrequest(request, fun)) {
2667                 request->child_state = REQUEST_DONE;
2668         }
2669 }
2670
2671
2672 /*
2673  *      This function is called periodically to see if any FD's are
2674  *      available for reading.
2675  */
2676 static void event_poll_detail(UNUSED void *ctx)
2677 {
2678         int rcode;
2679         RAD_REQUEST_FUNP fun;
2680         REQUEST *request;
2681         rad_listen_t *this;
2682         struct timeval when;
2683
2684         fr_event_now(el, &now);
2685         when = now;
2686         when.tv_sec += 1;
2687
2688         for (this = mainconfig.listen; this != NULL; this = this->next) {
2689                 if (this->type != RAD_LISTEN_DETAIL) continue;
2690
2691                 if (this->fd >= 0) continue;
2692
2693                 /*
2694                  *      Try to read something.
2695                  *
2696                  *      FIXME: This does poll AND receive.
2697                  */
2698                 rcode = this->recv(this, &fun, &request);
2699                 if (!rcode) continue;
2700                 
2701                 rad_assert(fun != NULL);
2702                 rad_assert(request != NULL);
2703                         
2704                 if (!thread_pool_addrequest(request, fun)) {
2705                         request->child_state = REQUEST_DONE;
2706                 }
2707         }
2708
2709         /*
2710          *      Reset the poll.
2711          */
2712         if (!fr_event_insert(el, event_poll_detail, NULL,
2713                              &when, NULL)) {
2714                 radlog(L_ERR, "Failed creating handler");
2715                 exit(1);
2716         }
2717 }
2718
2719
2720 static void event_status(struct timeval *wake)
2721 {
2722 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2723         int argval;
2724 #endif
2725
2726         if (debug_flag == 0) {
2727                 if (just_started) {
2728                         radlog(L_INFO, "Ready to process requests.");
2729                         just_started = FALSE;
2730                 }
2731                 return;
2732         }
2733
2734         if (!wake) {
2735                 DEBUG("Ready to process requests.");
2736
2737         } else if ((wake->tv_sec != 0) ||
2738                    (wake->tv_usec >= 100000)) {
2739                 DEBUG("Waking up in %d.%01u seconds.",
2740                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2741         }
2742
2743
2744         /*
2745          *      FIXME: Put this somewhere else, where it isn't called
2746          *      all of the time...
2747          */
2748
2749 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2750         /*
2751          *      If there are no child threads, then there may
2752          *      be child processes.  In that case, wait for
2753          *      their exit status, and throw that exit status
2754          *      away.  This helps get rid of zxombie children.
2755          */
2756         while (waitpid(-1, &argval, WNOHANG) > 0) {
2757                 /* do nothing */
2758         }
2759 #endif
2760
2761 }
2762
2763
2764 /*
2765  *      Externally-visibly functions.
2766  */
2767 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2768 {
2769         rad_listen_t *this, *head = NULL;
2770
2771         if (el) return 0;
2772
2773         time(&fr_start_time);
2774
2775         el = fr_event_list_create(event_status);
2776         if (!el) return 0;
2777
2778         pl = fr_packet_list_create(0);
2779         if (!el) return 0;
2780
2781         request_num_counter = 0;
2782
2783         /*
2784          *      Move all of the thread calls to this file?
2785          *
2786          *      It may be best for the mutexes to be in this file...
2787          */
2788         have_children = spawn_flag;
2789
2790 #ifdef WITH_PROXY
2791         if (mainconfig.proxy_requests) {
2792                 /*
2793                  *      Create the tree for managing proxied requests and
2794                  *      responses.
2795                  */
2796                 proxy_list = fr_packet_list_create(1);
2797                 if (!proxy_list) return 0;
2798
2799 #ifdef HAVE_PTHREAD_H
2800                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2801                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2802                                strerror(errno));
2803                         exit(1);
2804                 }
2805 #endif
2806         }
2807 #endif
2808
2809         /*
2810          *      Just before we spawn the child threads, force the log
2811          *      subsystem to re-open the log file for every write.
2812          */
2813         if (spawn_flag) force_log_reopen();
2814
2815 #ifdef HAVE_PTHREAD_H
2816 #ifndef __MINGW32__
2817         NO_SUCH_CHILD_PID = (pthread_t ) (0);
2818 #else
2819         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
2820 #endif
2821         if (thread_pool_init(cs, spawn_flag) < 0) {
2822                 exit(1);
2823         }
2824 #endif
2825
2826         if (check_config) {
2827                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
2828                        mainconfig.name);
2829                 return 1;
2830         }
2831
2832 #ifndef __MINGW32__
2833         /*
2834          *      Child threads need a pipe to signal us, as do the
2835          *      signal handlers.
2836          */
2837         if (pipe(self_pipe) < 0) {
2838                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2839                        strerror(errno));
2840                 exit(1);
2841         }
2842         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2843                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2844                        strerror(errno));
2845                 exit(1);
2846         }
2847         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2848                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2849                        strerror(errno));
2850                 exit(1);
2851         }
2852
2853         if (!fr_event_fd_insert(el, 0, self_pipe[0],
2854                                   event_signal_handler, el)) {
2855                 radlog(L_ERR, "Failed creating handler for signals");
2856                 exit(1);
2857         }
2858 #endif
2859
2860 #ifdef WITH_PROXY
2861         /*
2862          *      Mark the proxy Fd's as unused.
2863          */
2864         {
2865                 int i;
2866
2867                 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2868         }
2869 #endif
2870
2871        DEBUG("%s: #### Opening IP addresses and Ports ####",
2872                mainconfig.name);
2873
2874         if (listen_init(cs, &head) < 0) {
2875                 _exit(1);
2876         }
2877         
2878         /*
2879          *      Add all of the sockets to the event loop.
2880          */
2881         for (this = head;
2882              this != NULL;
2883              this = this->next) {
2884                 char buffer[256];
2885
2886                 this->print(this, buffer, sizeof(buffer));
2887
2888                 switch (this->type) {
2889 #ifdef WITH_DETAIL
2890                 case RAD_LISTEN_DETAIL:
2891                         DEBUG("Listening on %s", buffer);
2892                         has_detail_listener = TRUE;
2893                         break;
2894 #endif
2895
2896 #ifdef WITH_PROXY
2897                 case RAD_LISTEN_PROXY:
2898                         rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2899                         rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2900                         
2901                         proxy_fds[this->fd & 0x1f] = this->fd;
2902                         proxy_listeners[this->fd & 0x1f] = this;
2903                         if (!fr_packet_list_socket_add(proxy_list,
2904                                                          this->fd)) {
2905                                 rad_assert(0 == 1);
2906                         }
2907                         /* FALL-THROUGH */
2908 #endif
2909
2910                 default:
2911                         break;
2912                 }
2913
2914                 /*
2915                  *      The file descriptor isn't ready.  Poll for
2916                  *      when it will become ready.  This is for the
2917                  *      detail file fd's.
2918                  */
2919                 if (this->fd < 0) {
2920                         continue;
2921                 }
2922
2923                 event_new_fd(this);
2924         }
2925
2926         if (has_detail_listener) {
2927                 struct timeval when;
2928                 
2929                 gettimeofday(&when, NULL);
2930                 when.tv_sec += 1;
2931                 
2932                 if (!fr_event_insert(el, event_poll_detail, NULL,
2933                                      &when, NULL)) {
2934                         radlog(L_ERR, "Failed creating handler");
2935                         exit(1);
2936                 }
2937         }
2938
2939         mainconfig.listen = head;
2940
2941         return 1;
2942 }
2943
2944
2945 static int request_hash_cb(UNUSED void *ctx, void *data)
2946 {
2947         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2948
2949 #ifdef WITH_PROXY
2950         rad_assert(request->in_proxy_hash == FALSE);
2951 #endif
2952
2953         fr_event_delete(el, &request->ev);
2954         remove_from_request_hash(request);
2955         request_free(&request);
2956
2957         return 0;
2958 }
2959
2960
2961 #ifdef WITH_PROXY
2962 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2963 {
2964         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2965
2966         fr_packet_list_yank(proxy_list, request->proxy);
2967         request->in_proxy_hash = FALSE;
2968
2969         if (!request->in_request_hash) {
2970                 fr_event_delete(el, &request->ev);
2971                 request_free(&request);
2972         }
2973
2974         return 0;
2975 }
2976 #endif
2977
2978 void radius_event_free(void)
2979 {
2980         /*
2981          *      FIXME: Stop all threads, or at least check that
2982          *      they're all waiting on the semaphore, and the queues
2983          *      are empty.
2984          */
2985
2986 #ifdef WITH_PROXY
2987         /*
2988          *      There are requests in the proxy hash that aren't
2989          *      referenced from anywhere else.  Remove them first.
2990          */
2991         if (proxy_list) {
2992                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2993                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2994                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2995                 fr_packet_list_free(proxy_list);
2996                 proxy_list = NULL;
2997         }
2998 #endif
2999
3000         fr_packet_list_walk(pl, NULL, request_hash_cb);
3001
3002         fr_packet_list_free(pl);
3003         pl = NULL;
3004
3005         fr_event_list_free(el);
3006 }
3007
3008 int radius_event_process(void)
3009 {
3010         if (!el) return 0;
3011
3012         return fr_event_loop(el);
3013 }
3014
3015 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3016 {
3017         request->options = RAD_REQUEST_OPTION_DEBUG2;
3018
3019         if (request_pre_handler(request)) {
3020                 rad_assert(fun != NULL);
3021                 rad_assert(request != NULL);
3022                 
3023                 if (request->server) RDEBUG("server %s {",
3024                                              request->server); 
3025                 fun(request);
3026
3027                 if (request->server) RDEBUG("} # server %s",
3028                                              request->server);
3029
3030                 request_post_handler(request);
3031         }
3032
3033         DEBUG2("Going to the next request");
3034         return;
3035 }