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