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/modcall.h>
28 #include <freeradius-devel/heap.h>
29 #include <freeradius-devel/rad_assert.h>
32 * Define a structure for our module configuration.
34 * These variables do not need to be in a structure, but it's
35 * a lot cleaner to do so, and a pointer to the structure can
36 * be used as the instance handle.
38 typedef struct rlm_cache_t {
39 char const *xlat_name;
49 value_pair_map_t *maps; //!< Attribute map applied to users
52 pthread_mutex_t cache_mutex;
56 typedef struct rlm_cache_entry_t {
68 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
69 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
71 #define PTHREAD_MUTEX_LOCK(_x)
72 #define PTHREAD_MUTEX_UNLOCK(_x)
75 #define MAX_ATTRMAP 128
78 * A mapping of configuration file names to internal variables.
80 * Note that the string is dynamically allocated, so it MUST
81 * be freed. When the configuration file parse re-reads the string,
82 * it free's the old one, and strdup's the new one, placing the pointer
83 * to the strdup'd string into 'config.string'. This gets around
86 static const CONF_PARSER module_config[] = {
87 { "key", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED | PW_TYPE_XLAT, rlm_cache_t, key), NULL },
88 { "ttl", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_cache_t, ttl), "500" },
89 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_cache_t, max_entries), "16384" },
91 /* Should be a type which matches time_t, @fixme before 2038 */
92 { "epoch", FR_CONF_OFFSET(PW_TYPE_SIGNED, rlm_cache_t, epoch), "0" },
93 { "add_stats", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_cache_t, stats), "no" },
95 { NULL, -1, 0, NULL, NULL } /* end the list */
100 * Compare two entries by key. There may only be one entry with
103 static int cache_entry_cmp(void const *one, void const *two)
105 rlm_cache_entry_t const *a = one;
106 rlm_cache_entry_t const *b = two;
108 return strcmp(a->key, b->key);
111 static void cache_entry_free(void *data)
113 rlm_cache_entry_t *c = data;
115 pairfree(&c->control);
116 pairfree(&c->packet);
123 * Compare two entries by expiry time. There may be multiple
124 * entries with the same expiry time.
126 static int cache_heap_cmp(void const *one, void const *two)
128 rlm_cache_entry_t const *a = one;
129 rlm_cache_entry_t const *b = two;
131 if (a->expires < b->expires) return -1;
132 if (a->expires > b->expires) return +1;
138 * Merge a cached entry into a REQUEST.
140 static void CC_HINT(nonnull) cache_merge(rlm_cache_t *inst, REQUEST *request, rlm_cache_entry_t *c)
144 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
145 if (vp && (vp->vp_integer == 0)) {
146 RDEBUG2("Told not to merge entry into request");
150 RDEBUG2("Merging cache entry into request");
153 RDEBUG2("Merging cached control list");
154 radius_pairmove(request, &request->config_items, paircopy(request, c->control), false);
157 if (c->packet && request->packet) {
158 RDEBUG2("Merging cached request list");
159 radius_pairmove(request, &request->packet->vps, paircopy(request->packet, c->packet), false);
162 if (c->reply && request->reply) {
163 RDEBUG2("Merging cached reply list");
164 radius_pairmove(request, &request->reply->vps, paircopy(request->reply, c->reply), false);
168 vp = pairfind(request->packet->vps, PW_CACHE_ENTRY_HITS, 0, TAG_ANY);
170 vp = paircreate(request->packet, PW_CACHE_ENTRY_HITS, 0);
171 rad_assert(vp != NULL);
172 pairadd(&request->packet->vps, vp);
174 vp->vp_integer = c->hits;
180 * Find a cached entry.
182 static rlm_cache_entry_t *cache_find(rlm_cache_t *inst, REQUEST *request,
186 rlm_cache_entry_t *c, my_c;
190 * Look at the expiry heap.
192 c = fr_heap_peek(inst->heap);
194 rad_assert(rbtree_num_elements(inst->cache) == 0);
199 * If it's time to expire an old entry, do so now.
201 if (c->expires < request->timestamp) {
202 fr_heap_extract(inst->heap, c);
203 rbtree_deletebydata(inst->cache, c);
207 * Is there an entry for this key?
210 c = rbtree_finddata(inst->cache, &my_c);
214 * Yes, but it expired, OR the "forget all" epoch has
215 * passed. Delete it, and pretend it doesn't exist.
217 if ((c->expires < request->timestamp) ||
218 (c->created < inst->epoch)) {
220 RDEBUG("Removing expired entry");
222 fr_heap_extract(inst->heap, c);
223 rbtree_deletebydata(inst->cache, c);
228 RDEBUG("Found entry for \"%s\"", key);
231 * Update the expiry time based on the TTL.
232 * A TTL of 0 means "delete from the cache".
233 * A TTL < 0 means "delete from the cache and recreate the entry".
235 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
237 if (vp->vp_signed <= 0) goto delete;
240 c->expires = request->timestamp + ttl;
241 RDEBUG("Adding %d to the TTL", ttl);
249 /** Callback for map_to_request
251 * Simplifies merging VALUE_PAIRs into the current request.
253 static int _cache_add(VALUE_PAIR **out, REQUEST *request, UNUSED value_pair_map_t const *map, void *ctx)
257 vp = talloc_get_type_abort(ctx, VALUE_PAIR);
258 /* map_to_request will reparent */
259 *out = paircopy(request, vp);
261 if (!*out) return -1;
266 * Add an entry to the cache.
268 static rlm_cache_entry_t *cache_add(rlm_cache_t *inst, REQUEST *request, char const *key)
271 VALUE_PAIR *vp, *to_cache;
272 vp_cursor_t src_list, cached_request, cached_reply, cached_control;
276 value_pair_map_t const *map;
278 rlm_cache_entry_t *c;
280 if (rbtree_num_elements(inst->cache) >= inst->max_entries) {
281 RDEBUG("Cache is full: %d entries", inst->max_entries);
286 * TTL of 0 means "don't cache this entry"
288 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
289 if (vp && (vp->vp_signed == 0)) return NULL;
291 c = talloc_zero(NULL, rlm_cache_entry_t);
292 c->key = talloc_typed_strdup(c, key);
293 c->created = c->expires = request->timestamp;
296 * Use per-entry TTL if > 0, or globally defined one.
298 ttl = vp && (vp->vp_signed > 0) ? vp->vp_integer : inst->ttl;
301 RDEBUG("Creating entry for \"%s\"", key);
304 * Check to see if we need to merge the entry into the request
306 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
307 if (vp && (vp->vp_integer == 0)) {
309 RDEBUG2("Told not to merge new entry into request");
312 fr_cursor_init(&cached_request, &c->packet);
313 fr_cursor_init(&cached_reply, &c->reply);
314 fr_cursor_init(&cached_control, &c->control);
316 for (map = inst->maps; map != NULL; map = map->next) {
317 bool do_merge = merge;
319 rad_assert(map->lhs && map->rhs);
321 if (map_to_vp(&to_cache, request, map, NULL) < 0) {
322 RDEBUG("Skipping %s", map->rhs->name);
327 * Merge attributes into the current request if:
328 * - Map specifies an xlat'd string.
329 * - Map specifies a literal string.
330 * - Map specifies an exec.
331 * - Map src and dst lists differ.
332 * - Map src and dst attributes differ
334 * Unless Cache-Merge = no
336 if (do_merge) switch (map->rhs->type) {
337 case TMPL_TYPE_LITERAL:
343 if (map->rhs->tmpl_list == map->lhs->tmpl_list) do_merge = false;
347 rad_assert(map->lhs->type == TMPL_TYPE_ATTR);
348 if (map->rhs->tmpl_da == map->lhs->tmpl_da) do_merge = false;
356 * Reparent the VPs map_to_vp may return multiple.
358 for (vp = fr_cursor_init(&src_list, &to_cache);
360 vp = fr_cursor_next(&src_list)) {
364 * Prevent people from accidentally caching
365 * cache control attributes.
367 if (map->rhs->type == TMPL_TYPE_LIST) switch (vp->da->attr) {
369 case PW_CACHE_STATUS_ONLY:
370 case PW_CACHE_READ_ONLY:
372 case PW_CACHE_ENTRY_HITS:
373 RDEBUG2("Skipping %s", vp->da->name);
380 if (debug_flag) map_debug_log(request, map, vp);
381 (void) talloc_steal(c, vp);
385 switch (map->lhs->tmpl_list) {
386 case PAIR_LIST_REQUEST:
387 fr_cursor_insert(&cached_request, vp);
390 case PAIR_LIST_REPLY:
391 fr_cursor_insert(&cached_reply, vp);
394 case PAIR_LIST_CONTROL:
395 fr_cursor_insert(&cached_control, vp);
399 rad_assert(0); /* should have been caught by validation */
402 if (do_merge && map_dst_valid(request, map)) {
403 /* There's no reason for this to fail (we checked the dst was valid) */
404 RDEBUG2("Adding to request:");
405 if (map_to_request(request, map, _cache_add, vp) < 0) rad_assert(0);
410 if (!rbtree_insert(inst->cache, c)) {
411 REDEBUG("FAILED adding entry for key %s", key);
416 if (!fr_heap_insert(inst->heap, c)) {
417 REDEBUG("FAILED adding entry for key %s", key);
418 rbtree_deletebydata(inst->cache, c);
422 RDEBUG("Inserted entry, TTL %d seconds", ttl);
427 /** Verify that a map in the cache section makes sense
430 static int cache_verify(value_pair_map_t *map, UNUSED void *ctx)
432 if (modcall_fixup_update(map, ctx) < 0) return -1;
434 if ((map->lhs->type != TMPL_TYPE_ATTR) &&
435 (map->lhs->type != TMPL_TYPE_LIST)) {
436 cf_log_err(map->ci, "Left operand must be an attribute ref or a list");
440 switch (map->rhs->type) {
442 cf_log_err(map->ci, "Exec values are not allowed");
445 * Only =, :=, += and -= operators are supported for
448 case TMPL_TYPE_LITERAL:
459 cf_log_err(map->ci, "Operator \"%s\" not allowed for %s values",
460 fr_int2str(fr_tokens, map->op, "<INVALID>"),
461 fr_int2str(tmpl_types, map->rhs->type, "<INVALID>"));
472 * Allow single attribute values to be retrieved from the cache.
474 static ssize_t cache_xlat(void *instance, REQUEST *request,
475 char const *fmt, char *out, size_t freespace)
477 rlm_cache_entry_t *c;
478 rlm_cache_t *inst = instance;
479 VALUE_PAIR *vp, *vps;
481 DICT_ATTR const *target;
486 list = radius_list_name(&p, PAIR_LIST_REQUEST);
488 target = dict_attrbyname(p);
490 REDEBUG("Unknown attribute \"%s\"", p);
494 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
495 c = cache_find(inst, request, fmt);
498 RDEBUG("No cache entry for key \"%s\"", fmt);
504 case PAIR_LIST_REQUEST:
508 case PAIR_LIST_REPLY:
512 case PAIR_LIST_CONTROL:
516 case PAIR_LIST_UNKNOWN:
517 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
518 REDEBUG("Unknown list qualifier in \"%s\"", fmt);
522 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
523 REDEBUG("Unsupported list \"%s\"",
524 fr_int2str(pair_lists, list, "<UNKNOWN>"));
528 vp = pairfind(vps, target->attr, target->vendor, TAG_ANY);
530 RDEBUG("No instance of this attribute has been cached");
535 len = vp_prints_value(out, freespace, vp, 0);
536 if (is_truncated(len, freespace)) {
537 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
538 REDEBUG("Insufficient buffer space to write cached value");
542 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
548 * Only free memory we allocated. The strings allocated via
549 * cf_section_parse() do not need to be freed.
551 static int mod_detach(void *instance)
553 rlm_cache_t *inst = instance;
555 talloc_free(inst->maps);
557 fr_heap_delete(inst->heap);
558 rbtree_free(inst->cache);
560 #ifdef HAVE_PTHREAD_H
561 pthread_mutex_destroy(&inst->cache_mutex);
568 * Instantiate the module.
570 static int mod_instantiate(CONF_SECTION *conf, void *instance)
572 rlm_cache_t *inst = instance;
576 inst->xlat_name = cf_section_name2(conf);
577 if (!inst->xlat_name) {
578 inst->xlat_name = cf_section_name1(conf);
582 * Register the cache xlat function
584 xlat_register(inst->xlat_name, cache_xlat, NULL, inst);
586 rad_assert(inst->key && *inst->key);
588 if (inst->ttl == 0) {
589 cf_log_err_cs(conf, "Must set 'ttl' to non-zero");
593 if (inst->epoch != 0) {
594 cf_log_err_cs(conf, "Must not set 'epoch' in the configuration files");
598 #ifdef HAVE_PTHREAD_H
599 if (pthread_mutex_init(&inst->cache_mutex, NULL) < 0) {
600 ERROR("Failed initializing mutex: %s",
610 inst->cache = rbtree_create(NULL, cache_entry_cmp, cache_entry_free, 0);
612 ERROR("Failed to create cache");
615 fr_link_talloc_ctx_free(inst, inst->cache);
618 * The heap of entries to expire.
620 inst->heap = fr_heap_create(cache_heap_cmp,
621 offsetof(rlm_cache_entry_t, offset));
623 ERROR("Failed to create heap for the cache");
628 * Make sure the users don't screw up too badly.
630 if (map_afrom_cs(&inst->maps, cf_section_sub_find(inst->cs, "update"),
631 PAIR_LIST_REQUEST, PAIR_LIST_REQUEST, cache_verify, NULL, MAX_ATTRMAP) < 0) {
636 cf_log_err_cs(inst->cs, "Cache config must contain an update section, and "
637 "that section must not be empty");
646 * Do caching checks. Since we can update ANY VP list, we do
647 * exactly the same thing for all sections (autz / auth / etc.)
649 * If you want to cache something different in different sections,
650 * configure another cache module.
652 static rlm_rcode_t CC_HINT(nonnull) mod_cache_it(void *instance, REQUEST *request)
654 rlm_cache_entry_t *c;
655 rlm_cache_t *inst = instance;
661 if (radius_xlat(buffer, sizeof(buffer), request, inst->key, NULL, NULL) < 0) {
662 return RLM_MODULE_FAIL;
665 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
666 c = cache_find(inst, request, buffer);
669 * If yes, only return whether we found a valid cache entry
671 vp = pairfind(request->config_items, PW_CACHE_STATUS_ONLY, 0, TAG_ANY);
672 if (vp && vp->vp_integer) {
673 rcode = c ? RLM_MODULE_OK:
679 cache_merge(inst, request, c);
681 rcode = RLM_MODULE_OK;
685 vp = pairfind(request->config_items, PW_CACHE_READ_ONLY, 0, TAG_ANY);
686 if (vp && vp->vp_integer) {
687 rcode = RLM_MODULE_NOTFOUND;
691 c = cache_add(inst, request, buffer);
693 rcode = RLM_MODULE_NOOP;
697 rcode = RLM_MODULE_UPDATED;
700 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
703 * Reset control attributes
705 for (vp = fr_cursor_init(&cursor, &request->config_items);
707 vp = fr_cursor_next(&cursor)) {
708 if (vp->da->vendor == 0) switch (vp->da->attr) {
710 case PW_CACHE_READ_ONLY:
712 vp = fr_cursor_remove(&cursor);
723 * The module name should be the only globally exported symbol.
724 * That is, everything else should be 'static'.
726 * If the module needs to temporarily modify it's instantiation
727 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
728 * The server will then take care of ensuring that the module
729 * is single-threaded.
731 module_t rlm_cache = {
737 mod_instantiate, /* instantiation */
738 mod_detach, /* detach */
740 NULL, /* authentication */
741 mod_cache_it, /* authorization */
742 mod_cache_it, /* preaccounting */
743 mod_cache_it, /* accounting */
744 NULL, /* checksimul */
745 mod_cache_it, /* pre-proxy */
746 mod_cache_it, /* post-proxy */
747 mod_cache_it, /* post-auth */