0d413cca983915eb87c5192c320f31333b5785cf
[freeradius.git] / src / main / event.c
1 /*
2  * event.c      Server event handling
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/radius_snmp.h>
31
32 #include <freeradius-devel/rad_assert.h>
33
34 #include <signal.h>
35 #include <fcntl.h>
36
37 #ifdef HAVE_SYS_WAIT_H
38 #       include <sys/wait.h>
39 #endif
40
41 #define USEC (1000000)
42
43 extern pid_t radius_pid;
44 extern int dont_fork;
45 extern int check_config;
46
47 /*
48  *      Ridiculous amounts of local state.
49  */
50 static fr_event_list_t  *el = NULL;
51 static fr_packet_list_t *pl = NULL;
52 static int                      request_num_counter = 0;
53 static struct timeval           now;
54 static time_t                   start_time;
55 static int                      have_children;
56 static int                      has_detail_listener = FALSE;
57 static int                      read_from_detail = TRUE;
58 static int                      just_started = FALSE;
59
60 #ifndef __MINGW32__
61 static int self_pipe[2];
62 #endif
63
64 #ifdef HAVE_PTHREAD_H
65 static pthread_mutex_t  proxy_mutex;
66
67 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
68 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
69 #else
70 /*
71  *      This is easier than ifdef's throughout the code.
72  */
73 #define PTHREAD_MUTEX_LOCK(_x)
74 #define PTHREAD_MUTEX_UNLOCK(_x)
75 #endif
76
77 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
78
79 static fr_packet_list_t *proxy_list = NULL;
80
81 /*
82  *      We keep the proxy FD's here.  The RADIUS Id's are marked
83  *      "allocated" per Id, via a bit per proxy FD.
84  */
85 static int              proxy_fds[32];
86 static rad_listen_t     *proxy_listeners[32];
87
88 static void request_post_handler(REQUEST *request);
89 static void wait_a_bit(void *ctx);
90 static void event_poll_fd(void *ctx);
91 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         wait_a_bit(request);
795 }
796
797
798 /* maybe check this against wait_for_proxy_id_to_expire? */
799 static void no_response_to_proxied_request(void *ctx)
800 {
801         REQUEST *request = ctx;
802         home_server *home;
803         char buffer[128];
804
805         rad_assert(request->magic == REQUEST_MAGIC);
806         rad_assert(request->child_state == REQUEST_PROXIED);
807
808         radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s port %d",
809                request->number,
810                inet_ntop(request->proxy->dst_ipaddr.af,
811                          &request->proxy->dst_ipaddr.ipaddr,
812                          buffer, sizeof(buffer)),
813                request->proxy->dst_port);
814
815         check_for_zombie_home_server(request);
816
817         home = request->home_server;
818
819         post_proxy_fail_handler(request);
820
821         /*
822          *      Don't touch request due to race conditions
823          */
824         if (home->state == HOME_STATE_IS_DEAD) {
825                 rad_assert(home->ev != NULL); /* or it will never wake up */
826                 return;
827         }
828
829         /*
830          *      Enable the zombie period when we notice that the home
831          *      server hasn't responded.  We also back-date the start
832          *      of the zombie period to when the proxied request was
833          *      sent.
834          */
835         if (home->state == HOME_STATE_ALIVE) {
836                 DEBUG2("WARNING: Marking home server %s port %d as zombie (it looks like it is dead).",
837                        inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
838                                  buffer, sizeof(buffer)),
839                        home->port);
840                 home->state = HOME_STATE_ZOMBIE;
841                 home->zombie_period_start = now;
842                 home->zombie_period_start.tv_sec -= home->response_window;
843                 return;
844         }
845 }
846
847
848 static void wait_a_bit(void *ctx)
849 {
850         struct timeval when;
851         REQUEST *request = ctx;
852         fr_event_callback_t callback = NULL;
853
854         rad_assert(request->magic == REQUEST_MAGIC);
855
856         switch (request->child_state) {
857         case REQUEST_QUEUED:
858         case REQUEST_RUNNING:
859                 when = request->received;
860                 when.tv_sec += request->root->max_request_time;
861
862                 /*
863                  *      Normally called from the event loop with the
864                  *      proper event loop time.  Otherwise, called from
865                  *      post proxy fail handler, which sets "now", and
866                  *      this call won't re-set it, because we're not
867                  *      in the event loop.
868                  */
869                 fr_event_now(el, &now);
870
871                 /*
872                  *      Request still has more time.  Continue
873                  *      waiting.
874                  */
875                 if (timercmp(&now, &when, <)) {
876                         if (request->delay < (USEC / 10)) {
877                                 request->delay = USEC / 10;
878                         }
879                         request->delay += request->delay >> 1;
880                         request->when = now;
881                         tv_add(&request->when, request->delay);
882                         callback = wait_a_bit;
883                         break;
884                 }
885
886                 /*
887                  *      A child thread MAY still be running on the
888                  *      request.  Ask the thread to stop working on
889                  *      the request.
890                  */
891                 if (have_children) {
892                         /* FIXME: kill unresponsive children? */
893
894                         /*
895                          *      Print this error message ONLY if
896                          *      there's a child currently processing
897                          *      the request.  As we don't have thread
898                          *      locks here, there may be race
899                          *      conditions on this check.  But it's
900                          *      just an error message, so that's OK.
901                          */
902                         if (request->child_pid != NO_SUCH_CHILD_PID) {
903                                 radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d, in module %s component %s",
904                                (unsigned long)request->child_pid, request->number,
905                                        request->module ? request->module : "<server core>",
906                                        request->component ? request->component : "<server core>");
907                         }
908
909                         request->master_state = REQUEST_STOP_PROCESSING;
910                         
911                         request->delay = USEC / 4;
912                         tv_add(&request->when, request->delay);
913                         callback = wait_for_child_to_die;
914                         break;
915                 }
916
917                 /*
918                  *      Else there are no child threads.  We probably
919                  *      should have just marked the request as 'done'
920                  *      elsewhere, like in the post-proxy-fail
921                  *      handler.  But doing that would involve
922                  *      checking for max_request_time in multiple
923                  *      places, so this may be simplest.
924                  */
925                 request->child_state = REQUEST_DONE;
926                 /* FALL-THROUGH */
927
928                 /*
929                  *      Mark the request as no longer running,
930                  *      and clean it up.
931                  */
932         case REQUEST_DONE:
933                 request->child_pid = NO_SUCH_CHILD_PID;
934                 snmp_inc_counters(request);
935                 cleanup_delay(request);
936                 return;
937
938         case REQUEST_REJECT_DELAY:
939         case REQUEST_CLEANUP_DELAY:
940                 request->child_pid = NO_SUCH_CHILD_PID;
941                 snmp_inc_counters(request);
942
943         case REQUEST_PROXIED:
944                 rad_assert(request->next_callback != NULL);
945                 rad_assert(request->next_callback != wait_a_bit);
946
947                 request->when = request->next_when;
948                 callback = request->next_callback;
949                 request->next_callback = NULL;
950                 break;
951
952         default:
953                 rad_panic("Internal sanity check failure");
954                 return;
955         }
956
957         INSERT_EVENT(callback, request);
958 }
959
960
961 static int request_pre_handler(REQUEST *request)
962 {
963         int rcode;
964
965         rad_assert(request->magic == REQUEST_MAGIC);
966         rad_assert(request->packet != NULL);
967         rad_assert(request->packet->dst_port != 0);
968
969         request->child_state = REQUEST_RUNNING;
970
971         /*
972          *      Don't decode the packet if it's an internal "fake"
973          *      request.  Instead, just return so that the caller can
974          *      process it.
975          */
976         if (request->packet->dst_port == 0) {
977                 request->username = pairfind(request->packet->vps,
978                                              PW_USER_NAME);
979                 request->password = pairfind(request->packet->vps,
980                                              PW_USER_PASSWORD);
981                 return 1;
982         }
983
984         /*
985          *      Put the decoded packet into it's proper place.
986          */
987         if (request->proxy_reply != NULL) {
988                 rcode = request->proxy_listener->decode(request->proxy_listener,
989                                                         request);
990         } else if (request->packet->vps == NULL) {
991                 rcode = request->listener->decode(request->listener, request);
992
993         } else {
994                 rcode = 0;
995         }
996
997         if (rcode < 0) {
998                 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
999                 request->child_state = REQUEST_DONE;
1000                 return 0;
1001         }
1002
1003         if (!request->proxy) {
1004                 request->username = pairfind(request->packet->vps,
1005                                              PW_USER_NAME);
1006
1007         } else {
1008                 int post_proxy_type = 0;
1009                 VALUE_PAIR *vp;
1010
1011                 /*
1012                  *      Delete any reply we had accumulated until now.
1013                  */
1014                 pairfree(&request->reply->vps);
1015
1016                 /*
1017                  *      Run the packet through the post-proxy stage,
1018                  *      BEFORE playing games with the attributes.
1019                  */
1020                 vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1021                 if (vp) {
1022                         DEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1023                         post_proxy_type = vp->vp_integer;
1024                 }
1025
1026                 rad_assert(request->home_pool != NULL);
1027
1028                 if (request->home_pool->virtual_server) {
1029                         const char *old_server = request->server;
1030
1031                         request->server = request->home_pool->virtual_server;
1032                         DEBUG2(" server %s {", request->server);
1033                         rcode = module_post_proxy(post_proxy_type, request);
1034                         DEBUG2(" }");
1035                         request->server = old_server;
1036                 } else {
1037                         rcode = module_post_proxy(post_proxy_type, request);
1038                 }
1039
1040                 /*
1041                  *      There may NOT be a proxy reply, as we may be
1042                  *      running Post-Proxy-Type = Fail.
1043                  */
1044                 if (request->proxy_reply) {
1045                         /*
1046                          *      Delete the Proxy-State Attributes from
1047                          *      the reply.  These include Proxy-State
1048                          *      attributes from us and remote server.
1049                          */
1050                         pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1051
1052                         /*
1053                          *      Add the attributes left in the proxy
1054                          *      reply to the reply list.
1055                          */
1056                         pairadd(&request->reply->vps, request->proxy_reply->vps);
1057                         request->proxy_reply->vps = NULL;
1058
1059                         /*
1060                          *      Free proxy request pairs.
1061                          */
1062                         pairfree(&request->proxy->vps);
1063                 }
1064
1065                 switch (rcode) {
1066                 default:  /* Don't do anything */
1067                         break;
1068                 case RLM_MODULE_FAIL:
1069                         /* FIXME: debug print stuff */
1070                         request->child_state = REQUEST_DONE;
1071                         return 0;
1072
1073                 case RLM_MODULE_HANDLED:
1074                         /* FIXME: debug print stuff */
1075                         request->child_state = REQUEST_DONE;
1076                         return 0;
1077                 }
1078         }
1079
1080         return 1;
1081 }
1082
1083
1084 /*
1085  *      Do state handling when we proxy a request.
1086  */
1087 static int proxy_request(REQUEST *request)
1088 {
1089         struct timeval when;
1090         char buffer[128];
1091
1092         if (!insert_into_proxy_hash(request)) {
1093                 DEBUG("ERROR: Failed inserting request into proxy hash.");
1094                 return 0;
1095         }
1096
1097         request->proxy_listener->encode(request->proxy_listener, request);
1098
1099         when = request->received;
1100         when.tv_sec += request->root->max_request_time;
1101
1102         gettimeofday(&request->proxy_when, NULL);
1103
1104         request->next_when = request->proxy_when;
1105         request->next_when.tv_sec += request->home_server->response_window;
1106
1107         rad_assert(request->home_server->response_window > 0);
1108
1109         if (timercmp(&when, &request->next_when, <)) {
1110                 request->next_when = when;
1111         }
1112         request->next_callback = no_response_to_proxied_request;
1113
1114         DEBUG2("Proxying request %d to home server %s port %d",
1115                request->number,
1116                inet_ntop(request->proxy->dst_ipaddr.af,
1117                          &request->proxy->dst_ipaddr.ipaddr,
1118                          buffer, sizeof(buffer)),
1119                request->proxy->dst_port);
1120
1121         /*
1122          *      Note that we set proxied BEFORE sending the packet.
1123          *
1124          *      Once we send it, the request is tainted, as
1125          *      another thread may have picked it up.  Don't
1126          *      touch it!
1127          */
1128         request->num_proxied_requests = 1;
1129         request->num_proxied_responses = 0;
1130         request->child_pid = NO_SUCH_CHILD_PID;
1131         request->child_state = REQUEST_PROXIED;
1132         request->proxy_listener->send(request->proxy_listener,
1133                                       request);
1134         return 1;
1135 }
1136
1137 /*
1138  *      Return 1 if we did proxy it, or the proxy attempt failed
1139  *      completely.  Either way, the caller doesn't touch the request
1140  *      any more if we return 1.
1141  */
1142 static int successfully_proxied_request(REQUEST *request)
1143 {
1144         int rcode;
1145         int pre_proxy_type = 0;
1146         VALUE_PAIR *realmpair;
1147         VALUE_PAIR *strippedname;
1148         VALUE_PAIR *vp;
1149         char *realmname;
1150         home_server *home;
1151         REALM *realm = NULL;
1152         home_pool_t *pool;
1153
1154         /*
1155          *      If it was already proxied, do nothing.
1156          *
1157          *      FIXME: This should really be a serious error.
1158          */
1159         if (request->in_proxy_hash) {
1160                 return 0;
1161         }
1162
1163         realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
1164         if (!realmpair || (realmpair->length == 0)) {
1165                 return 0;
1166         }
1167
1168         realmname = (char *) realmpair->vp_strvalue;
1169
1170         realm = realm_find(realmname);
1171         if (!realm) {
1172                 DEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
1173                 return 0;
1174         }
1175
1176         /*
1177          *      Figure out which pool to use.
1178          */
1179         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1180                 pool = realm->auth_pool;
1181
1182         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1183                 pool = realm->acct_pool;
1184
1185         } else {
1186                 rad_panic("Internal sanity check failed");
1187         }
1188
1189         if (!pool) {
1190                 DEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
1191                        realmname);
1192                 return 0;
1193         }
1194
1195         home = home_server_ldb(realmname, pool, request);
1196         if (!home) {
1197                 DEBUG2("ERROR: Failed to find live home server for realm %s",
1198                        realmname);
1199                 return -1;
1200         }
1201         request->home_pool = pool;
1202
1203         /*
1204          *      Remember that we sent the request to a Realm.
1205          */
1206         pairadd(&request->packet->vps,
1207                 pairmake("Realm", realmname, T_OP_EQ));
1208
1209         /*
1210          *      We read the packet from a detail file, AND it came from
1211          *      the server we're about to send it to.  Don't do that.
1212          */
1213         if ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1214             (request->listener->type == RAD_LISTEN_DETAIL) &&
1215             (home->ipaddr.af == AF_INET) &&
1216             (request->packet->src_ipaddr.af == AF_INET) &&
1217             (home->ipaddr.ipaddr.ip4addr.s_addr == request->packet->src_ipaddr.ipaddr.ip4addr.s_addr)) {
1218                 DEBUG2("    rlm_realm: Packet came from realm %s, proxy cancelled", realmname);
1219                 return 0;
1220         }
1221
1222         /*
1223          *      Allocate the proxy packet, only if it wasn't already
1224          *      allocated by a module.  This check is mainly to support
1225          *      the proxying of EAP-TTLS and EAP-PEAP tunneled requests.
1226          *
1227          *      In those cases, the EAP module creates a "fake"
1228          *      request, and recursively passes it through the
1229          *      authentication stage of the server.  The module then
1230          *      checks if the request was supposed to be proxied, and
1231          *      if so, creates a proxy packet from the TUNNELED request,
1232          *      and not from the EAP request outside of the tunnel.
1233          *
1234          *      The proxy then works like normal, except that the response
1235          *      packet is "eaten" by the EAP module, and encapsulated into
1236          *      an EAP packet.
1237          */
1238         if (!request->proxy) {
1239                 if ((request->proxy = rad_alloc(TRUE)) == NULL) {
1240                         radlog(L_ERR|L_CONS, "no memory");
1241                         exit(1);
1242                 }
1243
1244                 /*
1245                  *      Copy the request, then look up name and
1246                  *      plain-text password in the copy.
1247                  *
1248                  *      Note that the User-Name attribute is the
1249                  *      *original* as sent over by the client.  The
1250                  *      Stripped-User-Name attribute is the one hacked
1251                  *      through the 'hints' file.
1252                  */
1253                 request->proxy->vps =  paircopy(request->packet->vps);
1254         }
1255
1256         /*
1257          *      Strip the name, if told to.
1258          *
1259          *      Doing it here catches the case of proxied tunneled
1260          *      requests.
1261          */
1262         if (realm->striprealm == TRUE &&
1263            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
1264                 /*
1265                  *      If there's a Stripped-User-Name attribute in
1266                  *      the request, then use THAT as the User-Name
1267                  *      for the proxied request, instead of the
1268                  *      original name.
1269                  *
1270                  *      This is done by making a copy of the
1271                  *      Stripped-User-Name attribute, turning it into
1272                  *      a User-Name attribute, deleting the
1273                  *      Stripped-User-Name and User-Name attributes
1274                  *      from the vps list, and making the new
1275                  *      User-Name the head of the vps list.
1276                  */
1277                 vp = pairfind(request->proxy->vps, PW_USER_NAME);
1278                 if (!vp) {
1279                         vp = radius_paircreate(request, NULL,
1280                                                PW_USER_NAME, PW_TYPE_STRING);
1281                         rad_assert(vp != NULL); /* handled by above function */
1282                         /* Insert at the START of the list */
1283                         vp->next = request->proxy->vps;
1284                         request->proxy->vps = vp;
1285                 }
1286                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
1287                        sizeof(vp->vp_strvalue));
1288                 vp->length = strippedname->length;
1289
1290                 /*
1291                  *      Do NOT delete Stripped-User-Name.
1292                  */
1293         }
1294
1295         /*
1296          *      If there is no PW_CHAP_CHALLENGE attribute but
1297          *      there is a PW_CHAP_PASSWORD we need to add it
1298          *      since we can't use the request authenticator
1299          *      anymore - we changed it.
1300          */
1301         if (pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
1302             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
1303                 vp = radius_paircreate(request, &request->proxy->vps,
1304                                        PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
1305                 vp->length = AUTH_VECTOR_LEN;
1306                 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
1307         }
1308
1309         /*
1310          *      The RFC's say we have to do this, but FreeRADIUS
1311          *      doesn't need it.
1312          */
1313         vp = radius_paircreate(request, &request->proxy->vps,
1314                                PW_PROXY_STATE, PW_TYPE_OCTETS);
1315         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
1316                  request->packet->id);
1317         vp->length = strlen(vp->vp_strvalue);
1318
1319         /*
1320          *      Should be done BEFORE inserting into proxy hash, as
1321          *      pre-proxy may use this information, or change it.
1322          */
1323         request->proxy->code = request->packet->code;
1324         request->proxy->dst_ipaddr = home->ipaddr;
1325         request->proxy->dst_port = home->port;
1326         request->home_server = home;
1327
1328         /*
1329          *      Call the pre-proxy routines.
1330          */
1331         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1332         if (vp) {
1333                 DEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
1334                 pre_proxy_type = vp->vp_integer;
1335         }
1336
1337         rad_assert(request->home_pool != NULL);
1338
1339         if (request->home_pool->virtual_server) {
1340                 const char *old_server = request->server;
1341                 
1342                 request->server = request->home_pool->virtual_server;
1343                 DEBUG2(" server %s {", request->server);
1344                 rcode = module_pre_proxy(pre_proxy_type, request);
1345                 DEBUG2(" }");
1346                         request->server = old_server;
1347         } else {
1348                 rcode = module_pre_proxy(pre_proxy_type, request);
1349         }
1350         switch (rcode) {
1351         case RLM_MODULE_FAIL:
1352         case RLM_MODULE_INVALID:
1353         case RLM_MODULE_NOTFOUND:
1354         case RLM_MODULE_USERLOCK:
1355         default:
1356                 /* FIXME: debug print failed stuff */
1357                 return -1;
1358
1359         case RLM_MODULE_REJECT:
1360         case RLM_MODULE_HANDLED:
1361                 return 0;
1362
1363         /*
1364          *      Only proxy the packet if the pre-proxy code succeeded.
1365          */
1366         case RLM_MODULE_NOOP:
1367         case RLM_MODULE_OK:
1368         case RLM_MODULE_UPDATED:
1369                 break;
1370         }
1371
1372         /*
1373          *      If it's a fake request, don't send the proxy
1374          *      packet.  The outer tunnel session will take
1375          *      care of doing that.
1376          */
1377         if (request->packet->dst_port == 0) {
1378                 request->home_server = NULL;
1379                 return 1;
1380         }
1381
1382         if (!proxy_request(request)) {
1383                 DEBUG("ERROR: Failed to proxy request %d", request->number);
1384                 return -1;
1385         }
1386         
1387         return 1;
1388 }
1389
1390
1391 static void request_post_handler(REQUEST *request)
1392 {
1393         int child_state = -1;
1394         struct timeval when;
1395         VALUE_PAIR *vp;
1396
1397         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
1398             (request->parent &&
1399              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
1400                 DEBUG2("Request %d was cancelled.", request->number);
1401                 request->child_pid = NO_SUCH_CHILD_PID;
1402                 request->child_state = REQUEST_DONE;
1403                 return;
1404         }
1405
1406         if (request->child_state != REQUEST_RUNNING) {
1407                 rad_panic("Internal sanity check failed");
1408         }
1409
1410         if ((request->reply->code == 0) &&
1411             ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
1412             (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
1413                 request->reply->code = PW_AUTHENTICATION_REJECT;
1414         }
1415
1416         if (request->root->proxy_requests &&
1417             !request->in_proxy_hash &&
1418             (request->reply->code == 0) &&
1419             (request->packet->dst_port != 0) &&
1420             (request->packet->code != PW_STATUS_SERVER)) {
1421                 int rcode = successfully_proxied_request(request);
1422
1423                 if (rcode == 1) return;
1424
1425                 /*
1426                  *      Failed proxying it (dead home servers, etc.)
1427                  *      Run it through Post-Proxy-Type = Fail, and
1428                  *      respond to the request.
1429                  *
1430                  *      Note that we're in a child thread here, so we
1431                  *      do NOT re-schedule the request.  Instead, we
1432                  *      do what we would have done, which is run the
1433                  *      pre-handler, a NULL request handler, and then
1434                  *      the post handler.
1435                  */
1436                 if ((rcode < 0) && setup_post_proxy_fail(request)) {
1437                         request_pre_handler(request);
1438                 }
1439
1440                 /*
1441                  *      Else we weren't supposed to proxy it.
1442                  */
1443         }
1444
1445         /*
1446          *      Fake requests don't get encoded or signed.  The caller
1447          *      also requires the reply VP's, so we don't free them
1448          *      here!
1449          */
1450         if (request->packet->dst_port == 0) {
1451                 /* FIXME: DEBUG going to the next request */
1452                 request->child_pid = NO_SUCH_CHILD_PID;
1453                 request->child_state = REQUEST_DONE;
1454                 return;
1455         }
1456
1457         /*
1458          *      Copy Proxy-State from the request to the reply.
1459          */
1460         vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1461         if (vp) pairadd(&request->reply->vps, vp);
1462
1463         /*
1464          *      Access-Requests get delayed or cached.
1465          */
1466         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1467                 gettimeofday(&request->next_when, NULL);
1468
1469                 if (request->reply->code == 0) {
1470                         /*
1471                          *      Check if the lack of response is intentional.
1472                          */
1473                         vp = pairfind(request->config_items,
1474                                       PW_RESPONSE_PACKET_TYPE);
1475                         if (!vp || (vp->vp_integer != 256)) {
1476                                 DEBUG2("There was no response configured: rejecting request %d",
1477                                        request->number);
1478                                 request->reply->code = PW_AUTHENTICATION_REJECT;
1479                         } else {
1480                                 DEBUG2("Not responding to request %d",
1481                                        request->number);
1482                         }
1483                 }
1484
1485                 /*
1486                  *      Run rejected packets through
1487                  *
1488                  *      Post-Auth-Type = Reject
1489                  */
1490                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1491                         pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
1492                         vp = radius_pairmake(request, &request->config_items,
1493                                              "Post-Auth-Type", "Reject",
1494                                              T_OP_SET);
1495                         if (vp) rad_postauth(request);
1496
1497                         /*
1498                          *      If configured, delay Access-Reject packets.
1499                          *
1500                          *      If request->root->reject_delay = 0, we discover
1501                          *      that we have to send the packet now.
1502                          */
1503                         when = request->received;
1504                         when.tv_sec += request->root->reject_delay;
1505
1506                         if (timercmp(&when, &request->next_when, >)) {
1507                                 DEBUG2("Delaying reject of request %d for %d seconds",
1508                                        request->number,
1509                                        request->root->reject_delay);
1510                                 request->next_when = when;
1511                                 request->next_callback = reject_delay;
1512                                 request->child_pid = NO_SUCH_CHILD_PID;
1513                                 request->child_state = REQUEST_REJECT_DELAY;
1514                                 return;
1515                         }
1516                 }
1517
1518                 request->next_when.tv_sec += request->root->cleanup_delay;
1519                 request->next_callback = cleanup_delay;
1520                 child_state = REQUEST_CLEANUP_DELAY;
1521
1522         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1523                 request->next_callback = NULL; /* just to be safe */
1524                 child_state = REQUEST_DONE;
1525
1526                 /*
1527                  *      FIXME: Status-Server should probably not be
1528                  *      handled here...
1529                  */
1530         } else if (request->packet->code == PW_STATUS_SERVER) {
1531                 request->next_callback = NULL;
1532                 child_state = REQUEST_DONE;
1533
1534         } else {
1535                 rad_panic("Unknown packet type");
1536         }
1537
1538         /*
1539          *      Suppress "no reply" packets here, unless we're reading
1540          *      from the "detail" file.  In that case, we've got to
1541          *      tell the detail file handler that the request is dead,
1542          *      and it should re-send it.
1543          *      If configured, encode, sign, and send.
1544          */
1545         if ((request->reply->code != 0) ||
1546             (request->listener->type == RAD_LISTEN_DETAIL)) {
1547                 request->listener->send(request->listener, request);
1548         }
1549
1550         /*
1551          *      Clean up.  These are no longer needed.
1552          */
1553         pairfree(&request->config_items);
1554
1555         pairfree(&request->packet->vps);
1556         request->username = NULL;
1557         request->password = NULL;
1558
1559         pairfree(&request->reply->vps);
1560
1561         if (request->proxy) {
1562                 pairfree(&request->proxy->vps);
1563
1564                 if (request->proxy_reply) {
1565                         pairfree(&request->proxy_reply->vps);
1566                 }
1567
1568                 /*
1569                  *      We're not tracking responses from the home
1570                  *      server, we can therefore free this memory in
1571                  *      the child thread.
1572                  */
1573                 if (!request->in_proxy_hash) {
1574                         rad_free(&request->proxy);
1575                         rad_free(&request->proxy_reply);
1576                         request->home_server = NULL;
1577                 }
1578         }
1579
1580         DEBUG2("Finished request %d.", request->number);
1581
1582         request->child_state = child_state;
1583 }
1584
1585
1586 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
1587 {
1588         char buffer[128];
1589
1590         RAD_SNMP_TYPE_INC(request->listener, total_dup_requests);
1591         RAD_SNMP_CLIENT_INC(request->listener, client, dup_requests);
1592
1593         switch (request->child_state) {
1594         case REQUEST_QUEUED:
1595         case REQUEST_RUNNING:
1596         discard:
1597                 radlog(L_ERR, "Discarding duplicate request from "
1598                        "client %s port %d - ID: %d due to unfinished request %d",
1599                        client->shortname,
1600                        request->packet->src_port,request->packet->id,
1601                        request->number);
1602                 break;
1603
1604         case REQUEST_PROXIED:
1605                 /*
1606                  *      We're not supposed to have duplicate
1607                  *      accounting packets.  The other states handle
1608                  *      duplicates fine (discard, or send duplicate
1609                  *      reply).  But we do NOT want to retransmit an
1610                  *      accounting request here, because that would
1611                  *      involve updating the Acct-Delay-Time, and
1612                  *      therefore changing the packet Id, etc.
1613                  *
1614                  *      Instead, we just discard the packet.  We may
1615                  *      eventually respond, or the client will send a
1616                  *      new accounting packet.
1617                  */
1618                 if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1619                         goto discard;
1620                 }
1621
1622                 check_for_zombie_home_server(request);
1623
1624                 /*
1625                  *      If we've just discovered that the home server is
1626                  *      dead, send the packet to another one.
1627                  */
1628                 if ((request->packet->dst_port != 0) &&
1629                     (request->home_server->state == HOME_STATE_IS_DEAD)) {
1630                         home_server *home;
1631
1632                         remove_from_proxy_hash(request);
1633
1634                         home = home_server_ldb(NULL, request->home_pool, request);
1635                         if (!home) {
1636                                 DEBUG2("Failed to find live home server for request %d", request->number);
1637                         no_home_servers:
1638                                 /*
1639                                  *      Do post-request processing,
1640                                  *      and any insertion of necessary
1641                                  *      events.
1642                                  */
1643                                 post_proxy_fail_handler(request);
1644                                 return;
1645                         }
1646
1647                         request->proxy->code = request->packet->code;
1648                         request->proxy->dst_ipaddr = home->ipaddr;
1649                         request->proxy->dst_port = home->port;
1650                         request->home_server = home;
1651
1652                         /*
1653                          *      Free the old packet, to force re-encoding
1654                          */
1655                         free(request->proxy->data);
1656                         request->proxy->data = NULL;
1657                         request->proxy->data_len = 0;
1658
1659                         /*
1660                          *      Try to proxy the request.
1661                          */
1662                         if (!proxy_request(request)) {
1663                                 DEBUG("ERROR: Failed to re-proxy request %d", request->number);
1664                                 goto no_home_servers;
1665                         }
1666
1667                         /*
1668                          *      This code executes in the main server
1669                          *      thread, so there's no need for locking.
1670                          */
1671                         rad_assert(request->next_callback != NULL);
1672                         INSERT_EVENT(request->next_callback, request);
1673                         request->next_callback = NULL;
1674                         return;
1675                 } /* else the home server is still alive */
1676
1677                 DEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
1678                        inet_ntop(request->proxy->dst_ipaddr.af,
1679                                  &request->proxy->dst_ipaddr.ipaddr,
1680                                  buffer, sizeof(buffer)),
1681                        request->proxy->dst_port,
1682                        request->proxy->id);
1683                 request->num_proxied_requests++;
1684                 request->proxy_listener->send(request->proxy_listener,
1685                                               request);
1686                 break;
1687
1688         case REQUEST_REJECT_DELAY:
1689                 DEBUG2("Waiting to send Access-Reject "
1690                        "to client %s port %d - ID: %d",
1691                        client->shortname,
1692                        request->packet->src_port, request->packet->id);
1693                 break;
1694
1695         case REQUEST_CLEANUP_DELAY:
1696         case REQUEST_DONE:
1697                 DEBUG2("Sending duplicate reply "
1698                        "to client %s port %d - ID: %d",
1699                        client->shortname,
1700                        request->packet->src_port, request->packet->id);
1701                 request->listener->send(request->listener, request);
1702                 break;
1703         }
1704 }
1705
1706
1707 static void received_conflicting_request(REQUEST *request,
1708                                          const RADCLIENT *client)
1709 {
1710         radlog(L_ERR, "Received conflicting packet from "
1711                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
1712                client->shortname,
1713                request->packet->src_port, request->packet->id,
1714                request->number);
1715
1716         /*
1717          *      Nuke it from the request hash, so we can receive new
1718          *      packets.
1719          */
1720         remove_from_request_hash(request);
1721
1722         switch (request->child_state) {
1723                 /*
1724                  *      It's queued or running.  Tell it to stop, and
1725                  *      wait for it to do so.
1726                  */
1727         case REQUEST_QUEUED:
1728         case REQUEST_RUNNING:
1729                 request->master_state = REQUEST_STOP_PROCESSING;
1730                 request->delay += request->delay >> 1;
1731
1732                 tv_add(&request->when, request->delay);
1733
1734                 INSERT_EVENT(wait_for_child_to_die, request);
1735                 return;
1736
1737                 /*
1738                  *      It's in some other state, and therefore also
1739                  *      in the event queue.  At some point, the
1740                  *      child will notice, and we can then delete it.
1741                  */
1742         default:
1743                 rad_assert(request->ev != NULL);
1744                 break;
1745         }
1746 }
1747
1748
1749 static int can_handle_new_request(RADIUS_PACKET *packet,
1750                                   RADCLIENT *client,
1751                                   struct main_config_t *root)
1752 {
1753         /*
1754          *      Count the total number of requests, to see if
1755          *      there are too many.  If so, return with an
1756          *      error.
1757          */
1758         if (root->max_requests) {
1759                 int request_count = fr_packet_list_num_elements(pl);
1760
1761                 /*
1762                  *      This is a new request.  Let's see if
1763                  *      it makes us go over our configured
1764                  *      bounds.
1765                  */
1766                 if (request_count > root->max_requests) {
1767                         radlog(L_ERR, "Dropping request (%d is too many): "
1768                                "from client %s port %d - ID: %d", request_count,
1769                                client->shortname,
1770                                packet->src_port, packet->id);
1771                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
1772                                "\tThe value for 'max_requests' is probably set too low.\n");
1773                         return 0;
1774                 } /* else there were a small number of requests */
1775         } /* else there was no configured limit for requests */
1776
1777         /*
1778          *      FIXME: Add per-client checks.  If one client is sending
1779          *      too many packets, start discarding them.
1780          *
1781          *      We increment the counters here, and decrement them
1782          *      when the response is sent... somewhere in this file.
1783          */
1784
1785         /*
1786          *      FUTURE: Add checks for system load.  If the system is
1787          *      busy, start dropping requests...
1788          *
1789          *      We can probably keep some statistics ourselves...  if
1790          *      there are more requests coming in than we can handle,
1791          *      start dropping some.
1792          */
1793
1794         return 1;
1795 }
1796
1797
1798 int received_request(rad_listen_t *listener,
1799                      RADIUS_PACKET *packet, REQUEST **prequest,
1800                      RADCLIENT *client)
1801 {
1802         RADIUS_PACKET **packet_p;
1803         REQUEST *request = NULL;
1804         struct main_config_t *root = &mainconfig;
1805
1806         packet_p = fr_packet_list_find(pl, packet);
1807         if (packet_p) {
1808                 request = fr_packet2myptr(REQUEST, packet, packet_p);
1809                 rad_assert(request->in_request_hash);
1810
1811                 if ((request->packet->data_len == packet->data_len) &&
1812                     (memcmp(request->packet->vector, packet->vector,
1813                             sizeof(packet->vector)) == 0)) {
1814                         received_retransmit(request, client);
1815                         return 0;
1816                 }
1817
1818                 /*
1819                  *      The new request is different from the old one,
1820                  *      but maybe the old is finished.  If so, delete
1821                  *      the old one.
1822                  */
1823                 switch (request->child_state) {
1824                         struct timeval when;
1825
1826                 default:
1827                         gettimeofday(&when, NULL);
1828                         when.tv_sec -= 1;
1829
1830                         /*
1831                          *      If the cached request was received
1832                          *      within the last second, then we
1833                          *      discard the NEW request instead of the
1834                          *      old one.  This will happen ONLY when
1835                          *      the client is severely broken, and is
1836                          *      sending conflicting packets very
1837                          *      quickly.
1838                          */
1839                         if (timercmp(&when, &request->received, <)) {
1840                                 radlog(L_ERR, "Discarding conflicting packet from "
1841                                        "client %s port %d - ID: %d due to recent request %d.",
1842                                        client->shortname,
1843                                        packet->src_port, packet->id,
1844                                        request->number);
1845                                 return 0;
1846                         }
1847
1848                         received_conflicting_request(request, client);
1849                         request = NULL;
1850                         break;
1851
1852                 case REQUEST_REJECT_DELAY:
1853                 case REQUEST_CLEANUP_DELAY:
1854                         request->child_state = REQUEST_DONE;
1855                 case REQUEST_DONE:
1856                         cleanup_delay(request);
1857                         request = NULL;
1858                         break;
1859                 }
1860         }
1861
1862         /*
1863          *      We may want to quench the new request.
1864          */
1865         if (!can_handle_new_request(packet, client, root)) {
1866                 return 0;
1867         }
1868
1869         /*
1870          *      Create and initialize the new request.
1871          */
1872         request = request_alloc(); /* never fails */
1873
1874         if ((request->reply = rad_alloc(0)) == NULL) {
1875                 radlog(L_ERR, "No memory");
1876                 exit(1);
1877         }
1878
1879         request->listener = listener;
1880         request->client = client;
1881         request->packet = packet;
1882         request->packet->timestamp = request->timestamp;
1883         request->number = request_num_counter++;
1884         request->priority = listener->type;
1885
1886         /*
1887          *      Set virtual server identity
1888          */
1889         if (client->server) {
1890                 request->server = client->server;
1891         } else if (listener->server) {
1892                 request->server = listener->server;
1893         } else {
1894                 request->server = NULL;
1895         }
1896
1897         /*
1898          *      Remember the request in the list.
1899          */
1900         if (!fr_packet_list_insert(pl, &request->packet)) {
1901                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
1902                 request_free(&request);
1903                 return 0;
1904         }
1905
1906         request->in_request_hash = TRUE;
1907         request->root = root;
1908         root->refcount++;
1909
1910         /*
1911          *      The request passes many of our sanity checks.
1912          *      From here on in, if anything goes wrong, we
1913          *      send a reject message, instead of dropping the
1914          *      packet.
1915          */
1916
1917         /*
1918          *      Build the reply template from the request.
1919          */
1920
1921         request->reply->sockfd = request->packet->sockfd;
1922         request->reply->dst_ipaddr = request->packet->src_ipaddr;
1923         request->reply->src_ipaddr = request->packet->dst_ipaddr;
1924         request->reply->dst_port = request->packet->src_port;
1925         request->reply->src_port = request->packet->dst_port;
1926         request->reply->id = request->packet->id;
1927         request->reply->code = 0; /* UNKNOWN code */
1928         memcpy(request->reply->vector, request->packet->vector,
1929                sizeof(request->reply->vector));
1930         request->reply->vps = NULL;
1931         request->reply->data = NULL;
1932         request->reply->data_len = 0;
1933
1934         request->master_state = REQUEST_ACTIVE;
1935         request->child_state = REQUEST_QUEUED;
1936         request->next_callback = NULL;
1937
1938         gettimeofday(&request->received, NULL);
1939         request->timestamp = request->received.tv_sec;
1940         request->when = request->received;
1941
1942         request->delay = USEC;
1943
1944         tv_add(&request->when, request->delay);
1945
1946         INSERT_EVENT(wait_a_bit, request);
1947
1948         *prequest = request;
1949         return 1;
1950 }
1951
1952
1953 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
1954 {
1955         char            buffer[128];
1956         home_server     *home;
1957         REQUEST         *request;
1958
1959         if (!home_server_find(&packet->src_ipaddr, packet->src_port)) {
1960                 radlog(L_ERR, "Ignoring request from unknown home server %s port %d",
1961                        inet_ntop(packet->src_ipaddr.af,
1962                                  &packet->src_ipaddr.ipaddr,
1963                                  buffer, sizeof(buffer)),
1964                                packet->src_port);
1965                 rad_free(&packet);
1966                 return NULL;
1967         }
1968
1969         /*
1970          *      Also removes from the proxy hash if responses == requests
1971          */
1972         request = lookup_in_proxy_hash(packet);
1973
1974         if (!request) {
1975                 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s port %d - ID %d",
1976                        inet_ntop(packet->src_ipaddr.af,
1977                                  &packet->src_ipaddr.ipaddr,
1978                                  buffer, sizeof(buffer)),
1979                        packet->src_port, packet->id);
1980                 rad_free(&packet);
1981                 return NULL;
1982         }
1983
1984         home = request->home_server;
1985
1986         gettimeofday(&now, NULL);
1987         home->state = HOME_STATE_ALIVE;
1988
1989         if (request->reply && request->reply->code != 0) {
1990                 DEBUG2("We already replied to this request.  Discarding response from home server.");
1991                 rad_free(&packet);
1992                 return NULL;
1993         }
1994
1995         /*
1996          *      We had previously received a reply, so we don't need
1997          *      to do anything here.
1998          */
1999         if (request->proxy_reply) {
2000                 if (memcmp(request->proxy_reply->vector,
2001                            packet->vector,
2002                            sizeof(request->proxy_reply->vector)) == 0) {
2003                         DEBUG2("Discarding duplicate reply from home server %s port %d  - ID: %d for request %d",
2004                                inet_ntop(packet->src_ipaddr.af,
2005                                          &packet->src_ipaddr.ipaddr,
2006                                          buffer, sizeof(buffer)),
2007                                packet->src_port, packet->id,
2008                                request->number);
2009                 } else {
2010                         /*
2011                          *      ? The home server gave us a new proxy
2012                          *      reply, which doesn't match the old
2013                          *      one.  Delete it.
2014                          */
2015                         DEBUG2("Ignoring conflicting proxy reply");
2016                 }
2017
2018                 /* assert that there's an event queued for request? */
2019                 rad_free(&packet);
2020                 return NULL;
2021         }
2022
2023         switch (request->child_state) {
2024         case REQUEST_QUEUED:
2025         case REQUEST_RUNNING:
2026                 rad_panic("Internal sanity check failed for child state");
2027                 break;
2028
2029         case REQUEST_REJECT_DELAY:
2030         case REQUEST_CLEANUP_DELAY:
2031         case REQUEST_DONE:
2032                 radlog(L_ERR, "Reply from home server %s port %d  - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
2033                        inet_ntop(packet->src_ipaddr.af,
2034                                  &packet->src_ipaddr.ipaddr,
2035                                  buffer, sizeof(buffer)),
2036                        packet->src_port, packet->id,
2037                        request->number);
2038                 /* assert that there's an event queued for request? */
2039                 rad_free(&packet);
2040                 return NULL;
2041
2042         case REQUEST_PROXIED:
2043                 break;
2044         }
2045
2046         request->proxy_reply = packet;
2047
2048 #if 0
2049         /*
2050          *      Perform RTT calculations, as per RFC 2988 (for TCP).
2051          *      Note that we do so only if we sent one request, and
2052          *      received one response.  If we sent two requests, we
2053          *      have no idea if the response is for the first, or for
2054          *      the second request/
2055          */
2056         if (request->num_proxied_requests == 1) {
2057                 int rtt;
2058                 home_server *home = request->home_server;
2059
2060                 rtt = now.tv_sec - request->proxy_when.tv_sec;
2061                 rtt *= USEC;
2062                 rtt += now.tv_usec;
2063                 rtt -= request->proxy_when.tv_usec;
2064
2065                 if (!home->has_rtt) {
2066                         home->has_rtt = TRUE;
2067
2068                         home->srtt = rtt;
2069                         home->rttvar = rtt / 2;
2070
2071                 } else {
2072                         home->rttvar -= home->rttvar >> 2;
2073                         home->rttvar += (home->srtt - rtt);
2074                         home->srtt -= home->srtt >> 3;
2075                         home->srtt += rtt >> 3;
2076                 }
2077
2078                 home->rto = home->srtt;
2079                 if (home->rttvar > (USEC / 4)) {
2080                         home->rto += home->rttvar * 4;
2081                 } else {
2082                         home->rto += USEC;
2083                 }
2084         }
2085 #endif
2086
2087         /*
2088          *      There's no incoming request, so it's a proxied packet
2089          *      we originated.
2090          */
2091         if (!request->packet) {
2092                 received_response_to_ping(request);
2093                 return NULL;
2094         }
2095
2096         request->child_state = REQUEST_QUEUED;
2097         request->when = now;
2098         request->delay = USEC;
2099         request->priority = RAD_LISTEN_PROXY;
2100         tv_add(&request->when, request->delay);
2101
2102         /*
2103          *      Wait a bit will take care of max_request_time
2104          */
2105         INSERT_EVENT(wait_a_bit, request);
2106
2107         return request;
2108 }
2109
2110
2111 static void handle_signal_self(int flag)
2112 {
2113         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
2114                 read_from_detail = TRUE;
2115         }
2116
2117         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
2118                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
2119                         fr_event_loop_exit(el, 1);
2120                 } else {
2121                         fr_event_loop_exit(el, 2);
2122                 }
2123
2124                 return;
2125         } /* else exit/term flags weren't set */
2126
2127         /*
2128          *      Tell the even loop to stop processing.
2129          */
2130         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
2131                 time_t when;
2132                 static time_t last_hup = 0;
2133
2134                 DEBUG("Received HUP signal.");
2135
2136                 when = time(NULL);
2137                 if ((int) (when - last_hup) < 5) {
2138                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
2139                         return;
2140                 }
2141                 last_hup = when;
2142
2143                 fr_event_loop_exit(el, 0x80);
2144         }
2145
2146         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
2147                 rad_listen_t *this;
2148                 
2149                 for (this = mainconfig.listen;
2150                      this != NULL;
2151                      this = this->next) {
2152                         if (this->type != RAD_LISTEN_PROXY) continue;
2153                         
2154                         if (!fr_event_fd_insert(el, 0, this->fd,
2155                                                 event_socket_handler, this)) {
2156                                 radlog(L_ERR, "Failed remembering handle for proxy socket!");
2157                                 _exit(1);
2158                         }
2159                 }
2160         }
2161 }
2162
2163 #ifdef __MINGW32__
2164 void radius_signal_self(int flag)
2165 {
2166         handle_signal_self(flag);
2167 }
2168 #else
2169 /*
2170  *      Inform ourselves that we received a signal.
2171  */
2172 void radius_signal_self(int flag)
2173 {
2174         ssize_t rcode;
2175         uint8_t buffer[16];
2176
2177         /*
2178          *      The caller is telling us it's OK to read from the
2179          *      detail files.  However, we're not even listening on
2180          *      the detail files.  Therefore, suppress the flag to
2181          *      avoid bothering the main worker thread.
2182          */
2183         if ((flag == RADIUS_SIGNAL_SELF_DETAIL) &&
2184             !has_detail_listener) {
2185                 return;
2186         }
2187
2188         /*
2189          *      The read MUST be non-blocking for this to work.
2190          */
2191         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2192         if (rcode > 0) {
2193                 ssize_t i;
2194
2195                 for (i = 1; i < rcode; i++) {
2196                         buffer[0] |= buffer[i];
2197                 }
2198         } else {
2199                 buffer[0] = 0;
2200         }
2201
2202         buffer[0] |= flag;
2203
2204         write(self_pipe[1], buffer, 1);
2205 }
2206
2207
2208 static void event_signal_handler(UNUSED fr_event_list_t *xel,
2209                                  UNUSED int fd, UNUSED void *ctx)
2210 {
2211         ssize_t i, rcode;
2212         char buffer[32];
2213
2214         rcode = read(self_pipe[0], buffer, sizeof(buffer));
2215         if (rcode <= 0) return;
2216
2217         /*
2218          *      Merge pending signals.
2219          */
2220         for (i = 1; i < rcode; i++) {
2221                 buffer[0] |= buffer[i];
2222         }
2223
2224         handle_signal_self(buffer[0]);
2225 }
2226 #endif
2227
2228 /*
2229  *      The given FD is closed.  Delete it from the list of FD's to poll,
2230  *      and set a timer to periodically look for an FD again.
2231  */
2232 static void event_reset_fd(rad_listen_t *listener, int fd, int usec)
2233 {
2234         struct timeval when;
2235         gettimeofday(&when, NULL);
2236
2237         tv_add(&when, usec);    
2238
2239         if ((fd >= 0) && !fr_event_fd_delete(el, 0, fd)) {
2240                 rad_panic("Failed deleting fd");
2241         }
2242         
2243         if (!fr_event_insert(el, event_poll_fd, listener,
2244                                &when, NULL)) {
2245                 rad_panic("Failed inserting event");
2246         }
2247 }
2248
2249
2250 /*
2251  *      Reads from the detail file if possible, OR sets up a timeout
2252  *      to see if the detail file is ready for reading.
2253  *
2254  *      FIXME: On Linux, use inotify to watch the detail file.  This
2255  *      
2256  */
2257 static void event_detail_handler(fr_event_list_t *xel, int fd, void *ctx)
2258 {
2259         rad_listen_t *listener = ctx;
2260         RAD_REQUEST_FUNP fun;
2261         REQUEST *request;
2262
2263         rad_assert(xel == el);
2264         rad_assert(fd == listener->fd);
2265
2266         xel = xel;
2267
2268         /*
2269          *      We're too busy to read from the detail file.  Stop
2270          *      watching the file, and instead go back to polling.
2271          */
2272         if (!read_from_detail) {
2273                 event_reset_fd(listener, fd, USEC);
2274                 return;
2275         }
2276         
2277         /*
2278          *      FIXME: Put this somewhere else, where it isn't called
2279          *      all of the time...
2280          */
2281 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2282         /*
2283          *      If there are no child threads, then there may
2284          *      be child processes.  In that case, wait for
2285          *      their exit status, and throw that exit status
2286          *      away.  This helps get rid of zxombie children.
2287          */
2288         while (waitpid(-1, &argval, WNOHANG) > 0) {
2289                 /* do nothing */
2290         }
2291 #endif
2292
2293         /*
2294          *      Didn't read anything from the detail file.
2295          *      Wake up in one second to check it again.
2296          */
2297         if (!listener->recv(listener, &fun, &request)) {
2298                 event_reset_fd(listener, fd, USEC);
2299                 return;
2300         }
2301
2302         /*
2303          *      Drop the request into the thread pool,
2304          *      and let the thread pool take care of
2305          *      doing something with it.
2306          */
2307         if (!thread_pool_addrequest(request, fun)) {
2308                 request->child_state = REQUEST_DONE;
2309         }
2310
2311         /*
2312          *      Reset based on the fd we were given, as detail_recv()
2313          *      may have read all of the file, and closed it.  It then
2314          *      sets listener->fd = -1.
2315          */
2316         event_reset_fd(listener, fd, *(int *) listener->data);
2317 }
2318
2319
2320 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
2321 {
2322         rad_listen_t *listener = ctx;
2323         RAD_REQUEST_FUNP fun;
2324         REQUEST *request;
2325
2326         rad_assert(xel == el);
2327
2328         xel = xel;
2329
2330         if (listener->fd < 0) rad_panic("Socket was closed on us!");
2331         
2332         /*
2333          *      FIXME: Put this somewhere else, where it isn't called
2334          *      all of the time...
2335          */
2336 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
2337         /*
2338          *      If there are no child threads, then there may
2339          *      be child processes.  In that case, wait for
2340          *      their exit status, and throw that exit status
2341          *      away.  This helps get rid of zxombie children.
2342          */
2343         while (waitpid(-1, &argval, WNOHANG) > 0) {
2344                 /* do nothing */
2345         }
2346 #endif
2347
2348         if (!listener->recv(listener, &fun, &request)) return;
2349
2350         if (!thread_pool_addrequest(request, fun)) {
2351                 request->child_state = REQUEST_DONE;
2352         }
2353
2354         /*
2355          *      If we've read a packet from a socket OTHER than the
2356          *      detail file, we start ignoring the detail file.
2357          *
2358          *      When the child thread pulls the request off of the
2359          *      queues, it will check if the queues are empty.  Once
2360          *      all queues are empty, it will signal us to read the
2361          *      detail file again.
2362          */
2363         read_from_detail = FALSE;
2364 }
2365
2366
2367 /*
2368  *      This function is called periodically to see if a file
2369  *      descriptor is available for reading.
2370  */
2371 static void event_poll_fd(void *ctx)
2372 {
2373         int rcode;
2374         RAD_REQUEST_FUNP fun;
2375         REQUEST *request;
2376         rad_listen_t *listener = ctx;
2377         fr_event_fd_handler_t handler;
2378
2379         /*
2380          *      Ignore the detail file if we're busy with other work.
2381          */
2382         if ((listener->type == RAD_LISTEN_DETAIL) && !read_from_detail) {
2383                 event_reset_fd(listener, listener->fd, USEC);
2384                 return;
2385         }
2386
2387         /*
2388          *      Try to read a RADIUS packet.  This also opens the FD.
2389          *
2390          *      FIXME: This does poll AND receive.
2391          */
2392         rcode = listener->recv(listener, &fun, &request);
2393
2394         /*
2395          *      We read a request.  Add it to the list for processing.
2396          */
2397         if (rcode == 1) {
2398                 rad_assert(fun != NULL);
2399                 rad_assert(request != NULL);
2400
2401                 if (!thread_pool_addrequest(request, fun)) {
2402                         request->child_state = REQUEST_DONE;
2403                 }
2404         }
2405
2406         /*
2407          *      Still no FD, OR the fd was read completely, and then
2408          *      closed.  Re-set the polling timer and return.
2409          */
2410         if (listener->fd < 0) {
2411                 event_reset_fd(listener, -1, USEC);
2412                 return;
2413         }
2414
2415         if (listener->type == RAD_LISTEN_DETAIL) {
2416                 handler = event_detail_handler;
2417         } else {
2418                 handler = event_socket_handler;
2419         }
2420
2421         /*
2422          *      We have an FD.  Start watching it.
2423          */
2424         if (!fr_event_fd_insert(el, 0, listener->fd,
2425                                   handler, listener)) {
2426                 char buffer[256];
2427                 
2428                 listener->print(listener, buffer, sizeof(buffer));
2429                 rad_panic("Failed creating handler for socket");
2430         }
2431 }
2432
2433
2434 static void event_status(struct timeval *wake)
2435 {
2436         if (debug_flag == 0) {
2437                 if (just_started) {
2438                         radlog(L_INFO, "Ready to process requests.");
2439                         just_started = FALSE;
2440                 }
2441                 return;
2442
2443         } else {
2444                 read_from_detail = TRUE;
2445         }
2446
2447         if (!wake) {
2448                 DEBUG("Ready to process requests.");
2449
2450         } else if ((wake->tv_sec != 0) ||
2451                    (wake->tv_usec >= 100000)) {
2452                 DEBUG("Waking up in %d.%01u seconds.\n",
2453                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
2454         }
2455 }
2456
2457
2458 /*
2459  *      Externally-visibly functions.
2460  */
2461 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
2462 {
2463         int i;
2464         rad_listen_t *this, *head = NULL;
2465
2466         if (el) return 0;
2467
2468         time(&start_time);
2469
2470         el = fr_event_list_create(event_status);
2471         if (!el) return 0;
2472
2473         pl = fr_packet_list_create(0);
2474         if (!el) return 0;
2475
2476         request_num_counter = 0;
2477
2478         /*
2479          *      Move all of the thread calls to this file?
2480          *
2481          *      It may be best for the mutexes to be in this file...
2482          */
2483         have_children = spawn_flag;
2484
2485         if (mainconfig.proxy_requests) {
2486                 /*
2487                  *      Create the tree for managing proxied requests and
2488                  *      responses.
2489                  */
2490                 proxy_list = fr_packet_list_create(1);
2491                 if (!proxy_list) return 0;
2492
2493 #ifdef HAVE_PTHREAD_H
2494                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
2495                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
2496                                strerror(errno));
2497                         exit(1);
2498                 }
2499 #endif
2500         }
2501
2502 #ifdef HAVE_PTHREAD_H
2503         if (thread_pool_init(cs, spawn_flag) < 0) {
2504                 exit(1);
2505         }
2506 #endif
2507
2508         if (check_config) {
2509                 DEBUG2("%s: #### Skipping IP addresses and Ports ####",
2510                        mainconfig.name);
2511                 return 1;
2512         }
2513
2514 #ifndef __MINGW32__
2515         /*
2516          *      Child threads need a pipe to signal us, as do the
2517          *      signal handlers.
2518          */
2519         if (pipe(self_pipe) < 0) {
2520                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
2521                        strerror(errno));
2522                 exit(1);
2523         }
2524         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2525                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2526                        strerror(errno));
2527                 exit(1);
2528         }
2529         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
2530                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
2531                        strerror(errno));
2532                 exit(1);
2533         }
2534
2535         if (!fr_event_fd_insert(el, 0, self_pipe[0],
2536                                   event_signal_handler, el)) {
2537                 radlog(L_ERR, "Failed creating handler for signals");
2538                 exit(1);
2539         }
2540 #endif
2541
2542         /*
2543          *      Mark the proxy Fd's as unused.
2544          */
2545         for (i = 0; i < 32; i++) proxy_fds[i] = -1;
2546
2547         DEBUG2("%s: #### Opening IP addresses and Ports ####",
2548                mainconfig.name);
2549
2550         if (listen_init(cs, &head) < 0) {
2551                 _exit(1);
2552         }
2553         
2554         /*
2555          *      Add all of the sockets to the event loop.
2556          *
2557          *      FIXME: New proxy sockets aren't currently added to the
2558          *      event loop.  They're allocated in a child thread, and
2559          *      we don't have (or want) a mutex around the event
2560          *      handling code.
2561          */
2562         for (this = head;
2563              this != NULL;
2564              this = this->next) {
2565                 char buffer[256];
2566
2567                 this->print(this, buffer, sizeof(buffer));
2568
2569                 switch (this->type) {
2570                 case RAD_LISTEN_DETAIL:
2571                         DEBUG("Listening on %s", buffer);
2572                         has_detail_listener = TRUE;
2573                         break;
2574
2575                 case RAD_LISTEN_SNMP:
2576                         DEBUG("Listening on SNMP %s", buffer);
2577                         break;
2578
2579                 case RAD_LISTEN_PROXY:
2580                         rad_assert(proxy_fds[this->fd & 0x1f] == -1);
2581                         rad_assert(proxy_listeners[this->fd & 0x1f] == NULL);
2582                         
2583                         proxy_fds[this->fd & 0x1f] = this->fd;
2584                         proxy_listeners[this->fd & 0x1f] = this;
2585                         if (!fr_packet_list_socket_add(proxy_list,
2586                                                          this->fd)) {
2587                                 rad_assert(0 == 1);
2588                         }
2589                         /* FALL-THROUGH */
2590
2591                 default:
2592                         DEBUG("Listening on %s", buffer);
2593                         break;
2594                 }
2595
2596                 /*
2597                  *      The file descriptor isn't ready.  Poll for
2598                  *      when it will become ready.  This is for SNMP
2599                  *      and detail file fd's.
2600                  */
2601                 if (this->fd < 0) {
2602                         struct timeval when;
2603
2604                         gettimeofday(&when, NULL);
2605                         when.tv_sec += 1;
2606
2607                         if (!fr_event_insert(el, event_poll_fd, this,
2608                                                &when, NULL)) {
2609                                 radlog(L_ERR, "Failed creating handler");
2610                                 exit(1);
2611                         }
2612                         continue;
2613                 }
2614
2615                 /*
2616                  *      The socket is open.  It MUST be a socket,
2617                  *      as we don't pre-open the detail files (yet).
2618                  *
2619                  *      FIXME: if we DO open the detail files automatically,
2620                  *      then much of this code becomes simpler.
2621                  */
2622                 if (!fr_event_fd_insert(el, 0, this->fd,
2623                                           event_socket_handler, this)) {
2624                         this->print(this, buffer, sizeof(buffer));
2625                         radlog(L_ERR, "Failed creating handler for socket %s",
2626                                buffer);
2627                         exit(1);
2628                 }
2629         }
2630
2631         mainconfig.listen = head;
2632
2633         return 1;
2634 }
2635
2636
2637 static int request_hash_cb(UNUSED void *ctx, void *data)
2638 {
2639         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
2640
2641         rad_assert(request->in_proxy_hash == FALSE);
2642
2643         fr_event_delete(el, &request->ev);
2644         remove_from_request_hash(request);
2645         request_free(&request);
2646
2647         return 0;
2648 }
2649
2650
2651 static int proxy_hash_cb(UNUSED void *ctx, void *data)
2652 {
2653         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
2654
2655         fr_packet_list_yank(proxy_list, request->proxy);
2656         request->in_proxy_hash = FALSE;
2657
2658         if (!request->in_request_hash) {
2659                 fr_event_delete(el, &request->ev);
2660                 request_free(&request);
2661         }
2662
2663         return 0;
2664 }
2665
2666
2667 void radius_event_free(void)
2668 {
2669         /*
2670          *      FIXME: Stop all threads, or at least check that
2671          *      they're all waiting on the semaphore, and the queues
2672          *      are empty.
2673          */
2674
2675         /*
2676          *      There are requests in the proxy hash that aren't
2677          *      referenced from anywhere else.  Remove them first.
2678          */
2679         if (proxy_list) {
2680                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
2681                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
2682                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2683                 fr_packet_list_free(proxy_list);
2684                 proxy_list = NULL;
2685         }
2686
2687         fr_packet_list_walk(pl, NULL, request_hash_cb);
2688
2689         fr_packet_list_free(pl);
2690         pl = NULL;
2691
2692         fr_event_list_free(el);
2693 }
2694
2695 int radius_event_process(void)
2696 {
2697         if (!el) return 0;
2698
2699         just_started = TRUE;
2700
2701         return fr_event_loop(el);
2702 }
2703
2704 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
2705 {
2706         if (request_pre_handler(request)) {
2707                 rad_assert(fun != NULL);
2708                 rad_assert(request != NULL);
2709                 
2710                 if (request->server) DEBUG("server %s {",
2711                                              request->server); 
2712                 fun(request);
2713
2714                 if (request->server) DEBUG("} # server %s",
2715                                              request->server);
2716
2717                 request_post_handler(request);
2718         }
2719
2720         DEBUG2("Going to the next request");
2721         return;
2722 }