s3: Rename new parameter "ldap ref follow" to "ldap follow referral".
[Samba/gebeck_regimport.git] / source3 / lib / gencache.c
blob6de653fa17d370abcf9adf5f31d17a4cd1afde1f
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"
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_TDB
29 #define TIMEOUT_LEN 12
30 #define CACHE_DATA_FMT "%12u/"
31 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
32 #define BLOB_TYPE "DATA_BLOB"
33 #define BLOB_TYPE_LEN 9
35 static struct tdb_context *cache;
36 static struct tdb_context *cache_notrans;
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 **/
46 /**
47 * Cache initialisation function. Opens cache tdb file or creates
48 * it if does not exist.
50 * @return true on successful initialisation of the cache or
51 * false on failure
52 **/
54 static bool gencache_init(void)
56 char* cache_fname = NULL;
57 int open_flags = O_RDWR|O_CREAT;
59 /* skip file open if it's already opened */
60 if (cache) return True;
62 cache_fname = lock_path("gencache.tdb");
64 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
66 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags, 0644);
68 if (!cache && (errno == EACCES)) {
69 open_flags = O_RDONLY;
70 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, open_flags,
71 0644);
72 if (cache) {
73 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
77 if (!cache) {
78 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
79 return False;
82 cache_fname = lock_path("gencache_notrans.tdb");
84 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
86 cache_notrans = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST,
87 open_flags, 0644);
88 if (cache_notrans == NULL) {
89 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
90 strerror(errno)));
91 tdb_close(cache);
92 return false;
95 return True;
98 static TDB_DATA last_stabilize_key(void)
100 TDB_DATA result;
101 result.dptr = (uint8_t *)"@LAST_STABILIZED";
102 result.dsize = 17;
103 return result;
107 * Set an entry in the cache file. If there's no such
108 * one, then add it.
110 * @param keystr string that represents a key of this entry
111 * @param blob DATA_BLOB value being cached
112 * @param timeout time when the value is expired
114 * @retval true when entry is successfuly stored
115 * @retval false on failure
118 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
119 time_t timeout)
121 int ret;
122 TDB_DATA databuf;
123 char* val;
124 time_t last_stabilize;
125 static int writecount;
127 if (tdb_data_cmp(string_term_tdb_data(keystr),
128 last_stabilize_key()) == 0) {
129 DEBUG(10, ("Can't store %s as a key\n", keystr));
130 return false;
133 if ((keystr == NULL) || (blob == NULL)) {
134 return false;
137 if (!gencache_init()) return False;
139 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
140 if (val == NULL) {
141 return False;
143 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
144 if (val == NULL) {
145 return false;
147 val = (char *)talloc_append_blob(NULL, val, *blob);
148 if (val == NULL) {
149 return false;
152 DEBUG(10, ("Adding cache entry with key = %s and timeout ="
153 " %s (%d seconds %s)\n", keystr, ctime(&timeout),
154 (int)(timeout - time(NULL)),
155 timeout > time(NULL) ? "ahead" : "in the past"));
157 ret = tdb_store_bystring(
158 cache_notrans, keystr,
159 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
161 TALLOC_FREE(val);
163 if (ret != 0) {
164 return false;
168 * Every 100 writes within a single process, stabilize the cache with
169 * a transaction. This is done to prevent a single transaction to
170 * become huge and chew lots of memory.
172 writecount += 1;
173 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
174 gencache_stabilize();
175 writecount = 0;
176 goto done;
180 * Every 5 minutes, call gencache_stabilize() to not let grow
181 * gencache_notrans.tdb too large.
184 last_stabilize = 0;
185 databuf = tdb_fetch(cache_notrans, last_stabilize_key());
186 if ((databuf.dptr != NULL)
187 && (databuf.dptr[databuf.dsize-1] == '\0')) {
188 last_stabilize = atoi((char *)databuf.dptr);
189 SAFE_FREE(databuf.dptr);
191 if ((last_stabilize
192 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
193 < time(NULL)) {
194 gencache_stabilize();
197 done:
198 return ret == 0;
202 * Delete one entry from the cache file.
204 * @param keystr string that represents a key of this entry
206 * @retval true upon successful deletion
207 * @retval false in case of failure
210 bool gencache_del(const char *keystr)
212 bool exists, was_expired;
213 bool ret = false;
214 DATA_BLOB value;
216 if (keystr == NULL) {
217 return false;
220 if (!gencache_init()) return False;
222 DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
225 * We delete an element by setting its timeout to 0. This way we don't
226 * have to do a transaction on gencache.tdb every time we delete an
227 * element.
230 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
232 if (!exists && was_expired) {
234 * gencache_get_data_blob has implicitly deleted this
235 * entry, so we have to return success here.
237 return true;
240 if (exists) {
241 data_blob_free(&value);
242 ret = gencache_set(keystr, "", 0);
244 return ret;
247 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
249 time_t res;
250 char *endptr;
252 res = strtol(val, &endptr, 10);
254 if ((endptr == NULL) || (*endptr != '/')) {
255 DEBUG(2, ("Invalid gencache data format: %s\n", val));
256 return false;
258 if (pres != NULL) {
259 *pres = res;
261 if (pendptr != NULL) {
262 *pendptr = endptr;
264 return true;
268 * Get existing entry from the cache file.
270 * @param keystr string that represents a key of this entry
271 * @param blob DATA_BLOB that is filled with entry's blob
272 * @param timeout pointer to a time_t that is filled with entry's
273 * timeout
275 * @retval true when entry is successfuly fetched
276 * @retval False for failure
279 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
280 time_t *timeout, bool *was_expired)
282 TDB_DATA databuf;
283 time_t t;
284 char *endptr;
285 bool expired = false;
287 if (keystr == NULL) {
288 goto fail;
291 if (tdb_data_cmp(string_term_tdb_data(keystr),
292 last_stabilize_key()) == 0) {
293 DEBUG(10, ("Can't get %s as a key\n", keystr));
294 goto fail;
297 if (!gencache_init()) {
298 goto fail;
301 databuf = tdb_fetch_bystring(cache_notrans, keystr);
303 if (databuf.dptr == NULL) {
304 databuf = tdb_fetch_bystring(cache, keystr);
307 if (databuf.dptr == NULL) {
308 DEBUG(10, ("Cache entry with key = %s couldn't be found \n",
309 keystr));
310 goto fail;
313 if (!gencache_pull_timeout((char *)databuf.dptr, &t, &endptr)) {
314 SAFE_FREE(databuf.dptr);
315 goto fail;
318 DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
319 "timeout = %s", t > time(NULL) ? "valid" :
320 "expired", keystr, endptr+1, ctime(&t)));
322 if (t == 0) {
323 /* Deleted */
324 SAFE_FREE(databuf.dptr);
325 goto fail;
328 if (t <= time(NULL)) {
331 * We're expired, delete the entry. We can't use gencache_del
332 * here, because that uses gencache_get_data_blob for checking
333 * the existence of a record. We know the thing exists and
334 * directly store an empty value with 0 timeout.
336 gencache_set(keystr, "", 0);
338 SAFE_FREE(databuf.dptr);
340 expired = true;
341 goto fail;
344 if (blob != NULL) {
345 *blob = data_blob(
346 endptr+1,
347 databuf.dsize - PTR_DIFF(endptr+1, databuf.dptr));
348 if (blob->data == NULL) {
349 SAFE_FREE(databuf.dptr);
350 DEBUG(0, ("memdup failed\n"));
351 goto fail;
355 SAFE_FREE(databuf.dptr);
357 if (timeout) {
358 *timeout = t;
361 return True;
363 fail:
364 if (was_expired != NULL) {
365 *was_expired = expired;
367 return false;
370 struct stabilize_state {
371 bool written;
372 bool error;
374 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
375 void *priv);
378 * Stabilize gencache
380 * Migrate the clear-if-first gencache data to the stable,
381 * transaction-based gencache.tdb
384 bool gencache_stabilize(void)
386 struct stabilize_state state;
387 int res;
388 char *now;
390 if (!gencache_init()) {
391 return false;
394 res = tdb_transaction_start(cache);
395 if (res == -1) {
396 DEBUG(10, ("Could not start transaction on gencache.tdb: "
397 "%s\n", tdb_errorstr(cache)));
398 return false;
400 res = tdb_transaction_start(cache_notrans);
401 if (res == -1) {
402 tdb_transaction_cancel(cache);
403 DEBUG(10, ("Could not start transaction on "
404 "gencache_notrans.tdb: %s\n",
405 tdb_errorstr(cache_notrans)));
406 return false;
409 state.error = false;
410 state.written = false;
412 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
413 if ((res == -1) || state.error) {
414 if ((tdb_transaction_cancel(cache_notrans) == -1)
415 || (tdb_transaction_cancel(cache) == -1)) {
416 smb_panic("tdb_transaction_cancel failed\n");
418 return false;
421 if (!state.written) {
422 if ((tdb_transaction_cancel(cache_notrans) == -1)
423 || (tdb_transaction_cancel(cache) == -1)) {
424 smb_panic("tdb_transaction_cancel failed\n");
426 return true;
429 res = tdb_transaction_commit(cache);
430 if (res == -1) {
431 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
432 "%s\n", tdb_errorstr(cache)));
433 if (tdb_transaction_cancel(cache_notrans) == -1) {
434 smb_panic("tdb_transaction_cancel failed\n");
436 return false;
439 res = tdb_transaction_commit(cache_notrans);
440 if (res == -1) {
441 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
442 "%s\n", tdb_errorstr(cache)));
443 return false;
446 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
447 if (now != NULL) {
448 tdb_store(cache_notrans, last_stabilize_key(),
449 string_term_tdb_data(now), 0);
450 TALLOC_FREE(now);
453 return true;
456 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
457 void *priv)
459 struct stabilize_state *state = (struct stabilize_state *)priv;
460 int res;
461 time_t timeout;
463 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
464 return 0;
467 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
468 DEBUG(10, ("Ignoring invalid entry\n"));
469 return 0;
471 if ((timeout < time(NULL)) || (val.dsize == 0)) {
472 res = tdb_delete(cache, key);
473 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
474 res = 0;
475 } else {
476 state->written = true;
478 } else {
479 res = tdb_store(cache, key, val, 0);
480 if (res == 0) {
481 state->written = true;
485 if (res == -1) {
486 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
487 tdb_errorstr(cache)));
488 state->error = true;
489 return -1;
492 if (tdb_delete(cache_notrans, key) == -1) {
493 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
494 "%s\n", tdb_errorstr(cache_notrans)));
495 state->error = true;
496 return -1;
498 return 0;
502 * Get existing entry from the cache file.
504 * @param keystr string that represents a key of this entry
505 * @param valstr buffer that is allocated and filled with the entry value
506 * buffer's disposing must be done outside
507 * @param timeout pointer to a time_t that is filled with entry's
508 * timeout
510 * @retval true when entry is successfuly fetched
511 * @retval False for failure
514 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
516 DATA_BLOB blob;
517 bool ret = False;
519 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
520 if (!ret) {
521 return false;
523 if ((blob.data == NULL) || (blob.length == 0)) {
524 SAFE_FREE(blob.data);
525 return false;
527 if (blob.data[blob.length-1] != '\0') {
528 /* Not NULL terminated, can't be a string */
529 SAFE_FREE(blob.data);
530 return false;
532 *value = SMB_STRDUP((char *)blob.data);
533 data_blob_free(&blob);
534 if (*value == NULL) {
535 return false;
537 return true;
541 * Set an entry in the cache file. If there's no such
542 * one, then add it.
544 * @param keystr string that represents a key of this entry
545 * @param value text representation value being cached
546 * @param timeout time when the value is expired
548 * @retval true when entry is successfuly stored
549 * @retval false on failure
552 bool gencache_set(const char *keystr, const char *value, time_t timeout)
554 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
555 return gencache_set_data_blob(keystr, &blob, timeout);
559 * Iterate through all entries which key matches to specified pattern
561 * @param fn pointer to the function that will be supplied with each single
562 * matching cache entry (key, value and timeout) as an arguments
563 * @param data void pointer to an arbitrary data that is passed directly to the fn
564 * function on each call
565 * @param keystr_pattern pattern the existing entries' keys are matched to
569 struct gencache_iterate_state {
570 void (*fn)(const char *key, const char *value, time_t timeout,
571 void *priv);
572 const char *pattern;
573 void *priv;
574 bool in_persistent;
577 static int gencache_iterate_fn(struct tdb_context *tdb, TDB_DATA key,
578 TDB_DATA value, void *priv)
580 struct gencache_iterate_state *state =
581 (struct gencache_iterate_state *)priv;
582 char *keystr;
583 char *free_key = NULL;
584 char *valstr;
585 char *free_val = NULL;
586 unsigned long u;
587 time_t timeout;
588 char *timeout_endp;
590 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
591 return 0;
594 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
595 return 0;
598 if (key.dptr[key.dsize-1] == '\0') {
599 keystr = (char *)key.dptr;
600 } else {
601 /* ensure 0-termination */
602 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
603 free_key = keystr;
606 if ((value.dptr == NULL) || (value.dsize <= TIMEOUT_LEN)) {
607 goto done;
610 if (fnmatch(state->pattern, keystr, 0) != 0) {
611 goto done;
614 if (value.dptr[value.dsize-1] == '\0') {
615 valstr = (char *)value.dptr;
616 } else {
617 /* ensure 0-termination */
618 valstr = SMB_STRNDUP((char *)value.dptr, value.dsize);
619 free_val = valstr;
622 u = strtoul(valstr, &timeout_endp, 10);
624 if ((*timeout_endp != '/') || ((timeout_endp-valstr) != TIMEOUT_LEN)) {
625 goto done;
628 timeout = u;
629 timeout_endp += 1;
631 DEBUG(10, ("Calling function with arguments "
632 "(key = %s, value = %s, timeout = %s)\n",
633 keystr, timeout_endp, ctime(&timeout)));
634 state->fn(keystr, timeout_endp, timeout, state->priv);
636 done:
637 SAFE_FREE(free_key);
638 SAFE_FREE(free_val);
639 return 0;
642 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
643 void* data, const char* keystr_pattern)
645 struct gencache_iterate_state state;
647 if ((fn == NULL) || (keystr_pattern == NULL)) {
648 return;
651 if (!gencache_init()) return;
653 DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
655 state.fn = fn;
656 state.pattern = keystr_pattern;
657 state.priv = data;
659 state.in_persistent = false;
660 tdb_traverse(cache_notrans, gencache_iterate_fn, &state);
662 state.in_persistent = true;
663 tdb_traverse(cache, gencache_iterate_fn, &state);