ldb_kv: Use ldb_msg_add_steal_value() in msg_add_distinguished_name()
[Samba.git] / source3 / lib / gencache.c
blob9ad85bbf55f155e5129a38e5c34352949d2882b9
1 /*
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/>.
24 #include "includes.h"
25 #include "lib/gencache.h"
26 #include "system/filesys.h"
27 #include "system/glob.h"
28 #include "util_tdb.h"
29 #include "tdb_wrap/tdb_wrap.h"
30 #include "zlib.h"
31 #include "lib/util/strv.h"
33 #undef DBGC_CLASS
34 #define DBGC_CLASS DBGC_TDB
36 static struct tdb_wrap *cache;
38 /**
39 * @file gencache.c
40 * @brief Generic, persistent and shared between processes cache mechanism
41 * for use by various parts of the Samba code
43 **/
45 static bool gencache_pull_timeout(TDB_DATA key,
46 TDB_DATA data,
47 time_t *pres,
48 DATA_BLOB *payload);
50 struct gencache_timeout {
51 time_t timeout;
54 bool gencache_timeout_expired(const struct gencache_timeout *t)
56 return t->timeout <= time(NULL);
59 /**
60 * Cache initialisation function. Opens cache tdb file or creates
61 * it if does not exist.
63 * @return true on successful initialisation of the cache or
64 * false on failure
65 **/
67 static bool gencache_init(void)
69 char* cache_fname = NULL;
70 int open_flags = O_RDWR|O_CREAT;
71 int hash_size;
73 /* skip file open if it's already opened */
74 if (cache) {
75 return true;
78 hash_size = lp_parm_int(-1, "gencache", "hash_size", 10000);
80 cache_fname = lock_path(talloc_tos(), "gencache.tdb");
81 if (cache_fname == NULL) {
82 return false;
85 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
87 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
88 TDB_INCOMPATIBLE_HASH|
89 TDB_NOSYNC|
90 TDB_MUTEX_LOCKING,
91 open_flags, 0644);
92 if (cache == NULL) {
93 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
94 strerror(errno)));
95 TALLOC_FREE(cache_fname);
96 return false;
98 TALLOC_FREE(cache_fname);
100 return true;
104 * Walk the hash chain for "key", deleting all expired entries for
105 * that hash chain
107 struct gencache_prune_expired_state {
108 TALLOC_CTX *mem_ctx;
109 char *keys;
112 static int gencache_prune_expired_fn(struct tdb_context *tdb,
113 TDB_DATA key,
114 TDB_DATA data,
115 void *private_data)
117 struct gencache_prune_expired_state *state = private_data;
118 struct gencache_timeout t;
119 bool ok = false;
120 bool expired = false;
122 if ((key.dsize == 0) || (key.dptr[key.dsize-1] != '\0')) {
123 /* not a valid record, should never happen */
124 return 0;
127 ok = gencache_pull_timeout(key, data, &t.timeout, NULL);
128 if (ok) {
129 expired = gencache_timeout_expired(&t);
132 if (!ok || expired) {
133 int ret;
135 ret = strv_add(state->mem_ctx, &state->keys, (char *)key.dptr);
136 if (ret != 0) {
138 * Exit the loop. It's unlikely that it will
139 * succeed next time.
141 return -1;
145 return 0;
148 static void gencache_prune_expired(struct tdb_context *tdb,
149 TDB_DATA chain_key)
151 struct gencache_prune_expired_state state = {
152 .mem_ctx = talloc_tos(),
154 char *keystr = NULL;
155 int ret;
157 ret = tdb_traverse_key_chain(
158 tdb, chain_key, gencache_prune_expired_fn, &state);
159 if (ret == -1) {
160 DBG_DEBUG("tdb_traverse_key_chain failed: %s\n",
161 tdb_errorstr(tdb));
162 return;
165 while ((keystr = strv_next(state.keys, keystr)) != NULL) {
166 TDB_DATA key = string_term_tdb_data(keystr);
169 * We expect the hash chain of "chain_key" to be
170 * locked. So between gencache_prune_expired_fn
171 * figuring out "keystr" is expired and the
172 * tdb_delete, nobody can have reset the timeout.
174 tdb_delete(tdb, key);
177 TALLOC_FREE(state.keys);
181 * Set an entry in the cache file. If there's no such
182 * one, then add it.
184 * @param keystr string that represents a key of this entry
185 * @param blob DATA_BLOB value being cached
186 * @param timeout time when the value is expired
188 * @retval true when entry is successfully stored
189 * @retval false on failure
192 bool gencache_set_data_blob(const char *keystr, DATA_BLOB blob,
193 time_t timeout)
195 TDB_DATA key;
196 int ret;
197 TDB_DATA dbufs[3];
198 uint32_t crc;
200 if ((keystr == NULL) || (blob.data == NULL)) {
201 return false;
204 key = string_term_tdb_data(keystr);
206 if (!gencache_init()) {
207 return false;
210 dbufs[0] = (TDB_DATA) { .dptr = (uint8_t *)&timeout,
211 .dsize = sizeof(time_t) };
212 dbufs[1] = (TDB_DATA) { .dptr = blob.data, .dsize = blob.length };
214 crc = crc32(0, Z_NULL, 0);
215 crc = crc32(crc, key.dptr, key.dsize);
216 crc = crc32(crc, dbufs[0].dptr, dbufs[0].dsize);
217 crc = crc32(crc, dbufs[1].dptr, dbufs[1].dsize);
219 dbufs[2] = (TDB_DATA) { .dptr = (uint8_t *)&crc,
220 .dsize = sizeof(crc) };
222 DBG_DEBUG("Adding cache entry with key=[%s] and timeout="
223 "[%s] (%ld seconds %s)\n", keystr,
224 timestring(talloc_tos(), timeout),
225 ((long int)timeout) - time(NULL),
226 timeout > time(NULL) ? "ahead" : "in the past");
228 ret = tdb_chainlock(cache->tdb, key);
229 if (ret == -1) {
230 DBG_WARNING("tdb_chainlock for key [%s] failed: %s\n",
231 keystr, tdb_errorstr(cache->tdb));
232 return false;
235 gencache_prune_expired(cache->tdb, key);
237 ret = tdb_storev(cache->tdb, key, dbufs, ARRAY_SIZE(dbufs), 0);
239 tdb_chainunlock(cache->tdb, key);
241 if (ret == 0) {
242 return true;
244 if (tdb_error(cache->tdb) != TDB_ERR_CORRUPT) {
245 return false;
248 ret = tdb_wipe_all(cache->tdb);
249 SMB_ASSERT(ret == 0);
251 return false;
255 * Delete one entry from the cache file.
257 * @param keystr string that represents a key of this entry
259 * @retval true upon successful deletion
260 * @retval false in case of failure
263 bool gencache_del(const char *keystr)
265 TDB_DATA key = string_term_tdb_data(keystr);
266 int ret;
268 if (keystr == NULL) {
269 return false;
272 if (!gencache_init()) {
273 return false;
276 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
278 ret = tdb_delete(cache->tdb, key);
280 if (ret == 0) {
281 return true;
283 if (tdb_error(cache->tdb) != TDB_ERR_CORRUPT) {
284 return false;
287 ret = tdb_wipe_all(cache->tdb);
288 SMB_ASSERT(ret == 0);
290 return true; /* We've deleted a bit more... */
293 static bool gencache_pull_timeout(TDB_DATA key,
294 TDB_DATA data,
295 time_t *pres,
296 DATA_BLOB *payload)
298 size_t crc_ofs;
299 uint32_t crc, stored_crc;
301 if ((data.dptr == NULL) ||
302 (data.dsize < (sizeof(time_t) + sizeof(uint32_t)))) {
303 return false;
306 crc_ofs = data.dsize - sizeof(uint32_t);
308 crc = crc32(0, Z_NULL, 0);
309 crc = crc32(crc, key.dptr, key.dsize);
310 crc = crc32(crc, data.dptr, crc_ofs);
312 memcpy(&stored_crc, data.dptr + crc_ofs, sizeof(uint32_t));
314 if (stored_crc != crc) {
315 return false;
318 if (pres != NULL) {
319 memcpy(pres, data.dptr, sizeof(time_t));
321 if (payload != NULL) {
322 *payload = (DATA_BLOB) {
323 .data = data.dptr+sizeof(time_t),
324 .length = data.dsize-sizeof(time_t)-sizeof(uint32_t),
327 return true;
330 struct gencache_parse_state {
331 void (*parser)(const struct gencache_timeout *timeout,
332 DATA_BLOB blob,
333 void *private_data);
334 void *private_data;
335 bool format_error;
338 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
340 struct gencache_parse_state *state = private_data;
341 struct gencache_timeout t;
342 DATA_BLOB payload;
343 bool ret;
345 ret = gencache_pull_timeout(key, data, &t.timeout, &payload);
346 if (!ret) {
347 state->format_error = true;
348 return 0;
350 state->parser(&t, payload, state->private_data);
352 return 0;
355 bool gencache_parse(const char *keystr,
356 void (*parser)(const struct gencache_timeout *timeout,
357 DATA_BLOB blob,
358 void *private_data),
359 void *private_data)
361 struct gencache_parse_state state = {
362 .parser = parser, .private_data = private_data
364 TDB_DATA key = string_term_tdb_data(keystr);
365 int ret;
367 if (keystr == NULL) {
368 return false;
370 if (!gencache_init()) {
371 return false;
374 ret = tdb_parse_record(cache->tdb, key,
375 gencache_parse_fn, &state);
376 if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_CORRUPT)) {
377 goto wipe;
379 if (ret == -1) {
380 return false;
382 if (state.format_error) {
383 ret = tdb_delete(cache->tdb, key);
384 if (ret == -1) {
385 goto wipe;
387 return false;
389 return true;
391 wipe:
392 ret = tdb_wipe_all(cache->tdb);
393 SMB_ASSERT(ret == 0);
394 return false;
397 struct gencache_get_data_blob_state {
398 TALLOC_CTX *mem_ctx;
399 DATA_BLOB *blob;
400 time_t timeout;
401 bool result;
404 static void gencache_get_data_blob_parser(const struct gencache_timeout *t,
405 DATA_BLOB blob,
406 void *private_data)
408 struct gencache_get_data_blob_state *state =
409 (struct gencache_get_data_blob_state *)private_data;
411 if (t->timeout == 0) {
412 state->result = false;
413 return;
415 state->timeout = t->timeout;
417 if (state->blob == NULL) {
418 state->result = true;
419 return;
422 *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
423 blob.length);
424 if (state->blob->data == NULL) {
425 state->result = false;
426 return;
428 state->result = true;
432 * Get existing entry from the cache file.
434 * @param keystr string that represents a key of this entry
435 * @param blob DATA_BLOB that is filled with entry's blob
436 * @param timeout pointer to a time_t that is filled with entry's
437 * timeout
439 * @retval true when entry is successfully fetched
440 * @retval false for failure
443 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
444 DATA_BLOB *blob,
445 time_t *timeout, bool *was_expired)
447 struct gencache_get_data_blob_state state;
448 bool expired = false;
450 state.result = false;
451 state.mem_ctx = mem_ctx;
452 state.blob = blob;
454 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
455 goto fail;
457 if (!state.result) {
458 goto fail;
460 if (state.timeout <= time(NULL)) {
462 * We're expired, delete the entry. We can't use gencache_del
463 * here, because that uses gencache_get_data_blob for checking
464 * the existence of a record. We know the thing exists and
465 * directly store an empty value with 0 timeout.
467 gencache_set(keystr, "", 0);
468 expired = true;
469 goto fail;
471 if (timeout) {
472 *timeout = state.timeout;
475 return true;
477 fail:
478 if (was_expired != NULL) {
479 *was_expired = expired;
481 if (state.result && state.blob) {
482 data_blob_free(state.blob);
484 return false;
488 * Get existing entry from the cache file.
490 * @param keystr string that represents a key of this entry
491 * @param valstr buffer that is allocated and filled with the entry value
492 * buffer's disposing must be done outside
493 * @param timeout pointer to a time_t that is filled with entry's
494 * timeout
496 * @retval true when entry is successfully fetched
497 * @retval false for failure
500 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
501 time_t *ptimeout)
503 DATA_BLOB blob;
504 bool ret = false;
506 ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
507 if (!ret) {
508 return false;
510 if ((blob.data == NULL) || (blob.length == 0)) {
511 data_blob_free(&blob);
512 return false;
514 if (blob.data[blob.length-1] != '\0') {
515 /* Not NULL terminated, can't be a string */
516 data_blob_free(&blob);
517 return false;
519 if (value) {
521 * talloc_move generates a type-punned warning here. As we
522 * leave the function immediately, do a simple talloc_steal.
524 *value = (char *)talloc_steal(mem_ctx, blob.data);
525 return true;
527 data_blob_free(&blob);
528 return true;
532 * Set an entry in the cache file. If there's no such
533 * one, then add it.
535 * @param keystr string that represents a key of this entry
536 * @param value text representation value being cached
537 * @param timeout time when the value is expired
539 * @retval true when entry is successfully stored
540 * @retval false on failure
543 bool gencache_set(const char *keystr, const char *value, time_t timeout)
545 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
546 return gencache_set_data_blob(keystr, blob, timeout);
549 struct gencache_iterate_blobs_state {
550 void (*fn)(const char *key, DATA_BLOB value,
551 time_t timeout, void *private_data);
552 const char *pattern;
553 void *private_data;
556 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
557 TDB_DATA data, void *priv)
559 struct gencache_iterate_blobs_state *state =
560 (struct gencache_iterate_blobs_state *)priv;
561 char *keystr;
562 char *free_key = NULL;
563 time_t timeout;
564 DATA_BLOB payload;
566 if (key.dptr[key.dsize-1] == '\0') {
567 keystr = (char *)key.dptr;
568 } else {
569 /* ensure 0-termination */
570 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
571 free_key = keystr;
572 if (keystr == NULL) {
573 goto done;
577 if (!gencache_pull_timeout(key, data, &timeout, &payload)) {
578 goto done;
581 if (timeout == 0) {
582 /* delete marker */
583 goto done;
586 if (fnmatch(state->pattern, keystr, 0) != 0) {
587 goto done;
590 DEBUG(10, ("Calling function with arguments "
591 "(key=[%s], timeout=[%s])\n",
592 keystr, timestring(talloc_tos(), timeout)));
594 state->fn(keystr, payload, timeout, state->private_data);
596 done:
597 TALLOC_FREE(free_key);
598 return 0;
601 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
602 time_t timeout, void *private_data),
603 void *private_data, const char *pattern)
605 struct gencache_iterate_blobs_state state;
606 int ret;
608 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
609 return;
612 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
614 state.fn = fn;
615 state.pattern = pattern;
616 state.private_data = private_data;
618 ret = tdb_traverse(cache->tdb, gencache_iterate_blobs_fn, &state);
620 if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_CORRUPT)) {
621 ret = tdb_wipe_all(cache->tdb);
622 SMB_ASSERT(ret == 0);
627 * Iterate through all entries which key matches to specified pattern
629 * @param fn pointer to the function that will be supplied with each single
630 * matching cache entry (key, value and timeout) as an arguments
631 * @param data void pointer to an arbitrary data that is passed directly to the fn
632 * function on each call
633 * @param keystr_pattern pattern the existing entries' keys are matched to
637 struct gencache_iterate_state {
638 void (*fn)(const char *key, const char *value, time_t timeout,
639 void *priv);
640 void *private_data;
643 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
644 time_t timeout, void *private_data)
646 struct gencache_iterate_state *state =
647 (struct gencache_iterate_state *)private_data;
648 char *valstr;
649 char *free_val = NULL;
651 if (value.data[value.length-1] == '\0') {
652 valstr = (char *)value.data;
653 } else {
654 /* ensure 0-termination */
655 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
656 free_val = valstr;
657 if (valstr == NULL) {
658 goto done;
662 DEBUG(10, ("Calling function with arguments "
663 "(key=[%s], value=[%s], timeout=[%s])\n",
664 key, valstr, timestring(talloc_tos(), timeout)));
666 state->fn(key, valstr, timeout, state->private_data);
668 done:
670 TALLOC_FREE(free_val);
673 void gencache_iterate(void (*fn)(const char *key, const char *value,
674 time_t timeout, void *dptr),
675 void *private_data, const char *pattern)
677 struct gencache_iterate_state state;
679 if (fn == NULL) {
680 return;
682 state.fn = fn;
683 state.private_data = private_data;
684 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);