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