Jumbo patch to clean up socket handling
[freeradius.git] / src / main / event.c
1 /*
2  * event.c      Server event handling
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/event.h>
30 #include <freeradius-devel/detail.h>
31
32 #include <freeradius-devel/rad_assert.h>
33
34 #include <signal.h>
35 #include <fcntl.h>
36
37 #ifdef HAVE_SYS_WAIT_H
38 #       include <sys/wait.h>
39 #endif
40
41 #define USEC (1000000)
42
43 extern pid_t radius_pid;
44 extern int dont_fork;
45 extern int check_config;
46 extern void force_log_reopen(void);
47 extern char *debug_condition;
48
49 /*
50  *      Ridiculous amounts of local state.
51  */
52 static fr_event_list_t  *el = NULL;
53 static fr_packet_list_t *pl = NULL;
54 static int                      request_num_counter = 0;
55 static struct timeval           now;
56 time_t                          fr_start_time;
57 static int                      have_children;
58 static int                      just_started = TRUE;
59
60 #ifndef __MINGW32__
61 #ifdef HAVE_PTHREAD_H
62 #define WITH_SELF_PIPE (1)
63 #endif
64 #endif
65
66 #ifdef WITH_SELF_PIPE
67 static int self_pipe[2];
68 #endif
69
70 #ifdef HAVE_PTHREAD_H
71 #ifdef WITH_PROXY
72 static pthread_mutex_t  proxy_mutex;
73 static rad_listen_t *proxy_listener_list = NULL;
74 #endif
75
76 #define PTHREAD_MUTEX_LOCK if (have_children) pthread_mutex_lock
77 #define PTHREAD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
78
79 static pthread_t NO_SUCH_CHILD_PID;
80 #else
81 /*
82  *      This is easier than ifdef's throughout the code.
83  */
84 #define PTHREAD_MUTEX_LOCK(_x)
85 #define PTHREAD_MUTEX_UNLOCK(_x)
86 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
87 {
88         radius_handle_request(request, fun);
89         return 1;
90 }
91 #endif
92
93 /*
94  *      We need mutexes around the event FD list *only* in certain
95  *      cases.
96  */
97 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
98 static pthread_mutex_t  fd_mutex;
99 #define FD_MUTEX_LOCK if (have_children) pthread_mutex_lock
100 #define FD_MUTEX_UNLOCK if (have_children) pthread_mutex_unlock
101 #else
102 /*
103  *      This is easier than ifdef's throughout the code.
104  */
105 #define FD_MUTEX_LOCK(_x)
106 #define FD_MUTEX_UNLOCK(_x)
107 #endif
108
109
110 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
111
112 #ifdef WITH_PROXY
113 static fr_packet_list_t *proxy_list = NULL;
114 static void remove_from_proxy_hash(REQUEST *request);
115
116 #else
117 #define remove_from_proxy_hash(foo)
118 #endif
119
120 static void request_post_handler(REQUEST *request);
121 static void wait_a_bit(void *ctx);
122 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx);
123 #ifdef WITH_DETAIL
124 static void event_poll_detail(void *ctx);
125 #endif
126
127 static void NEVER_RETURNS _rad_panic(const char *file, unsigned int line,
128                                     const char *msg)
129 {
130         radlog(L_ERR, "[%s:%d] %s", file, line, msg);
131         _exit(1);
132 }
133
134 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
135
136
137 static void tv_add(struct timeval *tv, int usec_delay)
138 {
139         if (usec_delay > USEC) {
140                 tv->tv_sec += usec_delay / USEC;
141                 usec_delay %= USEC;
142         }
143         tv->tv_usec += usec_delay;
144
145         if (tv->tv_usec > USEC) {
146                 tv->tv_usec -= USEC;
147                 tv->tv_sec++;
148         }
149 }
150
151 static void remove_from_request_hash(REQUEST *request)
152 {
153         if (!request->in_request_hash) return;
154
155         fr_packet_list_yank(pl, request->packet);
156         request->in_request_hash = FALSE;
157
158         request_stats_final(request);
159
160 #ifdef WITH_TCP
161         request->listener->count--;
162 #endif
163 }
164
165 #ifdef WITH_PROXY
166 static REQUEST *lookup_in_proxy_hash(RADIUS_PACKET *reply)
167 {
168         RADIUS_PACKET **proxy_p;
169         REQUEST *request;
170
171         PTHREAD_MUTEX_LOCK(&proxy_mutex);
172         proxy_p = fr_packet_list_find_byreply(proxy_list, reply);
173
174         if (!proxy_p) {
175                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
176                 return NULL;
177         }
178
179         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
180
181         if (!request) {
182                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
183                 return NULL;
184         }
185
186         request->num_proxied_responses++;
187
188         /*
189          *      Catch the most common case of everything working
190          *      correctly.
191          */
192         if (request->num_proxied_requests == request->num_proxied_responses) {
193                 remove_from_proxy_hash(request);
194         }
195
196         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
197
198         return request;
199 }
200
201
202 static void remove_from_proxy_hash(REQUEST *request)
203 {
204         /*
205          *      Check this without grabbing the mutex because it's a
206          *      lot faster that way.
207          */
208         if (!request->in_proxy_hash) return;
209
210         /*
211          *      The "not in hash" flag is definitive.  However, if the
212          *      flag says that it IS in the hash, there might still be
213          *      a race condition where it isn't.
214          */
215         PTHREAD_MUTEX_LOCK(&proxy_mutex);
216
217         if (!request->in_proxy_hash) {
218                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
219                 return;
220         }
221
222         fr_packet_list_yank(proxy_list, request->proxy);
223         fr_packet_list_id_free(proxy_list, request->proxy);
224
225         /*
226          *      On the FIRST reply, decrement the count of outstanding
227          *      requests.  Note that this is NOT the count of sent
228          *      packets, but whether or not the home server has
229          *      responded at all.
230          */
231         if (!request->proxy_reply &&
232             request->home_server &&
233             request->home_server->currently_outstanding) {
234                 request->home_server->currently_outstanding--;
235         }
236
237 #ifdef WITH_TCP
238         request->proxy_listener->count--;
239         request->proxy_listener = NULL;
240 #endif
241
242         /*
243          *      Got from YES in hash, to NO, not in hash while we hold
244          *      the mutex.  This guarantees that when another thread
245          *      grabs the mutex, the "not in hash" flag is correct.
246          */
247         request->in_proxy_hash = FALSE;
248
249         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
250 }
251 #endif  /* WITH_PROXY */
252
253 static void ev_request_free(REQUEST **prequest)
254 {
255         REQUEST *request;
256         
257         if (!prequest || !*prequest) return;
258
259         request = *prequest;
260
261 #ifdef WITH_COA
262         if (request->coa) {
263                 /*
264                  *      Divorce the child from the parent first,
265                  *      then clean up the child.
266                  */
267                 request->coa->parent = NULL;
268                 ev_request_free(&request->coa);
269         }
270
271         /*
272          *      Divorce the parent from the child, and leave the
273          *      parent still alive.
274          */
275         if (request->parent && (request->parent->coa == request)) {
276                 request->parent->coa = NULL;
277         }
278 #endif
279
280         if (request->ev) fr_event_delete(el, &request->ev);
281 #ifdef WITH_PROXY
282         if (request->in_proxy_hash) remove_from_proxy_hash(request);
283 #endif
284         if (request->in_request_hash) remove_from_request_hash(request);
285
286         request_free(prequest);
287 }
288
289 #ifdef WITH_TCP
290 static int remove_all_requests(void *ctx, void *data)
291 {
292         rad_listen_t *this = ctx;
293         RADIUS_PACKET **packet_p = data;
294         REQUEST *request;
295         
296         request = fr_packet2myptr(REQUEST, packet, packet_p);
297         if (request->packet->sockfd != this->fd) return 0;
298
299         switch (request->child_state) {
300         case REQUEST_RUNNING:
301                 rad_assert(request->ev != NULL); /* or it's lost forever */
302         case REQUEST_QUEUED:
303                 request->master_state = REQUEST_STOP_PROCESSING;
304                 return 0;
305
306                 /*
307                  *      Waiting for a reply.  There's no point in
308                  *      doing anything else.  We remove it from the
309                  *      request hash so that we can close the upstream
310                  *      socket.
311                  */
312         case REQUEST_PROXIED:
313                 remove_from_request_hash(request);
314                 request->child_state = REQUEST_DONE;
315                 return 0;
316
317         case REQUEST_REJECT_DELAY:
318         case REQUEST_CLEANUP_DELAY:
319         case REQUEST_DONE:
320                 ev_request_free(&request);
321                 break;
322         }
323
324         return 0;
325 }
326
327 #ifdef WITH_PROXY
328 static int remove_all_proxied_requests(void *ctx, void *data)
329 {
330         rad_listen_t *this = ctx;
331         RADIUS_PACKET **proxy_p = data;
332         REQUEST *request;
333         
334         request = fr_packet2myptr(REQUEST, proxy, proxy_p);
335         if (request->proxy->sockfd != this->fd) return 0;
336
337         switch (request->child_state) {
338         case REQUEST_RUNNING:
339                 rad_assert(request->ev != NULL); /* or it's lost forever */
340         case REQUEST_QUEUED:
341                 request->master_state = REQUEST_STOP_PROCESSING;
342                 return 0;
343
344                 /*
345                  *      Eventually we will discover that there is no
346                  *      response to the proxied request.
347                  */
348         case REQUEST_PROXIED:
349                 break;
350
351                 /*
352                  *      Keep it in the cache for duplicate detection.
353                  */
354         case REQUEST_REJECT_DELAY:
355         case REQUEST_CLEANUP_DELAY:
356         case REQUEST_DONE:
357                 break;
358         }
359
360         remove_from_proxy_hash(request);
361         return 0;
362 }
363 #endif  /* WITH_PROXY */
364 #endif  /* WITH_TCP */
365
366
367 #ifdef WITH_PROXY
368 static int proxy_id_alloc(REQUEST *request, RADIUS_PACKET *packet)
369 {
370         void *proxy_listener;
371
372         if (fr_packet_list_id_alloc(proxy_list, packet,
373                                     &proxy_listener)) {
374                 request->proxy_listener = proxy_listener;
375                 return 1;
376         }
377
378         if (!proxy_new_listener(request->home_server, 0)) {
379                 RDEBUG2("ERROR: Failed to create a new socket for proxying requests.");
380                 return 0;
381         }
382
383         if (!fr_packet_list_id_alloc(proxy_list, packet,
384                                      &proxy_listener)) {
385                 RDEBUG2("ERROR: Failed allocating Id for new socket when proxying requests.");
386                 return 0;
387         }
388         
389         request->proxy_listener = proxy_listener;
390         return 1;
391 }
392
393
394 static int insert_into_proxy_hash(REQUEST *request, int retransmit)
395 {
396         char buf[128];
397
398         rad_assert(request->proxy != NULL);
399         rad_assert(proxy_list != NULL);
400
401         PTHREAD_MUTEX_LOCK(&proxy_mutex);
402
403         if (!retransmit) {
404                 if (!proxy_id_alloc(request, request->proxy)) {
405                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
406                         return 0;
407                 }
408         } else {
409                 RADIUS_PACKET packet;
410
411 #ifdef WITH_TCP
412                 rad_assert(request->home_server->proto != IPPROTO_TCP);
413 #endif
414
415                 packet = *request->proxy;
416
417                 if (!proxy_id_alloc(request, &packet)) {
418                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
419                         return 0;
420                 }
421
422                 /*
423                  *      Yank the request, free the old Id, and
424                  *      remember the new Id.
425                  */
426                 fr_packet_list_yank(proxy_list, request->proxy);
427                 fr_packet_list_id_free(proxy_list, request->proxy);
428                 *request->proxy = packet;
429         }
430
431         if (!fr_packet_list_insert(proxy_list, &request->proxy)) {
432                 fr_packet_list_id_free(proxy_list, request->proxy);
433                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
434                 RDEBUG2("ERROR: Failed to insert entry into proxy list");
435                 return 0;
436         }
437
438         request->in_proxy_hash = TRUE;
439
440         /*
441          *      Keep track of maximum outstanding requests to a
442          *      particular home server.  'max_outstanding' is
443          *      enforced in home_server_ldb(), in realms.c.
444          */
445         if (request->home_server) {
446                 request->home_server->currently_outstanding++;
447         }
448
449 #ifdef WITH_TCP
450         request->proxy_listener->count++;
451 #endif
452
453         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
454
455         RDEBUG3(" proxy: allocating destination %s port %d - Id %d",
456                inet_ntop(request->proxy->dst_ipaddr.af,
457                          &request->proxy->dst_ipaddr.ipaddr, buf, sizeof(buf)),
458                request->proxy->dst_port,
459                request->proxy->id);
460
461         return 1;
462 }
463
464
465 /*
466  *      Called as BOTH an event, and in-line from other functions.
467  */
468 static void wait_for_proxy_id_to_expire(void *ctx)
469 {
470         REQUEST *request = ctx;
471
472         rad_assert(request->magic == REQUEST_MAGIC);
473         rad_assert(request->proxy != NULL);
474
475         if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
476         request->when = request->proxy_when;
477
478 #ifdef WITH_COA
479         if (((request->proxy->code == PW_COA_REQUEST) ||
480              (request->proxy->code == PW_DISCONNECT_REQUEST)) &&
481             (request->packet->code != request->proxy->code)) {
482                 request->when.tv_sec += request->home_server->coa_mrd;
483         } else
484 #endif
485         request->when.tv_sec += request->home_server->response_window;
486
487         if ((request->num_proxied_requests == request->num_proxied_responses) ||
488 #ifdef WITH_TCP
489             (request->home_server->proto == IPPROTO_TCP) ||
490 #endif
491             timercmp(&now, &request->when, >)) {
492                 if (request->packet) {
493                         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
494                                request->number, request->packet->id,
495                                (unsigned int) (request->timestamp - fr_start_time));
496                 } else {
497                         RDEBUG2("Cleaning up request %d with timestamp +%d",
498                                request->number,
499                                (unsigned int) (request->timestamp - fr_start_time));
500                 }
501
502                 ev_request_free(&request);
503                 return;
504         }
505
506         INSERT_EVENT(wait_for_proxy_id_to_expire, request);
507 }
508 #endif
509
510 #ifdef HAVE_PTHREAD_H
511 static void wait_for_child_to_die(void *ctx)
512 {
513         REQUEST *request = ctx;
514
515         rad_assert(request->magic == REQUEST_MAGIC);
516
517         if ((request->child_state == REQUEST_QUEUED) |
518             (request->child_state == REQUEST_RUNNING)) {
519                 request->delay += (request->delay >> 1);
520                 tv_add(&request->when, request->delay);
521
522                 RDEBUG2("Child is still stuck for request %d", request->number);
523
524                 INSERT_EVENT(wait_for_child_to_die, request);
525                 return;
526         }
527
528         RDEBUG2("Child is finally responsive for request %d", request->number);
529         remove_from_request_hash(request);
530
531 #ifdef WITH_PROXY
532         if (request->proxy) {
533                 wait_for_proxy_id_to_expire(request);
534                 return;
535         }
536 #endif
537
538         ev_request_free(&request);
539 }
540 #endif
541
542 static void cleanup_delay(void *ctx)
543 {
544         REQUEST *request = ctx;
545
546         rad_assert(request->magic == REQUEST_MAGIC);
547         rad_assert((request->child_state == REQUEST_CLEANUP_DELAY) ||
548                    (request->child_state == REQUEST_DONE));
549
550         remove_from_request_hash(request);
551
552 #ifdef WITH_PROXY
553         if (request->proxy && request->in_proxy_hash) {
554                 wait_for_proxy_id_to_expire(request);
555                 return;
556         }
557 #endif
558
559         RDEBUG2("Cleaning up request %d ID %d with timestamp +%d",
560                request->number, request->packet->id,
561                (unsigned int) (request->timestamp - fr_start_time));
562
563         ev_request_free(&request);
564 }
565
566
567 /*
568  *      In daemon mode, AND this request has debug flags set.
569  */
570 #define DEBUG_PACKET if (!debug_flag && request->options && request->radlog) debug_packet
571
572 static void debug_packet(REQUEST *request, RADIUS_PACKET *packet, int direction)
573 {
574         VALUE_PAIR *vp;
575         char buffer[1024];
576         const char *received, *from;
577         const fr_ipaddr_t *ip;
578         int port;
579
580         if (!packet) return;
581
582         rad_assert(request->radlog != NULL);
583
584         if (direction == 0) {
585                 received = "Received";
586                 from = "from";  /* what else? */
587                 ip = &packet->src_ipaddr;
588                 port = packet->src_port;
589
590         } else {
591                 received = "Sending";
592                 from = "to";    /* hah! */
593                 ip = &packet->dst_ipaddr;
594                 port = packet->dst_port;
595         }
596         
597         /*
598          *      Client-specific debugging re-prints the input
599          *      packet into the client log.
600          *
601          *      This really belongs in a utility library
602          */
603         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
604                 RDEBUG("%s %s packet %s host %s port %d, id=%d, length=%d",
605                        received, fr_packet_codes[packet->code], from,
606                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
607                        port, packet->id, packet->data_len);
608         } else {
609                 RDEBUG("%s packet %s host %s port %d code=%d, id=%d, length=%d",
610                        received, from,
611                        inet_ntop(ip->af, &ip->ipaddr, buffer, sizeof(buffer)),
612                        port,
613                        packet->code, packet->id, packet->data_len);
614         }
615
616         for (vp = packet->vps; vp != NULL; vp = vp->next) {
617                 vp_prints(buffer, sizeof(buffer), vp);
618                 request->radlog(L_DBG, 0, request, "\t%s", buffer);
619         }
620 }
621
622 static void reject_delay(void *ctx)
623 {
624         REQUEST *request = ctx;
625
626         rad_assert(request->magic == REQUEST_MAGIC);
627         rad_assert(request->child_state == REQUEST_REJECT_DELAY);
628
629         RDEBUG2("Sending delayed reject for request %d", request->number);
630
631         DEBUG_PACKET(request, request->reply, 1);
632
633         request->listener->send(request->listener, request);
634
635         request->when.tv_sec += request->root->cleanup_delay;
636         request->child_state = REQUEST_CLEANUP_DELAY;
637
638         INSERT_EVENT(cleanup_delay, request);
639 }
640
641
642 #ifdef WITH_PROXY
643 void revive_home_server(void *ctx)
644 {
645         home_server *home = ctx;
646         char buffer[128];
647
648 #ifdef WITH_TCP
649         rad_assert(home->proto != IPPROTO_TCP);
650 #endif
651
652         home->state = HOME_STATE_ALIVE;
653         home->currently_outstanding = 0;
654         home->revive_time = now;
655
656         /*
657          *      Delete any outstanding events.
658          */
659         if (home->ev) fr_event_delete(el, &home->ev);
660
661         radlog(L_INFO, "PROXY: Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
662                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
663                          buffer, sizeof(buffer)),
664                home->port);
665
666 }
667
668
669 static void no_response_to_ping(void *ctx)
670 {
671         REQUEST *request = ctx;
672         home_server *home;
673         char buffer[128];
674
675         rad_assert(request->home_server != NULL);
676
677         home = request->home_server;
678 #ifdef WITH_TCP
679         rad_assert(home->proto != IPPROTO_TCP);
680 #endif
681
682         home->num_received_pings = 0;
683
684         RDEBUG2("No response to status check %d from home server %s port %d",
685                request->number,
686                inet_ntop(request->proxy->dst_ipaddr.af,
687                          &request->proxy->dst_ipaddr.ipaddr,
688                          buffer, sizeof(buffer)),
689                request->proxy->dst_port);
690
691         wait_for_proxy_id_to_expire(request);
692 }
693
694
695 static void received_response_to_ping(REQUEST *request)
696 {
697         home_server *home;
698         char buffer[128];
699
700         rad_assert(request->home_server != NULL);
701
702         home = request->home_server;
703 #ifdef WITH_TCP
704         rad_assert(home->proto != IPPROTO_TCP);
705 #endif
706
707         home->num_received_pings++;
708
709         RDEBUG2("Received response to status check %d (%d in current sequence)",
710                request->number, home->num_received_pings);
711
712         /*
713          *      Remove the request from any hashes
714          */
715         fr_event_delete(el, &request->ev);
716         remove_from_proxy_hash(request);
717         rad_assert(request->in_request_hash == FALSE);
718
719         /*
720          *      The control socket may have marked the home server as
721          *      alive.  OR, it may have suddenly started responding to
722          *      requests again.  If so, don't re-do the "make alive"
723          *      work.
724          */
725         if (home->state == HOME_STATE_ALIVE) return;
726
727         /*
728          *      We haven't received enough ping responses to mark it
729          *      "alive".  Wait a bit.
730          */
731         if (home->num_received_pings < home->num_pings_to_alive) {
732                 return;
733         }
734
735         home->state = HOME_STATE_ALIVE;
736         home->currently_outstanding = 0;
737         home->revive_time = now;
738
739         if (!fr_event_delete(el, &home->ev)) {
740                 RDEBUG2("Hmm... no event for home server.  Oh well.");
741         }
742
743         radlog(L_INFO, "PROXY: Marking home server %s port %d alive",
744                inet_ntop(request->proxy->dst_ipaddr.af,
745                          &request->proxy->dst_ipaddr.ipaddr,
746                          buffer, sizeof(buffer)),
747                request->proxy->dst_port);
748 }
749
750
751 /*
752  *      Called from start of zombie period, OR after control socket
753  *      marks the home server dead.
754  */
755 static void ping_home_server(void *ctx)
756 {
757         uint32_t jitter;
758         home_server *home = ctx;
759         REQUEST *request;
760         VALUE_PAIR *vp;
761
762 #ifdef WITH_TCP
763         rad_assert(home->proto != IPPROTO_TCP);
764 #endif
765
766         if ((home->state == HOME_STATE_ALIVE) ||
767             (home->ping_check == HOME_PING_CHECK_NONE) ||
768             (home->ev != NULL)) {
769                 return;
770         }
771
772         request = request_alloc();
773         request->number = request_num_counter++;
774
775         request->proxy = rad_alloc(1);
776         rad_assert(request->proxy != NULL);
777
778         fr_event_now(el, &request->when);
779         home->when = request->when;
780
781         if (home->ping_check == HOME_PING_CHECK_STATUS_SERVER) {
782                 request->proxy->code = PW_STATUS_SERVER;
783
784                 radius_pairmake(request, &request->proxy->vps,
785                                 "Message-Authenticator", "0x00", T_OP_SET);
786
787         } else if (home->type == HOME_TYPE_AUTH) {
788                 request->proxy->code = PW_AUTHENTICATION_REQUEST;
789
790                 radius_pairmake(request, &request->proxy->vps,
791                                 "User-Name", home->ping_user_name, T_OP_SET);
792                 radius_pairmake(request, &request->proxy->vps,
793                                 "User-Password", home->ping_user_password, T_OP_SET);
794                 radius_pairmake(request, &request->proxy->vps,
795                                 "Service-Type", "Authenticate-Only", T_OP_SET);
796                 radius_pairmake(request, &request->proxy->vps,
797                                 "Message-Authenticator", "0x00", T_OP_SET);
798
799         } else {
800 #ifdef WITH_ACCOUNTING
801                 request->proxy->code = PW_ACCOUNTING_REQUEST;
802                 
803                 radius_pairmake(request, &request->proxy->vps,
804                                 "User-Name", home->ping_user_name, T_OP_SET);
805                 radius_pairmake(request, &request->proxy->vps,
806                                 "Acct-Status-Type", "Stop", T_OP_SET);
807                 radius_pairmake(request, &request->proxy->vps,
808                                 "Acct-Session-Id", "00000000", T_OP_SET);
809                 vp = radius_pairmake(request, &request->proxy->vps,
810                                      "Event-Timestamp", "0", T_OP_SET);
811                 vp->vp_date = now.tv_sec;
812 #else
813                 rad_assert("Internal sanity check failed");
814 #endif
815         }
816
817         radius_pairmake(request, &request->proxy->vps,
818                         "NAS-Identifier", "Status Check. Are you alive?",
819                         T_OP_SET);
820
821         request->proxy->dst_ipaddr = home->ipaddr;
822         request->proxy->dst_port = home->port;
823         request->home_server = home;
824
825         rad_assert(request->proxy_listener == NULL);
826
827         if (!insert_into_proxy_hash(request, FALSE)) {
828                 RDEBUG2("ERROR: Failed inserting status check %d into proxy hash.  Discarding it.",
829                        request->number);
830                 ev_request_free(&request);
831                 return;
832         }
833         rad_assert(request->proxy_listener != NULL);
834         request->proxy_listener->send(request->proxy_listener,
835                                       request);
836
837         request->next_callback = NULL;
838         request->child_state = REQUEST_PROXIED;
839         request->when.tv_sec += home->ping_timeout;;
840
841         INSERT_EVENT(no_response_to_ping, request);
842
843         /*
844          *      Add +/- 2s of jitter, as suggested in RFC 3539
845          *      and in the Issues and Fixes draft.
846          */
847         home->when.tv_sec += home->ping_interval - 2;
848
849         jitter = fr_rand();
850         jitter ^= (jitter >> 10);
851         jitter &= ((1 << 23) - 1); /* 22 bits of 1 */
852
853         tv_add(&home->when, jitter);
854
855         INSERT_EVENT(ping_home_server, home);
856 }
857
858
859 void mark_home_server_dead(home_server *home, struct timeval *when)
860 {
861         int previous_state = home->state;
862         char buffer[128];
863
864         radlog(L_INFO, "PROXY: Marking home server %s port %d as dead.",
865                inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
866                          buffer, sizeof(buffer)),
867                home->port);
868
869         home->state = HOME_STATE_IS_DEAD;
870         home->num_received_pings = 0;
871
872         if (home->ping_check != HOME_PING_CHECK_NONE) {
873                 /*
874                  *      If the control socket marks us dead, start
875                  *      pinging.  Otherwise, we already started
876                  *      pinging when it was marked "zombie".
877                  */
878                 if (previous_state == HOME_STATE_ALIVE) {
879                         ping_home_server(home);
880                 }
881
882         } else {
883                 /*
884                  *      Revive it after a fixed period of time.  This
885                  *      is very, very, bad.
886                  */
887                 home->when = *when;
888                 home->when.tv_sec += home->revive_interval;
889
890                 INSERT_EVENT(revive_home_server, home);
891         }
892 }
893
894 static void check_for_zombie_home_server(REQUEST *request)
895 {
896         home_server *home;
897         struct timeval when;
898
899         home = request->home_server;
900
901         if (home->state != HOME_STATE_ZOMBIE) return;
902
903         when = home->zombie_period_start;
904         when.tv_sec += home->zombie_period;
905
906         fr_event_now(el, &now);
907         if (timercmp(&now, &when, <)) {
908                 return;
909         }
910
911         mark_home_server_dead(home, &request->when);
912 }
913
914 static int proxy_to_virtual_server(REQUEST *request);
915
916 static int virtual_server_handler(UNUSED REQUEST *request)
917 {
918         proxy_to_virtual_server(request);
919         return 0;
920 }
921
922 static void proxy_fallback_handler(REQUEST *request)
923 {
924         /*
925          *      A proper time is required for wait_a_bit.
926          */
927         request->delay = USEC / 10;
928         gettimeofday(&now, NULL);
929         request->next_when = now;
930         tv_add(&request->next_when, request->delay);
931         request->next_callback = wait_a_bit;
932
933         /*
934          *      Re-queue the request.
935          */
936         request->child_state = REQUEST_QUEUED;
937         
938         rad_assert(request->proxy != NULL);
939         if (!thread_pool_addrequest(request, virtual_server_handler)) {
940                 request->child_state = REQUEST_DONE;
941         }
942
943 #ifdef HAVE_PTHREAD_H
944         /*
945          *      MAY free the request if we're over max_request_time,
946          *      AND we're not in threaded mode!
947          *
948          *      Note that we call this ONLY if we're threaded, as
949          *      if we're NOT threaded, request_post_handler() calls
950          *      wait_a_bit(), which means that "request" may not
951          *      exist any more...
952          */
953         if (have_children) wait_a_bit(request);
954 #endif
955 }
956
957
958 static int setup_post_proxy_fail(REQUEST *request)
959 {
960         DICT_VALUE *dval = NULL;
961         VALUE_PAIR *vp;
962
963         request->child_state = REQUEST_RUNNING;
964
965         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
966                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Authentication");
967
968         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
969                 dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Accounting");
970
971 #ifdef WITH_COA
972                 /*
973                  *      See no_response_to_coa_request
974                  */
975         } else if (((request->packet->code >> 8) & 0xff) == PW_COA_REQUEST) {
976                 request->packet->code &= 0xff; /* restore it */
977
978                 if (request->proxy->code == PW_COA_REQUEST) {
979                         dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-CoA");
980
981                 } else if (request->proxy->code == PW_DISCONNECT_REQUEST) {
982                         dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail-Disconnect");
983                 } else {
984                         return 0;
985                 }
986
987 #endif
988         } else {
989                 return 0;
990         }
991
992         if (!dval) dval = dict_valbyname(PW_POST_PROXY_TYPE, "Fail");
993
994         if (!dval) {
995                 pairdelete(&request->config_items, PW_POST_PROXY_TYPE);
996                 return 0;
997         }
998
999         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1000         if (!vp) vp = radius_paircreate(request, &request->config_items,
1001                                         PW_POST_PROXY_TYPE, PW_TYPE_INTEGER);
1002         vp->vp_integer = dval->value;
1003
1004         rad_assert(request->proxy_reply == NULL);
1005
1006         return 1;
1007 }
1008
1009
1010 static int null_handler(UNUSED REQUEST *request)
1011 {
1012         return 0;
1013 }
1014
1015 static void post_proxy_fail_handler(REQUEST *request)
1016 {
1017         /*
1018          *      A proper time is required for wait_a_bit.
1019          */
1020         request->delay = USEC / 10;
1021         gettimeofday(&now, NULL);
1022
1023         /*
1024          *      Not set up to run Post-Proxy-Type = Fail.
1025          *
1026          *      Mark the request as still running, and figure out what
1027          *      to do next.
1028          */
1029         if (!setup_post_proxy_fail(request)) {
1030                 request_post_handler(request);
1031
1032         } else {
1033                 /*
1034                  *      Re-queue the request.
1035                  */
1036                 request->child_state = REQUEST_QUEUED;
1037
1038                 /*
1039                  *      There is a post-proxy-type of fail.  We run
1040                  *      the request through the pre/post proxy
1041                  *      handlers, just like it was a real proxied
1042                  *      request.  However, we set the per-request
1043                  *      handler to NULL, as we don't want to do
1044                  *      anything else.
1045                  *
1046                  *      Note that when we're not threaded, this will
1047                  *      process the request even if it's greater than
1048                  *      max_request_time.  That's not fatal.
1049                  */
1050                 request->priority = 0;
1051                 rad_assert(request->proxy != NULL);
1052                 thread_pool_addrequest(request, null_handler);
1053         }
1054
1055         /*
1056          *      MAY free the request if we're over max_request_time,
1057          *      AND we're not in threaded mode!
1058          *
1059          *      Note that we call this ONLY if we're threaded, as
1060          *      if we're NOT threaded, request_post_handler() calls
1061          *      wait_a_bit(), which means that "request" may not
1062          *      exist any more...
1063          */
1064         if (have_children) wait_a_bit(request);
1065 }
1066
1067 /* maybe check this against wait_for_proxy_id_to_expire? */
1068 static void no_response_to_proxied_request(void *ctx)
1069 {
1070         REQUEST *request = ctx;
1071         home_server *home;
1072         char buffer[128];
1073
1074         rad_assert(request->magic == REQUEST_MAGIC);
1075         rad_assert(request->child_state == REQUEST_PROXIED);
1076
1077         /*
1078          *      If we've failed over to an internal home server,
1079          *      replace the callback with the correct one.  This
1080          *      is due to locking issues with child threads...
1081          */
1082         if (request->home_server->server) {
1083                 wait_a_bit(request);
1084                 return;
1085         }
1086
1087 #ifdef WITH_TCP
1088         if (request->home_server->proto != IPPROTO_TCP)
1089 #endif
1090                 check_for_zombie_home_server(request);
1091
1092         /*
1093          *      The default as of 2.1.7 is to allow requests to
1094          *      fail-over to a backup home server when this one does
1095          *      not respond.  The old behavior can be configured as
1096          *      well.
1097          */
1098         if (home->no_response_fail) {
1099                 radlog(L_ERR, "Rejecting request %d (proxy Id %d) due to lack of any response from home server %s port %d",
1100                        request->number, request->proxy->id,
1101                        inet_ntop(request->proxy->dst_ipaddr.af,
1102                                  &request->proxy->dst_ipaddr.ipaddr,
1103                                  buffer, sizeof(buffer)),
1104                        request->proxy->dst_port);
1105
1106                 post_proxy_fail_handler(request);
1107         }
1108
1109         home = request->home_server;
1110
1111         /*
1112          *      Don't touch request due to race conditions
1113          */
1114
1115 #ifdef WITH_TCP
1116         /*
1117          *      Do nothing more.  The home server didn't respond,
1118          *      but that isn't a catastrophic failure.  Some home
1119          *      servers don't respond to packets...
1120          */
1121         if (home->proto == IPPROTO_TCP) {
1122                 /*
1123                  *      FIXME: Set up TCP pinging on this connection.
1124                  *
1125                  *      Maybe the CONNECTION is dead, but the home
1126                  *      server is alive.  In that case, we need to start
1127                  *      pinging on the connection.
1128                  *
1129                  *      This means doing the pinging BEFORE the
1130                  *      post_proxy_fail_handler above, as it may do
1131                  *      something with the request, and cause the
1132                  *      proxy listener to go away!
1133                  */
1134                 return;
1135         }
1136 #endif
1137
1138         if (home->state == HOME_STATE_IS_DEAD) {
1139                 rad_assert(home->ev != NULL); /* or it will never wake up */
1140                 return;
1141         }
1142
1143         /*
1144          *      Enable the zombie period when we notice that the home
1145          *      server hasn't responded.  We do NOT back-date the start
1146          *      of the zombie period.
1147          */
1148         if (home->state == HOME_STATE_ALIVE) {
1149                 home->state = HOME_STATE_ZOMBIE;
1150                 home->zombie_period_start = now;        
1151
1152                 radlog(L_ERR, "PROXY: Marking home server %s port %d as zombie (it looks like it is dead).",
1153                        inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
1154                                  buffer, sizeof(buffer)),
1155                        home->port);
1156
1157                 /*
1158                  *      Start pinging the home server.
1159                  */
1160                 ping_home_server(home);
1161         }
1162 }
1163 #endif
1164
1165 static void wait_a_bit(void *ctx)
1166 {
1167         struct timeval when;
1168         REQUEST *request = ctx;
1169         fr_event_callback_t callback = NULL;
1170
1171         rad_assert(request->magic == REQUEST_MAGIC);
1172
1173         /*
1174          *      The socket was closed.  Tell the request that
1175          *      there is no point in continuing.
1176          */
1177         if (request->listener->status != RAD_LISTEN_STATUS_KNOWN) {
1178                 goto stop_processing;
1179         }
1180
1181 #ifdef WITH_COA
1182         /*
1183          *      The CoA request is a new (internally generated)
1184          *      request, created in a child thread.  We therefore need
1185          *      some way to tie its events back into the main event
1186          *      handler.
1187          */
1188         if (request->coa && !request->coa->proxy_reply &&
1189             request->coa->next_callback) {
1190                 request->coa->when = request->coa->next_when;
1191                 INSERT_EVENT(request->coa->next_callback, request->coa);
1192                 request->coa->next_callback = NULL;
1193                 request->coa->parent = NULL;
1194                 request->coa = NULL;
1195         }
1196 #endif
1197
1198         switch (request->child_state) {
1199         case REQUEST_QUEUED:
1200         case REQUEST_RUNNING:
1201                 when = request->received;
1202                 when.tv_sec += request->root->max_request_time;
1203
1204                 /*
1205                  *      Normally called from the event loop with the
1206                  *      proper event loop time.  Otherwise, called from
1207                  *      post proxy fail handler, which sets "now", and
1208                  *      this call won't re-set it, because we're not
1209                  *      in the event loop.
1210                  */
1211                 fr_event_now(el, &now);
1212
1213                 /*
1214                  *      Request still has more time.  Continue
1215                  *      waiting.
1216                  */
1217                 if (timercmp(&now, &when, <) ||
1218                     ((request->listener->type == RAD_LISTEN_DETAIL) &&
1219                      (request->child_state == REQUEST_QUEUED))) {
1220                         if (request->delay < (USEC / 10)) {
1221                                 request->delay = USEC / 10;
1222                         }
1223                         request->delay += request->delay >> 1;
1224
1225 #ifdef WITH_DETAIL
1226                         /*
1227                          *      Cap wait at some sane value for detail
1228                          *      files.
1229                          */
1230                         if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1231                             (request->delay > (request->root->max_request_time * USEC))) {
1232                                 request->delay = request->root->max_request_time * USEC;
1233                         }
1234 #endif
1235
1236                         request->when = now;
1237                         tv_add(&request->when, request->delay);
1238                         callback = wait_a_bit;
1239                         break;
1240                 }
1241
1242 #if defined(HAVE_PTHREAD_H) || defined(WITH_PROXY)
1243                 /*
1244                  *      A child thread MAY still be running on the
1245                  *      request.  Ask the thread to stop working on
1246                  *      the request.
1247                  */
1248                 if (have_children) {
1249                         /* FIXME: kill unresponsive children? */
1250
1251                         /*
1252                          *      Print this error message ONLY if
1253                          *      there's a child currently processing
1254                          *      the request.  As we don't have thread
1255                          *      locks here, there may be race
1256                          *      conditions on this check.  But it's
1257                          *      just an error message, so that's OK.
1258                          */
1259                         if (!pthread_equal(request->child_pid, NO_SUCH_CHILD_PID)) {
1260                                 radlog(L_ERR, "WARNING: Unresponsive child for request %d, in module %s component %s",
1261                                        request->number,
1262                                        request->module ? request->module : "<server core>",
1263                                        request->component ? request->component : "<server core>");
1264                         }
1265
1266                 stop_processing:
1267                         request->master_state = REQUEST_STOP_PROCESSING;
1268                         
1269                         request->delay = USEC / 4;
1270                         tv_add(&request->when, request->delay);
1271                         callback = wait_for_child_to_die;
1272                         break;
1273                 }
1274 #else  /* no child threads */
1275         stop_processing:
1276 #endif
1277
1278                 /*
1279                  *      Else there are no child threads.  We probably
1280                  *      should have just marked the request as 'done'
1281                  *      elsewhere, like in the post-proxy-fail
1282                  *      handler.  But doing that would involve
1283                  *      checking for max_request_time in multiple
1284                  *      places, so this may be simplest.
1285                  */
1286                 request->child_state = REQUEST_DONE;
1287                 /* FALL-THROUGH */
1288
1289                 /*
1290                  *      Mark the request as no longer running,
1291                  *      and clean it up.
1292                  */
1293         case REQUEST_DONE:
1294 #ifdef HAVE_PTHREAD_H
1295                 request->child_pid = NO_SUCH_CHILD_PID;
1296 #endif
1297
1298 #ifdef WTH_COA
1299                 /*
1300                  *      This is a CoA request.  It's been divorced
1301                  *      from everything else, so we clean it up now.
1302                  */
1303                 if (!request->in_request_hash &&
1304                     request->proxy &&
1305                     (request->packet->code != request->proxy->code) &&
1306                     ((request->proxy->code == PW_COA_REQUEST) ||
1307                      (request->proxy->code == PW_DISCONNECT_REQUEST))) {
1308                         /*
1309                          *      FIXME: Do CoA MIBs
1310                          */
1311                         ev_request_free(&request);
1312                         return;
1313                 }
1314 #endif
1315                 request_stats_final(request);
1316                 cleanup_delay(request);
1317                 return;
1318
1319         case REQUEST_REJECT_DELAY:
1320         case REQUEST_CLEANUP_DELAY:
1321 #ifdef HAVE_PTHREAD_H
1322                 request->child_pid = NO_SUCH_CHILD_PID;
1323 #endif
1324                 request_stats_final(request);
1325
1326         case REQUEST_PROXIED:
1327                 rad_assert(request->next_callback != NULL);
1328                 rad_assert(request->next_callback != wait_a_bit);
1329
1330                 request->when = request->next_when;
1331                 callback = request->next_callback;
1332                 request->next_callback = NULL;
1333                 break;
1334
1335         default:
1336                 rad_panic("Internal sanity check failure");
1337                 return;
1338         }
1339
1340         /*
1341          *      Something major went wrong.  Discard the request, and
1342          *      keep running.
1343          *
1344          *      FIXME: No idea why this happens or how to fix it...
1345          *      It seems to happen *only* when requests are proxied,
1346          *      and where the home server doesn't respond.  So it looks
1347          *      like a race condition above, but it happens in debug
1348          *      mode, with no threads...
1349          */
1350         if (!callback) {
1351                 RDEBUG("WARNING: Internal sanity check failed in event handler for request %d: Discarding the request!", request->number);
1352                 ev_request_free(&request);
1353                 return;
1354         }
1355
1356         INSERT_EVENT(callback, request);
1357 }
1358
1359 #ifdef WITH_COA
1360 static void no_response_to_coa_request(void *ctx)
1361 {
1362         REQUEST *request = ctx;
1363         char buffer[128];
1364
1365         rad_assert(request->magic == REQUEST_MAGIC);
1366         rad_assert(request->child_state == REQUEST_PROXIED);
1367         rad_assert(request->home_server != NULL);
1368         rad_assert(!request->in_request_hash);
1369
1370         radlog(L_ERR, "No response to CoA request sent to %s",
1371                inet_ntop(request->proxy->dst_ipaddr.af,
1372                          &request->proxy->dst_ipaddr.ipaddr,
1373                          buffer, sizeof(buffer)));
1374
1375         /*
1376          *      Hack.
1377          */
1378         request->packet->code |= (PW_COA_REQUEST << 8);
1379         post_proxy_fail_handler(request);
1380 }
1381
1382
1383 static int update_event_timestamp(RADIUS_PACKET *packet, time_t when)
1384 {
1385         VALUE_PAIR *vp;
1386
1387         vp = pairfind(packet->vps, PW_EVENT_TIMESTAMP);
1388         if (!vp) return 0;
1389
1390         vp->vp_date = when;
1391
1392         if (packet->data) {
1393                 free(packet->data);
1394                 packet->data = NULL;
1395                 packet->data_len = 0;
1396         }
1397
1398         return 1;               /* time stamp updated */
1399 }
1400
1401
1402 /*
1403  *      Called when we haven't received a response to a CoA request.
1404  */
1405 static void retransmit_coa_request(void *ctx)
1406 {
1407         int delay, frac;
1408         struct timeval mrd;
1409         REQUEST *request = ctx;
1410
1411         rad_assert(request->magic == REQUEST_MAGIC);
1412         rad_assert(request->child_state == REQUEST_PROXIED);
1413         rad_assert(request->home_server != NULL);
1414         rad_assert(!request->in_request_hash);
1415         rad_assert(request->parent == NULL);
1416         
1417         fr_event_now(el, &now);
1418
1419         /*
1420          *      Cap count at MRC, if it is non-zero.
1421          */
1422         if (request->home_server->coa_mrc &&
1423             (request->num_coa_requests >= request->home_server->coa_mrc)) {
1424                 no_response_to_coa_request(request);
1425                 return;
1426         }
1427
1428         /*
1429          *      RFC 5080 Section 2.2.1
1430          *
1431          *      RT = 2*RTprev + RAND*RTprev
1432          *         = 1.9 * RTprev + rand(0,.2) * RTprev
1433          *         = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
1434          */
1435         delay = fr_rand();
1436         delay ^= (delay >> 16);
1437         delay &= 0xffff;
1438         frac = request->delay / 5;
1439         delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
1440
1441         delay += (2 * request->delay) - (request->delay / 10);
1442
1443         /*
1444          *      Cap delay at MRT, if MRT is non-zero.
1445          */
1446         if (request->home_server->coa_mrt &&
1447             (delay > (request->home_server->coa_mrt * USEC))) {
1448                 int mrt_usec = request->home_server->coa_mrt * USEC;
1449
1450                 /*
1451                  *      delay = MRT + RAND * MRT
1452                  *            = 0.9 MRT + rand(0,.2)  * MRT
1453                  */
1454                 delay = fr_rand();
1455                 delay ^= (delay >> 15);
1456                 delay &= 0x1ffff;
1457                 delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
1458                 delay += mrt_usec - (mrt_usec / 10);
1459         }
1460
1461         request->delay = delay;
1462         request->when = now;
1463         tv_add(&request->when, request->delay);
1464         mrd = request->proxy_when;
1465         mrd.tv_sec += request->home_server->coa_mrd;
1466
1467         /*
1468          *      Cap duration at MRD.
1469          */
1470         if (timercmp(&mrd, &request->when, <)) {
1471                 request->when = mrd;
1472                 INSERT_EVENT(no_response_to_coa_request, request);
1473
1474         } else {
1475                 INSERT_EVENT(retransmit_coa_request, request);
1476         }
1477         
1478         if (update_event_timestamp(request->proxy, now.tv_sec)) {
1479                 if (!insert_into_proxy_hash(request, TRUE)) {
1480                         DEBUG("ERROR: Failed re-inserting CoA request into proxy hash.");
1481                         return;
1482                 }
1483
1484                 request->num_proxied_requests = 0;
1485                 request->num_proxied_responses = 0;
1486         }
1487
1488         request->num_proxied_requests++;
1489         request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
1490
1491         request->proxy_listener->send(request->proxy_listener,
1492                                       request);
1493 }
1494
1495
1496 /*
1497  *      The original request is either DONE, or in CLEANUP_DELAY.
1498  */
1499 static int originated_coa_request(REQUEST *request)
1500 {
1501         int delay, rcode, pre_proxy_type = 0;
1502         VALUE_PAIR *vp;
1503         REQUEST *coa;
1504         fr_ipaddr_t ipaddr;
1505         char buffer[256];
1506
1507         rad_assert(request->proxy == NULL);
1508         rad_assert(!request->in_proxy_hash);
1509         rad_assert(request->proxy_reply == NULL);
1510
1511         vp = pairfind(request->config_items, PW_SEND_COA_REQUEST);
1512         if (!vp && request->coa) vp = pairfind(request->coa->proxy->vps, PW_SEND_COA_REQUEST);
1513         if (vp) {
1514                 if (vp->vp_integer == 0) {
1515                         ev_request_free(&request->coa);
1516                         return 1;       /* success */
1517                 }
1518
1519                 if (!request->coa) request_alloc_coa(request);
1520                 if (!request->coa) return 0;
1521         }
1522
1523         coa = request->coa;
1524
1525         /*
1526          *      src_ipaddr will be set up in proxy_encode.
1527          */
1528         memset(&ipaddr, 0, sizeof(ipaddr));
1529         vp = pairfind(coa->proxy->vps, PW_PACKET_DST_IP_ADDRESS);
1530         if (vp) {
1531                 ipaddr.af = AF_INET;
1532                 ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1533
1534         } else if ((vp = pairfind(coa->proxy->vps,
1535                                   PW_PACKET_DST_IPV6_ADDRESS)) != NULL) {
1536                 ipaddr.af = AF_INET6;
1537                 ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1538                 
1539         } else if ((vp = pairfind(coa->proxy->vps,
1540                                   PW_HOME_SERVER_POOL)) != NULL) {
1541                 coa->home_pool = home_pool_byname(vp->vp_strvalue,
1542                                                   HOME_TYPE_COA);
1543                 if (!coa->home_pool) {
1544                         RDEBUG2("WARNING: No such home_server_pool %s",
1545                                vp->vp_strvalue);
1546         fail:
1547                         ev_request_free(&request->coa);
1548                         return 0;
1549                 }
1550
1551                 /*
1552                  *      Prefer
1553                  */
1554         } else if (request->client->coa_pool) {
1555                 coa->home_pool = request->client->coa_pool;
1556
1557         } else if (request->client->coa_server) {
1558                 coa->home_server = request->client->coa_server;
1559
1560         } else {
1561                 /*
1562                  *      If all else fails, send it to the client that
1563                  *      originated this request.
1564                  */
1565                 memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
1566         }
1567
1568         /*
1569          *      Use the pool, if it exists.
1570          */
1571         if (coa->home_pool) {
1572                 coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
1573                 if (!coa->home_server) {
1574                         RDEBUG("WARNING: No live home server for home_server_pool %s", vp->vp_strvalue);
1575                         goto fail;
1576                 }
1577
1578         } else if (!coa->home_server) {
1579                 int port = PW_COA_UDP_PORT;
1580
1581                 vp = pairfind(coa->proxy->vps, PW_PACKET_DST_PORT);
1582                 if (vp) port = vp->vp_integer;
1583
1584                 coa->home_server = home_server_find(&ipaddr, port);
1585                 if (!coa->home_server) {
1586                         RDEBUG2("WARNING: Unknown destination %s:%d for CoA request.",
1587                                inet_ntop(ipaddr.af, &ipaddr.ipaddr,
1588                                          buffer, sizeof(buffer)), port);
1589                         goto fail;
1590                 }
1591         }
1592
1593         vp = pairfind(coa->proxy->vps, PW_PACKET_TYPE);
1594         if (vp) {
1595                 switch (vp->vp_integer) {
1596                 case PW_COA_REQUEST:
1597                 case PW_DISCONNECT_REQUEST:
1598                         coa->proxy->code = vp->vp_integer;
1599                         break;
1600                         
1601                 default:
1602                         DEBUG("Cannot set CoA Packet-Type to code %d",
1603                               vp->vp_integer);
1604                         goto fail;
1605                 }
1606         }
1607
1608         if (!coa->proxy->code) coa->proxy->code = PW_COA_REQUEST;
1609
1610         /*
1611          *      The rest of the server code assumes that
1612          *      request->packet && request->reply exist.  Copy them
1613          *      from the original request.
1614          */
1615         rad_assert(coa->packet != NULL);
1616         rad_assert(coa->packet->vps == NULL);
1617         memcpy(coa->packet, request->packet, sizeof(*request->packet));
1618         coa->packet->vps = paircopy(request->packet->vps);
1619         coa->packet->data = NULL;
1620         rad_assert(coa->reply != NULL);
1621         rad_assert(coa->reply->vps == NULL);
1622         memcpy(coa->reply, request->reply, sizeof(*request->reply));
1623         coa->reply->vps = paircopy(request->reply->vps);
1624         coa->reply->data = NULL;
1625         coa->config_items = paircopy(request->config_items);
1626
1627         /*
1628          *      Call the pre-proxy routines.
1629          */
1630         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
1631         if (vp) {
1632                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
1633                 pre_proxy_type = vp->vp_integer;
1634         }
1635
1636         if (coa->home_pool && coa->home_pool->virtual_server) {
1637                 const char *old_server = coa->server;
1638                 
1639                 coa->server = coa->home_pool->virtual_server;
1640                 RDEBUG2(" server %s {", coa->server);
1641                 rcode = module_pre_proxy(pre_proxy_type, coa);
1642                 RDEBUG2(" }");
1643                 coa->server = old_server;
1644         } else {
1645                 rcode = module_pre_proxy(pre_proxy_type, coa);
1646         }
1647         switch (rcode) {
1648         default:
1649                 goto fail;
1650
1651         /*
1652          *      Only send the CoA packet if the pre-proxy code succeeded.
1653          */
1654         case RLM_MODULE_NOOP:
1655         case RLM_MODULE_OK:
1656         case RLM_MODULE_UPDATED:
1657                 break;
1658         }
1659
1660         /*
1661          *      Source IP / port is set when the proxy socket
1662          *      is chosen.
1663          */
1664         coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
1665         coa->proxy->dst_port = coa->home_server->port;
1666
1667         if (!insert_into_proxy_hash(coa, FALSE)) {
1668                 DEBUG("ERROR: Failed inserting CoA request into proxy hash.");
1669                 goto fail;
1670         }
1671
1672         /*
1673          *      We CANNOT divorce the CoA request from the parent
1674          *      request.  This function is running in a child thread,
1675          *      and we need access to the main event loop in order to
1676          *      to add the timers for the CoA packet.  See
1677          *      wait_a_bit().
1678          */
1679
1680         /*
1681          *      Forget about the original request completely at this
1682          *      point.
1683          */
1684         request = coa;
1685
1686         gettimeofday(&request->proxy_when, NULL);       
1687         request->received = request->next_when = request->proxy_when;
1688         rad_assert(request->proxy_reply == NULL);
1689
1690         /*
1691          *      Implement re-transmit algorithm as per RFC 5080
1692          *      Section 2.2.1.
1693          *
1694          *      We want IRT + RAND*IRT
1695          *      or 0.9 IRT + rand(0,.2) IRT
1696          *
1697          *      2^20 ~ USEC, and we want 2.
1698          *      rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
1699          */
1700         delay = (fr_rand() & ((1 << 22) - 1)) / 10;
1701         request->delay = delay * request->home_server->coa_irt;
1702         delay = request->home_server->coa_irt * USEC;
1703         delay -= delay / 10;
1704         delay += request->delay;
1705      
1706         request->delay = delay;
1707         tv_add(&request->next_when, delay);
1708         request->next_callback = retransmit_coa_request;
1709         
1710         /*
1711          *      Note that we set proxied BEFORE sending the packet.
1712          *
1713          *      Once we send it, the request is tainted, as
1714          *      another thread may have picked it up.  Don't
1715          *      touch it!
1716          */
1717         request->num_proxied_requests = 1;
1718         request->num_proxied_responses = 0;
1719         request->child_pid = NO_SUCH_CHILD_PID;
1720
1721         update_event_timestamp(request->proxy, request->proxy_when.tv_sec);
1722
1723         request->child_state = REQUEST_PROXIED;
1724
1725         DEBUG_PACKET(request, request->proxy, 1);
1726
1727         request->proxy_listener->send(request->proxy_listener,
1728                                       request);
1729         return 1;
1730 }
1731 #endif  /* WITH_COA */
1732
1733 #ifdef WITH_PROXY
1734 static int process_proxy_reply(REQUEST *request)
1735 {
1736         int rcode;
1737         int post_proxy_type = 0;
1738         VALUE_PAIR *vp;
1739         
1740         /*
1741          *      Delete any reply we had accumulated until now.
1742          */
1743         pairfree(&request->reply->vps);
1744         
1745         /*
1746          *      Run the packet through the post-proxy stage,
1747          *      BEFORE playing games with the attributes.
1748          */
1749         vp = pairfind(request->config_items, PW_POST_PROXY_TYPE);
1750         if (vp) {
1751                 RDEBUG2("  Found Post-Proxy-Type %s", vp->vp_strvalue);
1752                 post_proxy_type = vp->vp_integer;
1753         }
1754         
1755         if (request->home_pool && request->home_pool->virtual_server) {
1756                 const char *old_server = request->server;
1757                 
1758                 request->server = request->home_pool->virtual_server;
1759                 RDEBUG2(" server %s {", request->server);
1760                 rcode = module_post_proxy(post_proxy_type, request);
1761                 RDEBUG2(" }");
1762                 request->server = old_server;
1763         } else {
1764                 rcode = module_post_proxy(post_proxy_type, request);
1765         }
1766
1767 #ifdef WITH_COA
1768         if (request->packet->code == request->proxy->code)
1769           /*
1770            *    Don't run the next bit if we originated a CoA
1771            *    packet, after receiving an Access-Request or
1772            *    Accounting-Request.
1773            */
1774 #endif
1775         
1776         /*
1777          *      There may NOT be a proxy reply, as we may be
1778          *      running Post-Proxy-Type = Fail.
1779          */
1780         if (request->proxy_reply) {
1781                 /*
1782                  *      Delete the Proxy-State Attributes from
1783                  *      the reply.  These include Proxy-State
1784                  *      attributes from us and remote server.
1785                  */
1786                 pairdelete(&request->proxy_reply->vps, PW_PROXY_STATE);
1787                 
1788                 /*
1789                  *      Add the attributes left in the proxy
1790                  *      reply to the reply list.
1791                  */
1792                 pairadd(&request->reply->vps, request->proxy_reply->vps);
1793                 request->proxy_reply->vps = NULL;
1794                 
1795                 /*
1796                  *      Free proxy request pairs.
1797                  */
1798                 pairfree(&request->proxy->vps);
1799         }
1800         
1801         switch (rcode) {
1802         default:  /* Don't do anything */
1803                 break;
1804         case RLM_MODULE_FAIL:
1805                 /* FIXME: debug print stuff */
1806                 request->child_state = REQUEST_DONE;
1807                 return 0;
1808                 
1809         case RLM_MODULE_HANDLED:
1810                 /* FIXME: debug print stuff */
1811                 request->child_state = REQUEST_DONE;
1812                 return 0;
1813         }
1814
1815         return 1;
1816 }
1817 #endif
1818
1819 static int request_pre_handler(REQUEST *request)
1820 {
1821         int rcode;
1822
1823         rad_assert(request->magic == REQUEST_MAGIC);
1824         rad_assert(request->packet != NULL);
1825
1826         request->child_state = REQUEST_RUNNING;
1827
1828         /*
1829          *      Don't decode the packet if it's an internal "fake"
1830          *      request.  Instead, just return so that the caller can
1831          *      process it.
1832          */
1833         if (request->packet->dst_port == 0) {
1834                 request->username = pairfind(request->packet->vps,
1835                                              PW_USER_NAME);
1836                 request->password = pairfind(request->packet->vps,
1837                                              PW_USER_PASSWORD);
1838                 return 1;
1839         }
1840
1841 #ifdef WITH_PROXY
1842         /*
1843          *      Put the decoded packet into it's proper place.
1844          */
1845         if (request->proxy_reply != NULL) {
1846                 /*
1847                  *      FIXME: For now, we can only proxy RADIUS packets.
1848                  *
1849                  *      In order to proxy other packets, we need to
1850                  *      somehow cache the "decode" function.
1851                  */
1852                 rcode = rad_decode(request->proxy_reply, request->proxy,
1853                                    request->home_server->secret);
1854                 DEBUG_PACKET(request, request->proxy_reply, 0);
1855         } else
1856 #endif
1857         if (request->packet->vps == NULL) {
1858                 rcode = request->listener->decode(request->listener, request);
1859                 
1860                 if (debug_condition) {
1861                         int result = FALSE;
1862                         const char *my_debug = debug_condition;
1863
1864                         /*
1865                          *      Ignore parse errors.
1866                          */
1867                         radius_evaluate_condition(request, RLM_MODULE_OK, 0,
1868                                                   &my_debug, 1,
1869                                                   &result);
1870                         if (result) {
1871                                 request->options = 2;
1872                                 request->radlog = radlog_request;
1873                         }
1874                 }
1875                 
1876                 DEBUG_PACKET(request, request->packet, 0);
1877         } else {
1878                 rcode = 0;
1879         }
1880
1881         if (rcode < 0) {
1882                 radlog(L_ERR, "%s Dropping packet without response.", fr_strerror());
1883                 request->child_state = REQUEST_DONE;
1884                 return 0;
1885         }
1886
1887         if (!request->username) {
1888                 request->username = pairfind(request->packet->vps,
1889                                              PW_USER_NAME);
1890         }
1891
1892 #ifdef WITH_PROXY
1893         if (request->proxy) {
1894                 return process_proxy_reply(request);
1895 #endif
1896         }
1897
1898         return 1;
1899 }
1900
1901
1902 #ifdef WITH_PROXY
1903 /*
1904  *      Do state handling when we proxy a request.
1905  */
1906 static int proxy_request(REQUEST *request)
1907 {
1908         struct timeval when;
1909         char buffer[128];
1910
1911         if (request->home_server->server) {
1912                 RDEBUG("ERROR: Cannot perform real proxying to a virtual server.");
1913                 return 0;
1914         }
1915
1916         if (!insert_into_proxy_hash(request, FALSE)) {
1917                 RDEBUG("ERROR: Failed inserting request into proxy hash.");
1918                 return 0;
1919         }
1920
1921         request->proxy_listener->encode(request->proxy_listener, request);
1922
1923         when = request->received;
1924         when.tv_sec += request->root->max_request_time;
1925
1926         gettimeofday(&request->proxy_when, NULL);
1927
1928         request->next_when = request->proxy_when;
1929         request->next_when.tv_sec += request->home_server->response_window;
1930
1931         rad_assert(request->home_server->response_window > 0);
1932
1933         if (timercmp(&when, &request->next_when, <)) {
1934                 request->next_when = when;
1935         }
1936         request->next_callback = no_response_to_proxied_request;
1937
1938         RDEBUG2("Proxying request %d to home server %s port %d",
1939                request->number,
1940                inet_ntop(request->proxy->dst_ipaddr.af,
1941                          &request->proxy->dst_ipaddr.ipaddr,
1942                          buffer, sizeof(buffer)),
1943                request->proxy->dst_port);
1944
1945         /*
1946          *      Note that we set proxied BEFORE sending the packet.
1947          *
1948          *      Once we send it, the request is tainted, as
1949          *      another thread may have picked it up.  Don't
1950          *      touch it!
1951          */
1952         request->num_proxied_requests = 1;
1953         request->num_proxied_responses = 0;
1954 #ifdef HAVE_PTHREAD_H
1955         request->child_pid = NO_SUCH_CHILD_PID;
1956 #endif
1957         request->child_state = REQUEST_PROXIED;
1958
1959         DEBUG_PACKET(request, request->proxy, 1);
1960
1961         request->proxy_listener->send(request->proxy_listener,
1962                                       request);
1963         return 1;
1964 }
1965
1966
1967 /*
1968  *      "Proxy" the request by sending it to a new virtual server.
1969  */
1970 static int proxy_to_virtual_server(REQUEST *request)
1971 {
1972         REQUEST *fake;
1973         RAD_REQUEST_FUNP fun;
1974
1975         if (!request->home_server || !request->home_server->server) return 0;
1976
1977         if (request->parent) {
1978                 RDEBUG2("WARNING: Cancelling proxy request to virtual server %s as this request was itself proxied.", request->home_server->server);
1979                 return 0;
1980         }
1981
1982         fake = request_alloc_fake(request);
1983         if (!fake) {
1984                 RDEBUG2("WARNING: Out of memory");
1985                 return 0;
1986         }
1987
1988         fake->packet->vps = paircopy(request->proxy->vps);
1989         fake->server = request->home_server->server;
1990
1991         if (request->proxy->code == PW_AUTHENTICATION_REQUEST) {
1992                 fun = rad_authenticate;
1993
1994 #ifdef WITH_ACCOUNTING
1995         } else if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1996                 fun = rad_accounting;
1997 #endif
1998
1999         } else {
2000                 RDEBUG2("Unknown packet type %d", request->proxy->code);
2001                 ev_request_free(&fake);
2002                 return 0;
2003         }
2004
2005         RDEBUG2(">>> Sending proxied request internally to virtual server.");
2006         radius_handle_request(fake, fun);
2007         RDEBUG2("<<< Received proxied response code %d from internal virtual server.", fake->reply->code);
2008
2009         if (fake->reply->code != 0) {
2010                 request->proxy_reply = fake->reply;
2011                 fake->reply = NULL;
2012         } else {
2013                 /*
2014                  *      There was no response
2015                  */
2016                 setup_post_proxy_fail(request);
2017         }
2018
2019         ev_request_free(&fake);
2020
2021         process_proxy_reply(request);
2022
2023         /*
2024          *      Process it through the normal section again, but ONLY
2025          *      if we received a proxy reply..
2026          */
2027         if (request->proxy_reply) {
2028                 if (request->server) RDEBUG("server %s {",
2029                                             request->server != NULL ?
2030                                             request->server : ""); 
2031                 fun(request);
2032                 
2033                 if (request->server) RDEBUG("} # server %s",
2034                                             request->server != NULL ?
2035                                             request->server : "");
2036         }
2037
2038         return 2;               /* success, but NOT '1' !*/
2039 }
2040
2041 /*
2042  *      Return 1 if we did proxy it, or the proxy attempt failed
2043  *      completely.  Either way, the caller doesn't touch the request
2044  *      any more if we return 1.
2045  */
2046 static int successfully_proxied_request(REQUEST *request)
2047 {
2048         int rcode;
2049         int pre_proxy_type = 0;
2050         VALUE_PAIR *realmpair;
2051         VALUE_PAIR *strippedname;
2052         VALUE_PAIR *vp;
2053         char *realmname = NULL;
2054         home_server *home;
2055         REALM *realm = NULL;
2056         home_pool_t *pool;
2057
2058         /*
2059          *      If it was already proxied, do nothing.
2060          *
2061          *      FIXME: This should really be a serious error.
2062          */
2063         if (request->in_proxy_hash ||
2064             (request->proxy_reply && (request->proxy_reply->code != 0))) {
2065                 return 0;
2066         }
2067
2068         realmpair = pairfind(request->config_items, PW_PROXY_TO_REALM);
2069         if (!realmpair || (realmpair->length == 0)) {
2070                 int pool_type;
2071
2072                 vp = pairfind(request->config_items, PW_HOME_SERVER_POOL);
2073                 if (!vp) return 0;
2074
2075                 switch (request->packet->code) {
2076                 case PW_AUTHENTICATION_REQUEST:
2077                         pool_type = HOME_TYPE_AUTH;
2078                         break;
2079
2080 #ifdef WITH_ACCOUNTING
2081                 case PW_ACCOUNTING_REQUEST:
2082                         pool_type = HOME_TYPE_ACCT;
2083                         break;
2084 #endif
2085
2086 #ifdef WITH_COA
2087                 case PW_COA_REQUEST:
2088                 case PW_DISCONNECT_REQUEST:
2089                         pool_type = HOME_TYPE_COA;
2090                         break;
2091 #endif
2092
2093                 default:
2094                         return 0;
2095                 }
2096
2097                 pool = home_pool_byname(vp->vp_strvalue, pool_type);
2098                 if (!pool) {
2099                         RDEBUG2("ERROR: Cannot proxy to unknown pool %s",
2100                                 vp->vp_strvalue);
2101                         return 0;
2102                 }
2103
2104                 realmname = NULL; /* no realms */
2105                 realm = NULL;
2106                 goto found_pool;
2107         }
2108
2109         realmname = (char *) realmpair->vp_strvalue;
2110
2111         realm = realm_find2(realmname);
2112         if (!realm) {
2113                 RDEBUG2("ERROR: Cannot proxy to unknown realm %s", realmname);
2114                 return 0;
2115         }
2116
2117         /*
2118          *      Figure out which pool to use.
2119          */
2120         if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2121                 pool = realm->auth_pool;
2122
2123 #ifdef WITH_ACCOUNTING
2124         } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2125                 pool = realm->acct_pool;
2126 #endif
2127
2128 #ifdef WITH_COA
2129         } else if ((request->packet->code == PW_COA_REQUEST) ||
2130                    (request->packet->code == PW_DISCONNECT_REQUEST)) {
2131                 pool = realm->acct_pool;
2132 #endif
2133
2134         } else {
2135                 rad_panic("Internal sanity check failed");
2136         }
2137
2138         if (!pool) {
2139                 RDEBUG2(" WARNING: Cancelling proxy to Realm %s, as the realm is local.",
2140                        realmname);
2141                 return 0;
2142         }
2143
2144 found_pool:
2145         home = home_server_ldb(realmname, pool, request);
2146         if (!home) {
2147                 RDEBUG2("ERROR: Failed to find live home server for realm %s",
2148                        realmname);
2149                 return -1;
2150         }
2151         request->home_pool = pool;
2152
2153 #ifdef WITH_COA
2154         /*
2155          *      Once we've decided to proxy a request, we cannot send
2156          *      a CoA packet.  So we free up any CoA packet here.
2157          */
2158         ev_request_free(&request->coa);
2159 #endif
2160         /*
2161          *      Remember that we sent the request to a Realm.
2162          */
2163         if (realmname) pairadd(&request->packet->vps,
2164                                pairmake("Realm", realmname, T_OP_EQ));
2165
2166         /*
2167          *      Strip the name, if told to.
2168          *
2169          *      Doing it here catches the case of proxied tunneled
2170          *      requests.
2171          */
2172         if (realm && (realm->striprealm == TRUE) &&
2173            (strippedname = pairfind(request->proxy->vps, PW_STRIPPED_USER_NAME)) != NULL) {
2174                 /*
2175                  *      If there's a Stripped-User-Name attribute in
2176                  *      the request, then use THAT as the User-Name
2177                  *      for the proxied request, instead of the
2178                  *      original name.
2179                  *
2180                  *      This is done by making a copy of the
2181                  *      Stripped-User-Name attribute, turning it into
2182                  *      a User-Name attribute, deleting the
2183                  *      Stripped-User-Name and User-Name attributes
2184                  *      from the vps list, and making the new
2185                  *      User-Name the head of the vps list.
2186                  */
2187                 vp = pairfind(request->proxy->vps, PW_USER_NAME);
2188                 if (!vp) {
2189                         vp = radius_paircreate(request, NULL,
2190                                                PW_USER_NAME, PW_TYPE_STRING);
2191                         rad_assert(vp != NULL); /* handled by above function */
2192                         /* Insert at the START of the list */
2193                         vp->next = request->proxy->vps;
2194                         request->proxy->vps = vp;
2195                 }
2196                 memcpy(vp->vp_strvalue, strippedname->vp_strvalue,
2197                        sizeof(vp->vp_strvalue));
2198                 vp->length = strippedname->length;
2199
2200                 /*
2201                  *      Do NOT delete Stripped-User-Name.
2202                  */
2203         }
2204
2205         /*
2206          *      If there is no PW_CHAP_CHALLENGE attribute but
2207          *      there is a PW_CHAP_PASSWORD we need to add it
2208          *      since we can't use the request authenticator
2209          *      anymore - we changed it.
2210          */
2211         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2212             pairfind(request->proxy->vps, PW_CHAP_PASSWORD) &&
2213             pairfind(request->proxy->vps, PW_CHAP_CHALLENGE) == NULL) {
2214                 vp = radius_paircreate(request, &request->proxy->vps,
2215                                        PW_CHAP_CHALLENGE, PW_TYPE_OCTETS);
2216                 vp->length = AUTH_VECTOR_LEN;
2217                 memcpy(vp->vp_strvalue, request->packet->vector, AUTH_VECTOR_LEN);
2218         }
2219
2220         /*
2221          *      The RFC's say we have to do this, but FreeRADIUS
2222          *      doesn't need it.
2223          */
2224         vp = radius_paircreate(request, &request->proxy->vps,
2225                                PW_PROXY_STATE, PW_TYPE_OCTETS);
2226         snprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), "%d",
2227                  request->packet->id);
2228         vp->length = strlen(vp->vp_strvalue);
2229
2230         /*
2231          *      Should be done BEFORE inserting into proxy hash, as
2232          *      pre-proxy may use this information, or change it.
2233          */
2234         request->proxy->code = request->packet->code;
2235
2236         /*
2237          *      Call the pre-proxy routines.
2238          */
2239         vp = pairfind(request->config_items, PW_PRE_PROXY_TYPE);
2240         if (vp) {
2241                 RDEBUG2("  Found Pre-Proxy-Type %s", vp->vp_strvalue);
2242                 pre_proxy_type = vp->vp_integer;
2243         }
2244
2245         rad_assert(request->home_pool != NULL);
2246
2247         if (request->home_pool->virtual_server) {
2248                 const char *old_server = request->server;
2249                 
2250                 request->server = request->home_pool->virtual_server;
2251                 RDEBUG2(" server %s {", request->server);
2252                 rcode = module_pre_proxy(pre_proxy_type, request);
2253                 RDEBUG2(" }");
2254                         request->server = old_server;
2255         } else {
2256                 rcode = module_pre_proxy(pre_proxy_type, request);
2257         }
2258         switch (rcode) {
2259         case RLM_MODULE_FAIL:
2260         case RLM_MODULE_INVALID:
2261         case RLM_MODULE_NOTFOUND:
2262         case RLM_MODULE_USERLOCK:
2263         default:
2264                 /* FIXME: debug print failed stuff */
2265                 return -1;
2266
2267         case RLM_MODULE_REJECT:
2268         case RLM_MODULE_HANDLED:
2269                 return 0;
2270
2271         /*
2272          *      Only proxy the packet if the pre-proxy code succeeded.
2273          */
2274         case RLM_MODULE_NOOP:
2275         case RLM_MODULE_OK:
2276         case RLM_MODULE_UPDATED:
2277                 break;
2278         }
2279
2280         /*
2281          *      If it's a fake request, don't send the proxy
2282          *      packet.  The outer tunnel session will take
2283          *      care of doing that.
2284          */
2285         if (request->packet->dst_port == 0) {
2286                 request->home_server = NULL;
2287                 return 1;
2288         }
2289
2290         if (request->home_server->server) {
2291                 return proxy_to_virtual_server(request);
2292         }
2293
2294         if (!proxy_request(request)) {
2295                 RDEBUG("ERROR: Failed to proxy request %d", request->number);
2296                 return -1;
2297         }
2298         
2299         return 1;
2300 }
2301 #endif
2302
2303 static void request_post_handler(REQUEST *request)
2304 {
2305         int child_state = -1;
2306         struct timeval when;
2307         VALUE_PAIR *vp;
2308
2309         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
2310             (request->parent &&
2311              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
2312                 RDEBUG2("Request %d was cancelled.", request->number);
2313 #ifdef HAVE_PTHREAD_H
2314                 request->child_pid = NO_SUCH_CHILD_PID;
2315 #endif
2316                 child_state = REQUEST_DONE;
2317                 goto cleanup;
2318         }
2319
2320         if (request->child_state != REQUEST_RUNNING) {
2321                 rad_panic("Internal sanity check failed");
2322         }
2323
2324 #ifdef WITH_COA
2325         /*
2326          *      If it's not in the request hash, it's a CoA request.
2327          *      We hope.
2328          */
2329         if (!request->in_request_hash &&
2330             request->proxy &&
2331             ((request->proxy->code == PW_COA_REQUEST) ||
2332              (request->proxy->code == PW_DISCONNECT_REQUEST))) {
2333                 request->next_callback = NULL;
2334                 child_state = REQUEST_DONE;
2335                 goto cleanup;
2336         }
2337 #endif
2338
2339         /*
2340          *      Catch Auth-Type := Reject BEFORE proxying the packet.
2341          */
2342         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2343             (request->reply->code == 0) &&
2344             ((vp = pairfind(request->config_items, PW_AUTH_TYPE)) != NULL) &&
2345             (vp->vp_integer == PW_AUTHTYPE_REJECT)) {
2346                 request->reply->code = PW_AUTHENTICATION_REJECT;
2347         }
2348
2349 #ifdef WITH_PROXY
2350         if (request->root->proxy_requests &&
2351             !request->in_proxy_hash &&
2352             (request->reply->code == 0) &&
2353             (request->packet->dst_port != 0) &&
2354             (request->packet->code != PW_STATUS_SERVER)) {
2355                 int rcode = successfully_proxied_request(request);
2356
2357                 if (rcode == 1) return; /* request is invalid */
2358
2359                 /*
2360                  *      Failed proxying it (dead home servers, etc.)
2361                  *      Run it through Post-Proxy-Type = Fail, and
2362                  *      respond to the request.
2363                  *
2364                  *      Note that we're in a child thread here, so we
2365                  *      do NOT re-schedule the request.  Instead, we
2366                  *      do what we would have done, which is run the
2367                  *      pre-handler, a NULL request handler, and then
2368                  *      the post handler.
2369                  */
2370                 if ((rcode < 0) && setup_post_proxy_fail(request)) {
2371                         request_pre_handler(request);
2372                 }
2373
2374                 /*
2375                  *      Else we weren't supposed to proxy it,
2376                  *      OR we proxied it internally to a virutal server.
2377                  */
2378         }
2379 #endif
2380
2381         /*
2382          *      Fake requests don't get encoded or signed.  The caller
2383          *      also requires the reply VP's, so we don't free them
2384          *      here!
2385          */
2386         if (request->packet->dst_port == 0) {
2387                 /* FIXME: RDEBUG going to the next request */
2388 #ifdef HAVE_PTHREAD_H
2389                 request->child_pid = NO_SUCH_CHILD_PID;
2390 #endif
2391                 request->child_state = REQUEST_DONE;
2392                 return;
2393         }
2394
2395 #ifdef WITH_PROXY
2396         /*
2397          *      Copy Proxy-State from the request to the reply.
2398          */
2399         vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
2400         if (vp) pairadd(&request->reply->vps, vp);
2401 #endif
2402
2403         /*
2404          *      Access-Requests get delayed or cached.
2405          */
2406         switch (request->packet->code) {
2407         case PW_AUTHENTICATION_REQUEST:
2408                 gettimeofday(&request->next_when, NULL);
2409
2410                 if (request->reply->code == 0) {
2411                         /*
2412                          *      Check if the lack of response is intentional.
2413                          */
2414                         vp = pairfind(request->config_items,
2415                                       PW_RESPONSE_PACKET_TYPE);
2416                         if (!vp) {
2417                                 RDEBUG2("There was no response configured: rejecting request %d",
2418                                        request->number);
2419                                 request->reply->code = PW_AUTHENTICATION_REJECT;
2420
2421                         } else if (vp->vp_integer == 256) {
2422                                 RDEBUG2("Not responding to request %d",
2423                                        request->number);
2424
2425                                 /*
2426                                  *      Force cleanup after a long
2427                                  *      time, so that we don't
2428                                  *      re-process the packet.
2429                                  */
2430                                 request->next_when.tv_sec += request->root->max_request_time;
2431                                 request->next_callback = cleanup_delay;
2432                                 child_state = REQUEST_CLEANUP_DELAY;
2433                                 break;
2434                         } else {
2435                                 request->reply->code = vp->vp_integer;
2436
2437                         }
2438                 }
2439
2440                 /*
2441                  *      Run rejected packets through
2442                  *
2443                  *      Post-Auth-Type = Reject
2444                  */
2445                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2446                         pairdelete(&request->config_items, PW_POST_AUTH_TYPE);
2447                         vp = radius_pairmake(request, &request->config_items,
2448                                              "Post-Auth-Type", "Reject",
2449                                              T_OP_SET);
2450                         if (vp) rad_postauth(request);
2451
2452                         /*
2453                          *      If configured, delay Access-Reject packets.
2454                          *
2455                          *      If request->root->reject_delay = 0, we discover
2456                          *      that we have to send the packet now.
2457                          */
2458                         when = request->received;
2459                         when.tv_sec += request->root->reject_delay;
2460
2461                         if (timercmp(&when, &request->next_when, >)) {
2462                                 RDEBUG2("Delaying reject of request %d for %d seconds",
2463                                        request->number,
2464                                        request->root->reject_delay);
2465                                 request->next_when = when;
2466                                 request->next_callback = reject_delay;
2467 #ifdef HAVE_PTHREAD_H
2468                                 request->child_pid = NO_SUCH_CHILD_PID;
2469 #endif
2470                                 request->child_state = REQUEST_REJECT_DELAY;
2471                                 return;
2472                         }
2473                 }
2474
2475 #ifdef WITH_COA
2476         case PW_COA_REQUEST:
2477         case PW_DISCONNECT_REQUEST:
2478 #endif
2479                 request->next_when.tv_sec += request->root->cleanup_delay;
2480                 request->next_callback = cleanup_delay;
2481                 child_state = REQUEST_CLEANUP_DELAY;
2482                 break;
2483
2484         case PW_ACCOUNTING_REQUEST:
2485                 request->next_callback = NULL; /* just to be safe */
2486                 child_state = REQUEST_DONE;
2487                 break;
2488
2489                 /*
2490                  *      FIXME: Status-Server should probably not be
2491                  *      handled here...
2492                  */
2493         case PW_STATUS_SERVER:
2494                 request->next_callback = NULL;
2495                 child_state = REQUEST_DONE;
2496                 break;
2497
2498         default:
2499                 /*
2500                  *      DHCP, VMPS, etc.
2501                  */
2502                 request->next_callback = NULL;
2503                 child_state = REQUEST_DONE;
2504                 break;
2505         }
2506
2507         /*
2508          *      Suppress "no reply" packets here, unless we're reading
2509          *      from the "detail" file.  In that case, we've got to
2510          *      tell the detail file handler that the request is dead,
2511          *      and it should re-send it.
2512          *      If configured, encode, sign, and send.
2513          */
2514         if ((request->reply->code != 0) ||
2515             (request->listener->type == RAD_LISTEN_DETAIL)) {
2516                 DEBUG_PACKET(request, request->reply, 1);
2517                 request->listener->send(request->listener, request);
2518         }
2519
2520 #ifdef WITH_COA
2521         /*
2522          *      Now that we've completely processed the request,
2523          *      see if we need to originate a CoA request.
2524          */
2525         if (request->coa ||
2526             (pairfind(request->config_items, PW_SEND_COA_REQUEST) != NULL)) {
2527                 if (!originated_coa_request(request)) {
2528                         RDEBUG2("Do CoA Fail handler here");
2529                 }
2530                 /* request->coa is stil set, so we can update events */
2531         }
2532 #endif
2533
2534  cleanup:
2535         /*
2536          *      Clean up.  These are no longer needed.
2537          */
2538         pairfree(&request->config_items);
2539
2540         pairfree(&request->packet->vps);
2541         request->username = NULL;
2542         request->password = NULL;
2543
2544         pairfree(&request->reply->vps);
2545
2546 #ifdef WITH_PROXY
2547         if (request->proxy) {
2548                 pairfree(&request->proxy->vps);
2549
2550                 if (request->proxy_reply) {
2551                         pairfree(&request->proxy_reply->vps);
2552                 }
2553
2554 #if 0
2555                 /*
2556                  *      We're not tracking responses from the home
2557                  *      server, we can therefore free this memory in
2558                  *      the child thread.
2559                  */
2560                 if (!request->in_proxy_hash) {
2561                         rad_free(&request->proxy);
2562                         rad_free(&request->proxy_reply);
2563                         request->home_server = NULL;
2564                 }
2565 #endif
2566         }
2567 #endif
2568
2569         RDEBUG2("Finished request %d.", request->number);
2570         rad_assert(child_state >= 0);
2571         request->child_state = child_state;
2572
2573         /*
2574          *      Single threaded mode: update timers now.
2575          */
2576         if (!have_children) wait_a_bit(request);
2577 }
2578
2579
2580 static void received_retransmit(REQUEST *request, const RADCLIENT *client)
2581 {
2582 #ifdef WITH_PROXY
2583         char buffer[128];
2584 #endif
2585
2586         RAD_STATS_TYPE_INC(request->listener, total_dup_requests);
2587         RAD_STATS_CLIENT_INC(request->listener, client, total_dup_requests);
2588         
2589         switch (request->child_state) {
2590         case REQUEST_QUEUED:
2591         case REQUEST_RUNNING:
2592 #ifdef WITH_PROXY
2593         discard:
2594 #endif
2595                 radlog(L_ERR, "Discarding duplicate request from "
2596                        "client %s port %d - ID: %d due to unfinished request %d",
2597                        client->shortname,
2598                        request->packet->src_port,request->packet->id,
2599                        request->number);
2600                 break;
2601
2602 #ifdef WITH_PROXY
2603         case REQUEST_PROXIED:
2604                 /*
2605                  *      We're not supposed to have duplicate
2606                  *      accounting packets.  The other states handle
2607                  *      duplicates fine (discard, or send duplicate
2608                  *      reply).  But we do NOT want to retransmit an
2609                  *      accounting request here, because that would
2610                  *      involve updating the Acct-Delay-Time, and
2611                  *      therefore changing the packet Id, etc.
2612                  *
2613                  *      Instead, we just discard the packet.  We may
2614                  *      eventually respond, or the client will send a
2615                  *      new accounting packet.            
2616                  *
2617                  *      The same comments go for Status-Server, and
2618                  *      other packet types.
2619                  *
2620                  *      FIXME: coa: when we proxy CoA && Disconnect
2621                  *      packets, this logic has to be fixed.
2622                  */
2623                 if (request->packet->code != PW_AUTHENTICATION_REQUEST) {
2624                         goto discard;
2625                 }
2626
2627                 check_for_zombie_home_server(request);
2628
2629                 /*
2630                  *      If we've just discovered that the home server
2631                  *      is dead, OR the socket has been closed, look for
2632                  *      another connection to a home server.
2633                  */
2634                 if (((request->packet->dst_port != 0) &&
2635                      (request->home_server->state == HOME_STATE_IS_DEAD)) ||
2636                     (request->proxy_listener->status != RAD_LISTEN_STATUS_KNOWN)) {
2637                         home_server *home;
2638
2639                         remove_from_proxy_hash(request);
2640
2641                         home = home_server_ldb(NULL, request->home_pool, request);
2642                         if (!home) {
2643                                 RDEBUG2("Failed to find live home server for request %d", request->number);
2644                         no_home_servers:
2645                                 /*
2646                                  *      Do post-request processing,
2647                                  *      and any insertion of necessary
2648                                  *      events.
2649                                  */
2650                                 post_proxy_fail_handler(request);
2651                                 return;
2652                         }
2653
2654                         request->proxy->code = request->packet->code;
2655
2656                         /*
2657                          *      Free the old packet, to force re-encoding
2658                          */
2659                         free(request->proxy->data);
2660                         request->proxy->data = NULL;
2661                         request->proxy->data_len = 0;
2662
2663                         /*
2664                          *      This request failed over to a virtual
2665                          *      server.  Push it back onto the queue
2666                          *      to be processed.
2667                          */
2668                         if (request->home_server->server) {
2669                                 proxy_fallback_handler(request);
2670                                 return;
2671                         }
2672
2673                         /*
2674                          *      Try to proxy the request.
2675                          */
2676                         if (!proxy_request(request)) {
2677                                 RDEBUG("ERROR: Failed to re-proxy request %d", request->number);
2678                                 goto no_home_servers;
2679                         }
2680
2681                         /*
2682                          *      This code executes in the main server
2683                          *      thread, so there's no need for locking.
2684                          */
2685                         rad_assert(request->next_callback != NULL);
2686                         INSERT_EVENT(request->next_callback, request);
2687                         request->next_callback = NULL;
2688                         return;
2689                 } /* else the home server is still alive */
2690
2691 #ifdef WITH_TCP
2692                 if (request->home_server->proto == IPPROTO_TCP) {
2693                         DEBUG2("Suppressing duplicate proxied request to home server %s port %d proto TCP - ID: %d",
2694                                inet_ntop(request->proxy->dst_ipaddr.af,
2695                                          &request->proxy->dst_ipaddr.ipaddr,
2696                                          buffer, sizeof(buffer)),
2697                                request->proxy->dst_port,
2698                                request->proxy->id);
2699                         break;
2700                 }
2701 #endif
2702
2703                 RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
2704                        inet_ntop(request->proxy->dst_ipaddr.af,
2705                                  &request->proxy->dst_ipaddr.ipaddr,
2706                                  buffer, sizeof(buffer)),
2707                        request->proxy->dst_port,
2708                        request->proxy->id);
2709                 request->num_proxied_requests++;
2710
2711                 DEBUG_PACKET(request, request->proxy, 1);
2712                 request->proxy_listener->send(request->proxy_listener,
2713                                               request);
2714                 break;
2715 #endif
2716
2717         case REQUEST_REJECT_DELAY:
2718                 RDEBUG2("Waiting to send Access-Reject "
2719                        "to client %s port %d - ID: %d",
2720                        client->shortname,
2721                        request->packet->src_port, request->packet->id);
2722                 break;
2723
2724         case REQUEST_CLEANUP_DELAY:
2725         case REQUEST_DONE:
2726                 if (request->reply->code == 0) {
2727                         RDEBUG2("Ignoring retransmit from client %s port %d "
2728                                 "- ID: %d, no reply was configured",
2729                                 client->shortname,
2730                                 request->packet->src_port, request->packet->id);
2731                         return;
2732                 }
2733
2734                 /*
2735                  *      FIXME: This sends duplicate replies to
2736                  *      accounting requests, even if Acct-Delay-Time
2737                  *      or Event-Timestamp is in the packet.  In those
2738                  *      cases, the Id should be changed, and the packet
2739                  *      re-calculated.
2740                  */
2741                 RDEBUG2("Sending duplicate reply "
2742                        "to client %s port %d - ID: %d",
2743                        client->shortname,
2744                        request->packet->src_port, request->packet->id);
2745                 DEBUG_PACKET(request, request->reply, 1);
2746                 request->listener->send(request->listener, request);
2747                 break;
2748         }
2749 }
2750
2751
2752 static void received_conflicting_request(REQUEST *request,
2753                                          const RADCLIENT *client)
2754 {
2755         radlog(L_ERR, "Received conflicting packet from "
2756                "client %s port %d - ID: %d due to unfinished request %d.  Giving up on old request.",
2757                client->shortname,
2758                request->packet->src_port, request->packet->id,
2759                request->number);
2760
2761         /*
2762          *      Nuke it from the request hash, so we can receive new
2763          *      packets.
2764          */
2765         remove_from_request_hash(request);
2766
2767         switch (request->child_state) {
2768 #ifdef HAVE_PTHREAD_H
2769                 /*
2770                  *      It's queued or running.  Tell it to stop, and
2771                  *      wait for it to do so.
2772                  */
2773         case REQUEST_QUEUED:
2774         case REQUEST_RUNNING:
2775                 request->master_state = REQUEST_STOP_PROCESSING;
2776                 request->delay += request->delay >> 1;
2777
2778                 tv_add(&request->when, request->delay);
2779
2780                 INSERT_EVENT(wait_for_child_to_die, request);
2781                 return;
2782 #endif
2783
2784                 /*
2785                  *      Catch race conditions.  It may have switched
2786                  *      from running to done while this code is being
2787                  *      executed.
2788                  */
2789         case REQUEST_REJECT_DELAY:
2790         case REQUEST_CLEANUP_DELAY:
2791         case REQUEST_DONE:
2792                 break;
2793
2794                 /*
2795                  *      It's in some other state, and therefore also
2796                  *      in the event queue.  At some point, the
2797                  *      child will notice, and we can then delete it.
2798                  */
2799         case REQUEST_PROXIED:
2800         default:
2801                 break;
2802         }
2803 }
2804
2805
2806 static int can_handle_new_request(RADIUS_PACKET *packet,
2807                                   RADCLIENT *client,
2808                                   struct main_config_t *root)
2809 {
2810         /*
2811          *      Count the total number of requests, to see if
2812          *      there are too many.  If so, return with an
2813          *      error.
2814          */
2815         if (root->max_requests) {
2816                 int request_count = fr_packet_list_num_elements(pl);
2817
2818                 /*
2819                  *      This is a new request.  Let's see if
2820                  *      it makes us go over our configured
2821                  *      bounds.
2822                  */
2823                 if (request_count > root->max_requests) {
2824                         radlog(L_ERR, "Dropping request (%d is too many): "
2825                                "from client %s port %d - ID: %d", request_count,
2826                                client->shortname,
2827                                packet->src_port, packet->id);
2828                         radlog(L_INFO, "WARNING: Please check the configuration file.\n"
2829                                "\tThe value for 'max_requests' is probably set too low.\n");
2830                         return 0;
2831                 } /* else there were a small number of requests */
2832         } /* else there was no configured limit for requests */
2833
2834         /*
2835          *      FIXME: Add per-client checks.  If one client is sending
2836          *      too many packets, start discarding them.
2837          *
2838          *      We increment the counters here, and decrement them
2839          *      when the response is sent... somewhere in this file.
2840          */
2841
2842         /*
2843          *      FUTURE: Add checks for system load.  If the system is
2844          *      busy, start dropping requests...
2845          *
2846          *      We can probably keep some statistics ourselves...  if
2847          *      there are more requests coming in than we can handle,
2848          *      start dropping some.
2849          */
2850
2851         return 1;
2852 }
2853
2854
2855 int received_request(rad_listen_t *listener,
2856                      RADIUS_PACKET *packet, REQUEST **prequest,
2857                      RADCLIENT *client)
2858 {
2859         RADIUS_PACKET **packet_p;
2860         REQUEST *request = NULL;
2861         struct main_config_t *root = &mainconfig;
2862
2863         packet_p = fr_packet_list_find(pl, packet);
2864         if (packet_p) {
2865                 request = fr_packet2myptr(REQUEST, packet, packet_p);
2866                 rad_assert(request->in_request_hash);
2867
2868                 if ((request->packet->data_len == packet->data_len) &&
2869                     (memcmp(request->packet->vector, packet->vector,
2870                             sizeof(packet->vector)) == 0)) {
2871                         received_retransmit(request, client);
2872                         return 0;
2873                 }
2874
2875                 /*
2876                  *      The new request is different from the old one,
2877                  *      but maybe the old is finished.  If so, delete
2878                  *      the old one.
2879                  */
2880                 switch (request->child_state) {
2881                         struct timeval when;
2882
2883                 default:
2884                         /*
2885                          *      Special hacks for race conditions.
2886                          *      The reply is encoded, and therefore
2887                          *      likely sent.  We received a *new*
2888                          *      packet from the client, likely before
2889                          *      the next line or two of code which
2890                          *      updated the child state.  In this
2891                          *      case, just accept the new request.
2892                          */
2893                         if ((request->reply->code != 0) &&
2894                             request->reply->data) {
2895                                 radlog(L_INFO, "WARNING: Allowing fast client %s port %d - ID: %d for recent request %d.",
2896                                        client->shortname,
2897                                        packet->src_port, packet->id,
2898                                        request->number);
2899                                 remove_from_request_hash(request);
2900                                 request = NULL;
2901                                 break;
2902                         }
2903
2904                         gettimeofday(&when, NULL);
2905                         when.tv_sec -= 1;
2906
2907                         /*
2908                          *      If the cached request was received
2909                          *      within the last second, then we
2910                          *      discard the NEW request instead of the
2911                          *      old one.  This will happen ONLY when
2912                          *      the client is severely broken, and is
2913                          *      sending conflicting packets very
2914                          *      quickly.
2915                          */
2916                         if (timercmp(&when, &request->received, <)) {
2917                                 radlog(L_ERR, "Discarding conflicting packet from "
2918                                        "client %s port %d - ID: %d due to recent request %d.",
2919                                        client->shortname,
2920                                        packet->src_port, packet->id,
2921                                        request->number);
2922                                 return 0;
2923                         }
2924
2925                         received_conflicting_request(request, client);
2926                         request = NULL;
2927                         break;
2928
2929                 case REQUEST_REJECT_DELAY:
2930                 case REQUEST_CLEANUP_DELAY:
2931                         request->child_state = REQUEST_DONE;
2932                 case REQUEST_DONE:
2933                         cleanup_delay(request);
2934                         request = NULL;
2935                         break;
2936                 }
2937         }
2938
2939         /*
2940          *      We may want to quench the new request.
2941          */
2942         if ((listener->type != RAD_LISTEN_DETAIL) &&
2943             !can_handle_new_request(packet, client, root)) {
2944                 return 0;
2945         }
2946
2947         /*
2948          *      Create and initialize the new request.
2949          */
2950         request = request_alloc(); /* never fails */
2951
2952         if ((request->reply = rad_alloc(0)) == NULL) {
2953                 radlog(L_ERR, "No memory");
2954                 exit(1);
2955         }
2956
2957         request->listener = listener;
2958         request->client = client;
2959         request->packet = packet;
2960         request->packet->timestamp = request->timestamp;
2961         request->number = request_num_counter++;
2962         request->priority = listener->type;
2963 #ifdef HAVE_PTHREAD_H
2964         request->child_pid = NO_SUCH_CHILD_PID;
2965 #endif
2966
2967         /*
2968          *      Status-Server packets go to the head of the queue.
2969          */
2970         if (request->packet->code == PW_STATUS_SERVER) request->priority = 0;
2971
2972         /*
2973          *      Set virtual server identity
2974          */
2975         if (client->server) {
2976                 request->server = client->server;
2977         } else if (listener->server) {
2978                 request->server = listener->server;
2979         } else {
2980                 request->server = NULL;
2981         }
2982
2983         /*
2984          *      Remember the request in the list.
2985          */
2986         if (!fr_packet_list_insert(pl, &request->packet)) {
2987                 radlog(L_ERR, "Failed to insert request %d in the list of live requests: discarding", request->number);
2988                 ev_request_free(&request);
2989                 return 0;
2990         }
2991
2992         request->in_request_hash = TRUE;
2993         request->root = root;
2994         root->refcount++;
2995 #ifdef WITH_TCP
2996         request->listener->count++;
2997 #endif
2998
2999         /*
3000          *      The request passes many of our sanity checks.
3001          *      From here on in, if anything goes wrong, we
3002          *      send a reject message, instead of dropping the
3003          *      packet.
3004          */
3005
3006         /*
3007          *      Build the reply template from the request.
3008          */
3009
3010         request->reply->sockfd = request->packet->sockfd;
3011         request->reply->dst_ipaddr = request->packet->src_ipaddr;
3012         request->reply->src_ipaddr = request->packet->dst_ipaddr;
3013         request->reply->dst_port = request->packet->src_port;
3014         request->reply->src_port = request->packet->dst_port;
3015         request->reply->id = request->packet->id;
3016         request->reply->code = 0; /* UNKNOWN code */
3017         memcpy(request->reply->vector, request->packet->vector,
3018                sizeof(request->reply->vector));
3019         request->reply->vps = NULL;
3020         request->reply->data = NULL;
3021         request->reply->data_len = 0;
3022
3023         request->master_state = REQUEST_ACTIVE;
3024         request->child_state = REQUEST_QUEUED;
3025         request->next_callback = NULL;
3026
3027         gettimeofday(&request->received, NULL);
3028         request->timestamp = request->received.tv_sec;
3029         request->when = request->received;
3030
3031         request->delay = USEC;
3032
3033         tv_add(&request->when, request->delay);
3034
3035         INSERT_EVENT(wait_a_bit, request);
3036
3037         *prequest = request;
3038         return 1;
3039 }
3040
3041
3042 #ifdef WITH_PROXY
3043 REQUEST *received_proxy_response(RADIUS_PACKET *packet)
3044 {
3045         char            buffer[128];
3046         REQUEST         *request;
3047
3048         /*
3049          *      Also removes from the proxy hash if responses == requests
3050          */
3051         request = lookup_in_proxy_hash(packet);
3052
3053         if (!request) {
3054                 radlog(L_PROXY, "No outstanding request was found for reply from host %s port %d - ID %d",
3055                        inet_ntop(packet->src_ipaddr.af,
3056                                  &packet->src_ipaddr.ipaddr,
3057                                  buffer, sizeof(buffer)),
3058                        packet->src_port, packet->id);
3059                 return NULL;
3060         }
3061
3062         /*
3063          *      We haven't replied to the NAS, but we have seen an
3064          *      earlier reply from the home server.  Ignore this packet,
3065          *      as we're likely still processing the previous reply.
3066          */
3067         if (request->proxy_reply) {
3068                 if (memcmp(request->proxy_reply->vector,
3069                            packet->vector,
3070                            sizeof(request->proxy_reply->vector)) == 0) {
3071                         RDEBUG2("Discarding duplicate reply from host %s port %d  - ID: %d for request %d",
3072                                inet_ntop(packet->src_ipaddr.af,
3073                                          &packet->src_ipaddr.ipaddr,
3074                                          buffer, sizeof(buffer)),
3075                                packet->src_port, packet->id,
3076                                request->number);
3077                 } else {
3078                         /*
3079                          *      ? The home server gave us a new proxy
3080                          *      reply which doesn't match the old
3081                          *      one.  Delete it.
3082                          */
3083                         RDEBUG2("Ignoring conflicting proxy reply");
3084                 }
3085                 
3086                 /* assert that there's an event queued for request? */
3087                 return NULL;
3088         }
3089
3090         /*
3091          *      Verify the packet before doing ANYTHING with it.  This
3092          *      means we're doing more MD5 checks in the server core.
3093          *      However, we can fix that by moving to multiple threads
3094          *      listening on sockets.
3095          *
3096          *      We do this AFTER looking the request up in the hash,
3097          *      and AFTER vhecking if we saw a previous request.  This
3098          *      helps minimize the DoS effect of people attacking us
3099          *      with spoofed packets.
3100          */
3101         if (rad_verify(packet, request->proxy,
3102                        request->home_server->secret) != 0) {
3103                 DEBUG("Ignoring spoofed proxy reply.  Signature is invalid");
3104                 return NULL;
3105         }
3106
3107         gettimeofday(&now, NULL);
3108
3109         /*
3110          *      Maybe move this earlier in the decision process?
3111          *      Having it here means that late or duplicate proxy
3112          *      replies no longer get the home server marked as
3113          *      "alive".  This might be good for stability, though.
3114          *
3115          *      FIXME: Do we really want to do this whenever we
3116          *      receive a packet?  Setting this here means that we
3117          *      mark it alive on *any* packet, even if it's lost all
3118          *      of the *other* packets in the last 10s.
3119          */
3120         request->home_server->state = HOME_STATE_ALIVE;
3121         
3122 #ifdef WITH_COA
3123         /*
3124          *      When originating CoA, the "proxy" reply is the reply
3125          *      to the CoA request that we originated.  At this point,
3126          *      the original request is finished, and it has a reply.
3127          *
3128          *      However, if we haven't separated the two requests, do
3129          *      so now.  This is done so that cleaning up the original
3130          *      request won't cause the CoA request to be free'd.  See
3131          *      util.c, request_free()
3132          */
3133         if (request->parent && (request->parent->coa == request)) {
3134                 request->parent->coa = NULL;
3135                 request->parent = NULL;
3136
3137         } else
3138                 /*
3139                  *      Skip the next set of checks, as the original
3140                  *      reply is cached.  We want to be able to still
3141                  *      process the CoA reply, AND to reference the
3142                  *      original request/reply.
3143                  *
3144                  *      This is getting to be really quite a bit of a
3145                  *      hack.
3146                  */
3147 #endif
3148
3149         /*
3150          *      If there's a reply to the NAS, ignore everything
3151          *      related to proxy responses
3152          */
3153         if (request->reply && request->reply->code != 0) {
3154                 RDEBUG2("Ignoring proxy reply that arrived after we sent a reply to the NAS");
3155                 return NULL;
3156         }
3157         
3158 #ifdef WITH_STATS
3159         /*
3160          *      The average includes our time to receive packets and
3161          *      look them up in the hashes, which should be the same
3162          *      for all packets.
3163          *
3164          *      We update the response time only for the FIRST packet
3165          *      we receive.
3166          */
3167         if (request->home_server->ema.window > 0) {
3168                 radius_stats_ema(&request->home_server->ema,
3169                                  &now, &request->proxy_when);
3170         }
3171 #endif
3172
3173         switch (request->child_state) {
3174         case REQUEST_QUEUED:
3175         case REQUEST_RUNNING:
3176                 radlog(L_ERR, "Internal sanity check failed for child state");
3177                 /* FALL-THROUGH */
3178
3179         case REQUEST_REJECT_DELAY:
3180         case REQUEST_CLEANUP_DELAY:
3181         case REQUEST_DONE:
3182                 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'",
3183                        inet_ntop(packet->src_ipaddr.af,
3184                                  &packet->src_ipaddr.ipaddr,
3185                                  buffer, sizeof(buffer)),
3186                        packet->src_port, packet->id,
3187                        request->number);
3188                 /* assert that there's an event queued for request? */
3189                 return NULL;
3190
3191         case REQUEST_PROXIED:
3192                 break;
3193         }
3194
3195         request->proxy_reply = packet;
3196
3197 #if 0
3198         /*
3199          *      Perform RTT calculations, as per RFC 2988 (for TCP).
3200          *      Note that we only do so on the first response.
3201          */
3202         if ((request->num_proxied_responses == 1)
3203                 int rtt;
3204                 home_server *home = request->home_server;
3205
3206                 rtt = now.tv_sec - request->proxy_when.tv_sec;
3207                 rtt *= USEC;
3208                 rtt += now.tv_usec;
3209                 rtt -= request->proxy_when.tv_usec;
3210
3211                 if (!home->has_rtt) {
3212                         home->has_rtt = TRUE;
3213
3214                         home->srtt = rtt;
3215                         home->rttvar = rtt / 2;
3216
3217                 } else {
3218                         home->rttvar -= home->rttvar >> 2;
3219                         home->rttvar += (home->srtt - rtt);
3220                         home->srtt -= home->srtt >> 3;
3221                         home->srtt += rtt >> 3;
3222                 }
3223
3224                 home->rto = home->srtt;
3225                 if (home->rttvar > (USEC / 4)) {
3226                         home->rto += home->rttvar * 4;
3227                 } else {
3228                         home->rto += USEC;
3229                 }
3230         }
3231 #endif
3232
3233         /*
3234          *      There's no incoming request, so it's a proxied packet
3235          *      we originated.
3236          */
3237         if (!request->packet) {
3238                 received_response_to_ping(request);
3239                 request->proxy_reply = NULL; /* caller will free it */
3240                 ev_request_free(&request);
3241                 return NULL;
3242         }
3243
3244         request->child_state = REQUEST_QUEUED;
3245         request->when = now;
3246         request->delay = USEC;
3247         request->priority = RAD_LISTEN_PROXY;
3248         tv_add(&request->when, request->delay);
3249
3250         /*
3251          *      Wait a bit will take care of max_request_time
3252          */
3253         INSERT_EVENT(wait_a_bit, request);
3254
3255         return request;
3256 }
3257
3258 #endif /* WITH_PROXY */
3259
3260 #ifdef WITH_TCP
3261 static void tcp_socket_lifetime(void *ctx)
3262 {
3263         rad_listen_t *listener = ctx;
3264         char buffer[256];
3265
3266         listener->print(listener, buffer, sizeof(buffer));
3267
3268         DEBUG("Reached maximum lifetime on socket %s", buffer);
3269
3270         listener->status = RAD_LISTEN_STATUS_CLOSED;
3271         event_new_fd(listener);
3272 }
3273
3274 static void tcp_socket_idle_timeout(void *ctx)
3275 {
3276         rad_listen_t *listener = ctx;
3277         listen_socket_t *sock = listener->data;
3278         char buffer[256];
3279
3280         fr_event_now(el, &now); /* should always succeed... */
3281
3282         rad_assert(sock->home != NULL);
3283
3284         /*
3285          *      We implement idle timeout by polling, because it's
3286          *      cheaper than resetting the idle timeout every time
3287          *      we send / receive a packet.
3288          */
3289         if ((sock->last_packet + sock->home->idle_timeout) > now.tv_sec) {
3290                 struct timeval when;
3291                 void *fun = tcp_socket_idle_timeout;
3292                 
3293                 when.tv_sec = sock->last_packet;
3294                 when.tv_sec += sock->home->idle_timeout;
3295                 when.tv_usec = 0;
3296
3297                 if (sock->home->lifetime &&
3298                     (sock->opened + sock->home->lifetime < when.tv_sec)) {
3299                         when.tv_sec = sock->opened + sock->home->lifetime;
3300                         fun = tcp_socket_lifetime;
3301                 }
3302                 
3303                 if (!fr_event_insert(el, fun, listener, &when, &sock->ev)) {
3304                         rad_panic("Failed to insert event");
3305                 }
3306
3307                 return;
3308         }
3309
3310         listener->print(listener, buffer, sizeof(buffer));
3311         
3312         DEBUG("Reached idle timeout on socket %s", buffer);
3313
3314         listener->status = RAD_LISTEN_STATUS_CLOSED;
3315         event_new_fd(listener);
3316 }
3317 #endif
3318
3319 void event_new_fd(rad_listen_t *this)
3320 {
3321         char buffer[1024];
3322
3323         if (this->status == RAD_LISTEN_STATUS_KNOWN) return;
3324
3325         this->print(this, buffer, sizeof(buffer));
3326
3327         if (this->status == RAD_LISTEN_STATUS_INIT) {
3328                 if (just_started) {
3329                         DEBUG("Listening on %s", buffer);
3330                 } else {
3331                         DEBUG2(" ... adding new socket %s", buffer);
3332                 }
3333
3334 #ifdef WITH_PROXY
3335                 /*
3336                  *      Add it to the list of sockets we can use.
3337                  *      Server sockets (i.e. auth/acct) are never
3338                  *      added to the packet list.
3339                  */
3340                 if (this->type == RAD_LISTEN_PROXY) {
3341                         listen_socket_t *sock = this->data;
3342
3343                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3344                         if (!fr_packet_list_socket_add(proxy_list, this->fd,
3345                                                        &sock->other_ipaddr, sock->other_port,
3346                                                        this)) {
3347                                 radlog(L_ERR, "Fatal error adding socket: %s",
3348                                        fr_strerror());
3349                                 exit(1);
3350
3351                         }
3352
3353                         if (sock->home) {
3354                                 sock->home->num_connections++;
3355                                 
3356                                 /*
3357                                  *      If necessary, add it to the list of
3358                                  *      new proxy listeners.
3359                                  */
3360                                 if (sock->home->lifetime || sock->home->idle_timeout) {
3361                                         this->next = proxy_listener_list;
3362                                         proxy_listener_list = this;
3363                                 }
3364                         }
3365                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3366
3367                         /*
3368                          *      Tell the main thread that we've added
3369                          *      a proxy listener, but only if we need
3370                          *      to update the event list.  Do this
3371                          *      with the mutex unlocked, to reduce
3372                          *      contention.
3373                          */
3374                         if (sock->home) {
3375                                 if (sock->home->lifetime || sock->home->idle_timeout) {
3376                                         radius_signal_self(RADIUS_SIGNAL_SELF_NEW_FD);
3377                                 }
3378                         }
3379                 }
3380 #endif          
3381
3382 #ifdef WITH_DETAIL
3383                 /*
3384                  *      Detail files are always known, and aren't
3385                  *      put into the socket event loop.
3386                  */
3387                 if (this->type == RAD_LISTEN_DETAIL) {
3388                         this->status = RAD_LISTEN_STATUS_KNOWN;
3389                         
3390                         /*
3391                          *      Set up the first poll interval.
3392                          */
3393                         event_poll_detail(this);
3394                         return;
3395                 }
3396 #endif
3397
3398                 FD_MUTEX_LOCK(&fd_mutex);
3399                 if (!fr_event_fd_insert(el, 0, this->fd,
3400                                         event_socket_handler, this)) {
3401                         radlog(L_ERR, "Failed remembering handle for proxy socket!");
3402                         exit(1);
3403                 }
3404                 FD_MUTEX_UNLOCK(&fd_mutex);
3405                 
3406                 this->status = RAD_LISTEN_STATUS_KNOWN;
3407                 return;
3408         }
3409
3410         /*
3411          *      Something went wrong with the socket: make it harmless.
3412          */
3413         if (this->status == RAD_LISTEN_STATUS_REMOVE_FD) {
3414                 int devnull;
3415
3416                 /*
3417                  *      Remove it from the list of live FD's.
3418                  */
3419                 FD_MUTEX_LOCK(&fd_mutex);
3420                 fr_event_fd_delete(el, 0, this->fd);
3421                 FD_MUTEX_UNLOCK(&fd_mutex);
3422
3423 #ifdef WITH_PROXY
3424                 if (this->type != RAD_LISTEN_PROXY)
3425 #endif
3426                 {
3427                         if (this->count != 0) {
3428                                 fr_packet_list_walk(pl, this,
3429                                                     remove_all_requests);
3430                         }
3431
3432                         if (this->count == 0) {
3433                                 this->status = RAD_LISTEN_STATUS_FINISH;
3434                                 goto finish;
3435                         }
3436                 }               
3437 #ifdef WITH_PROXY
3438                 else {
3439                         int count = this->count;
3440
3441                         /*
3442                          *      Duplicate code
3443                          */
3444                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3445                         if (!fr_packet_list_socket_freeze(proxy_list,
3446                                                           this->fd)) {
3447                                 radlog(L_ERR, "Fatal error freezing socket: %s",
3448                                        fr_strerror());
3449                                 exit(1);
3450                         }
3451
3452                         /*
3453                          *      Doing this with the proxy mutex held
3454                          *      is a Bad Thing.  We should move to
3455                          *      finer-grained mutexes.
3456                          */
3457                         count = this->count;
3458                         if (count > 0) {
3459                                 fr_packet_list_walk(proxy_list, this,
3460                                                     remove_all_proxied_requests);
3461                         }
3462                         count = this->count; /* protected by mutex */
3463                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3464
3465                         if (count == 0) {
3466                                 this->status = RAD_LISTEN_STATUS_FINISH;
3467                                 goto finish;
3468                         }
3469                 }
3470 #endif
3471
3472                 /*
3473                  *      Re-open the socket, pointing it to /dev/null.
3474                  *      This means that all writes proceed without
3475                  *      blocking, and all reads return "no data".
3476                  *
3477                  *      This leaves the socket active, so any child
3478                  *      threads won't go insane.  But it means that
3479                  *      they cannot send or receive any packets.
3480                  *
3481                  *      This is EXTRA work in the normal case, when
3482                  *      sockets are closed without error.  But it lets
3483                  *      us have one simple processing method for all
3484                  *      sockets.
3485                  */
3486                 devnull = open("/dev/null", O_RDWR);
3487                 if (devnull < 0) {
3488                         radlog(L_ERR, "FATAL failure opening /dev/null: %s",
3489                                strerror(errno));
3490                         exit(1);
3491                 }
3492                 if (dup2(devnull, this->fd) < 0) {
3493                         radlog(L_ERR, "FATAL failure closing socket: %s",
3494                                strerror(errno));
3495                         exit(1);
3496                 }
3497                 close(devnull);
3498
3499                 this->status = RAD_LISTEN_STATUS_CLOSED;
3500
3501                 /*
3502                  *      Fall through to the next section.
3503                  */
3504         }
3505
3506         /*
3507          *      Called ONLY from the main thread.  On the following
3508          *      conditions:
3509          *
3510          *      idle timeout
3511          *      max lifetime
3512          *
3513          *      (and falling through from "forcibly close FD" above)
3514          *      client closed connection on us
3515          *      client sent us a bad packet.
3516          */
3517         if (this->status == RAD_LISTEN_STATUS_CLOSED) {
3518                 int count = this->count;
3519                 rad_assert(this->type != RAD_LISTEN_DETAIL);
3520
3521 #ifdef WITH_PROXY
3522                 /*
3523                  *      Remove it from the list of active sockets, so
3524                  *      that it isn't used when proxying new packets.
3525                  */
3526                 if (this->type == RAD_LISTEN_PROXY) {
3527                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3528                         if (!fr_packet_list_socket_freeze(proxy_list,
3529                                                           this->fd)) {
3530                                 radlog(L_ERR, "Fatal error freezing socket: %s",
3531                                        fr_strerror());
3532                                 exit(1);
3533                         }
3534                         count = this->count; /* protected by mutex */
3535                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3536                 }
3537 #endif
3538
3539                 /*
3540                  *      Requests are still using the socket.  Wait for
3541                  *      them to finish.
3542                  */
3543                 if (count != 0) {
3544                         struct timeval when;
3545                         listen_socket_t *sock = this->data;
3546
3547                         /*
3548                          *      Try again to clean up the socket in 30
3549                          *      seconds.
3550                          */
3551                         gettimeofday(&when, NULL);
3552                         when.tv_sec += 30;
3553                         
3554                         if (!fr_event_insert(el,
3555                                              (fr_event_callback_t) event_new_fd,
3556                                              this, &when, &sock->ev)) {
3557                                 rad_panic("Failed to insert event");
3558                         }
3559                        
3560                         return;
3561                 }
3562
3563                 /*
3564                  *      No one is using this socket: we can delete it
3565                  *      immediately.
3566                  */
3567                 this->status = RAD_LISTEN_STATUS_FINISH;
3568         }
3569         
3570 finish:
3571         if (this->status == RAD_LISTEN_STATUS_FINISH) {
3572                 listen_socket_t *sock = this->data;
3573
3574                 rad_assert(this->count == 0);
3575                 DEBUG2(" ... closing socket %s", buffer);
3576
3577                 /*
3578                  *      Remove it from the list of live FD's.  Note
3579                  *      that it MAY also have been removed above.  We
3580                  *      do it again here, to catch the case of sockets
3581                  *      closing on idle timeout, or max
3582                  *      lifetime... AFTER all requests have finished
3583                  *      using it.
3584                  */
3585                 FD_MUTEX_LOCK(&fd_mutex);
3586                 fr_event_fd_delete(el, 0, this->fd);
3587                 FD_MUTEX_UNLOCK(&fd_mutex);
3588                 
3589 #ifdef WITH_PROXY
3590                 /*
3591                  *      Remove it from the list of sockets to be used
3592                  *      when proxying.
3593                  */
3594                 if (this->type == RAD_LISTEN_PROXY) {
3595                         PTHREAD_MUTEX_LOCK(&proxy_mutex);
3596                         if (!fr_packet_list_socket_remove(proxy_list,
3597                                                           this->fd, NULL)) {
3598                                 radlog(L_ERR, "Fatal error removing socket: %s",
3599                                        fr_strerror());
3600                                 exit(1);
3601                         }
3602                         if (sock->home) sock->home->num_connections--;
3603                         PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3604                 }
3605 #endif
3606
3607                 /*
3608                  *      Remove any pending cleanups.
3609                  */
3610                 if (sock->ev) fr_event_delete(el, &sock->ev);
3611
3612                 /*
3613                  *      And finally, close the socket.
3614                  */
3615                 listen_free(&this);
3616         }
3617 }
3618
3619 static void handle_signal_self(int flag)
3620 {
3621         if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
3622                 if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
3623                         fr_event_loop_exit(el, 1);
3624                 } else {
3625                         fr_event_loop_exit(el, 2);
3626                 }
3627
3628                 return;
3629         } /* else exit/term flags weren't set */
3630
3631         /*
3632          *      Tell the even loop to stop processing.
3633          */
3634         if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
3635                 time_t when;
3636                 static time_t last_hup = 0;
3637
3638                 DEBUG("Received HUP signal.");
3639
3640                 when = time(NULL);
3641                 if ((int) (when - last_hup) < 5) {
3642                         radlog(L_INFO, "Ignoring HUP (less than 5s since last one)");
3643                         return;
3644                 }
3645                 last_hup = when;
3646
3647                 fr_event_loop_exit(el, 0x80);
3648         }
3649
3650 #ifdef WITH_DETAIL
3651         if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
3652                 rad_listen_t *this;
3653                 
3654                 /*
3655                  *      FIXME: O(N) loops suck.
3656                  */
3657                 for (this = mainconfig.listen;
3658                      this != NULL;
3659                      this = this->next) {
3660                         if (this->type != RAD_LISTEN_DETAIL) continue;
3661
3662                         /*
3663                          *      This one didn't send the signal, skip
3664                          *      it.
3665                          */
3666                         if (!this->decode(this, NULL)) continue;
3667
3668                         /*
3669                          *      Go service the interrupt.
3670                          */
3671                         event_poll_detail(this);
3672                 }
3673         }
3674 #endif
3675
3676 #ifdef WITH_PROXY
3677         /*
3678          *      Add event handlers for idle timeouts && maximum lifetime.XXX
3679          */
3680         if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
3681                 struct timeval when;
3682                 void *fun = NULL;
3683
3684                 if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3685
3686                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
3687
3688                 while (proxy_listener_list) {
3689                         rad_listen_t *this = proxy_listener_list;
3690                         listen_socket_t *sock = this->data;
3691
3692                         proxy_listener_list = this->next;
3693                         this->next = NULL;
3694
3695                         if (!sock->home) continue; /* skip UDP sockets */
3696
3697                         when = now;
3698
3699                         if (!sock->home->idle_timeout) {
3700                                 rad_assert(sock->home->lifetime != 0);
3701
3702                                 when.tv_sec += sock->home->lifetime;
3703                                 fun = tcp_socket_lifetime;
3704                         } else {
3705                                 rad_assert(sock->home->idle_timeout != 0);
3706
3707                                 when.tv_sec += sock->home->idle_timeout;
3708                                 fun = tcp_socket_idle_timeout;
3709                         }
3710
3711                         if (!fr_event_insert(el, fun, this, &when,
3712                                              &(sock->ev))) {
3713                                 rad_panic("Failed to insert event");
3714                         }
3715                 }
3716
3717                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
3718         }
3719 #endif
3720 }
3721
3722 #ifndef WITH_SELF_PIPE
3723 void radius_signal_self(int flag)
3724 {
3725         handle_signal_self(flag);
3726 }
3727 #else
3728 /*
3729  *      Inform ourselves that we received a signal.
3730  */
3731 void radius_signal_self(int flag)
3732 {
3733         ssize_t rcode;
3734         uint8_t buffer[16];
3735
3736         /*
3737          *      The read MUST be non-blocking for this to work.
3738          */
3739         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3740         if (rcode > 0) {
3741                 ssize_t i;
3742
3743                 for (i = 0; i < rcode; i++) {
3744                         buffer[0] |= buffer[i];
3745                 }
3746         } else {
3747                 buffer[0] = 0;
3748         }
3749
3750         buffer[0] |= flag;
3751
3752         write(self_pipe[1], buffer, 1);
3753 }
3754
3755
3756 static void event_signal_handler(UNUSED fr_event_list_t *xel,
3757                                  UNUSED int fd, UNUSED void *ctx)
3758 {
3759         ssize_t i, rcode;
3760         uint8_t buffer[32];
3761
3762         rcode = read(self_pipe[0], buffer, sizeof(buffer));
3763         if (rcode <= 0) return;
3764
3765         /*
3766          *      Merge pending signals.
3767          */
3768         for (i = 0; i < rcode; i++) {
3769                 buffer[0] |= buffer[i];
3770         }
3771
3772         handle_signal_self(buffer[0]);
3773 }
3774 #endif
3775
3776
3777 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd,
3778                                  void *ctx)
3779 {
3780         rad_listen_t *listener = ctx;
3781         RAD_REQUEST_FUNP fun;
3782         REQUEST *request;
3783
3784         rad_assert(xel == el);
3785
3786         xel = xel;
3787
3788         if (listener->fd < 0) rad_panic("Socket was closed on us!");
3789         
3790         if (!listener->recv(listener, &fun, &request)) return;
3791
3792         if (!thread_pool_addrequest(request, fun)) {
3793                 request->child_state = REQUEST_DONE;
3794         }
3795 }
3796
3797 typedef struct listen_detail_t {
3798         fr_event_t      *ev;
3799 } listen_detail_t;
3800
3801 /*
3802  *      This function is called periodically to see if this detail
3803  *      file is available for reading.
3804  */
3805 static void event_poll_detail(void *ctx)
3806 {
3807         int rcode, delay;
3808         RAD_REQUEST_FUNP fun;
3809         REQUEST *request;
3810         rad_listen_t *this = ctx;
3811         struct timeval when;
3812         listen_detail_t *detail = this->data;
3813
3814         rad_assert(this->type == RAD_LISTEN_DETAIL);
3815
3816         /*
3817          *      Try to read something.
3818          *
3819          *      FIXME: This does poll AND receive.
3820          */
3821         rcode = this->recv(this, &fun, &request);
3822         if (rcode != 0) {
3823                 rad_assert(fun != NULL);
3824                 rad_assert(request != NULL);
3825                 
3826                 if (!thread_pool_addrequest(request, fun)) {
3827                         request->child_state = REQUEST_DONE;
3828                 }
3829         }
3830
3831         if (!fr_event_now(el, &now)) gettimeofday(&now, NULL);
3832         when = now;
3833
3834         /*
3835          *      Backdoor API to get the delay until the next poll
3836          *      time.
3837          */
3838         delay = this->encode(this, NULL);
3839         tv_add(&when, delay);
3840
3841         if (!fr_event_insert(el, event_poll_detail, this,
3842                              &when, &detail->ev)) {
3843                 radlog(L_ERR, "Failed creating handler");
3844                 exit(1);
3845         }
3846 }
3847
3848
3849 static void event_status(struct timeval *wake)
3850 {
3851 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3852         int argval;
3853 #endif
3854
3855         if (debug_flag == 0) {
3856                 if (just_started) {
3857                         radlog(L_INFO, "Ready to process requests.");
3858                         just_started = FALSE;
3859                 }
3860                 return;
3861         }
3862
3863         if (!wake) {
3864                 DEBUG("Ready to process requests.");
3865
3866         } else if ((wake->tv_sec != 0) ||
3867                    (wake->tv_usec >= 100000)) {
3868                 DEBUG("Waking up in %d.%01u seconds.",
3869                       (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
3870         }
3871
3872
3873         /*
3874          *      FIXME: Put this somewhere else, where it isn't called
3875          *      all of the time...
3876          */
3877
3878 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
3879         /*
3880          *      If there are no child threads, then there may
3881          *      be child processes.  In that case, wait for
3882          *      their exit status, and throw that exit status
3883          *      away.  This helps get rid of zxombie children.
3884          */
3885         while (waitpid(-1, &argval, WNOHANG) > 0) {
3886                 /* do nothing */
3887         }
3888 #endif
3889
3890 }
3891
3892 /*
3893  *      Externally-visibly functions.
3894  */
3895 int radius_event_init(CONF_SECTION *cs, int spawn_flag)
3896 {
3897         rad_listen_t *head = NULL;
3898
3899         if (el) return 0;
3900
3901         time(&fr_start_time);
3902
3903         el = fr_event_list_create(event_status);
3904         if (!el) return 0;
3905
3906         pl = fr_packet_list_create(0);
3907         if (!pl) return 0;      /* leak el */
3908
3909         request_num_counter = 0;
3910
3911 #ifdef WITH_PROXY
3912         if (mainconfig.proxy_requests) {
3913                 pthread_mutexattr_t attr;
3914
3915                 /*
3916                  *      Create the tree for managing proxied requests and
3917                  *      responses.
3918                  */
3919                 proxy_list = fr_packet_list_create(1);
3920                 if (!proxy_list) return 0;
3921
3922 #ifdef HAVE_PTHREAD_H
3923                 pthread_mutexattr_init(&attr);
3924
3925 #ifdef PTHREAD_MUTEX_RECURSIVE
3926                 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) < 0) {
3927                         radlog(L_ERR, "FATAL: Failed to set type for proxy mutex: %s",
3928                                strerror(errno));
3929                         exit(1);
3930                 }
3931 #endif
3932
3933                 if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
3934                         radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
3935                                strerror(errno));
3936                         exit(1);
3937                 }
3938
3939                 pthread_mutexattr_destroy(&attr);
3940 #endif
3941         }
3942 #endif
3943
3944         /*
3945          *      Just before we spawn the child threads, force the log
3946          *      subsystem to re-open the log file for every write.
3947          */
3948         if (spawn_flag) force_log_reopen();
3949
3950 #ifdef HAVE_PTHREAD_H
3951 #ifndef __MINGW32__
3952         NO_SUCH_CHILD_PID = (pthread_t ) (0);
3953 #else
3954         NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
3955 #endif
3956         /*
3957          *      Initialize the threads ONLY if we're spawning, AND
3958          *      we're running normally.
3959          */
3960         if (spawn_flag && !check_config &&
3961             (thread_pool_init(cs, &spawn_flag) < 0)) {
3962                 exit(1);
3963         }
3964 #endif
3965
3966         /*
3967          *      Move all of the thread calls to this file?
3968          *
3969          *      It may be best for the mutexes to be in this file...
3970          */
3971         have_children = spawn_flag;
3972
3973         if (check_config) {
3974                 DEBUG("%s: #### Skipping IP addresses and Ports ####",
3975                        mainconfig.name);
3976                 return 1;
3977         }
3978
3979 #ifdef WITH_SELF_PIPE
3980         /*
3981          *      Child threads need a pipe to signal us, as do the
3982          *      signal handlers.
3983          */
3984         if (pipe(self_pipe) < 0) {
3985                 radlog(L_ERR, "radiusd: Error opening internal pipe: %s",
3986                        strerror(errno));
3987                 exit(1);
3988         }
3989         if (fcntl(self_pipe[0], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3990                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3991                        strerror(errno));
3992                 exit(1);
3993         }
3994         if (fcntl(self_pipe[1], F_SETFL, O_NONBLOCK | FD_CLOEXEC) < 0) {
3995                 radlog(L_ERR, "radiusd: Error setting internal flags: %s",
3996                        strerror(errno));
3997                 exit(1);
3998         }
3999
4000         if (!fr_event_fd_insert(el, 0, self_pipe[0],
4001                                   event_signal_handler, el)) {
4002                 radlog(L_ERR, "Failed creating handler for signals");
4003                 exit(1);
4004         }
4005 #endif  /* WITH_SELF_PIPE */
4006
4007        DEBUG("%s: #### Opening IP addresses and Ports ####",
4008                mainconfig.name);
4009
4010        /*
4011         *       The server temporarily switches to an unprivileged
4012         *       user very early in the bootstrapping process.
4013         *       However, some sockets MAY require privileged access
4014         *       (bind to device, or to port < 1024, or to raw
4015         *       sockets).  Those sockets need to call suid up/down
4016         *       themselves around the functions that need a privileged
4017         *       uid.
4018         */
4019         if (listen_init(cs, &head) < 0) {
4020                 _exit(1);
4021         }
4022         
4023         mainconfig.listen = head;
4024
4025         /*
4026          *      At this point, no one has any business *ever* going
4027          *      back to root uid.
4028          */
4029         fr_suid_down_permanent();
4030
4031         return 1;
4032 }
4033
4034
4035 static int request_hash_cb(UNUSED void *ctx, void *data)
4036 {
4037         REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
4038
4039 #ifdef WITH_PROXY
4040         rad_assert(request->in_proxy_hash == FALSE);
4041 #endif
4042
4043         ev_request_free(&request);
4044
4045         return 0;
4046 }
4047
4048
4049 #ifdef WITH_PROXY
4050 static int proxy_hash_cb(UNUSED void *ctx, void *data)
4051 {
4052         REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4053
4054         ev_request_free(&request);
4055
4056         return 0;
4057 }
4058 #endif
4059
4060 void radius_event_free(void)
4061 {
4062         /*
4063          *      FIXME: Stop all threads, or at least check that
4064          *      they're all waiting on the semaphore, and the queues
4065          *      are empty.
4066          */
4067
4068 #ifdef WITH_PROXY
4069         /*
4070          *      There are requests in the proxy hash that aren't
4071          *      referenced from anywhere else.  Remove them first.
4072          */
4073         if (proxy_list) {
4074                 PTHREAD_MUTEX_LOCK(&proxy_mutex);
4075                 fr_packet_list_walk(proxy_list, NULL, proxy_hash_cb);
4076                 PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4077                 fr_packet_list_free(proxy_list);
4078                 proxy_list = NULL;
4079         }
4080 #endif
4081
4082         fr_packet_list_walk(pl, NULL, request_hash_cb);
4083
4084         fr_packet_list_free(pl);
4085         pl = NULL;
4086
4087         fr_event_list_free(el);
4088 }
4089
4090 int radius_event_process(void)
4091 {
4092         if (!el) return 0;
4093
4094         return fr_event_loop(el);
4095 }
4096
4097 void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun)
4098 {
4099         request->options = RAD_REQUEST_OPTION_DEBUG2;
4100
4101         if (request_pre_handler(request)) {
4102                 rad_assert(fun != NULL);
4103                 rad_assert(request != NULL);
4104                 
4105                 if (request->server) RDEBUG("server %s {",
4106                                             request->server != NULL ?
4107                                             request->server : ""); 
4108                 fun(request);
4109
4110                 if (request->server) RDEBUG("} # server %s",
4111                                              request->server != NULL ?
4112                                             request->server : "");
4113
4114                 request_post_handler(request);
4115         }
4116
4117         DEBUG2("Going to the next request");
4118         return;
4119 }