2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License, version 2 if the
4 * License as published by the Free Software Foundation.
6 * This program is distributed in the hope that it will be useful,
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 * GNU General Public License for more details.
11 * You should have received a copy of the GNU General Public License
12 * along with this program; if not, write to the Free Software
13 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * @brief Cache values and merge them back into future requests.
21 * @copyright 2012-2013 The FreeRADIUS server project
25 #include <freeradius-devel/radiusd.h>
26 #include <freeradius-devel/modules.h>
27 #include <freeradius-devel/heap.h>
28 #include <freeradius-devel/rad_assert.h>
30 #define PW_CACHE_TTL 1140
31 #define PW_CACHE_STATUS_ONLY 1141
32 #define PW_CACHE_MERGE 1142
33 #define PW_CACHE_ENTRY_HITS 1143
36 * Define a structure for our module configuration.
38 * These variables do not need to be in a structure, but it's
39 * a lot cleaner to do so, and a pointer to the structure can
40 * be used as the instance handle.
42 typedef struct rlm_cache_t {
43 char const *xlat_name;
53 value_pair_map_t *maps; //!< Attribute map applied to users
56 pthread_mutex_t cache_mutex;
60 typedef struct rlm_cache_entry_t {
72 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
73 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
75 #define PTHREAD_MUTEX_LOCK(_x)
76 #define PTHREAD_MUTEX_UNLOCK(_x)
79 #define MAX_ATTRMAP 128
82 * Compare two entries by key. There may only be one entry with
85 static int cache_entry_cmp(void const *one, void const *two)
87 rlm_cache_entry_t const *a = one;
88 rlm_cache_entry_t const *b = two;
90 return strcmp(a->key, b->key);
93 static void cache_entry_free(void *data)
95 rlm_cache_entry_t *c = data;
97 pairfree(&c->control);
105 * Compare two entries by expiry time. There may be multiple
106 * entries with the same expiry time.
108 static int cache_heap_cmp(void const *one, void const *two)
110 rlm_cache_entry_t const *a = one;
111 rlm_cache_entry_t const *b = two;
113 if (a->expires < b->expires) return -1;
114 if (a->expires > b->expires) return +1;
120 * Merge a cached entry into a REQUEST.
122 static void CC_HINT(nonnull) cache_merge(rlm_cache_t *inst, REQUEST *request, rlm_cache_entry_t *c)
126 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
127 if (vp && (vp->vp_integer == 0)) {
128 RDEBUG2("Told not to merge entry into request");
133 RDEBUG2("Merging cached control list:");
134 rdebug_pair_list(2, request, c->control);
136 pairadd(&request->config_items, paircopy(request, c->control));
139 if (c->packet && request->packet) {
140 RDEBUG2("Merging cached request list:");
141 rdebug_pair_list(2, request, c->packet);
143 pairadd(&request->packet->vps,
144 paircopy(request->packet, c->packet));
147 if (c->reply && request->reply) {
148 RDEBUG2("Merging cached reply list:");
149 rdebug_pair_list(2, request, c->reply);
151 pairadd(&request->reply->vps,
152 paircopy(request->reply, c->reply));
156 vp = paircreate(request->packet, PW_CACHE_ENTRY_HITS, 0);
157 rad_assert(vp != NULL);
159 vp->vp_integer = c->hits;
161 pairadd(&request->packet->vps, vp);
167 * Find a cached entry.
169 static rlm_cache_entry_t *cache_find(rlm_cache_t *inst, REQUEST *request,
173 rlm_cache_entry_t *c, my_c;
177 * Look at the expiry heap.
179 c = fr_heap_peek(inst->heap);
181 rad_assert(rbtree_num_elements(inst->cache) == 0);
186 * If it's time to expire an old entry, do so now.
188 if (c->expires < request->timestamp) {
189 fr_heap_extract(inst->heap, c);
190 rbtree_deletebydata(inst->cache, c);
194 * Is there an entry for this key?
197 c = rbtree_finddata(inst->cache, &my_c);
201 * Yes, but it expired, OR the "forget all" epoch has
202 * passed. Delete it, and pretend it doesn't exist.
204 if ((c->expires < request->timestamp) ||
205 (c->created < inst->epoch)) {
207 RDEBUG("Entry has expired, removing");
209 fr_heap_extract(inst->heap, c);
210 rbtree_deletebydata(inst->cache, c);
215 RDEBUG("Found entry for \"%s\"", key);
218 * Update the expiry time based on the TTL.
219 * A TTL of 0 means "delete from the cache".
221 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
223 if (vp->vp_integer == 0) goto delete;
225 ttl = vp->vp_integer;
226 c->expires = request->timestamp + ttl;
227 RDEBUG("Adding %d to the TTL", ttl);
236 * Add an entry to the cache.
238 static rlm_cache_entry_t *cache_add(rlm_cache_t *inst, REQUEST *request,
242 VALUE_PAIR *vp, *found, **to_req, **to_cache, **from;
248 value_pair_map_t const *map;
250 rlm_cache_entry_t *c;
253 if (rbtree_num_elements(inst->cache) >= inst->max_entries) {
254 RDEBUG("Cache is full: %d entries", inst->max_entries);
259 * TTL of 0 means "don't cache this entry"
261 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
262 if (vp && (vp->vp_integer == 0)) return NULL;
264 c = talloc_zero(inst, rlm_cache_entry_t);
265 c->key = talloc_typed_strdup(c, key);
266 c->created = c->expires = request->timestamp;
269 * Use per-entry TTL, or globally defined one.
272 ttl = vp->vp_integer;
278 RDEBUG("Creating entry for \"%s\"", key);
281 * Check to see if we need to merge the entry into the request
283 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
284 if (vp && (vp->vp_integer == 0)) {
286 RDEBUG2("Told not to merge new entry into request");
289 for (map = inst->maps; map != NULL; map = map->next) {
290 rad_assert(map->dst && map->src);
293 * Specifying inner/outer request doesn't work here
294 * but there's no easy fix...
296 switch (map->dst->vpt_list) {
297 case PAIR_LIST_REQUEST:
298 to_cache = &c->packet;
301 case PAIR_LIST_REPLY:
302 to_cache = &c->reply;
305 case PAIR_LIST_CONTROL:
306 to_cache = &c->control;
315 * Resolve the destination in the current request.
316 * We need to add the to_cache there too if any of these
319 * - Map specifies an xlat'd string.
320 * - Map specifies a literal string.
321 * - Map src and dst lists differ.
322 * - Map src and dst attributes differ
325 if (merge && (!map->src->vpt_da ||
326 (map->src->vpt_list != map->dst->vpt_list) ||
327 (map->src->vpt_da != map->dst->vpt_da))) {
330 * It's ok if the list isn't valid here...
331 * It might be valid later when we merge
334 if (radius_request(&context, map->dst->vpt_request) == 0) {
335 to_req = radius_list(context, map->dst->vpt_list);
340 * We infer that src was an attribute ref from the fact
343 RDEBUG4(":: dst is \"%s\" src is \"%s\"",
344 fr_int2str(vpt_types, map->dst->type, "<INVALID>"),
345 fr_int2str(vpt_types, map->src->type, "<INVALID>"));
347 switch (map->src->type) {
353 da = map->src->vpt_da;
354 rad_assert(da != NULL);
357 if (radius_request(&context, map->src->vpt_request) == 0) {
358 from = radius_list(context, map->src->vpt_list);
362 * Can't add the attribute if the list isn't
367 fr_cursor_init(&cursor, from);
368 found = fr_cursor_next_by_da(&cursor, da, TAG_ANY);
370 RWDEBUG("\"%s\" not found, skipping",
375 RDEBUG("\t%s %s &%s", map->dst->name,
376 fr_int2str(fr_tokens, map->op, "<INVALID>"),
383 vp = map->dst->type == VPT_TYPE_LIST ?
384 paircopyvp(c, found) :
385 paircopyvpdata(c, map->dst->vpt_da, found);
389 pairadd(to_cache, vp);
392 vp = paircopyvp(request, vp);
393 radius_pairmove(request, to_req, vp, false);
399 vp = map->dst->type == VPT_TYPE_LIST ?
400 paircopyvp(c, found) :
401 paircopyvpdata(c, map->dst->vpt_da, found);
405 pairadd(to_cache, vp);
408 vp = paircopyvp(request, vp);
409 radius_pairmove(request, to_req, vp, false);
412 } while ((found = fr_cursor_next_by_da(&cursor, da, TAG_ANY)));
426 rad_assert(map->src->type == VPT_TYPE_LIST);
430 if (radius_request(&context, map->src->vpt_request) == 0) {
431 from = radius_list(context, map->src->vpt_list);
436 fr_cursor_init(&out, &found);
437 for (i = fr_cursor_init(&in, from);
439 i = fr_cursor_next(&in)) {
441 * Prevent cache control attributes being added to the cache.
443 switch (i->da->attr) {
445 case PW_CACHE_STATUS_ONLY:
447 case PW_CACHE_ENTRY_HITS:
448 RDEBUG("\tskipping %s", i->da->name);
454 vp = paircopyvp(c, i);
459 RDEBUG("\t%s %s &%s:%s", map->dst->name,
460 fr_int2str(fr_tokens, map->op, "<INVALID>"),
461 fr_int2str(pair_lists, map->src->vpt_list, "<INVALID>"), vp->da->name);
463 fr_cursor_insert(&out, vp);
466 pairadd(to_cache, found);
468 vp = paircopy(request, found);
469 radius_pairmove(request, to_req, vp, false);
475 * It was most likely a double quoted string that now
476 * needs to be expanded.
479 if (radius_xlat(buffer, sizeof(buffer), request, map->src->name, NULL, NULL) <= 0) {
483 RDEBUG("\t%s %s \"%s\"", map->dst->name,
484 fr_int2str(fr_tokens, map->op, "<INVALID>"),
487 vp = pairalloc(map->dst, map->dst->vpt_da);
491 if (!pairparsevalue(vp, buffer)) {
496 pairadd(to_cache, vp);
499 vp = paircopyvp(request, vp);
500 radius_pairmove(request, to_req, vp, false);
507 case VPT_TYPE_LITERAL:
508 RDEBUG("\t%s %s '%s'", map->dst->name,
509 fr_int2str(fr_tokens, map->op, "<INVALID>"),
512 vp = pairalloc(map->dst, map->dst->vpt_da);
516 if (!pairparsevalue(vp, map->src->name)) {
521 pairadd(to_cache, vp);
524 vp = paircopyvp(request, vp);
525 radius_pairmove(request, to_req, vp, false);
536 if (!rbtree_insert(inst->cache, c)) {
537 REDEBUG("FAILED adding entry for key %s", key);
542 if (!fr_heap_insert(inst->heap, c)) {
543 REDEBUG("FAILED adding entry for key %s", key);
544 rbtree_deletebydata(inst->cache, c);
548 RDEBUG("Inserted entry, TTL %d seconds", ttl);
554 * Verify that the cache section makes sense.
556 static int cache_verify(rlm_cache_t *inst, value_pair_map_t **head)
558 value_pair_map_t *map;
560 if (radius_attrmap(cf_section_sub_find(inst->cs, "update"),
561 head, PAIR_LIST_REQUEST,
562 PAIR_LIST_REQUEST, MAX_ATTRMAP) < 0) {
567 cf_log_err_cs(inst->cs,
568 "Cache config must contain an update section, and "
569 "that section must not be empty");
574 for (map = *head; map != NULL; map = map->next) {
575 if ((map->dst->type != VPT_TYPE_ATTR) &&
576 (map->dst->type != VPT_TYPE_LIST)) {
577 cf_log_err(map->ci, "Left operand must be an attribute "
584 * Can't copy an xlat expansion or literal into a list,
585 * we don't know what type of attribute we'd need
588 * The only exception is where were using a unary
591 if ((map->dst->type == VPT_TYPE_LIST) &&
592 (map->op != T_OP_CMP_FALSE) &&
593 ((map->src->type == VPT_TYPE_XLAT) || (map->src->type == VPT_TYPE_LITERAL))) {
594 cf_log_err(map->ci, "Can't copy value into list (we don't know which attribute to create)");
599 switch (map->src->type) {
601 cf_log_err(map->ci, "Exec values are not allowed");
606 * Only =, :=, += and -= operators are supported for
609 case VPT_TYPE_LITERAL:
611 * @fixme: This should be moved into a common function
612 * with the check in do_compile_modupdate.
614 if (map->dst->type == VPT_TYPE_ATTR) {
618 MEM(vp = pairalloc(map->dst, map->dst->vpt_da));
621 ret = pairparsevalue(vp, map->src->name);
624 cf_log_err(map->ci, "%s", fr_strerror());
640 cf_log_err(map->ci, "Operator \"%s\" not "
641 "allowed for %s values",
642 fr_int2str(fr_tokens, map->op,
644 fr_int2str(vpt_types, map->src->type,
656 * Allow single attribute values to be retrieved from the cache.
658 static ssize_t cache_xlat(void *instance, REQUEST *request,
659 char const *fmt, char *out, size_t freespace)
661 rlm_cache_entry_t *c;
662 rlm_cache_t *inst = instance;
663 VALUE_PAIR *vp, *vps;
665 DICT_ATTR const *target;
670 list = radius_list_name(&p, PAIR_LIST_REQUEST);
672 target = dict_attrbyname(p);
674 REDEBUG("Unknown attribute \"%s\"", p);
678 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
679 c = cache_find(inst, request, fmt);
682 RDEBUG("No cache entry for key \"%s\"", fmt);
688 case PAIR_LIST_REQUEST:
692 case PAIR_LIST_REPLY:
696 case PAIR_LIST_CONTROL:
700 case PAIR_LIST_UNKNOWN:
701 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
702 REDEBUG("Unknown list qualifier in \"%s\"", fmt);
706 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
707 REDEBUG("Unsupported list \"%s\"",
708 fr_int2str(pair_lists, list, "¿Unknown?"));
712 vp = pairfind(vps, target->attr, target->vendor, TAG_ANY);
714 RDEBUG("No instance of this attribute has been cached");
719 len = vp_prints_value(out, freespace, vp, 0);
720 if (is_truncated(len, freespace)) {
721 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
722 REDEBUG("Insufficient buffer space to write cached value");
726 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
732 * A mapping of configuration file names to internal variables.
734 * Note that the string is dynamically allocated, so it MUST
735 * be freed. When the configuration file parse re-reads the string,
736 * it free's the old one, and strdup's the new one, placing the pointer
737 * to the strdup'd string into 'config.string'. This gets around
740 static const CONF_PARSER module_config[] = {
741 { "key", PW_TYPE_STRING | PW_TYPE_REQUIRED,
742 offsetof(rlm_cache_t, key), NULL, NULL},
743 { "ttl", PW_TYPE_INTEGER,
744 offsetof(rlm_cache_t, ttl), NULL, "500" },
745 { "max_entries", PW_TYPE_INTEGER,
746 offsetof(rlm_cache_t, max_entries), NULL, "16384" },
747 { "epoch", PW_TYPE_INTEGER,
748 offsetof(rlm_cache_t, epoch), NULL, "0" },
749 { "add_stats", PW_TYPE_BOOLEAN,
750 offsetof(rlm_cache_t, stats), NULL, "no" },
752 { NULL, -1, 0, NULL, NULL } /* end the list */
757 * Only free memory we allocated. The strings allocated via
758 * cf_section_parse() do not need to be freed.
760 static int mod_detach(void *instance)
762 rlm_cache_t *inst = instance;
764 talloc_free(inst->maps);
766 fr_heap_delete(inst->heap);
767 rbtree_free(inst->cache);
769 #ifdef HAVE_PTHREAD_H
770 pthread_mutex_destroy(&inst->cache_mutex);
777 * Instantiate the module.
779 static int mod_instantiate(CONF_SECTION *conf, void *instance)
781 rlm_cache_t *inst = instance;
785 inst->xlat_name = cf_section_name2(conf);
786 if (!inst->xlat_name) {
787 inst->xlat_name = cf_section_name1(conf);
791 * Register the cache xlat function
793 xlat_register(inst->xlat_name, cache_xlat, NULL, inst);
795 rad_assert(inst->key && *inst->key);
797 if (inst->ttl == 0) {
798 cf_log_err_cs(conf, "Must set 'ttl' to non-zero");
802 if (inst->epoch != 0) {
803 cf_log_err_cs(conf, "Must not set 'epoch' in the configuration files");
807 #ifdef HAVE_PTHREAD_H
808 if (pthread_mutex_init(&inst->cache_mutex, NULL) < 0) {
809 ERROR("Failed initializing mutex: %s",
818 inst->cache = rbtree_create(cache_entry_cmp, cache_entry_free, 0);
820 ERROR("Failed to create cache");
825 * The heap of entries to expire.
827 inst->heap = fr_heap_create(cache_heap_cmp,
828 offsetof(rlm_cache_entry_t, offset));
830 ERROR("Failed to create heap for the cache");
835 * Make sure the users don't screw up too badly.
837 if (cache_verify(inst, &inst->maps) < 0) {
845 * Do caching checks. Since we can update ANY VP list, we do
846 * exactly the same thing for all sections (autz / auth / etc.)
848 * If you want to cache something different in different sections,
849 * configure another cache module.
851 static rlm_rcode_t CC_HINT(nonnull) mod_cache_it(void *instance, REQUEST *request)
853 rlm_cache_entry_t *c;
854 rlm_cache_t *inst = instance;
859 if (radius_xlat(buffer, sizeof(buffer), request, inst->key, NULL, NULL) < 0) {
860 return RLM_MODULE_FAIL;
863 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
864 c = cache_find(inst, request, buffer);
867 * If yes, only return whether we found a valid cache entry
869 vp = pairfind(request->config_items, PW_CACHE_STATUS_ONLY, 0, TAG_ANY);
870 if (vp && vp->vp_integer) {
871 rcode = c ? RLM_MODULE_OK:
877 cache_merge(inst, request, c);
879 rcode = RLM_MODULE_OK;
883 c = cache_add(inst, request, buffer);
885 rcode = RLM_MODULE_NOOP;
889 rcode = RLM_MODULE_UPDATED;
892 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
898 * The module name should be the only globally exported symbol.
899 * That is, everything else should be 'static'.
901 * If the module needs to temporarily modify it's instantiation
902 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
903 * The server will then take care of ensuring that the module
904 * is single-threaded.
906 module_t rlm_cache = {
912 mod_instantiate, /* instantiation */
913 mod_detach, /* detach */
915 NULL, /* authentication */
916 mod_cache_it, /* authorization */
917 mod_cache_it, /* preaccounting */
918 mod_cache_it, /* accounting */
919 NULL, /* checksimul */
920 mod_cache_it, /* pre-proxy */
921 mod_cache_it, /* post-proxy */
922 mod_cache_it, /* post-auth */