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