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