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