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>
31 * Define a structure for our module configuration.
33 * These variables do not need to be in a structure, but it's
34 * a lot cleaner to do so, and a pointer to the structure can
35 * be used as the instance handle.
37 typedef struct rlm_cache_t {
38 char const *xlat_name;
48 value_pair_map_t *maps; //!< Attribute map applied to users
51 pthread_mutex_t cache_mutex;
55 typedef struct rlm_cache_entry_t {
67 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
68 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
70 #define PTHREAD_MUTEX_LOCK(_x)
71 #define PTHREAD_MUTEX_UNLOCK(_x)
74 #define MAX_ATTRMAP 128
77 * A mapping of configuration file names to internal variables.
79 * Note that the string is dynamically allocated, so it MUST
80 * be freed. When the configuration file parse re-reads the string,
81 * it free's the old one, and strdup's the new one, placing the pointer
82 * to the strdup'd string into 'config.string'. This gets around
85 static const CONF_PARSER module_config[] = {
86 { "key", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED | PW_TYPE_XLAT, rlm_cache_t, key), NULL },
87 { "ttl", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_cache_t, ttl), "500" },
88 { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_cache_t, max_entries), "16384" },
90 /* Should be a type which matches time_t, @fixme before 2038 */
91 { "epoch", FR_CONF_OFFSET(PW_TYPE_SIGNED, rlm_cache_t, epoch), "0" },
92 { "add_stats", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, rlm_cache_t, stats), "no" },
94 { NULL, -1, 0, NULL, NULL } /* end the list */
99 * Compare two entries by key. There may only be one entry with
102 static int cache_entry_cmp(void const *one, void const *two)
104 rlm_cache_entry_t const *a = one;
105 rlm_cache_entry_t const *b = two;
107 return strcmp(a->key, b->key);
110 static void cache_entry_free(void *data)
112 rlm_cache_entry_t *c = data;
114 pairfree(&c->control);
115 pairfree(&c->packet);
122 * Compare two entries by expiry time. There may be multiple
123 * entries with the same expiry time.
125 static int cache_heap_cmp(void const *one, void const *two)
127 rlm_cache_entry_t const *a = one;
128 rlm_cache_entry_t const *b = two;
130 if (a->expires < b->expires) return -1;
131 if (a->expires > b->expires) return +1;
137 * Merge a cached entry into a REQUEST.
139 static void CC_HINT(nonnull) cache_merge(rlm_cache_t *inst, REQUEST *request, rlm_cache_entry_t *c)
143 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
144 if (vp && (vp->vp_integer == 0)) {
145 RDEBUG2("Told not to merge entry into request");
150 RDEBUG2("Merging cached control list:");
151 rdebug_pair_list(2, request, c->control);
153 pairadd(&request->config_items, paircopy(request, c->control));
156 if (c->packet && request->packet) {
157 RDEBUG2("Merging cached request list:");
158 rdebug_pair_list(2, request, c->packet);
160 pairadd(&request->packet->vps,
161 paircopy(request->packet, c->packet));
164 if (c->reply && request->reply) {
165 RDEBUG2("Merging cached reply list:");
166 rdebug_pair_list(2, request, c->reply);
168 pairadd(&request->reply->vps,
169 paircopy(request->reply, c->reply));
173 vp = paircreate(request->packet, PW_CACHE_ENTRY_HITS, 0);
174 rad_assert(vp != NULL);
176 vp->vp_integer = c->hits;
178 pairadd(&request->packet->vps, vp);
184 * Find a cached entry.
186 static rlm_cache_entry_t *cache_find(rlm_cache_t *inst, REQUEST *request,
190 rlm_cache_entry_t *c, my_c;
194 * Look at the expiry heap.
196 c = fr_heap_peek(inst->heap);
198 rad_assert(rbtree_num_elements(inst->cache) == 0);
203 * If it's time to expire an old entry, do so now.
205 if (c->expires < request->timestamp) {
206 fr_heap_extract(inst->heap, c);
207 rbtree_deletebydata(inst->cache, c);
211 * Is there an entry for this key?
214 c = rbtree_finddata(inst->cache, &my_c);
218 * Yes, but it expired, OR the "forget all" epoch has
219 * passed. Delete it, and pretend it doesn't exist.
221 if ((c->expires < request->timestamp) ||
222 (c->created < inst->epoch)) {
224 RDEBUG("Entry has expired, removing");
226 fr_heap_extract(inst->heap, c);
227 rbtree_deletebydata(inst->cache, c);
232 RDEBUG("Found entry for \"%s\"", key);
235 * Update the expiry time based on the TTL.
236 * A TTL of 0 means "delete from the cache".
237 * A TTL < 0 means "delete from the cache and recreate the entry".
239 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
241 if (vp->vp_signed <= 0) goto delete;
244 c->expires = request->timestamp + ttl;
245 RDEBUG("Adding %d to the TTL", ttl);
253 /** Callback for map_to_request
255 * Simplifies merging VALUE_PAIRs into the current request.
257 static int _cache_add(VALUE_PAIR **out, REQUEST *request, UNUSED value_pair_map_t const *map, void *ctx)
261 vp = talloc_get_type_abort(ctx, VALUE_PAIR);
262 /* map_to_request will reparent */
263 *out = paircopy(request, vp);
265 if (!*out) return -1;
270 * Add an entry to the cache.
272 static rlm_cache_entry_t *cache_add(rlm_cache_t *inst, REQUEST *request, char const *key)
275 VALUE_PAIR *vp, *to_cache;
276 vp_cursor_t src_list, cached_request, cached_reply, cached_control;
280 value_pair_map_t const *map;
282 rlm_cache_entry_t *c;
284 if (rbtree_num_elements(inst->cache) >= inst->max_entries) {
285 RDEBUG("Cache is full: %d entries", inst->max_entries);
290 * TTL of 0 means "don't cache this entry"
292 vp = pairfind(request->config_items, PW_CACHE_TTL, 0, TAG_ANY);
293 if (vp && (vp->vp_signed == 0)) return NULL;
295 c = talloc_zero(NULL, rlm_cache_entry_t);
296 c->key = talloc_typed_strdup(c, key);
297 c->created = c->expires = request->timestamp;
300 * Use per-entry TTL if > 0, or globally defined one.
302 ttl = vp && (vp->vp_signed > 0) ? vp->vp_integer : inst->ttl;
305 RDEBUG("Creating entry for \"%s\"", key);
308 * Check to see if we need to merge the entry into the request
310 vp = pairfind(request->config_items, PW_CACHE_MERGE, 0, TAG_ANY);
311 if (vp && (vp->vp_integer == 0)) {
313 RDEBUG2("Told not to merge new entry into request");
316 fr_cursor_init(&cached_request, &c->packet);
317 fr_cursor_init(&cached_reply, &c->reply);
318 fr_cursor_init(&cached_control, &c->control);
320 for (map = inst->maps; map != NULL; map = map->next) {
321 bool do_merge = merge;
323 rad_assert(map->lhs && map->rhs);
325 if (map_to_vp(&to_cache, request, map, NULL) < 0) {
326 RDEBUG("Skipping %s", map->rhs->name);
331 * Merge attributes into the current request if:
332 * - Map specifies an xlat'd string.
333 * - Map specifies a literal string.
334 * - Map specifies an exec.
335 * - Map src and dst lists differ.
336 * - Map src and dst attributes differ
338 * Unless Cache-Merge = no
340 if (do_merge) switch (map->rhs->type) {
341 case TMPL_TYPE_LITERAL:
347 if (map->rhs->tmpl_list == map->lhs->tmpl_list) do_merge = false;
351 rad_assert(map->lhs->type == TMPL_TYPE_ATTR);
352 if (map->rhs->tmpl_da == map->lhs->tmpl_da) do_merge = false;
360 * Reparent the VPs map_to_vp may return multiple.
362 for (vp = fr_cursor_init(&src_list, &to_cache);
364 vp = fr_cursor_next(&src_list)) {
368 * Prevent people from accidentally caching
369 * cache control attributes.
371 if (map->rhs->type == TMPL_TYPE_LIST) switch (vp->da->attr) {
373 case PW_CACHE_STATUS_ONLY:
374 case PW_CACHE_READ_ONLY:
376 case PW_CACHE_ENTRY_HITS:
377 RDEBUG2("Skipping %s", vp->da->name);
384 if (debug_flag) map_debug_log(request, map, vp);
385 (void) talloc_steal(c, vp);
389 switch (map->lhs->tmpl_list) {
390 case PAIR_LIST_REQUEST:
391 fr_cursor_insert(&cached_request, vp);
394 case PAIR_LIST_REPLY:
395 fr_cursor_insert(&cached_reply, vp);
398 case PAIR_LIST_CONTROL:
399 fr_cursor_insert(&cached_control, vp);
403 rad_assert(0); /* should have been caught by validation */
406 if (do_merge && map_dst_valid(request, map)) {
407 /* There's no reason for this to fail (we checked the dst was valid) */
408 RDEBUG2("Adding to request:");
409 if (map_to_request(request, map, _cache_add, vp) < 0) rad_assert(0);
414 if (!rbtree_insert(inst->cache, c)) {
415 REDEBUG("FAILED adding entry for key %s", key);
420 if (!fr_heap_insert(inst->heap, c)) {
421 REDEBUG("FAILED adding entry for key %s", key);
422 rbtree_deletebydata(inst->cache, c);
426 RDEBUG("Inserted entry, TTL %d seconds", ttl);
432 * Verify that the cache section makes sense.
434 static int cache_verify(rlm_cache_t *inst, value_pair_map_t **head)
436 value_pair_map_t *map;
438 if (map_afrom_cs(head, cf_section_sub_find(inst->cs, "update"),
439 PAIR_LIST_REQUEST, PAIR_LIST_REQUEST, MAX_ATTRMAP) < 0) {
444 cf_log_err_cs(inst->cs,
445 "Cache config must contain an update section, and "
446 "that section must not be empty");
451 for (map = *head; map != NULL; map = map->next) {
452 if ((map->lhs->type != TMPL_TYPE_ATTR) &&
453 (map->lhs->type != TMPL_TYPE_LIST)) {
454 cf_log_err(map->ci, "Left operand must be an attribute "
461 * Can't copy an xlat expansion or literal into a list,
462 * we don't know what type of attribute we'd need
465 * The only exception is where were using a unary
468 if ((map->lhs->type == TMPL_TYPE_LIST) &&
469 (map->op != T_OP_CMP_FALSE) &&
470 ((map->rhs->type == TMPL_TYPE_XLAT) || (map->rhs->type == TMPL_TYPE_LITERAL))) {
471 cf_log_err(map->ci, "Can't copy value into list (we don't know which attribute to create)");
476 switch (map->rhs->type) {
478 cf_log_err(map->ci, "Exec values are not allowed");
483 * Only =, :=, += and -= operators are supported for
486 case TMPL_TYPE_LITERAL:
488 * @fixme: This should be moved into a common function
489 * with the check in do_compile_modupdate.
491 if (map->lhs->type == TMPL_TYPE_ATTR) {
495 MEM(vp = pairalloc(map->lhs, map->lhs->tmpl_da));
498 ret = pairparsevalue(vp, map->rhs->name, 0);
501 cf_log_err(map->ci, "%s", fr_strerror());
517 cf_log_err(map->ci, "Operator \"%s\" not "
518 "allowed for %s values",
519 fr_int2str(fr_tokens, map->op,
521 fr_int2str(tmpl_types, map->rhs->type,
533 * Allow single attribute values to be retrieved from the cache.
535 static ssize_t cache_xlat(void *instance, REQUEST *request,
536 char const *fmt, char *out, size_t freespace)
538 rlm_cache_entry_t *c;
539 rlm_cache_t *inst = instance;
540 VALUE_PAIR *vp, *vps;
542 DICT_ATTR const *target;
547 list = radius_list_name(&p, PAIR_LIST_REQUEST);
549 target = dict_attrbyname(p);
551 REDEBUG("Unknown attribute \"%s\"", p);
555 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
556 c = cache_find(inst, request, fmt);
559 RDEBUG("No cache entry for key \"%s\"", fmt);
565 case PAIR_LIST_REQUEST:
569 case PAIR_LIST_REPLY:
573 case PAIR_LIST_CONTROL:
577 case PAIR_LIST_UNKNOWN:
578 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
579 REDEBUG("Unknown list qualifier in \"%s\"", fmt);
583 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
584 REDEBUG("Unsupported list \"%s\"",
585 fr_int2str(pair_lists, list, "<UNKNOWN>"));
589 vp = pairfind(vps, target->attr, target->vendor, TAG_ANY);
591 RDEBUG("No instance of this attribute has been cached");
596 len = vp_prints_value(out, freespace, vp, 0);
597 if (is_truncated(len, freespace)) {
598 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
599 REDEBUG("Insufficient buffer space to write cached value");
603 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
609 * Only free memory we allocated. The strings allocated via
610 * cf_section_parse() do not need to be freed.
612 static int mod_detach(void *instance)
614 rlm_cache_t *inst = instance;
616 talloc_free(inst->maps);
618 fr_heap_delete(inst->heap);
619 rbtree_free(inst->cache);
621 #ifdef HAVE_PTHREAD_H
622 pthread_mutex_destroy(&inst->cache_mutex);
629 * Instantiate the module.
631 static int mod_instantiate(CONF_SECTION *conf, void *instance)
633 rlm_cache_t *inst = instance;
637 inst->xlat_name = cf_section_name2(conf);
638 if (!inst->xlat_name) {
639 inst->xlat_name = cf_section_name1(conf);
643 * Register the cache xlat function
645 xlat_register(inst->xlat_name, cache_xlat, NULL, inst);
647 rad_assert(inst->key && *inst->key);
649 if (inst->ttl == 0) {
650 cf_log_err_cs(conf, "Must set 'ttl' to non-zero");
654 if (inst->epoch != 0) {
655 cf_log_err_cs(conf, "Must not set 'epoch' in the configuration files");
659 #ifdef HAVE_PTHREAD_H
660 if (pthread_mutex_init(&inst->cache_mutex, NULL) < 0) {
661 ERROR("Failed initializing mutex: %s",
671 inst->cache = rbtree_create(NULL, cache_entry_cmp, cache_entry_free, 0);
673 ERROR("Failed to create cache");
676 fr_link_talloc_ctx_free(inst, inst->cache);
679 * The heap of entries to expire.
681 inst->heap = fr_heap_create(cache_heap_cmp,
682 offsetof(rlm_cache_entry_t, offset));
684 ERROR("Failed to create heap for the cache");
689 * Make sure the users don't screw up too badly.
691 if (cache_verify(inst, &inst->maps) < 0) {
699 * Do caching checks. Since we can update ANY VP list, we do
700 * exactly the same thing for all sections (autz / auth / etc.)
702 * If you want to cache something different in different sections,
703 * configure another cache module.
705 static rlm_rcode_t CC_HINT(nonnull) mod_cache_it(void *instance, REQUEST *request)
707 rlm_cache_entry_t *c;
708 rlm_cache_t *inst = instance;
714 if (radius_xlat(buffer, sizeof(buffer), request, inst->key, NULL, NULL) < 0) {
715 return RLM_MODULE_FAIL;
718 PTHREAD_MUTEX_LOCK(&inst->cache_mutex);
719 c = cache_find(inst, request, buffer);
722 * If yes, only return whether we found a valid cache entry
724 vp = pairfind(request->config_items, PW_CACHE_STATUS_ONLY, 0, TAG_ANY);
725 if (vp && vp->vp_integer) {
726 rcode = c ? RLM_MODULE_OK:
732 cache_merge(inst, request, c);
734 rcode = RLM_MODULE_OK;
738 vp = pairfind(request->config_items, PW_CACHE_READ_ONLY, 0, TAG_ANY);
739 if (vp && vp->vp_integer) {
740 rcode = RLM_MODULE_NOTFOUND;
744 c = cache_add(inst, request, buffer);
746 rcode = RLM_MODULE_NOOP;
750 rcode = RLM_MODULE_UPDATED;
753 PTHREAD_MUTEX_UNLOCK(&inst->cache_mutex);
756 * Reset control attributes
758 for (vp = fr_cursor_init(&cursor, &request->config_items);
760 vp = fr_cursor_next(&cursor)) {
761 if (vp->da->vendor == 0) switch (vp->da->attr) {
763 case PW_CACHE_READ_ONLY:
765 vp = fr_cursor_remove(&cursor);
776 * The module name should be the only globally exported symbol.
777 * That is, everything else should be 'static'.
779 * If the module needs to temporarily modify it's instantiation
780 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
781 * The server will then take care of ensuring that the module
782 * is single-threaded.
784 module_t rlm_cache = {
790 mod_instantiate, /* instantiation */
791 mod_detach, /* detach */
793 NULL, /* authentication */
794 mod_cache_it, /* authorization */
795 mod_cache_it, /* preaccounting */
796 mod_cache_it, /* accounting */
797 NULL, /* checksimul */
798 mod_cache_it, /* pre-proxy */
799 mod_cache_it, /* post-proxy */
800 mod_cache_it, /* post-auth */