2 Unix SMB/CIFS implementation.
4 Generic, persistent and shared between processes cache mechanism for use
5 by various parts of the Samba code
7 Copyright (C) Rafal Szczesniak 2002
8 Copyright (C) Volker Lendecke 2009
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "lib/gencache.h"
26 #include "system/filesys.h"
27 #include "system/glob.h"
29 #include "tdb_wrap/tdb_wrap.h"
33 #define DBGC_CLASS DBGC_TDB
35 static struct tdb_wrap *cache;
36 static struct tdb_wrap *cache_notrans;
40 * @brief Generic, persistent and shared between processes cache mechanism
41 * for use by various parts of the Samba code
45 struct gencache_timeout {
49 bool gencache_timeout_expired(const struct gencache_timeout *t)
51 return t->timeout <= time(NULL);
55 * Cache initialisation function. Opens cache tdb file or creates
56 * it if does not exist.
58 * @return true on successful initialisation of the cache or
62 static bool gencache_init(void)
64 char* cache_fname = NULL;
65 int open_flags = O_RDWR|O_CREAT;
68 /* skip file open if it's already opened */
73 hash_size = lp_parm_int(-1, "gencache", "hash_size", 10000);
75 cache_fname = cache_path(talloc_tos(), "gencache.tdb");
76 if (cache_fname == NULL) {
80 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
82 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
83 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
86 if (!cache && (errno == EACCES)) {
87 open_flags = O_RDONLY;
88 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
89 TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
92 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
95 TALLOC_FREE(cache_fname);
98 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
102 cache_fname = lock_path(talloc_tos(), "gencache_notrans.tdb");
103 if (cache_fname == NULL) {
108 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
110 cache_notrans = tdb_wrap_open(NULL, cache_fname, hash_size,
112 TDB_INCOMPATIBLE_HASH|
116 if (cache_notrans == NULL) {
117 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
119 TALLOC_FREE(cache_fname);
123 TALLOC_FREE(cache_fname);
128 static TDB_DATA last_stabilize_key(void)
130 const char key[] = "@LAST_STABILIZED";
133 .dptr = discard_const_p(uint8_t, key),
134 .dsize = sizeof(key),
138 struct gencache_have_val_state {
140 const DATA_BLOB *data;
144 static void gencache_have_val_parser(const struct gencache_timeout *old_timeout,
148 struct gencache_have_val_state *state =
149 (struct gencache_have_val_state *)private_data;
150 time_t now = time(NULL);
151 int cache_time_left, new_time_left, additional_time;
154 * Excuse the many variables, but these time calculations are
155 * confusing to me. We do not want to write to gencache with a
156 * possibly expensive transaction if we are about to write the same
157 * value, just extending the remaining timeout by less than 10%.
160 cache_time_left = old_timeout->timeout - now;
161 if (cache_time_left <= 0) {
163 * timed out, write new value
168 new_time_left = state->new_timeout - now;
169 if (new_time_left <= 0) {
171 * Huh -- no new timeout?? Write it.
176 if (new_time_left < cache_time_left) {
178 * Someone wants to shorten the timeout. Let it happen.
184 * By how much does the new timeout extend the remaining cache time?
186 additional_time = new_time_left - cache_time_left;
188 if (additional_time * 10 < 0) {
190 * Integer overflow. We extend by so much that we have to write it.
196 * The comparison below is essentially equivalent to
198 * new_time_left > cache_time_left * 1.10
200 * but without floating point calculations.
203 if (additional_time * 10 > cache_time_left) {
205 * We extend the cache timeout by more than 10%. Do it.
211 * Now the more expensive data compare.
213 if (data_blob_cmp(state->data, &data) != 0) {
215 * Write a new value. Certainly do it.
221 * Extending the timeout by less than 10% for the same cache value is
222 * not worth the trouble writing a value into gencache under a
223 * possibly expensive transaction.
228 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
231 struct gencache_have_val_state state;
233 state.new_timeout = timeout;
237 if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
243 static int last_stabilize_parser(TDB_DATA key, TDB_DATA data,
246 time_t *last_stabilize = private_data;
248 if ((data.dsize != 0) && (data.dptr[data.dsize-1] == '\0')) {
249 *last_stabilize = atoi((char *)data.dptr);
255 * Set an entry in the cache file. If there's no such
258 * @param keystr string that represents a key of this entry
259 * @param blob DATA_BLOB value being cached
260 * @param timeout time when the value is expired
262 * @retval true when entry is successfully stored
263 * @retval false on failure
266 bool gencache_set_data_blob(const char *keystr, DATA_BLOB blob,
271 time_t last_stabilize;
272 static int writecount;
276 if ((keystr == NULL) || (blob.data == NULL)) {
280 key = string_term_tdb_data(keystr);
282 ret = tdb_data_cmp(key, last_stabilize_key());
284 DEBUG(10, ("Can't store %s as a key\n", keystr));
288 if (!gencache_init()) {
292 if ((timeout != 0) && gencache_have_val(keystr, &blob, timeout)) {
293 DEBUG(10, ("Did not store value for %s, we already got it\n",
298 dbufs[0] = (TDB_DATA) { .dptr = (uint8_t *)&timeout,
299 .dsize = sizeof(time_t) };
300 dbufs[1] = (TDB_DATA) { .dptr = blob.data, .dsize = blob.length };
302 crc = crc32(0, Z_NULL, 0);
303 crc = crc32(crc, key.dptr, key.dsize);
304 crc = crc32(crc, dbufs[0].dptr, dbufs[0].dsize);
305 crc = crc32(crc, dbufs[1].dptr, dbufs[1].dsize);
307 dbufs[2] = (TDB_DATA) { .dptr = (uint8_t *)&crc,
308 .dsize = sizeof(crc) };
310 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
311 "[%s] (%d seconds %s)\n", keystr,
312 timestring(talloc_tos(), timeout),
313 (int)(timeout - time(NULL)),
314 timeout > time(NULL) ? "ahead" : "in the past"));
316 ret = tdb_storev(cache_notrans->tdb, key, dbufs, ARRAY_SIZE(dbufs), 0);
322 * Every 100 writes within a single process, stabilize the cache with
323 * a transaction. This is done to prevent a single transaction to
324 * become huge and chew lots of memory.
327 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
328 gencache_stabilize();
334 * Every 5 minutes, call gencache_stabilize() to not let grow
335 * gencache_notrans.tdb too large.
340 tdb_parse_record(cache_notrans->tdb, last_stabilize_key(),
341 last_stabilize_parser, &last_stabilize);
344 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
346 gencache_stabilize();
353 static void gencache_del_parser(const struct gencache_timeout *t,
357 if (t->timeout != 0) {
358 bool *exists = private_data;
364 * Delete one entry from the cache file.
366 * @param keystr string that represents a key of this entry
368 * @retval true upon successful deletion
369 * @retval false in case of failure
372 bool gencache_del(const char *keystr)
374 TDB_DATA key = string_term_tdb_data(keystr);
379 if (keystr == NULL) {
383 if (!gencache_init()) {
387 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
389 ret = tdb_chainlock(cache_notrans->tdb, key);
394 gencache_parse(keystr, gencache_del_parser, &exists);
398 * We delete an element by setting its timeout to
399 * 0. This way we don't have to do a transaction on
400 * gencache.tdb every time we delete an element.
402 result = gencache_set(keystr, "", 0);
405 tdb_chainunlock(cache_notrans->tdb, key);
410 static bool gencache_pull_timeout(TDB_DATA key,
416 uint32_t crc, stored_crc;
418 if ((data.dptr == NULL) ||
419 (data.dsize < (sizeof(time_t) + sizeof(uint32_t)))) {
423 crc_ofs = data.dsize - sizeof(uint32_t);
425 crc = crc32(0, Z_NULL, 0);
426 crc = crc32(crc, key.dptr, key.dsize);
427 crc = crc32(crc, data.dptr, crc_ofs);
429 memcpy(&stored_crc, data.dptr + crc_ofs, sizeof(uint32_t));
431 if (stored_crc != crc) {
436 memcpy(pres, data.dptr, sizeof(time_t));
438 if (payload != NULL) {
439 *payload = (DATA_BLOB) {
440 .data = data.dptr+sizeof(time_t),
441 .length = data.dsize-sizeof(time_t)-sizeof(uint32_t),
447 struct gencache_parse_state {
448 void (*parser)(const struct gencache_timeout *timeout,
452 bool copy_to_notrans;
455 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
457 struct gencache_parse_state *state;
458 struct gencache_timeout t;
462 ret = gencache_pull_timeout(key, data, &t.timeout, &payload);
466 state = (struct gencache_parse_state *)private_data;
467 state->parser(&t, payload, state->private_data);
469 if (state->copy_to_notrans) {
470 tdb_store(cache_notrans->tdb, key, data, 0);
476 bool gencache_parse(const char *keystr,
477 void (*parser)(const struct gencache_timeout *timeout,
482 struct gencache_parse_state state;
483 TDB_DATA key = string_term_tdb_data(keystr);
486 if (keystr == NULL) {
489 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
492 if (!gencache_init()) {
496 state.parser = parser;
497 state.private_data = private_data;
498 state.copy_to_notrans = false;
500 ret = tdb_chainlock(cache_notrans->tdb, key);
505 ret = tdb_parse_record(cache_notrans->tdb, key,
506 gencache_parse_fn, &state);
508 tdb_chainunlock(cache_notrans->tdb, key);
512 state.copy_to_notrans = true;
514 ret = tdb_parse_record(cache->tdb, key, gencache_parse_fn, &state);
516 if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_NOEXIST)) {
518 * The record does not exist. Set a delete-marker in
519 * gencache_notrans, so that we don't have to look at
520 * the fcntl-based cache again.
522 gencache_set(keystr, "", 0);
525 tdb_chainunlock(cache_notrans->tdb, key);
530 struct gencache_get_data_blob_state {
537 static void gencache_get_data_blob_parser(const struct gencache_timeout *t,
541 struct gencache_get_data_blob_state *state =
542 (struct gencache_get_data_blob_state *)private_data;
544 if (t->timeout == 0) {
545 state->result = false;
548 state->timeout = t->timeout;
550 if (state->blob == NULL) {
551 state->result = true;
555 *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
557 if (state->blob->data == NULL) {
558 state->result = false;
561 state->result = true;
565 * Get existing entry from the cache file.
567 * @param keystr string that represents a key of this entry
568 * @param blob DATA_BLOB that is filled with entry's blob
569 * @param timeout pointer to a time_t that is filled with entry's
572 * @retval true when entry is successfully fetched
573 * @retval false for failure
576 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
578 time_t *timeout, bool *was_expired)
580 struct gencache_get_data_blob_state state;
581 bool expired = false;
583 state.result = false;
584 state.mem_ctx = mem_ctx;
587 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
593 if (state.timeout <= time(NULL)) {
595 * We're expired, delete the entry. We can't use gencache_del
596 * here, because that uses gencache_get_data_blob for checking
597 * the existence of a record. We know the thing exists and
598 * directly store an empty value with 0 timeout.
600 gencache_set(keystr, "", 0);
605 *timeout = state.timeout;
611 if (was_expired != NULL) {
612 *was_expired = expired;
614 if (state.result && state.blob) {
615 data_blob_free(state.blob);
620 struct stabilize_state {
623 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
629 * Migrate the clear-if-first gencache data to the stable,
630 * transaction-based gencache.tdb
633 bool gencache_stabilize(void)
635 struct stabilize_state state;
639 if (!gencache_init()) {
643 res = tdb_transaction_start_nonblock(cache->tdb);
645 if (tdb_error(cache->tdb) == TDB_ERR_NOLOCK)
648 * Someone else already does the stabilize,
649 * this does not have to be done twice
654 DEBUG(10, ("Could not start transaction on gencache.tdb: "
655 "%s\n", tdb_errorstr(cache->tdb)));
659 res = tdb_lockall_nonblock(cache_notrans->tdb);
661 tdb_transaction_cancel(cache->tdb);
662 DEBUG(10, ("Could not get allrecord lock on "
663 "gencache_notrans.tdb: %s\n",
664 tdb_errorstr(cache_notrans->tdb)));
668 state.written = false;
670 res = tdb_traverse(cache_notrans->tdb, stabilize_fn, &state);
672 tdb_unlockall(cache_notrans->tdb);
673 tdb_transaction_cancel(cache->tdb);
677 if (!state.written) {
678 tdb_unlockall(cache_notrans->tdb);
679 tdb_transaction_cancel(cache->tdb);
683 res = tdb_transaction_commit(cache->tdb);
685 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
686 "%s\n", tdb_errorstr(cache->tdb)));
687 tdb_unlockall(cache_notrans->tdb);
691 res = tdb_wipe_all(cache_notrans->tdb);
693 DBG_DEBUG("tdb_wipe_all on gencache_notrans.tdb failed: %s\n",
694 tdb_errorstr(cache_notrans->tdb));
697 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
699 tdb_store(cache_notrans->tdb, last_stabilize_key(),
700 string_term_tdb_data(now), 0);
704 res = tdb_unlockall(cache_notrans->tdb);
706 DEBUG(10, ("tdb_unlockall on gencache.tdb failed: "
707 "%s\n", tdb_errorstr(cache->tdb)));
714 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
717 struct stabilize_state *state = (struct stabilize_state *)priv;
721 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
725 if (!gencache_pull_timeout(key, val, &timeout, NULL)) {
726 DEBUG(10, ("Ignoring invalid entry\n"));
729 if ((timeout < time(NULL)) || (val.dsize == 0)) {
730 res = tdb_delete(cache->tdb, key);
732 state->written = true;
733 } else if (tdb_error(cache->tdb) == TDB_ERR_NOEXIST) {
737 res = tdb_store(cache->tdb, key, val, 0);
739 state->written = true;
744 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
745 tdb_errorstr(cache->tdb)));
753 * Get existing entry from the cache file.
755 * @param keystr string that represents a key of this entry
756 * @param valstr buffer that is allocated and filled with the entry value
757 * buffer's disposing must be done outside
758 * @param timeout pointer to a time_t that is filled with entry's
761 * @retval true when entry is successfully fetched
762 * @retval false for failure
765 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
771 ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
775 if ((blob.data == NULL) || (blob.length == 0)) {
776 data_blob_free(&blob);
779 if (blob.data[blob.length-1] != '\0') {
780 /* Not NULL terminated, can't be a string */
781 data_blob_free(&blob);
786 * talloc_move generates a type-punned warning here. As we
787 * leave the function immediately, do a simple talloc_steal.
789 *value = (char *)talloc_steal(mem_ctx, blob.data);
792 data_blob_free(&blob);
797 * Set an entry in the cache file. If there's no such
800 * @param keystr string that represents a key of this entry
801 * @param value text representation value being cached
802 * @param timeout time when the value is expired
804 * @retval true when entry is successfully stored
805 * @retval false on failure
808 bool gencache_set(const char *keystr, const char *value, time_t timeout)
810 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
811 return gencache_set_data_blob(keystr, blob, timeout);
814 struct gencache_iterate_blobs_state {
815 void (*fn)(const char *key, DATA_BLOB value,
816 time_t timeout, void *private_data);
822 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
823 TDB_DATA data, void *priv)
825 struct gencache_iterate_blobs_state *state =
826 (struct gencache_iterate_blobs_state *)priv;
828 char *free_key = NULL;
832 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
835 if (state->in_persistent && tdb_exists(cache_notrans->tdb, key)) {
839 if (key.dptr[key.dsize-1] == '\0') {
840 keystr = (char *)key.dptr;
842 /* ensure 0-termination */
843 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
845 if (keystr == NULL) {
850 if (!gencache_pull_timeout(key, data, &timeout, &payload)) {
859 if (fnmatch(state->pattern, keystr, 0) != 0) {
863 DEBUG(10, ("Calling function with arguments "
864 "(key=[%s], timeout=[%s])\n",
865 keystr, timestring(talloc_tos(), timeout)));
867 state->fn(keystr, payload, timeout, state->private_data);
870 TALLOC_FREE(free_key);
874 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
875 time_t timeout, void *private_data),
876 void *private_data, const char *pattern)
878 struct gencache_iterate_blobs_state state;
880 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
884 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
887 state.pattern = pattern;
888 state.private_data = private_data;
890 state.in_persistent = false;
891 tdb_traverse(cache_notrans->tdb, gencache_iterate_blobs_fn, &state);
893 state.in_persistent = true;
894 tdb_traverse(cache->tdb, gencache_iterate_blobs_fn, &state);
898 * Iterate through all entries which key matches to specified pattern
900 * @param fn pointer to the function that will be supplied with each single
901 * matching cache entry (key, value and timeout) as an arguments
902 * @param data void pointer to an arbitrary data that is passed directly to the fn
903 * function on each call
904 * @param keystr_pattern pattern the existing entries' keys are matched to
908 struct gencache_iterate_state {
909 void (*fn)(const char *key, const char *value, time_t timeout,
914 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
915 time_t timeout, void *private_data)
917 struct gencache_iterate_state *state =
918 (struct gencache_iterate_state *)private_data;
920 char *free_val = NULL;
922 if (value.data[value.length-1] == '\0') {
923 valstr = (char *)value.data;
925 /* ensure 0-termination */
926 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
928 if (valstr == NULL) {
933 DEBUG(10, ("Calling function with arguments "
934 "(key=[%s], value=[%s], timeout=[%s])\n",
935 key, valstr, timestring(talloc_tos(), timeout)));
937 state->fn(key, valstr, timeout, state->private_data);
941 TALLOC_FREE(free_val);
944 void gencache_iterate(void (*fn)(const char *key, const char *value,
945 time_t timeout, void *dptr),
946 void *private_data, const char *pattern)
948 struct gencache_iterate_state state;
954 state.private_data = private_data;
955 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);