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
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #define DBGC_CLASS DBGC_TDB
28 #define TIMEOUT_LEN 12
29 #define CACHE_DATA_FMT "%12u/"
30 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
31 #define BLOB_TYPE "DATA_BLOB"
32 #define BLOB_TYPE_LEN 9
34 static struct tdb_context *cache;
35 static struct tdb_context *cache_notrans;
39 * @brief Generic, persistent and shared between processes cache mechanism
40 * for use by various parts of the Samba code
46 * Cache initialisation function. Opens cache tdb file or creates
47 * it if does not exist.
49 * @return true on successful initialisation of the cache or
53 static bool gencache_init(void)
55 char* cache_fname = NULL;
56 int open_flags = O_RDWR|O_CREAT;
58 /* skip file open if it's already opened */
59 if (cache) return True;
61 cache_fname = lock_path("gencache.tdb");
63 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
65 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags, 0644);
67 if (!cache && (errno == EACCES)) {
68 open_flags = O_RDONLY;
69 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags,
72 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
77 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
81 cache_fname = lock_path("gencache_notrans.tdb");
83 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
85 cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST,
87 if (cache_notrans == NULL) {
88 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
97 static TDB_DATA last_stabilize_key(void)
100 result.dptr = (uint8_t *)"@LAST_STABILIZED";
106 * Set an entry in the cache file. If there's no such
109 * @param keystr string that represents a key of this entry
110 * @param blob DATA_BLOB value being cached
111 * @param timeout time when the value is expired
113 * @retval true when entry is successfuly stored
114 * @retval false on failure
117 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
123 time_t last_stabilize;
124 static int writecount;
126 if (tdb_data_cmp(string_term_tdb_data(keystr),
127 last_stabilize_key()) == 0) {
128 DEBUG(10, ("Can't store %s as a key\n", keystr));
132 if ((keystr == NULL) || (blob == NULL)) {
136 if (!gencache_init()) return False;
138 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
142 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
146 val = (char *)talloc_append_blob(NULL, val, *blob);
151 DEBUG(10, ("Adding cache entry with key = %s and timeout ="
152 " %s (%d seconds %s)\n", keystr, ctime(&timeout),
153 (int)(timeout - time(NULL)),
154 timeout > time(NULL) ? "ahead" : "in the past"));
156 ret = tdb_store_bystring(
157 cache_notrans, keystr,
158 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
167 * Every 100 writes within a single process, stabilize the cache with
168 * a transaction. This is done to prevent a single transaction to
169 * become huge and chew lots of memory.
172 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
173 gencache_stabilize();
179 * Every 5 minutes, call gencache_stabilize() to not let grow
180 * gencache_notrans.tdb too large.
184 databuf = tdb_fetch(cache_notrans, last_stabilize_key());
185 if ((databuf.dptr != NULL)
186 && (databuf.dptr[databuf.dsize-1] == '\0')) {
187 last_stabilize = atoi((char *)databuf.dptr);
188 SAFE_FREE(databuf.dptr);
191 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
193 gencache_stabilize();
201 * Delete one entry from the cache file.
203 * @param keystr string that represents a key of this entry
205 * @retval true upon successful deletion
206 * @retval false in case of failure
209 bool gencache_del(const char *keystr)
211 bool exists, was_expired;
215 if (keystr == NULL) {
219 if (!gencache_init()) return False;
221 DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
224 * We delete an element by setting its timeout to 0. This way we don't
225 * have to do a transaction on gencache.tdb every time we delete an
229 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
231 if (!exists && was_expired) {
233 * gencache_get_data_blob has implicitly deleted this
234 * entry, so we have to return success here.
240 data_blob_free(&value);
241 ret = gencache_set(keystr, "", 0);
246 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
251 res = strtol(val, &endptr, 10);
253 if ((endptr == NULL) || (*endptr != '/')) {
254 DEBUG(2, ("Invalid gencache data format: %s\n", val));
260 if (pendptr != NULL) {
267 * Get existing entry from the cache file.
269 * @param keystr string that represents a key of this entry
270 * @param blob DATA_BLOB that is filled with entry's blob
271 * @param timeout pointer to a time_t that is filled with entry's
274 * @retval true when entry is successfuly fetched
275 * @retval False for failure
278 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
279 time_t *timeout, bool *was_expired)
284 bool expired = false;
286 if (keystr == NULL) {
290 if (tdb_data_cmp(string_term_tdb_data(keystr),
291 last_stabilize_key()) == 0) {
292 DEBUG(10, ("Can't get %s as a key\n", keystr));
296 if (!gencache_init()) {
300 databuf = tdb_fetch_bystring(cache_notrans, keystr);
302 if (databuf.dptr == NULL) {
303 databuf = tdb_fetch_bystring(cache, keystr);
306 if (databuf.dptr == NULL) {
307 DEBUG(10, ("Cache entry with key = %s couldn't be found \n",
312 if (!gencache_pull_timeout((char *)databuf.dptr, &t, &endptr)) {
313 SAFE_FREE(databuf.dptr);
317 DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
318 "timeout = %s", t > time(NULL) ? "valid" :
319 "expired", keystr, endptr+1, ctime(&t)));
323 SAFE_FREE(databuf.dptr);
327 if (t <= time(NULL)) {
330 * We're expired, delete the entry. We can't use gencache_del
331 * here, because that uses gencache_get_data_blob for checking
332 * the existence of a record. We know the thing exists and
333 * directly store an empty value with 0 timeout.
335 gencache_set(keystr, "", 0);
337 SAFE_FREE(databuf.dptr);
346 databuf.dsize - PTR_DIFF(endptr+1, databuf.dptr));
347 if (blob->data == NULL) {
348 SAFE_FREE(databuf.dptr);
349 DEBUG(0, ("memdup failed\n"));
354 SAFE_FREE(databuf.dptr);
363 if (was_expired != NULL) {
364 *was_expired = expired;
369 struct stabilize_state {
373 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
379 * Migrate the clear-if-first gencache data to the stable,
380 * transaction-based gencache.tdb
383 bool gencache_stabilize(void)
385 struct stabilize_state state;
389 if (!gencache_init()) {
393 res = tdb_transaction_start_nonblock(cache);
396 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
398 * Someone else already does the stabilize,
399 * this does not have to be done twice
404 DEBUG(10, ("Could not start transaction on gencache.tdb: "
405 "%s\n", tdb_errorstr(cache)));
408 res = tdb_transaction_start(cache_notrans);
410 tdb_transaction_cancel(cache);
411 DEBUG(10, ("Could not start transaction on "
412 "gencache_notrans.tdb: %s\n",
413 tdb_errorstr(cache_notrans)));
418 state.written = false;
420 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
421 if ((res == -1) || state.error) {
422 if ((tdb_transaction_cancel(cache_notrans) == -1)
423 || (tdb_transaction_cancel(cache) == -1)) {
424 smb_panic("tdb_transaction_cancel failed\n");
429 if (!state.written) {
430 if ((tdb_transaction_cancel(cache_notrans) == -1)
431 || (tdb_transaction_cancel(cache) == -1)) {
432 smb_panic("tdb_transaction_cancel failed\n");
437 res = tdb_transaction_commit(cache);
439 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
440 "%s\n", tdb_errorstr(cache)));
441 if (tdb_transaction_cancel(cache_notrans) == -1) {
442 smb_panic("tdb_transaction_cancel failed\n");
447 res = tdb_transaction_commit(cache_notrans);
449 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
450 "%s\n", tdb_errorstr(cache)));
454 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
456 tdb_store(cache_notrans, last_stabilize_key(),
457 string_term_tdb_data(now), 0);
464 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
467 struct stabilize_state *state = (struct stabilize_state *)priv;
471 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
475 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
476 DEBUG(10, ("Ignoring invalid entry\n"));
479 if ((timeout < time(NULL)) || (val.dsize == 0)) {
480 res = tdb_delete(cache, key);
481 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
484 state->written = true;
487 res = tdb_store(cache, key, val, 0);
489 state->written = true;
494 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
495 tdb_errorstr(cache)));
500 if (tdb_delete(cache_notrans, key) == -1) {
501 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
502 "%s\n", tdb_errorstr(cache_notrans)));
510 * Get existing entry from the cache file.
512 * @param keystr string that represents a key of this entry
513 * @param valstr buffer that is allocated and filled with the entry value
514 * buffer's disposing must be done outside
515 * @param timeout pointer to a time_t that is filled with entry's
518 * @retval true when entry is successfuly fetched
519 * @retval False for failure
522 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
527 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
531 if ((blob.data == NULL) || (blob.length == 0)) {
532 SAFE_FREE(blob.data);
535 if (blob.data[blob.length-1] != '\0') {
536 /* Not NULL terminated, can't be a string */
537 SAFE_FREE(blob.data);
540 *value = SMB_STRDUP((char *)blob.data);
541 data_blob_free(&blob);
542 if (*value == NULL) {
549 * Set an entry in the cache file. If there's no such
552 * @param keystr string that represents a key of this entry
553 * @param value text representation value being cached
554 * @param timeout time when the value is expired
556 * @retval true when entry is successfuly stored
557 * @retval false on failure
560 bool gencache_set(const char *keystr, const char *value, time_t timeout)
562 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
563 return gencache_set_data_blob(keystr, &blob, timeout);
567 * Iterate through all entries which key matches to specified pattern
569 * @param fn pointer to the function that will be supplied with each single
570 * matching cache entry (key, value and timeout) as an arguments
571 * @param data void pointer to an arbitrary data that is passed directly to the fn
572 * function on each call
573 * @param keystr_pattern pattern the existing entries' keys are matched to
577 struct gencache_iterate_state {
578 void (*fn)(const char *key, const char *value, time_t timeout,
585 static int gencache_iterate_fn(struct tdb_context *tdb, TDB_DATA key,
586 TDB_DATA value, void *priv)
588 struct gencache_iterate_state *state =
589 (struct gencache_iterate_state *)priv;
591 char *free_key = NULL;
593 char *free_val = NULL;
598 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
602 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
606 if (key.dptr[key.dsize-1] == '\0') {
607 keystr = (char *)key.dptr;
609 /* ensure 0-termination */
610 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
614 if ((value.dptr == NULL) || (value.dsize <= TIMEOUT_LEN)) {
618 if (fnmatch(state->pattern, keystr, 0) != 0) {
622 if (value.dptr[value.dsize-1] == '\0') {
623 valstr = (char *)value.dptr;
625 /* ensure 0-termination */
626 valstr = SMB_STRNDUP((char *)value.dptr, value.dsize);
630 u = strtoul(valstr, &timeout_endp, 10);
632 if ((*timeout_endp != '/') || ((timeout_endp-valstr) != TIMEOUT_LEN)) {
639 DEBUG(10, ("Calling function with arguments "
640 "(key = %s, value = %s, timeout = %s)\n",
641 keystr, timeout_endp, ctime(&timeout)));
642 state->fn(keystr, timeout_endp, timeout, state->priv);
650 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
651 void* data, const char* keystr_pattern)
653 struct gencache_iterate_state state;
655 if ((fn == NULL) || (keystr_pattern == NULL)) {
659 if (!gencache_init()) return;
661 DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
664 state.pattern = keystr_pattern;
667 state.in_persistent = false;
668 tdb_traverse(cache_notrans, gencache_iterate_fn, &state);
670 state.in_persistent = true;
671 tdb_traverse(cache, gencache_iterate_fn, &state);