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/glob.h"
28 #define DBGC_CLASS DBGC_TDB
30 #define TIMEOUT_LEN 12
31 #define CACHE_DATA_FMT "%12u/"
32 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
33 #define BLOB_TYPE "DATA_BLOB"
34 #define BLOB_TYPE_LEN 9
36 static struct tdb_context *cache;
37 static struct tdb_context *cache_notrans;
41 * @brief Generic, persistent and shared between processes cache mechanism
42 * for use by various parts of the Samba code
48 * Cache initialisation function. Opens cache tdb file or creates
49 * it if does not exist.
51 * @return true on successful initialisation of the cache or
55 static bool gencache_init(void)
57 char* cache_fname = NULL;
58 int open_flags = O_RDWR|O_CREAT;
59 bool first_try = true;
61 /* skip file open if it's already opened */
62 if (cache) return True;
64 cache_fname = lock_path("gencache.tdb");
66 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
69 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
72 ret = tdb_check(cache, NULL, NULL);
77 DEBUG(0, ("gencache_init: tdb_check(%s) failed\n",
82 DEBUG(0, ("gencache_init: tdb_check(%s) failed - retry after CLEAR_IF_FIRST\n",
84 cache = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
93 if (!cache && (errno == EACCES)) {
94 open_flags = O_RDONLY;
95 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
98 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
103 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
107 cache_fname = lock_path("gencache_notrans.tdb");
109 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
111 cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
113 if (cache_notrans == NULL) {
114 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
124 static TDB_DATA last_stabilize_key(void)
127 result.dptr = (uint8_t *)"@LAST_STABILIZED";
133 * Set an entry in the cache file. If there's no such
136 * @param keystr string that represents a key of this entry
137 * @param blob DATA_BLOB value being cached
138 * @param timeout time when the value is expired
140 * @retval true when entry is successfuly stored
141 * @retval false on failure
144 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
150 time_t last_stabilize;
151 static int writecount;
153 if (tdb_data_cmp(string_term_tdb_data(keystr),
154 last_stabilize_key()) == 0) {
155 DEBUG(10, ("Can't store %s as a key\n", keystr));
159 if ((keystr == NULL) || (blob == NULL)) {
163 if (!gencache_init()) return False;
165 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
169 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
173 val = (char *)talloc_append_blob(NULL, val, *blob);
178 DEBUG(10, ("Adding cache entry with key = %s and timeout ="
179 " %s (%d seconds %s)\n", keystr, ctime(&timeout),
180 (int)(timeout - time(NULL)),
181 timeout > time(NULL) ? "ahead" : "in the past"));
183 ret = tdb_store_bystring(
184 cache_notrans, keystr,
185 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
194 * Every 100 writes within a single process, stabilize the cache with
195 * a transaction. This is done to prevent a single transaction to
196 * become huge and chew lots of memory.
199 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
200 gencache_stabilize();
206 * Every 5 minutes, call gencache_stabilize() to not let grow
207 * gencache_notrans.tdb too large.
211 databuf = tdb_fetch(cache_notrans, last_stabilize_key());
212 if ((databuf.dptr != NULL)
213 && (databuf.dptr[databuf.dsize-1] == '\0')) {
214 last_stabilize = atoi((char *)databuf.dptr);
215 SAFE_FREE(databuf.dptr);
218 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
220 gencache_stabilize();
228 * Delete one entry from the cache file.
230 * @param keystr string that represents a key of this entry
232 * @retval true upon successful deletion
233 * @retval false in case of failure
236 bool gencache_del(const char *keystr)
238 bool exists, was_expired;
242 if (keystr == NULL) {
246 if (!gencache_init()) return False;
248 DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
251 * We delete an element by setting its timeout to 0. This way we don't
252 * have to do a transaction on gencache.tdb every time we delete an
256 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
258 if (!exists && was_expired) {
260 * gencache_get_data_blob has implicitly deleted this
261 * entry, so we have to return success here.
267 data_blob_free(&value);
268 ret = gencache_set(keystr, "", 0);
273 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
282 res = strtol(val, &endptr, 10);
284 if ((endptr == NULL) || (*endptr != '/')) {
285 DEBUG(2, ("Invalid gencache data format: %s\n", val));
291 if (pendptr != NULL) {
297 struct gencache_parse_state {
298 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
302 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
304 struct gencache_parse_state *state;
310 if (data.dptr == NULL) {
313 ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
317 state = (struct gencache_parse_state *)private_data;
318 blob = data_blob_const(
319 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
320 state->parser(t, blob, state->private_data);
324 bool gencache_parse(const char *keystr,
325 void (*parser)(time_t timeout, DATA_BLOB blob,
329 struct gencache_parse_state state;
333 if (keystr == NULL) {
336 if (tdb_data_cmp(string_term_tdb_data(keystr),
337 last_stabilize_key()) == 0) {
340 if (!gencache_init()) {
344 key = string_term_tdb_data(keystr);
345 state.parser = parser;
346 state.private_data = private_data;
348 ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
352 ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
356 struct gencache_get_data_blob_state {
362 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
365 struct gencache_get_data_blob_state *state =
366 (struct gencache_get_data_blob_state *)private_data;
369 state->result = false;
372 state->timeout = timeout;
374 if (state->blob == NULL) {
375 state->result = true;
379 *state->blob = data_blob(blob.data, blob.length);
380 if (state->blob->data == NULL) {
381 state->result = false;
384 state->result = true;
388 * Get existing entry from the cache file.
390 * @param keystr string that represents a key of this entry
391 * @param blob DATA_BLOB that is filled with entry's blob
392 * @param timeout pointer to a time_t that is filled with entry's
395 * @retval true when entry is successfuly fetched
396 * @retval False for failure
399 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
400 time_t *timeout, bool *was_expired)
402 struct gencache_get_data_blob_state state;
403 bool expired = false;
405 state.result = false;
408 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
414 if (state.timeout <= time(NULL)) {
416 * We're expired, delete the entry. We can't use gencache_del
417 * here, because that uses gencache_get_data_blob for checking
418 * the existence of a record. We know the thing exists and
419 * directly store an empty value with 0 timeout.
421 gencache_set(keystr, "", 0);
426 *timeout = state.timeout;
432 if (was_expired != NULL) {
433 *was_expired = expired;
435 if (state.result && state.blob) {
436 data_blob_free(state.blob);
441 struct stabilize_state {
445 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
451 * Migrate the clear-if-first gencache data to the stable,
452 * transaction-based gencache.tdb
455 bool gencache_stabilize(void)
457 struct stabilize_state state;
461 if (!gencache_init()) {
465 res = tdb_transaction_start_nonblock(cache);
468 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
470 * Someone else already does the stabilize,
471 * this does not have to be done twice
476 DEBUG(10, ("Could not start transaction on gencache.tdb: "
477 "%s\n", tdb_errorstr(cache)));
480 res = tdb_transaction_start(cache_notrans);
482 tdb_transaction_cancel(cache);
483 DEBUG(10, ("Could not start transaction on "
484 "gencache_notrans.tdb: %s\n",
485 tdb_errorstr(cache_notrans)));
490 state.written = false;
492 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
493 if ((res == -1) || state.error) {
494 if ((tdb_transaction_cancel(cache_notrans) == -1)
495 || (tdb_transaction_cancel(cache) == -1)) {
496 smb_panic("tdb_transaction_cancel failed\n");
501 if (!state.written) {
502 if ((tdb_transaction_cancel(cache_notrans) == -1)
503 || (tdb_transaction_cancel(cache) == -1)) {
504 smb_panic("tdb_transaction_cancel failed\n");
509 res = tdb_transaction_commit(cache);
511 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
512 "%s\n", tdb_errorstr(cache)));
513 if (tdb_transaction_cancel(cache_notrans) == -1) {
514 smb_panic("tdb_transaction_cancel failed\n");
519 res = tdb_transaction_commit(cache_notrans);
521 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
522 "%s\n", tdb_errorstr(cache)));
526 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
528 tdb_store(cache_notrans, last_stabilize_key(),
529 string_term_tdb_data(now), 0);
536 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
539 struct stabilize_state *state = (struct stabilize_state *)priv;
543 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
547 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
548 DEBUG(10, ("Ignoring invalid entry\n"));
551 if ((timeout < time(NULL)) || (val.dsize == 0)) {
552 res = tdb_delete(cache, key);
553 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
556 state->written = true;
559 res = tdb_store(cache, key, val, 0);
561 state->written = true;
566 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
567 tdb_errorstr(cache)));
572 if (tdb_delete(cache_notrans, key) == -1) {
573 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
574 "%s\n", tdb_errorstr(cache_notrans)));
582 * Get existing entry from the cache file.
584 * @param keystr string that represents a key of this entry
585 * @param valstr buffer that is allocated and filled with the entry value
586 * buffer's disposing must be done outside
587 * @param timeout pointer to a time_t that is filled with entry's
590 * @retval true when entry is successfuly fetched
591 * @retval False for failure
594 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
599 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
603 if ((blob.data == NULL) || (blob.length == 0)) {
604 SAFE_FREE(blob.data);
607 if (blob.data[blob.length-1] != '\0') {
608 /* Not NULL terminated, can't be a string */
609 SAFE_FREE(blob.data);
613 *value = SMB_STRDUP((char *)blob.data);
614 data_blob_free(&blob);
615 if (*value == NULL) {
620 data_blob_free(&blob);
625 * Set an entry in the cache file. If there's no such
628 * @param keystr string that represents a key of this entry
629 * @param value text representation value being cached
630 * @param timeout time when the value is expired
632 * @retval true when entry is successfuly stored
633 * @retval false on failure
636 bool gencache_set(const char *keystr, const char *value, time_t timeout)
638 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
639 return gencache_set_data_blob(keystr, &blob, timeout);
642 struct gencache_iterate_blobs_state {
643 void (*fn)(const char *key, DATA_BLOB value,
644 time_t timeout, void *private_data);
650 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
651 TDB_DATA data, void *priv)
653 struct gencache_iterate_blobs_state *state =
654 (struct gencache_iterate_blobs_state *)priv;
656 char *free_key = NULL;
660 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
663 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
667 if (key.dptr[key.dsize-1] == '\0') {
668 keystr = (char *)key.dptr;
670 /* ensure 0-termination */
671 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
675 if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
680 if (fnmatch(state->pattern, keystr, 0) != 0) {
684 DEBUG(10, ("Calling function with arguments (key=%s, timeout=%s)\n",
685 keystr, ctime(&timeout)));
688 data_blob_const(endptr,
689 data.dsize - PTR_DIFF(endptr, data.dptr)),
690 timeout, state->private_data);
697 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
698 time_t timeout, void *private_data),
699 void *private_data, const char *pattern)
701 struct gencache_iterate_blobs_state state;
703 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
707 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
710 state.pattern = pattern;
711 state.private_data = private_data;
713 state.in_persistent = false;
714 tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
716 state.in_persistent = true;
717 tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
721 * Iterate through all entries which key matches to specified pattern
723 * @param fn pointer to the function that will be supplied with each single
724 * matching cache entry (key, value and timeout) as an arguments
725 * @param data void pointer to an arbitrary data that is passed directly to the fn
726 * function on each call
727 * @param keystr_pattern pattern the existing entries' keys are matched to
731 struct gencache_iterate_state {
732 void (*fn)(const char *key, const char *value, time_t timeout,
737 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
738 time_t timeout, void *private_data)
740 struct gencache_iterate_state *state =
741 (struct gencache_iterate_state *)private_data;
743 char *free_val = NULL;
745 if (value.data[value.length-1] == '\0') {
746 valstr = (char *)value.data;
748 /* ensure 0-termination */
749 valstr = SMB_STRNDUP((char *)value.data, value.length);
753 DEBUG(10, ("Calling function with arguments "
754 "(key = %s, value = %s, timeout = %s)\n",
755 key, valstr, ctime(&timeout)));
757 state->fn(key, valstr, timeout, state->private_data);
762 void gencache_iterate(void (*fn)(const char *key, const char *value,
763 time_t timeout, void *dptr),
764 void *private_data, const char *pattern)
766 struct gencache_iterate_state state;
772 state.private_data = private_data;
773 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);