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