import from HEAD
[freeradius.git] / src / main / request_list.c
1 /*
2  * request_list.c       Hide the handling of the REQUEST list from
3  *                      the main server.
4  *
5  * Version:     $Id$
6  *
7  *   This program is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU General Public License as published by
9  *   the Free Software Foundation; either version 2 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This program is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with this program; if not, write to the Free Software
19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * Copyright 2003-2004  The FreeRADIUS server project
22  */
23 static const char rcsid[] = "$Id$";
24
25 #include "autoconf.h"
26 #include "libradius.h"
27
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "radiusd.h"
32 #include "rad_assert.h"
33 #include "request_list.h"
34 #include "radius_snmp.h"
35
36
37 /*
38  *      We keep the incoming requests in an array, indexed by ID.
39  *
40  *      Each array element contains a linked list of containers of
41  *      active requests, a count of the number of requests, and a time
42  *      at which the first request in the list must be serviced.
43  *
44  *      Note that we ALSO keep a tree view of the same data, below.
45  *      Both views are needed for the server to work optimally.
46  */
47 typedef struct REQNODE {
48         struct REQNODE *prev, *next;
49         REQUEST *req;
50 } REQNODE;
51
52 typedef struct REQUESTINFO {
53         REQNODE *first_request;
54         REQNODE *last_request;
55         int request_count;
56         time_t last_cleaned_list;
57 } REQUESTINFO;
58
59 static REQUESTINFO      request_list[256];
60
61 /*
62  *      Remember the next request at which we start walking
63  *      the list.
64  */
65 static REQUEST *last_request = NULL;
66
67 /*
68  *      It MAY make more sense here to key off of the packet ID, just
69  *      like the request_list.  Then again, saving another 8 lookups
70  *      (on average) isn't much of a problem.
71  *
72  *      The "request_cmp" function keys off of the packet ID first,
73  *      so the first 8 layers of the tree will be the fanned-out
74  *      tree for packet ID's.
75  */
76 static rbtree_t         *request_tree;
77
78 #ifdef HAVE_PTHREAD_H
79 static pthread_mutex_t  proxy_mutex;
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 #endif
87
88 /*
89  *      We keep track of packets we're proxying, keyed by
90  *      source socket, and destination ip/port, and Id.
91  */
92 static rbtree_t         *proxy_tree;
93
94 /*
95  *      We keep track of free/used Id's, by destination ip/port.
96  *
97  *      We need a different tree than above, because this one is NOT
98  *      keyed by Id.  Instead, we use this one to allocate Id's.
99  */
100 static rbtree_t         *proxy_id_tree;
101
102 /*
103  *      We keep the proxy FD's here.  The RADIUS Id's are marked
104  *      "allocated" per Id, via a bit per proxy FD.
105  */
106 static int              proxy_fds[32];
107
108 static uint32_t         proxy_ipaddr;
109
110 /*
111  *      We can use 256 RADIUS Id's per dst ipaddr/port, per server
112  *      socket.  So, to allocate them, we key off of dst ipaddr/port,
113  *      and then search the RADIUS Id's, looking for an unused socket.
114  *
115  *      We do NOT key off of socket fd's, here, either.  Instead,
116  *      we look for a free Id from a sockfd, any sockfd.
117  */
118 typedef struct proxy_id_t {
119         uint32_t        dst_ipaddr;
120         int             dst_port;
121
122         /*
123          *      FIXME: Allocate more proxy sockets when this gets full.
124          */
125         int             index;
126         uint32_t        mask;   /* of FD's we know about. */
127         uint32_t        id[1];  /* really id[256] */
128 } proxy_id_t;
129
130
131 /*
132  *      Find a matching entry in the proxy ID tree.
133  */
134 static int proxy_id_cmp(const void *one, const void *two)
135 {
136         const proxy_id_t *a = one;
137         const proxy_id_t *b = two;
138
139         /*
140          *      The following comparisons look weird, but it's
141          *      the only way to make the comparisons work.
142          */
143         if (a->dst_ipaddr < b->dst_ipaddr) return -1;
144         if (a->dst_ipaddr > b->dst_ipaddr) return +1;
145
146         if (a->dst_port < b->dst_port) return -1;
147         if (a->dst_port > b->dst_port) return +1;
148         
149         /*
150          *      Everything's equal.  Say so.
151          */
152         return 0;
153 }
154
155
156 /*
157  *      Compare two REQUEST data structures, based on a number
158  *      of criteria.
159  */
160 static int request_cmp(const void *one, const void *two)
161 {
162         const REQUEST *a = one;
163         const REQUEST *b = two;
164
165         /*
166          *      The following comparisons look weird, but it's
167          *      the only way to make the comparisons work.
168          */
169
170         /*
171          *      If the packets didn't arrive on the same socket,
172          *      they're not identical, no matter what their src/dst
173          *      ip/ports say.
174          */
175         if (a->packet->sockfd < b->packet->sockfd) return -1;
176         if (a->packet->sockfd > b->packet->sockfd) return +1;
177
178         if (a->packet->id < b->packet->id) return -1;
179         if (a->packet->id > b->packet->id) return +1;
180
181         if (a->packet->code < b->packet->code) return -1;
182         if (a->packet->code > b->packet->code) return +1;
183
184         if (a->packet->src_ipaddr < b->packet->src_ipaddr) return -1;
185         if (a->packet->src_ipaddr > b->packet->src_ipaddr) return +1;
186
187         if (a->packet->src_port < b->packet->src_port) return -1;
188         if (a->packet->src_port > b->packet->src_port) return +1;
189
190         /*
191          *      Hmm... we may be listening on IPADDR_ANY, in which case
192          *      the destination IP is important, too.
193          */
194         if (a->packet->dst_ipaddr < b->packet->dst_ipaddr) return -1;
195         if (a->packet->dst_ipaddr > b->packet->dst_ipaddr) return +1;
196
197         if (a->packet->dst_port < b->packet->dst_port) return -1;
198         if (a->packet->dst_port > b->packet->dst_port) return +1;
199
200         /*
201          *      Everything's equal.  Say so.
202          */
203         return 0;
204 }
205
206 /*
207  *      Compare two REQUEST data structures, based on a number
208  *      of criteria, for proxied packets.
209  */
210 static int proxy_cmp(const void *one, const void *two)
211 {
212         const REQUEST *a = one;
213         const REQUEST *b = two;
214
215         rad_assert(a->magic == REQUEST_MAGIC);
216         rad_assert(b->magic == REQUEST_MAGIC);
217
218         rad_assert(a->proxy != NULL);
219         rad_assert(b->proxy != NULL);
220
221         /*
222          *      The following code looks unreasonable, but it's
223          *      the only way to make the comparisons work.
224          */
225         if (a->proxy->sockfd < b->proxy->sockfd) return -1;
226         if (a->proxy->sockfd > b->proxy->sockfd) return +1;
227
228         if (a->proxy->id < b->proxy->id) return -1;
229         if (a->proxy->id > b->proxy->id) return +1;
230
231         /*
232          *      We've got to check packet codes, too.  But
233          *      this should be done later, by someone else...
234          */
235
236         if (a->proxy->dst_ipaddr < b->proxy->dst_ipaddr) return -1;
237         if (a->proxy->dst_ipaddr > b->proxy->dst_ipaddr) return +1;
238
239         if (a->proxy->dst_port < b->proxy->dst_port) return -1;
240         if (a->proxy->dst_port > b->proxy->dst_port) return +1;
241
242         /*
243          *      FIXME: Check the Proxy-State attribute, too.
244          *      This will help cut down on duplicates.
245          */
246
247         /*
248          *      Everything's equal.  Say so.
249          */
250         return 0;
251 }
252
253
254 /*
255  *      Initialize the request list.
256  */
257 int rl_init(void)
258 {
259         /*
260          *      Initialize the request_list[] array.
261          */
262         memset(request_list, 0, sizeof(request_list));
263
264         request_tree = rbtree_create(request_cmp, NULL, 0);
265         if (!request_tree) {
266                 rad_assert("FAIL" == NULL);
267         }
268
269         /*
270          *      Create the tree for managing proxied requests and
271          *      responses.
272          */
273         proxy_tree = rbtree_create(proxy_cmp, NULL, 1);
274         if (!proxy_tree) {
275                 rad_assert("FAIL" == NULL);
276         }
277
278         /*
279          *      Create the tree for allocating proxy ID's.
280          */
281         proxy_id_tree = rbtree_create(proxy_id_cmp, NULL, 0);
282         if (!proxy_id_tree) {
283                 rad_assert("FAIL" == NULL);
284         }
285
286 #ifdef HAVE_PTHREAD_H
287         /*
288          *      For now, always create the mutex.
289          *
290          *      Later, we can only create it if there are multiple threads.
291          */
292         if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
293                 radlog(L_ERR, "FATAL: Failed to initialize proxy mutex: %s",
294                        strerror(errno));
295                 exit(1);
296         }
297 #endif
298
299         /*
300          *      The Id allocation table is done by bits, so we have
301          *      32 bits per Id.  These bits indicate which entry
302          *      in the proxy_fds array is used for that Id.
303          *
304          *      This design allows 256*32 = 8k requests to be
305          *      outstanding to a home server, before something goes
306          *      wrong.
307          */
308         {
309                 int i;
310                 rad_listen_t *listener;
311
312                 /*
313                  *      Mark the Fd's as unused.
314                  */
315                 for (i = 0; i < 32; i++) proxy_fds[i] = -1;
316
317                 for (listener = mainconfig.listen;
318                      listener != NULL;
319                      listener = listener->next) {
320                         if (listener->type == RAD_LISTEN_PROXY) {
321                                 proxy_ipaddr = listener->ipaddr;
322                                 proxy_fds[listener->fd & 0x1f] = listener->fd;
323                                 break;
324                         }
325                 }
326         }
327
328         return 1;
329 }
330
331
332 /*
333  *      Delete a request from the proxy trees.
334  */
335 static void rl_delete_proxy(REQUEST *request, rbnode_t *node)
336 {
337         proxy_id_t      myid, *entry;
338
339         rad_assert(node != NULL);
340
341         rbtree_delete(proxy_tree, node);
342         
343         myid.dst_ipaddr = request->proxy->dst_ipaddr;
344         myid.dst_port = request->proxy->dst_port;
345
346         /*
347          *      Find the Id in the array of allocated Id's,
348          *      and delete it.
349          */
350         entry = rbtree_finddata(proxy_id_tree, &myid);
351         if (entry) {
352                 int i;
353
354                 DEBUG3(" proxy: de-allocating %08x:%d %d",
355                        entry->dst_ipaddr,
356                        entry->dst_port,
357                        request->proxy->id);
358
359                 /*
360                  *      Find the proxy socket associated with this
361                  *      Id.  We loop over all 32 proxy fd's, but we
362                  *      partially index by proxy fd's, which means
363                  *      that we almost always break out of the loop
364                  *      quickly.
365                  */
366                 for (i = 0; i < 32; i++) {
367                         int offset;
368
369                         offset = (request->proxy->sockfd + i) & 0x1f;
370                   
371                         if (proxy_fds[offset] == request->proxy->sockfd) {
372                                 
373                                 entry->id[request->proxy->id] &= ~(1 << offset);
374                                 break;
375                         }
376                 } /* else die horribly? */
377         } else {
378                 /*
379                  *      Hmm... not sure what to do here.
380                  */
381                 DEBUG3(" proxy: FAILED TO FIND %08x:%d %d",
382                        myid.dst_ipaddr,
383                        myid.dst_port,
384                        request->proxy->id);
385         }
386 }
387
388
389 /*
390  *      Delete a particular request.
391  */
392 void rl_delete(REQUEST *request)
393 {
394         int id;
395         REQNODE *prev, *next;
396
397         prev = ((REQNODE *) request->container)->prev;
398         next = ((REQNODE *) request->container)->next;
399
400         id = request->packet->id;
401
402         /*
403          *      Update the last request we touched.
404          *
405          *      This is so the periodic "walk & clean list"
406          *      function, below, doesn't walk over all requests
407          *      all of the time.  Rather, it tries to amortize
408          *      the cost...
409          */
410         if (last_request == request) {
411                 last_request = rl_next(last_request);
412         }
413
414
415         if (prev == NULL) {
416                 request_list[id].first_request = next;
417         } else {
418                 prev->next = next;
419         }
420
421         if (next == NULL) {
422                 request_list[id].last_request = prev;
423         } else {
424                 next->prev = prev;
425         }
426
427         free(request->container);
428
429 #ifdef WITH_SNMP
430         /*
431          *      Update the SNMP statistics.
432          *
433          *      Note that we do NOT do this in rad_respond(),
434          *      as that function is called from child threads.
435          *      Instead, we update the stats when a request is
436          *      deleted, because only the main server thread calls
437          *      this function...
438          */
439         if (mainconfig.do_snmp) {
440                 switch (request->reply->code) {
441                 case PW_AUTHENTICATION_ACK:
442                   rad_snmp.auth.total_responses++;
443                   rad_snmp.auth.total_access_accepts++;
444                   break;
445
446                 case PW_AUTHENTICATION_REJECT:
447                   rad_snmp.auth.total_responses++;
448                   rad_snmp.auth.total_access_rejects++;
449                   break;
450
451                 case PW_ACCESS_CHALLENGE:
452                   rad_snmp.auth.total_responses++;
453                   rad_snmp.auth.total_access_challenges++;
454                   break;
455
456                 case PW_ACCOUNTING_RESPONSE:
457                   rad_snmp.acct.total_responses++;
458                   break;
459
460                 default:
461                         break;
462                 }
463         }
464 #endif
465
466         /*
467          *      Delete the request from the tree.
468          */
469         {
470                 rbnode_t *node;
471
472                 node = rbtree_find(request_tree, request);
473                 rad_assert(node != NULL);
474                 rbtree_delete(request_tree, node);
475
476
477                 /*
478                  *      If there's a proxied packet, and we're still
479                  *      waiting for a reply, then delete the packet
480                  *      from the list of outstanding proxied requests.
481                  */
482                 if (request->proxy &&
483                     (request->proxy_outstanding > 0)) {
484                         pthread_mutex_lock(&proxy_mutex);
485                         node = rbtree_find(proxy_tree, request);
486                         rl_delete_proxy(request, node);
487                         pthread_mutex_unlock(&proxy_mutex);
488                 }
489         }
490
491         request_free(&request);
492         request_list[id].request_count--;
493
494 }
495
496 /*
497  *      Add a request to the request list.
498  */
499 void rl_add(REQUEST *request)
500 {
501         int id = request->packet->id;
502         REQNODE *node;
503
504         rad_assert(request->container == NULL);
505
506         request->container = rad_malloc(sizeof(REQNODE));
507         node = (REQNODE *) request->container;
508         node->req = request;
509
510         node->prev = NULL;
511         node->next = NULL;
512
513         if (!request_list[id].first_request) {
514                 rad_assert(request_list[id].request_count == 0);
515
516                 request_list[id].first_request = node;
517                 request_list[id].last_request = node;
518         } else {
519                 rad_assert(request_list[id].request_count != 0);
520
521                 node->prev = request_list[id].last_request;
522                 request_list[id].last_request->next = node;
523                 request_list[id].last_request = node;
524         }
525
526         /*
527          *      Insert the request into the tree.
528          */
529         if (rbtree_insert(request_tree, request) == 0) {
530                 rad_assert("FAIL" == NULL);
531         }
532
533         request_list[id].request_count++;
534 }
535
536 /*
537  *      Look up a particular request, using:
538  *
539  *      Request ID, request code, source IP, source port,
540  *
541  *      Note that we do NOT use the request vector to look up requests.
542  *
543  *      We MUST NOT have two requests with identical (id/code/IP/port), and
544  *      different vectors.  This is a serious error!
545  */
546 REQUEST *rl_find(RADIUS_PACKET *packet)
547 {
548         REQUEST myrequest;
549
550         myrequest.packet = packet;
551
552         return rbtree_finddata(request_tree, &myrequest);
553 }
554
555 /*
556  *      See mainconfig.c
557  */
558 extern int proxy_new_listener(void);
559
560 /*
561  *      Add an entry to the proxy tree.
562  *
563  *      This is the ONLY function in this source file which may be called
564  *      from a child thread.  It therefore needs mutexes...
565  */
566 int rl_add_proxy(REQUEST *request)
567 {
568         int             i, found, proxy;
569         uint32_t        mask;
570         proxy_id_t      myid, *entry;
571
572         myid.dst_ipaddr = request->proxy->dst_ipaddr;
573         myid.dst_port = request->proxy->dst_port;
574
575         /*
576          *      Proxied requests get sent out the proxy FD ONLY.
577          *
578          *      FIXME: Once we allocate multiple proxy FD's, move this
579          *      code to below, so we can have more than 256 requests
580          *      outstanding.
581          */
582         request->proxy_outstanding = 1;
583
584         pthread_mutex_lock(&proxy_mutex);
585
586         /*
587          *      Assign a proxy ID.
588          */
589         entry = rbtree_finddata(proxy_id_tree, &myid);
590         if (!entry) {   /* allocate it */
591                 entry = rad_malloc(sizeof(*entry) + sizeof(entry->id) * 255);
592                 
593                 entry->dst_ipaddr = request->proxy->dst_ipaddr;
594                 entry->dst_port = request->proxy->dst_port;
595                 entry->index = 0;
596
597                 DEBUG3(" proxy: creating %08x:%d",
598                        entry->dst_ipaddr,
599                        entry->dst_port);
600                 
601                 /*
602                  *      Insert the new home server entry into
603                  *      the tree.
604                  *
605                  *      FIXME: We don't (currently) delete the
606                  *      entries, so this is technically a
607                  *      memory leak.
608                  */
609                 if (rbtree_insert(proxy_id_tree, entry) == 0) {
610                         DEBUG2("ERROR: Failed to insert entry into proxy Id tree");
611                         free(entry);
612                         return 0;
613                 }
614
615                 /*
616                  *      Clear out bits in the array which DO have
617                  *      proxy Fd's associated with them.  We do this
618                  *      by getting the mask of bits which have proxy
619                  *      fd's...  */
620                 mask = 0;
621                 for (i = 0; i < 32; i++) {
622                         if (proxy_fds[i] != -1) {
623                                 mask |= (1 << i);
624                         }
625                 }
626                 rad_assert(mask != 0);
627
628                 /*
629                  *      Set bits here indicate that the Fd is in use.
630                  */
631                 entry->mask = mask;
632
633                 mask = ~mask;
634
635                 /*
636                  *      Set the bits which are unused (and therefore
637                  *      allocated).  The clear bits indicate that the Id
638                  *      for that FD is unused.
639                  */
640                 for (i = 0; i < 256; i++) {
641                         entry->id[i] = mask;
642                 }
643         } /* else the entry already existed in the proxy Id tree */
644         
645  retry:
646         /*
647          *      Try to find a free Id.
648          */
649         found = -1;
650         for (i = 0; i < 256; i++) {
651                 /*
652                  *      Some bits are still zero..
653                  */
654                 if (entry->id[(i + entry->index) & 0xff] != (uint32_t) ~0) {
655                         found = (i + entry->index) & 0xff;
656                         break;
657                 }
658
659                 /*
660                  *      Hmm... do we want to re-use Id's, when we
661                  *      haven't seen all of the responses?
662                  */
663         }
664         
665         /*
666          *      No free Id, try to get a new FD.
667          */
668         if (found < 0) {
669                 /*
670                  *      First, see if there were FD's recently allocated,
671                  *      which we don't know about.
672                  */
673                 mask = 0;
674                 for (i = 0; i < 32; i++) {
675                         if (proxy_fds[i] < 0) continue;
676
677                         mask |= (1 << i);
678                 }
679
680                 /*
681                  *      There ARE more FD's than we know about.
682                  *      Update the masks for Id's, and re-try.
683                  */
684                 if (entry->mask != mask) {
685                         /*
686                          *      New mask always has more bits than
687                          *      the old one, but never fewer bits.
688                          */
689                         rad_assert((entry->mask & mask) == entry->mask);
690
691                         /*
692                          *      Clear the bits we already know about,
693                          *      and then or in those bits into the
694                          *      global mask.
695                          */
696                         mask ^= entry->mask;
697                         entry->mask |= mask;
698                         mask = ~mask;
699                         
700                         /*
701                          *      Clear the bits in the Id's for the new
702                          *      FD's.
703                          */
704                         for (i = 0; i < 256; i++) {
705                                 entry->id[i] &= mask;
706                         }
707                         
708                         /*
709                          *      And try again to allocate an Id.
710                          */
711                         goto retry;
712                 } /* else no new Fd's were allocated. */
713
714                 /*
715                  *      If all Fd's are allocated, die.
716                  */
717                 if (~mask == 0) {
718                         radlog(L_ERR|L_CONS, "ERROR: More than 8000 proxied requests outstanding for home server %08x:%d",
719                                ntohs(entry->dst_ipaddr), entry->dst_port);
720                         return 0;
721                 }
722                 
723                 /*
724                  *      Allocate a new proxy Fd.  This function adds it
725                  *      into the list of listeners.
726                  */
727                 proxy = proxy_new_listener();
728                 if (proxy < 0) {
729                         DEBUG2("ERROR: Failed to create a new socket for proxying requests.");
730                         return 0;
731                 }
732
733                 /*
734                  *
735                  */
736                 found = -1;
737                 for (i = 0; i < 32; i++) {
738                         /*
739                          *      Found a free entry.  Save the socket,
740                          *      and remember where we saved it.
741                          */
742                         if (proxy_fds[(proxy + i) & 0x1f] == -1) {
743                                 proxy_fds[(proxy + i) & 0x1f] = proxy;
744                                 found = (proxy + i) & 0x1f;
745                                 break;
746                         }
747                 }
748                 rad_assert(found >= 0); /* i.e. the mask had free bits. */
749
750                 mask = 1 << found;
751                 entry->mask |= mask;
752                 mask = ~mask;
753
754                 /*
755                  *      Clear the relevant bits in the mask.
756                  */
757                 for (i = 0; i < 256; i++) {
758                         entry->id[i] &= mask;
759                 }
760
761                 /*
762                  *      Pick a random Id to start from, as we've
763                  *      just guaranteed that it's free.
764                  */
765                 found = lrad_rand() & 0xff;
766         }
767         
768         /*
769          *      Mark next (hopefully unused) entry.
770          */
771         entry->index = (found + 1) & 0xff;
772         
773         /*
774          *      We now have to find WHICH proxy fd to use.
775          */
776         proxy = -1;
777         for (i = 0; i < 32; i++) {
778                 /*
779                  *      FIXME: pick a random socket to use?
780                  */
781                 if ((entry->id[found] & (1 << i)) == 0) {
782                         proxy = i;
783                         break;
784                 }
785         }
786
787         /*
788          *      There was no bit clear, which we had just checked above...
789          */
790         rad_assert(proxy != -1);
791
792         /*
793          *      Mark the Id as allocated, for thei Fd.
794          */
795         entry->id[found] |= (1 << proxy);
796         request->proxy->id = found;
797         request->proxy->src_ipaddr = proxy_ipaddr;
798
799         rad_assert(proxy_fds[proxy] != -1);
800         request->proxy->sockfd = proxy_fds[proxy];
801
802         DEBUG3(" proxy: allocating %08x:%d %d",
803                entry->dst_ipaddr,
804                entry->dst_port,
805                request->proxy->id);
806         
807         if (!rbtree_insert(proxy_tree, request)) {
808                 DEBUG2("ERROR: Failed to insert entry into proxy tree");
809                 return 0;
810         }
811         
812         pthread_mutex_unlock(&proxy_mutex);
813
814         return 1;
815 }
816
817
818 /*
819  *      Look up a particular request, using:
820  *
821  *      Request Id, request code, source IP, source port,
822  *
823  *      Note that we do NOT use the request vector to look up requests.
824  *
825  *      We MUST NOT have two requests with identical (id/code/IP/port), and
826  *      different vectors.  This is a serious error!
827  */
828 REQUEST *rl_find_proxy(RADIUS_PACKET *packet)
829 {
830         rbnode_t        *node;
831         REQUEST         myrequest, *maybe = NULL;
832         RADIUS_PACKET   myproxy;
833
834         /*
835          *      If we use the socket FD as an indicator,
836          *      then that implicitely contains information
837          *      as to our src ipaddr/port, so we don't need
838          *      to use that in the comparisons.
839          */
840         myproxy.sockfd = packet->sockfd;
841         myproxy.id = packet->id;
842         myproxy.dst_ipaddr = packet->src_ipaddr;
843         myproxy.dst_port = packet->src_port;
844
845 #ifndef NDEBUG
846         myrequest.magic = REQUEST_MAGIC;
847 #endif
848         myrequest.proxy = &myproxy;
849
850         pthread_mutex_lock(&proxy_mutex);
851         node = rbtree_find(proxy_tree, &myrequest);
852
853         if (node) {
854                 maybe = rbtree_node2data(proxy_tree, node);
855                 rad_assert(maybe->proxy_outstanding > 0);
856                 maybe->proxy_outstanding--;
857                 
858                 /*
859                  *      Received all of the replies we expect.
860                  *      delete it from both trees.
861                  */
862                 if (maybe->proxy_outstanding == 0) {
863                         rl_delete_proxy(&myrequest, node);
864                 }
865         }
866         pthread_mutex_unlock(&proxy_mutex);
867
868         return maybe;
869 }
870
871
872 /*
873  *      Walk over all requests, performing a callback for each request.
874  */
875 int rl_walk(RL_WALK_FUNC walker, void *data)
876 {
877         int id, rcode;
878         REQNODE *curreq, *next;
879
880         /*
881          *      Walk over all 256 ID's.
882          */
883         for (id = 0; id < 256; id++) {
884
885                 /*
886                  *      Walk over the request list for each ID.
887                  */
888                 for (curreq = request_list[id].first_request;
889                                 curreq != NULL ;
890                                 curreq = next) {
891                         /*
892                          *      The callback MIGHT delete the current
893                          *      request, so we CANNOT depend on curreq->next
894                          *      to be there, when going to the next element
895                          *      in the 'for' loop.
896                          */
897                         next = curreq->next;
898
899                         rcode = walker(curreq->req, data);
900                         if (rcode != RL_WALK_CONTINUE) {
901                                 return rcode;
902                         }
903                 }
904         }
905
906         return 0;
907 }
908
909
910 /*
911  *      Walk from one request to the next.
912  */
913 REQUEST *rl_next(REQUEST *request)
914 {
915         int id, start_id;
916         int count;
917
918         /*
919          *      If we were passed a request, then go to the "next" one.
920          */
921         if (request != NULL) {
922                 rad_assert(request->magic == REQUEST_MAGIC);
923
924                 /*
925                  *      It has a "next", return it.
926                  */
927                 if (((REQNODE *)request->container)->next != NULL) {
928                         return ((REQNODE *)request->container)->next->req;
929                 } else {
930                         /*
931                          *      No "next", increment the ID, and look
932                          *      at that one.
933                          */
934                         start_id = request->packet->id + 1;
935                         start_id &= 0xff;
936                         count = 255;
937                 }
938         } else {
939                 /*
940                  *      No input request, start looking at ID 0.
941                  */
942                 start_id = 0;
943                 count = 256;
944         }
945
946         /*
947          *      Check all ID's, wrapping around at 255.
948          */
949         for (id = start_id; id < (start_id + count); id++) {
950
951                 /*
952                  *      This ID has a request, return it.
953                  */
954                 if (request_list[id & 0xff].first_request != NULL) {
955                         rad_assert(request_list[id&0xff].first_request->req != request);
956
957                         return request_list[id & 0xff].first_request->req;
958                 }
959         }
960
961         /*
962          *      No requests at all in the list. Nothing to do.
963          */
964         DEBUG3("rl_next:  returning NULL");
965         return NULL;
966 }
967
968
969 /*
970  *      Return the number of requests in the request list.
971  */
972 int rl_num_requests(void)
973 {
974         int id;
975         int request_count = 0;
976
977         for (id = 0; id < 256; id++) {
978                 request_count += request_list[id].request_count;
979         }
980
981         return request_count;
982 }
983
984
985 typedef struct rl_walk_t {
986         time_t  now;
987         time_t  smallest;
988 } rl_walk_t;
989
990
991 /*
992  *  Refresh a request, by using proxy_retry_delay, cleanup_delay,
993  *  max_request_time, etc.
994  *
995  *  When walking over the request list, all of the per-request
996  *  magic is done here.
997  */
998 static int refresh_request(REQUEST *request, void *data)
999 {
1000         rl_walk_t *info = (rl_walk_t *) data;
1001         time_t difference;
1002         child_pid_t child_pid;
1003
1004         rad_assert(request->magic == REQUEST_MAGIC);
1005
1006         /*
1007          *  If the request is marked as a delayed reject, AND it's
1008          *  time to send the reject, then do so now.
1009          */
1010         if (request->finished &&
1011             ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) != 0)) {
1012                 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
1013
1014                 difference = info->now - request->timestamp;
1015                 if (difference >= (time_t) mainconfig.reject_delay) {
1016
1017                         /*
1018                          *  Clear the 'delayed reject' bit, so that we
1019                          *  don't do this again.
1020                          */
1021                         request->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
1022                         rad_send(request->reply, request->packet,
1023                                  request->secret);
1024                 }
1025         }
1026
1027         /*
1028          *  If the request has finished processing, AND it's child has
1029          *  been cleaned up, AND it's time to clean up the request,
1030          *  OR, it's an accounting request.  THEN, go delete it.
1031          *
1032          *  If this is a request which had the "don't cache" option
1033          *  set, then delete it immediately, as it CANNOT have a
1034          *  duplicate.
1035          */
1036         if (request->finished &&
1037             ((request->timestamp + mainconfig.cleanup_delay <= info->now) ||
1038              ((request->options & RAD_REQUEST_OPTION_DONT_CACHE) != 0))) {
1039                 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
1040
1041                 /*
1042                  *  Request completed, delete it, and unlink it
1043                  *  from the currently 'alive' list of requests.
1044                  */
1045                 DEBUG2("Cleaning up request %d ID %d with timestamp %08lx",
1046                                 request->number, request->packet->id,
1047                                 (unsigned long) request->timestamp);
1048
1049                 /*
1050                  *  Delete the request.
1051                  */
1052                 rl_delete(request);
1053                 return RL_WALK_CONTINUE;
1054         }
1055
1056         /*
1057          *  Maybe the child process handling the request has hung:
1058          *  kill it, and continue.
1059          */
1060         if ((request->timestamp + mainconfig.max_request_time) <= info->now) {
1061                 int number;
1062
1063                 child_pid = request->child_pid;
1064                 number = request->number;
1065
1066                 /*
1067                  *      There MUST be a RAD_PACKET reply.
1068                  */
1069                 rad_assert(request->reply != NULL);
1070
1071                 /*
1072                  *      If we've tried to proxy the request, and
1073                  *      the proxy server hasn't responded, then
1074                  *      we send a REJECT back to the caller.
1075                  *
1076                  *      For safety, we assert that there is no child
1077                  *      handling the request.  If the assertion fails,
1078                  *      it means that we've sent a proxied request to
1079                  *      the home server, and the child thread is still
1080                  *      sitting on the request!
1081                  */
1082                 if (request->proxy && !request->proxy_reply) {
1083                         rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
1084
1085                         radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s:%d",
1086                                request->number,
1087                                client_name(request->packet->src_ipaddr),
1088                                request->packet->src_port);
1089                         request_reject(request);
1090                         request->finished = TRUE;
1091                         return RL_WALK_CONTINUE;
1092                 }
1093
1094                 if (mainconfig.kill_unresponsive_children) {
1095                         if (child_pid != NO_SUCH_CHILD_PID) {
1096                                 /*
1097                                  *  This request seems to have hung
1098                                  *   - kill it
1099                                  */
1100 #ifdef HAVE_PTHREAD_H
1101                                 radlog(L_ERR, "Killing unresponsive thread for request %d",
1102                                        request->number);
1103                                 pthread_cancel(child_pid);
1104 #endif
1105                         } /* else no proxy reply, quietly fail */
1106
1107                         /*
1108                          *      Maybe we haven't killed it.  In that
1109                          *      case, print a warning.
1110                          */
1111                 } else if ((child_pid != NO_SUCH_CHILD_PID) &&
1112                            ((request->options & RAD_REQUEST_OPTION_LOGGED_CHILD) == 0)) {
1113                         radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d",
1114                                (unsigned long)child_pid, number);
1115
1116                         /*
1117                          *  Set the option that we've sent a log message,
1118                          *  so that we don't send more than one message
1119                          *  per request.
1120                          */
1121                         request->options |= RAD_REQUEST_OPTION_LOGGED_CHILD;
1122                 }
1123
1124                 /*
1125                  *  Send a reject message for the request, mark it
1126                  *  finished, and forget about the child.
1127                  */
1128                 request_reject(request);
1129                 request->child_pid = NO_SUCH_CHILD_PID;
1130                 if (mainconfig.kill_unresponsive_children)
1131                         request->finished = TRUE;
1132                 return RL_WALK_CONTINUE;
1133         } /* the request has been in the queue for too long */
1134
1135         /*
1136          *  If the request is still being processed, then due to the
1137          *  above check, it's still within it's time limit.  In that
1138          *  case, don't do anything.
1139          */
1140         if (request->child_pid != NO_SUCH_CHILD_PID) {
1141                 return RL_WALK_CONTINUE;
1142         }
1143
1144         /*
1145          *  The request is finished.
1146          */
1147         if (request->finished) goto setup_timeout;
1148
1149         /*
1150          *  We're not proxying requests at all.
1151          */
1152         if (!mainconfig.proxy_requests) goto setup_timeout;
1153
1154         /*
1155          *  We're proxying synchronously, so we don't retry it here.
1156          *  Some other code takes care of retrying the proxy requests.
1157          */
1158         if (mainconfig.proxy_synchronous) goto setup_timeout;
1159
1160         /*
1161          *  The proxy retry delay is zero, meaning don't retry.
1162          */
1163         if (mainconfig.proxy_retry_delay == 0) goto setup_timeout;
1164
1165         /*
1166          *  There is no proxied request for this packet, so there's
1167          *  no proxy retries.
1168          */
1169         if (!request->proxy) goto setup_timeout;
1170
1171         /*
1172          *  We've already seen the proxy reply, so we don't need
1173          *  to send another proxy request.
1174          */
1175         if (request->proxy_reply) goto setup_timeout;
1176
1177         /*
1178          *  It's not yet time to re-send this proxied request.
1179          */
1180         if (request->proxy_next_try > info->now) goto setup_timeout;
1181
1182         /*
1183          *  If the proxy retry count is zero, then
1184          *  we've sent the last try, and have NOT received
1185          *  a reply from the end server.  In that case,
1186          *  we don't bother trying again, but just mark
1187          *  the request as finished, and go to the next one.
1188          */
1189         if (request->proxy_try_count == 0) {
1190                 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
1191                 request_reject(request);
1192                 realm_disable(request->proxy->dst_ipaddr,request->proxy->dst_port);
1193                 request->finished = TRUE;
1194                 goto setup_timeout;
1195         }
1196
1197         /*
1198          *  We're trying one more time, so count down
1199          *  the tries, and set the next try time.
1200          */
1201         request->proxy_try_count--;
1202         request->proxy_next_try = info->now + mainconfig.proxy_retry_delay;
1203
1204         /* Fix up Acct-Delay-Time */
1205         if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
1206                 VALUE_PAIR *delaypair;
1207                 delaypair = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME);
1208
1209                 if (!delaypair) {
1210                         delaypair = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
1211                         if (!delaypair) {
1212                                 radlog(L_ERR|L_CONS, "no memory");
1213                                 exit(1);
1214                         }
1215                         pairadd(&request->proxy->vps, delaypair);
1216                 }
1217                 delaypair->lvalue = info->now - request->proxy->timestamp;
1218
1219                 /* Must recompile the valuepairs to wire format */
1220                 free(request->proxy->data);
1221                 request->proxy->data = NULL;
1222         } /* proxy accounting request */
1223
1224         /*
1225          *  Assert that we have NOT seen the proxy reply yet.
1226          *
1227          *  If we HAVE seen it, then we SHOULD NOT be bugging the
1228          *  home server!
1229          */
1230         rad_assert(request->proxy_reply == NULL);
1231
1232         /*
1233          *  Send the proxy packet.
1234          */
1235         request->proxy_outstanding++;
1236         rad_send(request->proxy, NULL, request->proxysecret);
1237
1238 setup_timeout:
1239         /*
1240          *  Don't do more long-term checks, if we've got to wake
1241          *  up now.
1242          */
1243         if (info->smallest == 0) {
1244                 return RL_WALK_CONTINUE;
1245         }
1246
1247         /*
1248          *  The request is finished.  Wake up when it's time to
1249          *  clean it up.
1250          */
1251         if (request->finished) {
1252                 difference = (request->timestamp + mainconfig.cleanup_delay) - info->now;
1253
1254                 /*
1255                  *  If the request is marked up to be rejected later,
1256                  *  then wake up later.
1257                  */
1258                 if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) != 0) {
1259                         if (difference >= (time_t) mainconfig.reject_delay) {
1260                                 difference = (time_t) mainconfig.reject_delay;
1261                         }
1262                 }
1263
1264         } else if (request->proxy && !request->proxy_reply) {
1265                 /*
1266                  *  The request is NOT finished, but there is an
1267                  *  outstanding proxy request, with no matching
1268                  *  proxy reply.
1269                  *
1270                  *  Wake up when it's time to re-send
1271                  *  the proxy request.
1272                  *
1273                  *  But in synchronous proxy, we don't retry but we update
1274                  *  the next retry time as NAS has not resent the request
1275                  *  in the given retry window.
1276                  */
1277                 if (mainconfig.proxy_synchronous) {
1278                         /*
1279                          *      If the retry_delay * count has passed,
1280                          *      then mark the realm dead.
1281                          */
1282                         if (info->now > (request->timestamp + (mainconfig.proxy_retry_delay * mainconfig.proxy_retry_count))) {
1283                                 rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
1284                                 request_reject(request);
1285                                 
1286                                 realm_disable(request->proxy->dst_ipaddr,
1287                                               request->proxy->dst_port);
1288                                 request->finished = TRUE;
1289                                 goto setup_timeout;
1290                         }
1291                         request->proxy_next_try = info->now + mainconfig.proxy_retry_delay;
1292                 }
1293                 difference = request->proxy_next_try - info->now;
1294         } else {
1295                 /*
1296                  *  The request is NOT finished.
1297                  *
1298                  *  Wake up when it's time to kill the errant
1299                  *  thread/process.
1300                  */
1301                 difference = (request->timestamp + mainconfig.max_request_time) - info->now;
1302         }
1303
1304         /*
1305          *  If the server is CPU starved, then we CAN miss a time
1306          *  for servicing requests.  In which case the 'difference'
1307          *  value will be negative.  select() doesn't like that,
1308          *  so we fix it.
1309          */
1310         if (difference < 0) {
1311                 difference = 0;
1312         }
1313
1314         /*
1315          *  Update the 'smallest' time.
1316          */
1317         if ((info->smallest < 0) ||
1318                 (difference < info->smallest)) {
1319                 info->smallest = difference;
1320         }
1321
1322         return RL_WALK_CONTINUE;
1323 }
1324
1325
1326 /*
1327  *  Clean up the request list, every so often.
1328  *
1329  *  This is done by walking through ALL of the list, and
1330  *  - marking any requests which are finished, and expired
1331  *  - killing any processes which are NOT finished after a delay
1332  *  - deleting any marked requests.
1333  */
1334 struct timeval *rl_clean_list(time_t now)
1335 {
1336         /*
1337          *  Static variables, so that we don't do all of this work
1338          *  more than once per second.
1339          *
1340          *  Note that we have 'tv' and 'last_tv'.  'last_tv' is
1341          *  pointed to by 'last_tv_ptr', and depending on the
1342          *  system implementation of select(), it MAY be modified.
1343          *
1344          *  In that was, we want to use the ORIGINAL value, from
1345          *  'tv', and wipe out the (possibly modified) last_tv.
1346          */
1347         static time_t last_cleaned_list = 0;
1348         static struct timeval tv, *last_tv_ptr = NULL;
1349         static struct timeval last_tv;
1350
1351         rl_walk_t info;
1352
1353         info.now = now;
1354         info.smallest = -1;
1355
1356         /*
1357          *  If we've already set up the timeout or cleaned the
1358          *  request list this second, then don't do it again.  We
1359          *  simply return the sleep delay from last time.
1360          *
1361          *  Note that if we returned NULL last time, there was nothing
1362          *  to do.  BUT we've been woken up since then, which can only
1363          *  happen if we received a packet.  And if we've received a
1364          *  packet, then there's some work to do in the future.
1365          *
1366          *  FIXME: We can probably use gettimeofday() for finer clock
1367          *  resolution, as the current method will cause it to sleep
1368          *  too long...
1369          */
1370         if ((last_tv_ptr != NULL) &&
1371             (last_cleaned_list == now) &&
1372             (tv.tv_sec != 0)) {
1373                 int i;
1374
1375                 /*
1376                  *  If we're NOT walking the entire request list,
1377                  *  then we want to iteratively check the request
1378                  *  list.
1379                  *
1380                  *  If there is NO previous request, go look for one.
1381                  */
1382                 if (!last_request)
1383                         last_request = rl_next(last_request);
1384
1385                 /*
1386                  *  On average, there will be one request per
1387                  *  'cleanup_delay' requests, which needs to be
1388                  *  serviced.
1389                  *
1390                  *  And only do this servicing, if we have a request
1391                  *  to service.
1392                  */
1393                 if (last_request)
1394                         for (i = 0; i < mainconfig.cleanup_delay; i++) {
1395                                 REQUEST *next;
1396
1397                                 /*
1398                                  *  This function call MAY delete the
1399                                  *  request pointed to by 'last_request'.
1400                                  */
1401                                 next = rl_next(last_request);
1402                                 refresh_request(last_request, &info);
1403                                 last_request = next;
1404
1405                                 /*
1406                                  *  Nothing to do any more, exit.
1407                                  */
1408                                 if (!last_request)
1409                                         break;
1410                         }
1411
1412                 last_tv = tv;
1413                 DEBUG2("Waking up in %d seconds...",
1414                                 (int) last_tv_ptr->tv_sec);
1415                 return last_tv_ptr;
1416         }
1417         last_cleaned_list = now;
1418         last_request = NULL;
1419         DEBUG2("--- Walking the entire request list ---");
1420
1421         /*
1422          *  Hmmm... this is Big Magic.  We make it seem like
1423          *  there's an additional second to wait, for a whole
1424          *  host of reasons which I can't explain adequately,
1425          *  but which cause the code to Just Work Right.
1426          */
1427         info.now--;
1428
1429         rl_walk(refresh_request, &info);
1430
1431         /*
1432          *  We haven't found a time at which we need to wake up.
1433          *  Return NULL, so that the select() call will sleep forever.
1434          */
1435         if (info.smallest < 0) {
1436                 /*
1437                  *  If we're not proxying, then there really isn't anything
1438                  *  to do.
1439                  *
1440                  *  If we ARE proxying, then we can safely sleep
1441                  *  forever if we're told to NEVER send proxy retries
1442                  *  ourselves, until the NAS kicks us again.
1443                  *
1444                  *  Otherwise, there are no outstanding requests, then
1445                  *  we can sleep forever.  This happens when we get
1446                  *  woken up with a bad packet.  It's discarded, so if
1447                  *  there are no live requests, we can safely sleep
1448                  *  forever.
1449                  */
1450                 if ((!mainconfig.proxy_requests) ||
1451                     mainconfig.proxy_synchronous ||
1452                     (rl_num_requests() == 0)) {
1453                         DEBUG2("Nothing to do.  Sleeping until we see a request.");
1454                         last_tv_ptr = NULL;
1455                         return NULL;
1456                 }
1457
1458                 /*
1459                  *  We ARE proxying.  In that case, we avoid a race condition
1460                  *  where a child thread handling a request proxies the
1461                  *  packet, and sets the retry delay.  In that case, we're
1462                  *  supposed to wake up in N seconds, but we can't, as
1463                  *  we're sleeping forever.
1464                  *
1465                  *  Instead, we prevent the problem by waking up anyhow
1466                  *  at the 'proxy_retry_delay' time, even if there's
1467                  *  nothing to do.  In the worst case, this will cause
1468                  *  the server to wake up every N seconds, to do a small
1469                  *  amount of unnecessary work.
1470                  */
1471                 info.smallest = mainconfig.proxy_retry_delay;
1472         }
1473         /*
1474          *  Set the time (in seconds) for how long we're
1475          *  supposed to sleep.
1476          */
1477         tv.tv_sec = info.smallest;
1478         tv.tv_usec = 0;
1479         DEBUG2("Waking up in %d seconds...", (int) info.smallest);
1480
1481         /*
1482          *  Remember how long we should sleep for.
1483          */
1484         last_tv = tv;
1485         last_tv_ptr = &last_tv;
1486         return last_tv_ptr;
1487 }