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 "system/filesys.h"
26 #include "system/glob.h"
30 #define DBGC_CLASS DBGC_TDB
32 #define TIMEOUT_LEN 12
33 #define CACHE_DATA_FMT "%12u/"
34 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
35 #define BLOB_TYPE "DATA_BLOB"
36 #define BLOB_TYPE_LEN 9
38 static struct tdb_context *cache;
39 static struct tdb_context *cache_notrans;
43 * @brief Generic, persistent and shared between processes cache mechanism
44 * for use by various parts of the Samba code
50 * Cache initialisation function. Opens cache tdb file or creates
51 * it if does not exist.
53 * @return true on successful initialisation of the cache or
57 static bool gencache_init(void)
59 char* cache_fname = NULL;
60 int open_flags = O_RDWR|O_CREAT;
61 bool first_try = true;
63 /* skip file open if it's already opened */
64 if (cache) return True;
66 cache_fname = lock_path("gencache.tdb");
68 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
71 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
74 ret = tdb_check(cache, NULL, NULL);
79 DEBUG(0, ("gencache_init: tdb_check(%s) failed\n",
84 DEBUG(0, ("gencache_init: tdb_check(%s) failed - retry after CLEAR_IF_FIRST\n",
86 cache = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
95 if (!cache && (errno == EACCES)) {
96 open_flags = O_RDONLY;
97 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
100 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
105 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
109 cache_fname = lock_path("gencache_notrans.tdb");
111 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
113 cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
115 if (cache_notrans == NULL) {
116 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
126 static TDB_DATA last_stabilize_key(void)
129 result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
135 * Set an entry in the cache file. If there's no such
138 * @param keystr string that represents a key of this entry
139 * @param blob DATA_BLOB value being cached
140 * @param timeout time when the value is expired
142 * @retval true when entry is successfuly stored
143 * @retval false on failure
146 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
152 time_t last_stabilize;
153 static int writecount;
155 if (tdb_data_cmp(string_term_tdb_data(keystr),
156 last_stabilize_key()) == 0) {
157 DEBUG(10, ("Can't store %s as a key\n", keystr));
161 if ((keystr == NULL) || (blob == NULL)) {
165 if (!gencache_init()) return False;
167 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
171 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
175 val = (char *)talloc_append_blob(NULL, val, *blob);
180 DEBUG(10, ("Adding cache entry with key = %s and timeout ="
181 " %s (%d seconds %s)\n", keystr, ctime(&timeout),
182 (int)(timeout - time(NULL)),
183 timeout > time(NULL) ? "ahead" : "in the past"));
185 ret = tdb_store_bystring(
186 cache_notrans, keystr,
187 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
196 * Every 100 writes within a single process, stabilize the cache with
197 * a transaction. This is done to prevent a single transaction to
198 * become huge and chew lots of memory.
201 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
202 gencache_stabilize();
208 * Every 5 minutes, call gencache_stabilize() to not let grow
209 * gencache_notrans.tdb too large.
213 databuf = tdb_fetch(cache_notrans, last_stabilize_key());
214 if ((databuf.dptr != NULL)
215 && (databuf.dptr[databuf.dsize-1] == '\0')) {
216 last_stabilize = atoi((char *)databuf.dptr);
217 SAFE_FREE(databuf.dptr);
220 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
222 gencache_stabilize();
230 * Delete one entry from the cache file.
232 * @param keystr string that represents a key of this entry
234 * @retval true upon successful deletion
235 * @retval false in case of failure
238 bool gencache_del(const char *keystr)
240 bool exists, was_expired;
244 if (keystr == NULL) {
248 if (!gencache_init()) return False;
250 DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
253 * We delete an element by setting its timeout to 0. This way we don't
254 * have to do a transaction on gencache.tdb every time we delete an
258 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
260 if (!exists && was_expired) {
262 * gencache_get_data_blob has implicitly deleted this
263 * entry, so we have to return success here.
269 data_blob_free(&value);
270 ret = gencache_set(keystr, "", 0);
275 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
284 res = strtol(val, &endptr, 10);
286 if ((endptr == NULL) || (*endptr != '/')) {
287 DEBUG(2, ("Invalid gencache data format: %s\n", val));
293 if (pendptr != NULL) {
299 struct gencache_parse_state {
300 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
304 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
306 struct gencache_parse_state *state;
312 if (data.dptr == NULL) {
315 ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
319 state = (struct gencache_parse_state *)private_data;
320 blob = data_blob_const(
321 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
322 state->parser(t, blob, state->private_data);
326 bool gencache_parse(const char *keystr,
327 void (*parser)(time_t timeout, DATA_BLOB blob,
331 struct gencache_parse_state state;
335 if (keystr == NULL) {
338 if (tdb_data_cmp(string_term_tdb_data(keystr),
339 last_stabilize_key()) == 0) {
342 if (!gencache_init()) {
346 key = string_term_tdb_data(keystr);
347 state.parser = parser;
348 state.private_data = private_data;
350 ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
354 ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
358 struct gencache_get_data_blob_state {
364 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
367 struct gencache_get_data_blob_state *state =
368 (struct gencache_get_data_blob_state *)private_data;
371 state->result = false;
374 state->timeout = timeout;
376 if (state->blob == NULL) {
377 state->result = true;
381 *state->blob = data_blob(blob.data, blob.length);
382 if (state->blob->data == NULL) {
383 state->result = false;
386 state->result = true;
390 * Get existing entry from the cache file.
392 * @param keystr string that represents a key of this entry
393 * @param blob DATA_BLOB that is filled with entry's blob
394 * @param timeout pointer to a time_t that is filled with entry's
397 * @retval true when entry is successfuly fetched
398 * @retval False for failure
401 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
402 time_t *timeout, bool *was_expired)
404 struct gencache_get_data_blob_state state;
405 bool expired = false;
407 state.result = false;
410 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
416 if (state.timeout <= time(NULL)) {
418 * We're expired, delete the entry. We can't use gencache_del
419 * here, because that uses gencache_get_data_blob for checking
420 * the existence of a record. We know the thing exists and
421 * directly store an empty value with 0 timeout.
423 gencache_set(keystr, "", 0);
428 *timeout = state.timeout;
434 if (was_expired != NULL) {
435 *was_expired = expired;
437 if (state.result && state.blob) {
438 data_blob_free(state.blob);
443 struct stabilize_state {
447 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
453 * Migrate the clear-if-first gencache data to the stable,
454 * transaction-based gencache.tdb
457 bool gencache_stabilize(void)
459 struct stabilize_state state;
463 if (!gencache_init()) {
467 res = tdb_transaction_start_nonblock(cache);
470 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
472 * Someone else already does the stabilize,
473 * this does not have to be done twice
478 DEBUG(10, ("Could not start transaction on gencache.tdb: "
479 "%s\n", tdb_errorstr(cache)));
482 res = tdb_transaction_start(cache_notrans);
484 tdb_transaction_cancel(cache);
485 DEBUG(10, ("Could not start transaction on "
486 "gencache_notrans.tdb: %s\n",
487 tdb_errorstr(cache_notrans)));
492 state.written = false;
494 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
495 if ((res == -1) || state.error) {
496 if ((tdb_transaction_cancel(cache_notrans) == -1)
497 || (tdb_transaction_cancel(cache) == -1)) {
498 smb_panic("tdb_transaction_cancel failed\n");
503 if (!state.written) {
504 if ((tdb_transaction_cancel(cache_notrans) == -1)
505 || (tdb_transaction_cancel(cache) == -1)) {
506 smb_panic("tdb_transaction_cancel failed\n");
511 res = tdb_transaction_commit(cache);
513 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
514 "%s\n", tdb_errorstr(cache)));
515 if (tdb_transaction_cancel(cache_notrans) == -1) {
516 smb_panic("tdb_transaction_cancel failed\n");
521 res = tdb_transaction_commit(cache_notrans);
523 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
524 "%s\n", tdb_errorstr(cache)));
528 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
530 tdb_store(cache_notrans, last_stabilize_key(),
531 string_term_tdb_data(now), 0);
538 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
541 struct stabilize_state *state = (struct stabilize_state *)priv;
545 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
549 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
550 DEBUG(10, ("Ignoring invalid entry\n"));
553 if ((timeout < time(NULL)) || (val.dsize == 0)) {
554 res = tdb_delete(cache, key);
555 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
558 state->written = true;
561 res = tdb_store(cache, key, val, 0);
563 state->written = true;
568 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
569 tdb_errorstr(cache)));
574 if (tdb_delete(cache_notrans, key) == -1) {
575 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
576 "%s\n", tdb_errorstr(cache_notrans)));
584 * Get existing entry from the cache file.
586 * @param keystr string that represents a key of this entry
587 * @param valstr buffer that is allocated and filled with the entry value
588 * buffer's disposing must be done outside
589 * @param timeout pointer to a time_t that is filled with entry's
592 * @retval true when entry is successfuly fetched
593 * @retval False for failure
596 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
601 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
605 if ((blob.data == NULL) || (blob.length == 0)) {
606 SAFE_FREE(blob.data);
609 if (blob.data[blob.length-1] != '\0') {
610 /* Not NULL terminated, can't be a string */
611 SAFE_FREE(blob.data);
615 *value = SMB_STRDUP((char *)blob.data);
616 data_blob_free(&blob);
617 if (*value == NULL) {
622 data_blob_free(&blob);
627 * Set an entry in the cache file. If there's no such
630 * @param keystr string that represents a key of this entry
631 * @param value text representation value being cached
632 * @param timeout time when the value is expired
634 * @retval true when entry is successfuly stored
635 * @retval false on failure
638 bool gencache_set(const char *keystr, const char *value, time_t timeout)
640 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
641 return gencache_set_data_blob(keystr, &blob, timeout);
644 struct gencache_iterate_blobs_state {
645 void (*fn)(const char *key, DATA_BLOB value,
646 time_t timeout, void *private_data);
652 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
653 TDB_DATA data, void *priv)
655 struct gencache_iterate_blobs_state *state =
656 (struct gencache_iterate_blobs_state *)priv;
658 char *free_key = NULL;
662 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
665 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
669 if (key.dptr[key.dsize-1] == '\0') {
670 keystr = (char *)key.dptr;
672 /* ensure 0-termination */
673 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
677 if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
682 if (fnmatch(state->pattern, keystr, 0) != 0) {
686 DEBUG(10, ("Calling function with arguments (key=%s, timeout=%s)\n",
687 keystr, ctime(&timeout)));
690 data_blob_const(endptr,
691 data.dsize - PTR_DIFF(endptr, data.dptr)),
692 timeout, state->private_data);
699 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
700 time_t timeout, void *private_data),
701 void *private_data, const char *pattern)
703 struct gencache_iterate_blobs_state state;
705 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
709 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
712 state.pattern = pattern;
713 state.private_data = private_data;
715 state.in_persistent = false;
716 tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
718 state.in_persistent = true;
719 tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
723 * Iterate through all entries which key matches to specified pattern
725 * @param fn pointer to the function that will be supplied with each single
726 * matching cache entry (key, value and timeout) as an arguments
727 * @param data void pointer to an arbitrary data that is passed directly to the fn
728 * function on each call
729 * @param keystr_pattern pattern the existing entries' keys are matched to
733 struct gencache_iterate_state {
734 void (*fn)(const char *key, const char *value, time_t timeout,
739 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
740 time_t timeout, void *private_data)
742 struct gencache_iterate_state *state =
743 (struct gencache_iterate_state *)private_data;
745 char *free_val = NULL;
747 if (value.data[value.length-1] == '\0') {
748 valstr = (char *)value.data;
750 /* ensure 0-termination */
751 valstr = SMB_STRNDUP((char *)value.data, value.length);
755 DEBUG(10, ("Calling function with arguments "
756 "(key = %s, value = %s, timeout = %s)\n",
757 key, valstr, ctime(&timeout)));
759 state->fn(key, valstr, timeout, state->private_data);
764 void gencache_iterate(void (*fn)(const char *key, const char *value,
765 time_t timeout, void *dptr),
766 void *private_data, const char *pattern)
768 struct gencache_iterate_state state;
774 state.private_data = private_data;
775 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);