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