Print out correct packet information...
[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 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
483 {
484         VALUE_PAIR *vp;
485         char buffer[1024];
486         const char *received, *from;
487         const fr_ipaddr_t *ip;
488         int port;
489
490         if (!packet) return;
491
492         if (direction == 0) {
493                 received = "Received";
494                 from = "from";  /* what else? */
495                 ip = &packet->src_ipaddr;
496                 port = packet->src_port;
497
498         } else {
499                 received = "Sending";
500                 from = "to";    /* hah! */
501                 ip = &packet->dst_ipaddr;
502                 port = packet->dst_port;
503         }
504         
505         /*
506          *      Client-specific debugging re-prints the input
507          *      packet into the client log.
508          *
509          *      This really belongs in a utility library
510          */
511         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
512                 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
513                        received, packet_codes[packet->code], from,
514                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
515                        port, packet->id, packet->data_len);
516         } else {
517                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
518                        received, from,
519                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
520                        port,
521                        packet->code, packet->id, packet->data_len);
522         }
523
524         for (vp = packet->vps; vp != NULL; vp = vp->next) {
525                 vp_prints(buffer, sizeof(buffer), vp);
526                 request->radlog(L_DBG, 0, request, "\t%s", buffer);
527         }
528 }
529
530 static void reject_delay(void *ctx)
531 {
532         REQUEST *request = ctx;
533
534         rad_assert(request->magic == REQUEST_MAGIC);
535         rad_assert(request->child_state == REQUEST_REJECT_DELAY);
536
537         RDEBUG2("Sending delayed reject for request %d", request->number);
538
539         if (request->options) {
540                 debug_packet(request, request->reply, 1);
541         }
542         request->listener->send(request->listener, request);
543
544         request->when.tv_sec += request->root->cleanup_delay;
545         request->child_state = REQUEST_CLEANUP_DELAY;
546
547         INSERT_EVENT(cleanup_delay, request);
548 }
549
550
551 #ifdef WITH_PROXY
552 static void revive_home_server(void *ctx)
553 {
554         home_server *home = ctx;
555         char buffer[128];
556
557         home->state = HOME_STATE_ALIVE;
558         radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
559                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
560                          buffer, sizeof(buffer)),
561                home->port);
562         home->currently_outstanding = 0;
563         home->revive_time = now;
564 }
565
566
567 static void no_response_to_ping(void *ctx)
568 {
569         REQUEST *request = ctx;
570         home_server *home = request->home_server;
571         char buffer[128];
572
573         home->num_received_pings = 0;
574
575         RDEBUG2("No response to status check %d from home server %s port %d",
576                request->number,
577                inet_ntop(request->proxy->dst_ipaddr.af,
578                          &request->proxy->dst_ipaddr.ipaddr,
579                          buffer, sizeof(buffer)),
580                request->proxy->dst_port);
581
582         wait_for_proxy_id_to_expire(request);
583 }
584
585
586 static void received_response_to_ping(REQUEST *request)
587 {
588         home_server *home = request->home_server;
589         char buffer[128];
590
591         home->num_received_pings++;
592
593         RDEBUG2("Received response to status check %d (%d in current sequence)",
594                request->number, home->num_received_pings);
595
596         if (home->num_received_pings < home->num_pings_to_alive) {
597                 wait_for_proxy_id_to_expire(request);
598                 return;
599         }
600
601         radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
602                inet_ntop(request->proxy->dst_ipaddr.af,
603                          &request->proxy->dst_ipaddr.ipaddr,
604                          buffer, sizeof(buffer)),
605                request->proxy->dst_port);
606
607         if (!fr_event_delete(el, &home->ev)) {
608                 RDEBUG2("Hmm... no event for home server, WTF?");
609         }
610
611         if (!fr_event_delete(el, &request->ev)) {
612                 RDEBUG2("Hmm... no event for request, WTF?");
613         }
614
615         wait_for_proxy_id_to_expire(request);
616
617         home->state = HOME_STATE_ALIVE;
618         home->currently_outstanding = 0;
619         home->revive_time = now;
620 }
621
622
623 static void ping_home_server(void *ctx)
624 {
625         uint32_t jitter;
626         home_server *home = ctx;
627         REQUEST *request;
628         VALUE_PAIR *vp;
629
630         if (home->state == HOME_STATE_ALIVE) {
631                 radlog(L_INFO, "Suspicious proxy state... continuing");
632                 return;
633         }
634
635         request = request_alloc();
636         request->number = request_num_counter++;
637
638         request->proxy = rad_alloc(1);
639         rad_assert(request->proxy != NULL);
640
641         fr_event_now(el, &request->when);
642         home->when = request->when;
643
644         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
645                 request->proxy->code = PW_STATUS_SERVER;
646
647                 radius_pairmake(request, &request->proxy->vps,
648                                 "Message-Authenticator", "0x00", T_OP_SET);
649
650         } else if (home->type == HOME_TYPE_AUTH) {
651                 request->proxy->code = PW_AUTHENTICATION_REQUEST;
652
653                 radius_pairmake(request, &request->proxy->vps,
654                                 "User-Name", home->ping_user_name, T_OP_SET);
655                 radius_pairmake(request, &request->proxy->vps,
656                                 "User-Password", home->ping_user_password, T_OP_SET);
657                 radius_pairmake(request, &request->proxy->vps,
658                                 "Service-Type", "Authenticate-Only", T_OP_SET);
659                 radius_pairmake(request, &request->proxy->vps,
660                                 "Message-Authenticator", "0x00", T_OP_SET);
661
662         } else {
663 #ifdef WITH_ACCOUNTING
664                 request->proxy->code = PW_ACCOUNTING_REQUEST;
665                 
666                 radius_pairmake(request, &request->proxy->vps,
667                                 "User-Name", home->ping_user_name, T_OP_SET);
668                 radius_pairmake(request, &request->proxy->vps,
669                                 "Acct-Status-Type", "Stop", T_OP_SET);
670                 radius_pairmake(request, &request->proxy->vps,
671                                 "Acct-Session-Id", "00000000", T_OP_SET);
672                 vp = radius_pairmake(request, &request->proxy->vps,
673                                      "Event-Timestamp", "0", T_OP_SET);
674                 vp->vp_date = now.tv_sec;
675 #else
676                 rad_assert("Internal sanity check failed");
677 #endif
678         }
679
680         radius_pairmake(request, &request->proxy->vps,
681                         "NAS-Identifier", "Status Check. Are you alive?",
682                         T_OP_SET);
683
684         request->proxy->dst_ipaddr = home->ipaddr;
685         request->proxy->dst_port = home->port;
686         request->home_server = home;
687
688         rad_assert(request->proxy_listener == NULL);
689
690         if (!insert_into_proxy_hash(request)) {
691                 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash.  Discarding it.",
692                        request->number);
693                 request_free(&request);
694                 return;
695         }
696         rad_assert(request->proxy_listener != NULL);
697         request->proxy_listener->send(request->proxy_listener,
698                                       request);
699
700         request->next_callback = NULL;
701         request->child_state = REQUEST_PROXIED;
702         request->when.tv_sec += home->ping_timeout;;
703
704         INSERT_EVENT(no_response_to_ping, request);
705
706         /*
707          *      Add +/- 2s of jitter, as suggested in RFC 3539
708          *      and in the Issues and Fixes draft.
709          */
710         home->when.tv_sec += home->ping_interval - 2;
711
712         jitter = fr_rand();
713         jitter ^= (jitter >> 10);
714         jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
715
716         tv_add(&home->when, jitter);
717
718
719         INSERT_EVENT(ping_home_server, home);
720 }
721
722
723 static void check_for_zombie_home_server(REQUEST *request)
724 {
725         home_server *home;
726         struct timeval when;
727         char buffer[128];
728
729         home = request->home_server;
730
731         if (home->state != HOME_STATE_ZOMBIE) return;
732
733         when = home->zombie_period_start;
734         when.tv_sec += home->zombie_period;
735
736         fr_event_now(el, &now);
737         if (timercmp(&now, &when, <)) {
738                 return;
739         }
740
741         /*
742          *      It's been a zombie for too long, mark it as
743          *      dead.
744          */
745         radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
746                inet_ntop(request->proxy->dst_ipaddr.af,
747                          &request->proxy->dst_ipaddr.ipaddr,
748                          buffer, sizeof(buffer)),
749                request->proxy->dst_port);
750         home->state = HOME_STATE_IS_DEAD;
751         home->num_received_pings = 0;
752         home->when = request->when;
753
754         if (home->ping_check != HOME_PING_CHECK_NONE) {
755                 rad_assert((home->ping_check == HOME_PING_CHECK_STATUS_SERVER) ||
756                            (home->ping_user_name != NULL));
757                 home->when.tv_sec += home->ping_interval;
758
759                 INSERT_EVENT(ping_home_server, home);
760         } else {
761                 home->when.tv_sec += home->revive_interval;
762
763                 INSERT_EVENT(revive_home_server, home);
764         }
765 }
766
767 static int proxy_to_virtual_server(REQUEST *request);
768
769 static int virtual_server_handler(UNUSED REQUEST *request)
770 {
771         proxy_to_virtual_server(request);
772         return 0;
773 }
774
775 static void proxy_fallback_handler(REQUEST *request)
776 {
777         /*
778          *      A proper time is required for wait_a_bit.
779          */
780         request->delay = USEC / 10;
781         gettimeofday(&now, NULL);
782         request->next_when = now;
783         tv_add(&request->next_when, request->delay);
784         request->next_callback = wait_a_bit;
785
786         /*
787          *      Re-queue the request.
788          */
789         request->child_state = REQUEST_QUEUED;
790         
791         rad_assert(request->proxy != NULL);
792         if (!thread_pool_addrequest(request, virtual_server_handler)) {
793                 request->child_state = REQUEST_DONE;
794         }
795
796 #ifdef HAVE_PTHREAD_H
797         /*
798          *      MAY free the request if we're over max_request_time,
799          *      AND we're not in threaded mode!
800          *
801          *      Note that we call this ONLY if we're threaded, as
802          *      if we're NOT threaded, request_post_handler() calls
803          *      wait_a_bit(), which means that "request" may not
804          *      exist any more...
805          */
806         if (have_children) wait_a_bit(request);
807 #endif
808 }
809
810
811 static int setup_post_proxy_fail(REQUEST *request)
812 {
813         DICT_VALUE *dval = NULL;
814         VALUE_PAIR *vp;
815
816         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
817                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
818
819         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
820                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
821
822         } else {
823                 return 0;
824         }
825
826         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
827
828         if (!dval) {
829                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
830                 return 0;
831         }
832
833         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
834         if (!vp) vp = radius_paircreate(request, &request->config_items,
835                                         PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
836         vp->vp_integer = dval->value;
837
838         rad_assert(request->proxy_reply == NULL);
839
840         return 1;
841 }
842
843
844 static int null_handler(UNUSED REQUEST *request)
845 {
846         return 0;
847 }
848
849 static void post_proxy_fail_handler(REQUEST *request)
850 {
851         /*
852          *      A proper time is required for wait_a_bit.
853          */
854         request->delay = USEC / 10;
855         gettimeofday(&now, NULL);
856
857         /*
858          *      Not set up to run Post-Proxy-Type = Fail.
859          *
860          *      Mark the request as still running, and figure out what
861          *      to do next.
862          */
863         if (!setup_post_proxy_fail(request)) {
864                 request->child_state = REQUEST_RUNNING;
865                 request_post_handler(request);
866
867         } else {
868                 /*
869                  *      Re-queue the request.
870                  */
871                 request->child_state = REQUEST_QUEUED;
872
873                 /*
874                  *      There is a post-proxy-type of fail.  We run
875                  *      the request through the pre/post proxy
876                  *      handlers, just like it was a real proxied
877                  *      request.  However, we set the per-request
878                  *      handler to NULL, as we don't want to do
879                  *      anything else.
880                  *
881                  *      Note that when we're not threaded, this will
882                  *      process the request even if it's greater than
883                  *      max_request_time.  That's not fatal.
884                  */
885                 request->priority = 0;
886                 rad_assert(request->proxy != NULL);
887                 thread_pool_addrequest(request, null_handler);
888         }
889
890         /*
891          *      MAY free the request if we're over max_request_time,
892          *      AND we're not in threaded mode!
893          *
894          *      Note that we call this ONLY if we're threaded, as
895          *      if we're NOT threaded, request_post_handler() calls
896          *      wait_a_bit(), which means that "request" may not
897          *      exist any more...
898          */
899         if (have_children) wait_a_bit(request);
900 }
901
902
903 /* maybe check this against wait_for_proxy_id_to_expire? */
904 static void no_response_to_proxied_request(void *ctx)
905 {
906         REQUEST *request = ctx;
907         home_server *home;
908         char buffer[128];
909
910         rad_assert(request->magic == REQUEST_MAGIC);
911         rad_assert(request->child_state == REQUEST_PROXIED);
912
913         /*
914          *      If we've failed over to an internal home server,
915          *      replace the callback with the correct one.  This
916          *      is due to locking issues with child threads...
917          */
918         if (request->home_server->server) {
919                 wait_a_bit(request);
920                 return;
921         }
922
923         radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
924                request->number,
925                inet_ntop(request->proxy->dst_ipaddr.af,
926                          &request->proxy->dst_ipaddr.ipaddr,
927                          buffer, sizeof(buffer)),
928                request->proxy->dst_port);
929
930         check_for_zombie_home_server(request);
931
932         home = request->home_server;
933
934         post_proxy_fail_handler(request);
935
936         /*
937          *      Don't touch request due to race conditions
938          */
939         if (home->state == HOME_STATE_IS_DEAD) {
940                 rad_assert(home->ev != NULL); /* or it will never wake up */
941                 return;
942         }
943
944         /*
945          *      Enable the zombie period when we notice that the home
946          *      server hasn't responded.  We also back-date the start
947          *      of the zombie period to when the proxied request was
948          *      sent.
949          */
950         if (home->state == HOME_STATE_ALIVE) {
951                 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
952                        inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
953                                  buffer, sizeof(buffer)),
954                        home->port);
955                 home->state = HOME_STATE_ZOMBIE;
956                 home->zombie_period_start = now;
957                 home->zombie_period_start.tv_sec -= home->response_window;
958                 return;
959         }
960 }
961 #endif
962
963 static void wait_a_bit(void *ctx)
964 {
965         struct timeval when;
966         REQUEST *request = ctx;
967         fr_event_callback_t callback = NULL;
968
969         rad_assert(request->magic == REQUEST_MAGIC);
970
971         switch (request->child_state) {
972         case REQUEST_QUEUED:
973         case REQUEST_RUNNING:
974                 when = request->received;
975                 when.tv_sec += request->root->max_request_time;
976
977                 /*
978                  *      Normally called from the event loop with the
979                  *      proper event loop time.  Otherwise, called from
980                  *      post proxy fail handler, which sets "now", and
981                  *      this call won't re-set it, because we're not
982                  *      in the event loop.
983                  */
984                 fr_event_now(el, &now);
985
986                 /*
987                  *      Request still has more time.  Continue
988                  *      waiting.
989                  */
990                 if (timercmp(&now, &when, <) ||
991                     ((request->listener->type == RAD_LISTEN_DETAIL) &&
992                      (request->child_state == REQUEST_QUEUED))) {
993                         if (request->delay < (USEC / 10)) {
994                                 request->delay = USEC / 10;
995                         }
996                         request->delay += request->delay >> 1;
997
998 #ifdef WITH_DETAIL
999                         /*
1000                          *      Cap wait at some sane value for detail
1001                          *      files.
1002                          */
1003                         if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1004                             (request->delay > (request->root->max_request_time * USEC))) {
1005                                 request->delay = request->root->max_request_time * USEC;
1006                         }
1007 #endif
1008
1009                         request->when = now;
1010                         tv_add(&request->when, request->delay);
1011                         callback = wait_a_bit;
1012                         break;
1013                 }
1014
1015 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1016                 /*
1017                  *      A child thread MAY still be running on the
1018                  *      request.  Ask the thread to stop working on
1019                  *      the request.
1020                  */
1021                 if (have_children) {
1022                         /* FIXME: kill unresponsive children? */
1023
1024                         /*
1025                          *      Print this error message ONLY if
1026                          *      there's a child currently processing
1027                          *      the request.  As we don't have thread
1028                          *      locks here, there may be race
1029                          *      conditions on this check.  But it's
1030                          *      just an error message, so that's OK.
1031                          */
1032                         if (request->child_pid != NO_SUCH_CHILD_PID) {
1033                                 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
1034                                (unsigned long)request->child_pid, request->number,
1035                                        request->module ? request->module : "<server core>",
1036                                        request->component ? request->component : "<server core>");
1037                         }
1038
1039                         request->master_state = REQUEST_STOP_PROCESSING;
1040                         
1041                         request->delay = USEC / 4;
1042                         tv_add(&request->when, request->delay);
1043                         callback = wait_for_child_to_die;
1044                         break;
1045                 }
1046 #endif
1047
1048                 /*
1049                  *      Else there are no child threads.  We probably
1050                  *      should have just marked the request as 'done'
1051                  *      elsewhere, like in the post-proxy-fail
1052                  *      handler.  But doing that would involve
1053                  *      checking for max_request_time in multiple
1054                  *      places, so this may be simplest.
1055                  */
1056                 request->child_state = REQUEST_DONE;
1057                 /* FALL-THROUGH */
1058
1059                 /*
1060                  *      Mark the request as no longer running,
1061                  *      and clean it up.
1062                  */
1063         case REQUEST_DONE:
1064 #ifdef HAVE_PTHREAD_H
1065                 request->child_pid = NO_SUCH_CHILD_PID;
1066 #endif
1067                 request_stats_final(request);
1068                 cleanup_delay(request);
1069                 return;
1070
1071         case REQUEST_REJECT_DELAY:
1072         case REQUEST_CLEANUP_DELAY:
1073 #ifdef HAVE_PTHREAD_H
1074                 request->child_pid = NO_SUCH_CHILD_PID;
1075 #endif
1076                 request_stats_final(request);
1077
1078         case REQUEST_PROXIED:
1079                 rad_assert(request->next_callback != NULL);
1080                 rad_assert(request->next_callback != wait_a_bit);
1081
1082                 request->when = request->next_when;
1083                 callback = request->next_callback;
1084                 request->next_callback = NULL;
1085                 break;
1086
1087         default:
1088                 rad_panic("Internal sanity check failure");
1089                 return;
1090         }
1091
1092         /*
1093          *      Something major went wrong.  Discard the request, and
1094          *      keep running.
1095          *
1096          *      FIXME: No idea why this happens or how to fix it...
1097          *      It seems to happen *only* when requests are proxied,
1098          *      and where the home server doesn't respond.  So it looks
1099          *      like a race condition above, but it happens in debug
1100          *      mode, with no threads...
1101          */
1102         if (!callback) {
1103                 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1104                 fr_event_delete(el, &request->ev);
1105                 remove_from_proxy_hash(request);
1106                 remove_from_request_hash(request);
1107                 request_free(&request);
1108                 return;
1109         }
1110
1111         INSERT_EVENT(callback, request);
1112 }
1113
1114
1115 #ifdef WITH_PROXY
1116 static int process_proxy_reply(REQUEST *request)
1117 {
1118         int rcode;
1119         int post_proxy_type = 0;
1120         VALUE_PAIR *vp;
1121         
1122         /*
1123          *      Delete any reply we had accumulated until now.
1124          */
1125         pairfree(&request->reply->vps);
1126         
1127         /*
1128          *      Run the packet through the post-proxy stage,
1129          *      BEFORE playing games with the attributes.
1130          */
1131         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1132         if (vp) {
1133                 RDEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1134                 post_proxy_type = vp->vp_integer;
1135         }
1136         
1137         rad_assert(request->home_pool != NULL);
1138         
1139         if (request->home_pool->virtual_server) {
1140                 const char *old_server = request->server;
1141                 
1142                 request->server = request->home_pool->virtual_server;
1143                 RDEBUG2(" server %s {", request->server);
1144                 rcode = module_post_proxy(post_proxy_type, request);
1145                 RDEBUG2(" }");
1146                 request->server = old_server;
1147         } else {
1148                 rcode = module_post_proxy(post_proxy_type, request);
1149         }
1150         
1151         /*
1152          *      There may NOT be a proxy reply, as we may be
1153          *      running Post-Proxy-Type = Fail.
1154          */
1155         if (request->proxy_reply) {
1156                 /*
1157                  *      Delete the Proxy-State Attributes from
1158                  *      the reply.  These include Proxy-State
1159                  *      attributes from us and remote server.
1160                  */
1161                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1162                 
1163                 /*
1164                  *      Add the attributes left in the proxy
1165                  *      reply to the reply list.
1166                  */
1167                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1168                 request->proxy_reply->vps = NULL;
1169                 
1170                 /*
1171                  *      Free proxy request pairs.
1172                  */
1173                 pairfree(&request->proxy->vps);
1174         }
1175         
1176         switch (rcode) {
1177         default:  /* Don't do anything */
1178                 break;
1179         case RLM_MODULE_FAIL:
1180                 /* FIXME: debug print stuff */
1181                 request->child_state = REQUEST_DONE;
1182                 return 0;
1183                 
1184         case RLM_MODULE_HANDLED:
1185                 /* FIXME: debug print stuff */
1186                 request->child_state = REQUEST_DONE;
1187                 return 0;
1188         }
1189
1190         return 1;
1191 }
1192 #endif
1193
1194 static int request_pre_handler(REQUEST *request)
1195 {
1196         int rcode;
1197
1198         rad_assert(request->magic == REQUEST_MAGIC);
1199         rad_assert(request->packet != NULL);
1200
1201         request->child_state = REQUEST_RUNNING;
1202
1203         /*
1204          *      Don't decode the packet if it's an internal "fake"
1205          *      request.  Instead, just return so that the caller can
1206          *      process it.
1207          */
1208         if (request->packet->dst_port == 0) {
1209                 request->username = pairfind(request->packet->vps,
1210                                              PW_USER_NAME);
1211                 request->password = pairfind(request->packet->vps,
1212                                              PW_USER_PASSWORD);
1213                 return 1;
1214         }
1215
1216 #ifdef WITH_PROXY
1217         /*
1218          *      Put the decoded packet into it's proper place.
1219          */
1220         if (request->proxy_reply != NULL) {
1221                 rcode = request->proxy_listener->decode(request->proxy_listener,
1222                                                         request);
1223                 if (request->options) {
1224                         debug_packet(request, request->proxy_reply, 0);
1225                 }
1226         } else
1227 #endif
1228         if (request->packet->vps == NULL) {
1229                 rcode = request->listener->decode(request->listener, request);
1230                 
1231                 if (debug_condition) {
1232                         int result = FALSE;
1233                         
1234                         /*
1235                          *      Ignore parse errors.
1236                          */
1237                         radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1238                                                   &debug_condition, 1,
1239                                                   &result);
1240                         if (result) {
1241                                 request->priority = 2;
1242                                 request->radlog = radlog_request;
1243                         }
1244                 }
1245                 
1246                 if (request->options) {
1247                         debug_packet(request, request->packet, 0);
1248                 }
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 (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                 if (request->options) {
1844                         debug_packet(request, request->reply, 1);
1845                 }
1846                 request->listener->send(request->listener, request);
1847         }
1848
1849         /*
1850          *      Clean up.  These are no longer needed.
1851          */
1852         pairfree(&request->config_items);
1853
1854         pairfree(&request->packet->vps);
1855         request->username = NULL;
1856         request->password = NULL;
1857
1858         pairfree(&request->reply->vps);
1859
1860 #ifdef WITH_PROXY
1861         if (request->proxy) {
1862                 pairfree(&request->proxy->vps);
1863
1864                 if (request->proxy_reply) {
1865                         pairfree(&request->proxy_reply->vps);
1866                 }
1867
1868 #if 0
1869                 /*
1870                  *      We're not tracking responses from the home
1871                  *      server, we can therefore free this memory in
1872                  *      the child thread.
1873                  */
1874                 if (!request->in_proxy_hash) {
1875                         rad_free(&request->proxy);
1876                         rad_free(&request->proxy_reply);
1877                         request->home_server = NULL;
1878                 }
1879 #endif
1880         }
1881 #endif
1882
1883         RDEBUG2("Finished request %d.", request->number);
1884
1885         request->child_state = child_state;
1886
1887         /*
1888          *      Single threaded mode: update timers now.
1889          */
1890         if (!have_children) wait_a_bit(request);
1891 }
1892
1893
1894 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1895 {
1896 #ifdef WITH_PROXY
1897         char buffer[128];
1898 #endif
1899
1900         RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
1901         RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
1902
1903         switch (request->child_state) {
1904         case REQUEST_QUEUED:
1905         case REQUEST_RUNNING:
1906 #ifdef WITH_PROXY
1907         discard:
1908 #endif
1909                 radlog(L_ERR, "Discarding duplicate request from "
1910                        "client %s port %d - ID: %d due to unfinished request %d",
1911                        client->shortname,
1912                        request->packet->src_port,request->packet->id,
1913                        request->number);
1914                 break;
1915
1916 #ifdef WITH_PROXY
1917         case REQUEST_PROXIED:
1918                 /*
1919                  *      We're not supposed to have duplicate
1920                  *      accounting packets.  The other states handle
1921                  *      duplicates fine (discard, or send duplicate
1922                  *      reply).  But we do NOT want to retransmit an
1923                  *      accounting request here, because that would
1924                  *      involve updating the Acct-Delay-Time, and
1925                  *      therefore changing the packet Id, etc.
1926                  *
1927                  *      Instead, we just discard the packet.  We may
1928                  *      eventually respond, or the client will send a
1929                  *      new accounting packet.
1930                  */
1931                 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1932                         goto discard;
1933                 }
1934
1935                 check_for_zombie_home_server(request);
1936
1937                 /*
1938                  *      If we've just discovered that the home server is
1939                  *      dead, send the packet to another one.
1940                  */
1941                 if ((request->packet->dst_port != 0) &&
1942                     (request->home_server->state == HOME_STATE_IS_DEAD)) {
1943                         home_server *home;
1944
1945                         remove_from_proxy_hash(request);
1946
1947                         home = home_server_ldb(NULL, request->home_pool, request);
1948                         if (!home) {
1949                                 RDEBUG2("Failed to find live home server for request %d", request->number);
1950                         no_home_servers:
1951                                 /*
1952                                  *      Do post-request processing,
1953                                  *      and any insertion of necessary
1954                                  *      events.
1955                                  */
1956                                 post_proxy_fail_handler(request);
1957                                 return;
1958                         }
1959
1960                         request->proxy->code = request->packet->code;
1961                         request->proxy->dst_ipaddr = home->ipaddr;
1962                         request->proxy->dst_port = home->port;
1963                         request->home_server = home;
1964
1965                         /*
1966                          *      Free the old packet, to force re-encoding
1967                          */
1968                         free(request->proxy->data);
1969                         request->proxy->data = NULL;
1970                         request->proxy->data_len = 0;
1971
1972                         /*
1973                          *      This request failed over to a virtual
1974                          *      server.  Push it back onto the queue
1975                          *      to be processed.
1976                          */
1977                         if (request->home_server->server) {
1978                                 proxy_fallback_handler(request);
1979                                 return;
1980                         }
1981
1982                         /*
1983                          *      Try to proxy the request.
1984                          */
1985                         if (!proxy_request(request)) {
1986                                 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
1987                                 goto no_home_servers;
1988                         }
1989
1990                         /*
1991                          *      This code executes in the main server
1992                          *      thread, so there's no need for locking.
1993                          */
1994                         rad_assert(request->next_callback != NULL);
1995                         INSERT_EVENT(request->next_callback, request);
1996                         request->next_callback = NULL;
1997                         return;
1998                 } /* else the home server is still alive */
1999
2000                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2001                        inet_ntop(request->proxy->dst_ipaddr.af,
2002                                  &request->proxy->dst_ipaddr.ipaddr,
2003                                  buffer, sizeof(buffer)),
2004                        request->proxy->dst_port,
2005                        request->proxy->id);
2006                 request->num_proxied_requests++;
2007
2008                 if (request->options) {
2009                         debug_packet(request, request->proxy, 1);
2010                 }
2011
2012                 request->proxy_listener->send(request->proxy_listener,
2013                                               request);
2014                 break;
2015 #endif
2016
2017         case REQUEST_REJECT_DELAY:
2018                 RDEBUG2("Waiting to send Access-Reject "
2019                        "to client %s port %d - ID: %d",
2020                        client->shortname,
2021                        request->packet->src_port, request->packet->id);
2022                 break;
2023
2024         case REQUEST_CLEANUP_DELAY:
2025         case REQUEST_DONE:
2026                 RDEBUG2("Sending duplicate reply "
2027                        "to client %s port %d - ID: %d",
2028                        client->shortname,
2029                        request->packet->src_port, request->packet->id);
2030                 if (request->options) {
2031                         debug_packet(request, request->reply, 1);
2032                 }
2033                 request->listener->send(request->listener, request);
2034                 break;
2035         }
2036 }
2037
2038
2039 static void received_conflicting_request(REQUEST *request,
2040                                          const RADCLIENT *client)
2041 {
2042         radlog(L_ERR, "Received conflicting packet from "
2043                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
2044                client->shortname,
2045                request->packet->src_port, request->packet->id,
2046                request->number);
2047
2048         /*
2049          *      Nuke it from the request hash, so we can receive new
2050          *      packets.
2051          */
2052         remove_from_request_hash(request);
2053
2054         switch (request->child_state) {
2055 #ifdef HAVE_PTHREAD_H
2056                 /*
2057                  *      It's queued or running.  Tell it to stop, and
2058                  *      wait for it to do so.
2059                  */
2060         case REQUEST_QUEUED:
2061         case REQUEST_RUNNING:
2062                 request->master_state = REQUEST_STOP_PROCESSING;
2063                 request->delay += request->delay >> 1;
2064
2065                 tv_add(&request->when, request->delay);
2066
2067                 INSERT_EVENT(wait_for_child_to_die, request);
2068                 return;
2069 #endif
2070
2071                 /*
2072                  *      It's in some other state, and therefore also
2073                  *      in the event queue.  At some point, the
2074                  *      child will notice, and we can then delete it.
2075                  */
2076         default:
2077                 rad_assert(request->ev != NULL);
2078                 break;
2079         }
2080 }
2081
2082
2083 static int can_handle_new_request(RADIUS_PACKET *packet,
2084                                   RADCLIENT *client,
2085                                   struct main_config_t *root)
2086 {
2087         /*
2088          *      Count the total number of requests, to see if
2089          *      there are too many.  If so, return with an
2090          *      error.
2091          */
2092         if (root->max_requests) {
2093                 int request_count = fr_packet_list_num_elements(pl);
2094
2095                 /*
2096                  *      This is a new request.  Let's see if
2097                  *      it makes us go over our configured
2098                  *      bounds.
2099                  */
2100                 if (request_count > root->max_requests) {
2101                         radlog(L_ERR, "Dropping request (%d is too many): "
2102                                "from client %s port %d - ID: %d", request_count,
2103                                client->shortname,
2104                                packet->src_port, packet->id);
2105                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2106                                "\tThe value for 'max_requests' is probably set too low.\n");
2107                         return 0;
2108                 } /* else there were a small number of requests */
2109         } /* else there was no configured limit for requests */
2110
2111         /*
2112          *      FIXME: Add per-client checks.  If one client is sending
2113          *      too many packets, start discarding them.
2114          *
2115          *      We increment the counters here, and decrement them
2116          *      when the response is sent... somewhere in this file.
2117          */
2118
2119         /*
2120          *      FUTURE: Add checks for system load.  If the system is
2121          *      busy, start dropping requests...
2122          *
2123          *      We can probably keep some statistics ourselves...  if
2124          *      there are more requests coming in than we can handle,
2125          *      start dropping some.
2126          */
2127
2128         return 1;
2129 }
2130
2131
2132 int received_request(rad_listen_t *listener,
2133                      RADIUS_PACKET *packet, REQUEST **prequest,
2134                      RADCLIENT *client)
2135 {
2136         RADIUS_PACKET **packet_p;
2137         REQUEST *request = NULL;
2138         struct main_config_t *root = &mainconfig;
2139
2140         packet_p = fr_packet_list_find(pl, packet);
2141         if (packet_p) {
2142                 request = fr_packet2myptr(REQUEST, packet, packet_p);
2143                 rad_assert(request->in_request_hash);
2144
2145                 if ((request->packet->data_len == packet->data_len) &&
2146                     (memcmp(request->packet->vector, packet->vector,
2147                             sizeof(packet->vector)) == 0)) {
2148                         received_retransmit(request, client);
2149                         return 0;
2150                 }
2151
2152                 /*
2153                  *      The new request is different from the old one,
2154                  *      but maybe the old is finished.  If so, delete
2155                  *      the old one.
2156                  */
2157                 switch (request->child_state) {
2158                         struct timeval when;
2159
2160                 default:
2161                         gettimeofday(&when, NULL);
2162                         when.tv_sec -= 1;
2163
2164                         /*
2165                          *      If the cached request was received
2166                          *      within the last second, then we
2167                          *      discard the NEW request instead of the
2168                          *      old one.  This will happen ONLY when
2169                          *      the client is severely broken, and is
2170                          *      sending conflicting packets very
2171                          *      quickly.
2172                          */
2173                         if (timercmp(&when, &request->received, <)) {
2174                                 radlog(L_ERR, "Discarding conflicting packet from "
2175                                        "client %s port %d - ID: %d due to recent request %d.",
2176                                        client->shortname,
2177                                        packet->src_port, packet->id,
2178                                        request->number);
2179                                 return 0;
2180                         }
2181
2182                         received_conflicting_request(request, client);
2183                         request = NULL;
2184                         break;
2185
2186                 case REQUEST_REJECT_DELAY:
2187                 case REQUEST_CLEANUP_DELAY:
2188                         request->child_state = REQUEST_DONE;
2189                 case REQUEST_DONE:
2190                         cleanup_delay(request);
2191                         request = NULL;
2192                         break;
2193                 }
2194         }
2195
2196         /*
2197          *      We may want to quench the new request.
2198          */
2199         if ((listener->type != RAD_LISTEN_DETAIL) &&
2200             !can_handle_new_request(packet, client, root)) {
2201                 return 0;
2202         }
2203
2204         /*
2205          *      Create and initialize the new request.
2206          */
2207         request = request_alloc(); /* never fails */
2208
2209         if ((request->reply = rad_alloc(0)) == NULL) {
2210                 radlog(L_ERR, "No memory");
2211                 exit(1);
2212         }
2213
2214         request->listener = listener;
2215         request->client = client;
2216         request->packet = packet;
2217         request->packet->timestamp = request->timestamp;
2218         request->number = request_num_counter++;
2219         request->priority = listener->type;
2220
2221         /*
2222          *      Status-Server packets go to the head of the queue.
2223          */
2224         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2225
2226         /*
2227          *      Set virtual server identity
2228          */
2229         if (client->server) {
2230                 request->server = client->server;
2231         } else if (listener->server) {
2232                 request->server = listener->server;
2233         } else {
2234                 request->server = NULL;
2235         }
2236
2237         /*
2238          *      Remember the request in the list.
2239          */
2240         if (!fr_packet_list_insert(pl, &request->packet)) {
2241                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2242                 request_free(&request);
2243                 return 0;
2244         }
2245
2246         request->in_request_hash = TRUE;
2247         request->root = root;
2248         root->refcount++;
2249
2250         /*
2251          *      The request passes many of our sanity checks.
2252          *      From here on in, if anything goes wrong, we
2253          *      send a reject message, instead of dropping the
2254          *      packet.
2255          */
2256
2257         /*
2258          *      Build the reply template from the request.
2259          */
2260
2261         request->reply->sockfd = request->packet->sockfd;
2262         request->reply->dst_ipaddr = request->packet->src_ipaddr;
2263         request->reply->src_ipaddr = request->packet->dst_ipaddr;
2264         request->reply->dst_port = request->packet->src_port;
2265         request->reply->src_port = request->packet->dst_port;
2266         request->reply->id = request->packet->id;
2267         request->reply->code = 0; /* UNKNOWN code */
2268         memcpy(request->reply->vector, request->packet->vector,
2269                sizeof(request->reply->vector));
2270         request->reply->vps = NULL;
2271         request->reply->data = NULL;
2272         request->reply->data_len = 0;
2273
2274         request->master_state = REQUEST_ACTIVE;
2275         request->child_state = REQUEST_QUEUED;
2276         request->next_callback = NULL;
2277
2278         gettimeofday(&request->received, NULL);
2279         request->timestamp = request->received.tv_sec;
2280         request->when = request->received;
2281
2282         request->delay = USEC;
2283
2284         tv_add(&request->when, request->delay);
2285
2286         INSERT_EVENT(wait_a_bit, request);
2287
2288         *prequest = request;
2289         return 1;
2290 }
2291
2292
2293 #ifdef WITH_PROXY
2294 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
2295 {
2296         char            buffer[128];
2297         home_server     *home;
2298         REQUEST         *request;
2299
2300         if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
2301                 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
2302                        inet_ntop(packet->src_ipaddr.af,
2303                                  &packet->src_ipaddr.ipaddr,
2304                                  buffer, sizeof(buffer)),
2305                                packet->src_port);
2306                 rad_free(&packet);
2307                 return NULL;
2308         }
2309
2310         /*
2311          *      Also removes from the proxy hash if responses == requests
2312          */
2313         request = lookup_in_proxy_hash(packet);
2314
2315         if (!request) {
2316                 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
2317                        inet_ntop(packet->src_ipaddr.af,
2318                                  &packet->src_ipaddr.ipaddr,
2319                                  buffer, sizeof(buffer)),
2320                        packet->src_port, packet->id);
2321                 rad_free(&packet);
2322                 return NULL;
2323         }
2324
2325         home = request->home_server;
2326
2327         gettimeofday(&now, NULL);
2328
2329         home->state = HOME_STATE_ALIVE;
2330
2331         if (request->reply && request->reply->code != 0) {
2332                 RDEBUG2("We already replied to this request.  Discarding response from home server.");
2333                 rad_free(&packet);
2334                 return NULL;
2335         }
2336
2337         /*
2338          *      We had previously received a reply, so we don't need
2339          *      to do anything here.
2340          */
2341         if (request->proxy_reply) {
2342                 if (memcmp(request->proxy_reply->vector,
2343                            packet->vector,
2344                            sizeof(request->proxy_reply->vector)) == 0) {
2345                         RDEBUG2("Discarding duplicate reply from home server %s port %d  - ID: %d for request %d",
2346                                inet_ntop(packet->src_ipaddr.af,
2347                                          &packet->src_ipaddr.ipaddr,
2348                                          buffer, sizeof(buffer)),
2349                                packet->src_port, packet->id,
2350                                request->number);
2351                 } else {
2352                         /*
2353                          *      ? The home server gave us a new proxy
2354                          *      reply, which doesn't match the old
2355                          *      one.  Delete it.
2356                          */
2357                         RDEBUG2("Ignoring conflicting proxy reply");
2358                 }
2359
2360                 /* assert that there's an event queued for request? */
2361                 rad_free(&packet);
2362                 return NULL;
2363         }
2364 #ifdef WITH_STATS
2365         /*
2366          *      The average includes our time to receive packets and
2367          *      look them up in the hashes, which should be the same
2368          *      for all packets.
2369          *
2370          *      We update the response time only for the FIRST packet
2371          *      we receive.
2372          */
2373         else if (home->ema.window > 0) {
2374                 radius_stats_ema(&home->ema, &now, &request->proxy_when);
2375         }
2376 #endif
2377
2378
2379         switch (request->child_state) {
2380         case REQUEST_QUEUED:
2381         case REQUEST_RUNNING:
2382                 rad_panic("Internal sanity check failed for child state");
2383                 break;
2384
2385         case REQUEST_REJECT_DELAY:
2386         case REQUEST_CLEANUP_DELAY:
2387         case REQUEST_DONE:
2388                 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'",
2389                        inet_ntop(packet->src_ipaddr.af,
2390                                  &packet->src_ipaddr.ipaddr,
2391                                  buffer, sizeof(buffer)),
2392                        packet->src_port, packet->id,
2393                        request->number);
2394                 /* assert that there's an event queued for request? */
2395                 rad_free(&packet);
2396                 return NULL;
2397
2398         case REQUEST_PROXIED:
2399                 break;
2400         }
2401
2402         request->proxy_reply = packet;
2403
2404 #if 0
2405         /*
2406          *      Perform RTT calculations, as per RFC 2988 (for TCP).
2407          *      Note that we do so only if we sent one request, and
2408          *      received one response.  If we sent two requests, we
2409          *      have no idea if the response is for the first, or for
2410          *      the second request/
2411          */
2412         if (request->num_proxied_requests == 1) {
2413                 int rtt;
2414                 home_server *home = request->home_server;
2415
2416                 rtt = now.tv_sec - request->proxy_when.tv_sec;
2417                 rtt *= USEC;
2418                 rtt += now.tv_usec;
2419                 rtt -= request->proxy_when.tv_usec;
2420
2421                 if (!home->has_rtt) {
2422                         home->has_rtt = TRUE;
2423
2424                         home->srtt = rtt;
2425                         home->rttvar = rtt / 2;
2426
2427                 } else {
2428                         home->rttvar -= home->rttvar >> 2;
2429                         home->rttvar += (home->srtt - rtt);
2430                         home->srtt -= home->srtt >> 3;
2431                         home->srtt += rtt >> 3;
2432                 }
2433
2434                 home->rto = home->srtt;
2435                 if (home->rttvar > (USEC / 4)) {
2436                         home->rto += home->rttvar * 4;
2437                 } else {
2438                         home->rto += USEC;
2439                 }
2440         }
2441 #endif
2442
2443         /*
2444          *      There's no incoming request, so it's a proxied packet
2445          *      we originated.
2446          */
2447         if (!request->packet) {
2448                 received_response_to_ping(request);
2449                 return NULL;
2450         }
2451
2452         request->child_state = REQUEST_QUEUED;
2453         request->when = now;
2454         request->delay = USEC;
2455         request->priority = RAD_LISTEN_PROXY;
2456         tv_add(&request->when, request->delay);
2457
2458         /*
2459          *      Wait a bit will take care of max_request_time
2460          */
2461         INSERT_EVENT(wait_a_bit, request);
2462
2463         return request;
2464 }
2465 #endif
2466
2467 void event_new_fd(rad_listen_t *this)
2468 {
2469         char buffer[1024];
2470         
2471         this->print(this, buffer, sizeof(buffer));
2472         
2473         if (this->status == RAD_LISTEN_STATUS_INIT) {
2474                 if (just_started) {
2475                         DEBUG("Listening on %s", buffer);
2476                 } else {
2477                         DEBUG2(" ... adding new socket %s", buffer);
2478                 }
2479                 if (!fr_event_fd_insert(el, 0, this->fd,
2480                                         event_socket_handler, this)) {
2481                         radlog(L_ERR, "Failed remembering handle for proxy socket!");
2482                         exit(1);
2483                 }
2484                 
2485                 this->status = RAD_LISTEN_STATUS_KNOWN;
2486                 return;
2487         }
2488         
2489         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
2490                 DEBUG2(" ... closing socket %s", buffer);
2491                 
2492                 fr_event_fd_delete(el, 0, this->fd);
2493                 this->status = RAD_LISTEN_STATUS_FINISH;
2494                 
2495                 /*
2496                  *      Close the fd AFTER fixing up the requests and
2497                  *      listeners, so that they don't send/recv on the
2498                  *      wrong socket (if someone manages to open
2499                  *      another one).
2500                  */
2501                 close(this->fd);
2502                 this->fd = -1;
2503         }
2504 }
2505
2506 #ifdef WITH_DETAIL
2507 static void event_detail_timer(void *ctx)
2508 {
2509         rad_listen_t *listener = ctx;
2510         RAD_REQUEST_FUNP fun;
2511         REQUEST *request;
2512
2513         if (listener->recv(listener, &fun, &request)) {
2514                 if (!thread_pool_addrequest(request, fun)) {
2515                         request->child_state = REQUEST_DONE;
2516                 }
2517         }
2518 }
2519 #endif
2520
2521 static void handle_signal_self(int flag)
2522 {
2523         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2524                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2525                         fr_event_loop_exit(el, 1);
2526                 } else {
2527                         fr_event_loop_exit(el, 2);
2528                 }
2529
2530                 return;
2531         } /* else exit/term flags weren't set */
2532
2533         /*
2534          *      Tell the even loop to stop processing.
2535          */
2536         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2537                 time_t when;
2538                 static time_t last_hup = 0;
2539
2540                 DEBUG("Received HUP signal.");
2541
2542                 when = time(NULL);
2543                 if ((int) (when - last_hup) < 5) {
2544                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2545                         return;
2546                 }
2547                 last_hup = when;
2548
2549                 fr_event_loop_exit(el, 0x80);
2550         }
2551
2552 #ifdef WITH_DETAIL
2553         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2554                 rad_listen_t *this;
2555                 
2556                 for (this = mainconfig.listen;
2557                      this != NULL;
2558                      this = this->next) {
2559                         int delay;
2560                         struct timeval when;
2561
2562                         if (this->type != RAD_LISTEN_DETAIL) continue;
2563                         
2564                         delay = detail_delay(this);
2565                         if (!delay) continue;
2566
2567                         fr_event_now(el, &now);
2568                         when = now;
2569                         tv_add(&when, delay);
2570
2571                         if (delay > 100000) {
2572                                 DEBUG("Delaying next detail event for %d.%01u seconds.",
2573                                        delay / USEC, (delay % USEC) / 100000);
2574                         }
2575
2576                         if (!fr_event_insert(el, event_detail_timer, this,
2577                                              &when, NULL)) {
2578                                 radlog(L_ERR, "Failed remembering timer");
2579                                 exit(1);
2580                         }
2581                 }
2582         }
2583 #endif
2584
2585         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2586                 rad_listen_t *this;
2587                 
2588                 for (this = mainconfig.listen;
2589                      this != NULL;
2590                      this = this->next) {
2591                         if (this->status == RAD_LISTEN_STATUS_KNOWN) continue;
2592
2593                         event_new_fd(this);
2594                 }
2595         }
2596 }
2597
2598 #ifdef __MINGW32__
2599 void radius_signal_self(int flag)
2600 {
2601         handle_signal_self(flag);
2602 }
2603 #else
2604 /*
2605  *      Inform ourselves that we received a signal.
2606  */
2607 void radius_signal_self(int flag)
2608 {
2609         ssize_t rcode;
2610         uint8_t buffer[16];
2611
2612         /*
2613          *      The read MUST be non-blocking for this to work.
2614          */
2615         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2616         if (rcode > 0) {
2617                 ssize_t i;
2618
2619                 for (i = 0; i < rcode; i++) {
2620                         buffer[0] |= buffer[i];
2621                 }
2622         } else {
2623                 buffer[0] = 0;
2624         }
2625
2626         buffer[0] |= flag;
2627
2628         write(self_pipe[1], buffer, 1);
2629 }
2630
2631
2632 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2633                                  UNUSED int fd, UNUSED void *ctx)
2634 {
2635         ssize_t i, rcode;
2636         uint8_t buffer[32];
2637
2638         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2639         if (rcode <= 0) return;
2640
2641         /*
2642          *      Merge pending signals.
2643          */
2644         for (i = 0; i < rcode; i++) {
2645                 buffer[0] |= buffer[i];
2646         }
2647
2648         handle_signal_self(buffer[0]);
2649 }
2650 #endif
2651
2652
2653 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
2654                                  void *ctx)
2655 {
2656         rad_listen_t *listener = ctx;
2657         RAD_REQUEST_FUNP fun;
2658         REQUEST *request;
2659
2660         rad_assert(xel == el);
2661
2662         xel = xel;
2663
2664         if (listener->fd < 0) rad_panic("Socket was closed on us!");
2665         
2666         if (!listener->recv(listener, &fun, &request)) return;
2667
2668         if (!thread_pool_addrequest(request, fun)) {
2669                 request->child_state = REQUEST_DONE;
2670         }
2671 }
2672
2673
2674 /*
2675  *      This function is called periodically to see if any FD's are
2676  *      available for reading.
2677  */
2678 static void event_poll_detail(UNUSED void *ctx)
2679 {
2680         int rcode;
2681         RAD_REQUEST_FUNP fun;
2682         REQUEST *request;
2683         rad_listen_t *this;
2684         struct timeval when;
2685
2686         fr_event_now(el, &now);
2687         when = now;
2688         when.tv_sec += 1;
2689
2690         for (this = mainconfig.listen; this != NULL; this = this->next) {
2691                 if (this->type != RAD_LISTEN_DETAIL) continue;
2692
2693                 if (this->fd >= 0) continue;
2694
2695                 /*
2696                  *      Try to read something.
2697                  *
2698                  *      FIXME: This does poll AND receive.
2699                  */
2700                 rcode = this->recv(this, &fun, &request);
2701                 if (!rcode) continue;
2702                 
2703                 rad_assert(fun != NULL);
2704                 rad_assert(request != NULL);
2705                         
2706                 if (!thread_pool_addrequest(request, fun)) {
2707                         request->child_state = REQUEST_DONE;
2708                 }
2709         }
2710
2711         /*
2712          *      Reset the poll.
2713          */
2714         if (!fr_event_insert(el, event_poll_detail, NULL,
2715                              &when, NULL)) {
2716                 radlog(L_ERR, "Failed creating handler");
2717                 exit(1);
2718         }
2719 }
2720
2721
2722 static void event_status(struct timeval *wake)
2723 {
2724 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2725         int argval;
2726 #endif
2727
2728         if (debug_flag == 0) {
2729                 if (just_started) {
2730                         radlog(L_INFO, "Ready to process requests.");
2731                         just_started = FALSE;
2732                 }
2733                 return;
2734         }
2735
2736         if (!wake) {
2737                 DEBUG("Ready to process requests.");
2738
2739         } else if ((wake->tv_sec != 0) ||
2740                    (wake->tv_usec >= 100000)) {
2741                 DEBUG("Waking up in %d.%01u seconds.",
2742                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2743         }
2744
2745
2746         /*
2747          *      FIXME: Put this somewhere else, where it isn't called
2748          *      all of the time...
2749          */
2750
2751 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2752         /*
2753          *      If there are no child threads, then there may
2754          *      be child processes.  In that case, wait for
2755          *      their exit status, and throw that exit status
2756          *      away.  This helps get rid of zxombie children.
2757          */
2758         while (waitpid(-1, &argval, WNOHANG) > 0) {
2759                 /* do nothing */
2760         }
2761 #endif
2762
2763 }
2764
2765
2766 /*
2767  *      Externally-visibly functions.
2768  */
2769 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2770 {
2771         rad_listen_t *this, *head = NULL;
2772
2773         if (el) return 0;
2774
2775         time(&fr_start_time);
2776
2777         el = fr_event_list_create(event_status);
2778         if (!el) return 0;
2779
2780         pl = fr_packet_list_create(0);
2781         if (!el) return 0;
2782
2783         request_num_counter = 0;
2784
2785         /*
2786          *      Move all of the thread calls to this file?
2787          *
2788          *      It may be best for the mutexes to be in this file...
2789          */
2790         have_children = spawn_flag;
2791
2792 #ifdef WITH_PROXY
2793         if (mainconfig.proxy_requests) {
2794                 /*
2795                  *      Create the tree for managing proxied requests and
2796                  *      responses.
2797                  */
2798                 proxy_list = fr_packet_list_create(1);
2799                 if (!proxy_list) return 0;
2800
2801 #ifdef HAVE_PTHREAD_H
2802                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2803                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2804                                strerror(errno));
2805                         exit(1);
2806                 }
2807 #endif
2808         }
2809 #endif
2810
2811         /*
2812          *      Just before we spawn the child threads, force the log
2813          *      subsystem to re-open the log file for every write.
2814          */
2815         if (spawn_flag) force_log_reopen();
2816
2817 #ifdef HAVE_PTHREAD_H
2818         if (thread_pool_init(cs, spawn_flag) < 0) {
2819                 exit(1);
2820         }
2821 #endif
2822
2823         if (check_config) {
2824                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
2825                        mainconfig.name);
2826                 return 1;
2827         }
2828
2829 #ifndef __MINGW32__
2830         /*
2831          *      Child threads need a pipe to signal us, as do the
2832          *      signal handlers.
2833          */
2834         if (pipe(self_pipe) < 0) {
2835                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2836                        strerror(errno));
2837                 exit(1);
2838         }
2839         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2840                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2841                        strerror(errno));
2842                 exit(1);
2843         }
2844         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2845                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2846                        strerror(errno));
2847                 exit(1);
2848         }
2849
2850         if (!fr_event_fd_insert(el, 0, self_pipe[0],
2851                                   event_signal_handler, el)) {
2852                 radlog(L_ERR, "Failed creating handler for signals");
2853                 exit(1);
2854         }
2855 #endif
2856
2857 #ifdef WITH_PROXY
2858         /*
2859          *      Mark the proxy Fd's as unused.
2860          */
2861         {
2862                 int i;
2863
2864                 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2865         }
2866 #endif
2867
2868        DEBUG("%s: #### Opening IP addresses and Ports ####",
2869                mainconfig.name);
2870
2871         if (listen_init(cs, &head) < 0) {
2872                 _exit(1);
2873         }
2874         
2875         /*
2876          *      Add all of the sockets to the event loop.
2877          */
2878         for (this = head;
2879              this != NULL;
2880              this = this->next) {
2881                 char buffer[256];
2882
2883                 this->print(this, buffer, sizeof(buffer));
2884
2885                 switch (this->type) {
2886 #ifdef WITH_DETAIL
2887                 case RAD_LISTEN_DETAIL:
2888                         DEBUG("Listening on %s", buffer);
2889                         has_detail_listener = TRUE;
2890                         break;
2891 #endif
2892
2893 #ifdef WITH_PROXY
2894                 case RAD_LISTEN_PROXY:
2895                         rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2896                         rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2897                         
2898                         proxy_fds[this->fd & 0x1f] = this->fd;
2899                         proxy_listeners[this->fd & 0x1f] = this;
2900                         if (!fr_packet_list_socket_add(proxy_list,
2901                                                          this->fd)) {
2902                                 rad_assert(0 == 1);
2903                         }
2904                         /* FALL-THROUGH */
2905 #endif
2906
2907                 default:
2908                         break;
2909                 }
2910
2911                 /*
2912                  *      The file descriptor isn't ready.  Poll for
2913                  *      when it will become ready.  This is for the
2914                  *      detail file fd's.
2915                  */
2916                 if (this->fd < 0) {
2917                         continue;
2918                 }
2919
2920                 event_new_fd(this);
2921         }
2922
2923         if (has_detail_listener) {
2924                 struct timeval when;
2925                 
2926                 gettimeofday(&when, NULL);
2927                 when.tv_sec += 1;
2928                 
2929                 if (!fr_event_insert(el, event_poll_detail, NULL,
2930                                      &when, NULL)) {
2931                         radlog(L_ERR, "Failed creating handler");
2932                         exit(1);
2933                 }
2934         }
2935
2936         mainconfig.listen = head;
2937
2938         return 1;
2939 }
2940
2941
2942 static int request_hash_cb(UNUSED void *ctx, void *data)
2943 {
2944         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2945
2946 #ifdef WITH_PROXY
2947         rad_assert(request->in_proxy_hash == FALSE);
2948 #endif
2949
2950         fr_event_delete(el, &request->ev);
2951         remove_from_request_hash(request);
2952         request_free(&request);
2953
2954         return 0;
2955 }
2956
2957
2958 #ifdef WITH_PROXY
2959 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2960 {
2961         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2962
2963         fr_packet_list_yank(proxy_list, request->proxy);
2964         request->in_proxy_hash = FALSE;
2965
2966         if (!request->in_request_hash) {
2967                 fr_event_delete(el, &request->ev);
2968                 request_free(&request);
2969         }
2970
2971         return 0;
2972 }
2973 #endif
2974
2975 void radius_event_free(void)
2976 {
2977         /*
2978          *      FIXME: Stop all threads, or at least check that
2979          *      they're all waiting on the semaphore, and the queues
2980          *      are empty.
2981          */
2982
2983 #ifdef WITH_PROXY
2984         /*
2985          *      There are requests in the proxy hash that aren't
2986          *      referenced from anywhere else.  Remove them first.
2987          */
2988         if (proxy_list) {
2989                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2990                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2991                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2992                 fr_packet_list_free(proxy_list);
2993                 proxy_list = NULL;
2994         }
2995 #endif
2996
2997         fr_packet_list_walk(pl, NULL, request_hash_cb);
2998
2999         fr_packet_list_free(pl);
3000         pl = NULL;
3001
3002         fr_event_list_free(el);
3003 }
3004
3005 int radius_event_process(void)
3006 {
3007         if (!el) return 0;
3008
3009         return fr_event_loop(el);
3010 }
3011
3012 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
3013 {
3014         request->options = RAD_REQUEST_OPTION_DEBUG2;
3015
3016         if (request_pre_handler(request)) {
3017                 rad_assert(fun != NULL);
3018                 rad_assert(request != NULL);
3019                 
3020                 if (request->server) RDEBUG("server %s {",
3021                                              request->server); 
3022                 fun(request);
3023
3024                 if (request->server) RDEBUG("} # server %s",
3025                                              request->server);
3026
3027                 request_post_handler(request);
3028         }
3029
3030         DEBUG2("Going to the next request");
3031         return;
3032 }