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