librpc: Shorten dcerpc_binding_handle_call a bit
[Samba/gebeck_regimport.git] / source3 / lib / gencache.c
blob08adf2173a74c2cb65351dbac126b345aa0ab502
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 "system/filesys.h"
26 #include "system/glob.h"
27 #include "util_tdb.h"
29 #undef DBGC_CLASS
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;
41 /**
42 * @file gencache.c
43 * @brief Generic, persistent and shared between processes cache mechanism
44 * for use by various parts of the Samba code
46 **/
49 /**
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
54 * false on failure
55 **/
57 static bool gencache_init(void)
59 char* cache_fname = NULL;
60 int open_flags = O_RDWR|O_CREAT;
62 /* skip file open if it's already opened */
63 if (cache) return True;
65 cache_fname = cache_path("gencache.tdb");
67 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);
70 if (cache) {
71 int ret;
72 ret = tdb_check(cache, NULL, NULL);
73 if (ret != 0) {
74 tdb_close(cache);
77 * Retry with CLEAR_IF_FIRST.
79 * Warning: Converting this to dbwrap won't work
80 * directly. gencache.c does transactions on this tdb,
81 * and dbwrap forbids this for CLEAR_IF_FIRST
82 * databases. tdb does allow transactions on
83 * CLEAR_IF_FIRST databases, so lets use it here to
84 * clean up a broken database.
86 cache = tdb_open_log(cache_fname, 0,
87 TDB_DEFAULT|
88 TDB_INCOMPATIBLE_HASH|
89 TDB_CLEAR_IF_FIRST,
90 open_flags, 0644);
94 if (!cache && (errno == EACCES)) {
95 open_flags = O_RDONLY;
96 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
97 0644);
98 if (cache) {
99 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
103 if (!cache) {
104 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
105 return False;
108 cache_fname = lock_path("gencache_notrans.tdb");
110 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
112 cache_notrans = tdb_open_log(cache_fname, 0,
113 TDB_CLEAR_IF_FIRST|
114 TDB_INCOMPATIBLE_HASH|
115 TDB_NOSYNC,
116 open_flags, 0644);
117 if (cache_notrans == NULL) {
118 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
119 strerror(errno)));
120 tdb_close(cache);
121 cache = NULL;
122 return false;
125 return True;
128 static TDB_DATA last_stabilize_key(void)
130 TDB_DATA result;
131 result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
132 result.dsize = 17;
133 return result;
136 struct gencache_have_val_state {
137 time_t new_timeout;
138 const DATA_BLOB *data;
139 bool gotit;
142 static void gencache_have_val_parser(time_t old_timeout, DATA_BLOB data,
143 void *private_data)
145 struct gencache_have_val_state *state =
146 (struct gencache_have_val_state *)private_data;
147 time_t now = time(NULL);
148 int cache_time_left, new_time_left, additional_time;
151 * Excuse the many variables, but these time calculations are
152 * confusing to me. We do not want to write to gencache with a
153 * possibly expensive transaction if we are about to write the same
154 * value, just extending the remaining timeout by less than 10%.
157 cache_time_left = old_timeout - now;
158 if (cache_time_left <= 0) {
160 * timed out, write new value
162 return;
165 new_time_left = state->new_timeout - now;
166 if (new_time_left <= 0) {
168 * Huh -- no new timeout?? Write it.
170 return;
173 if (new_time_left < cache_time_left) {
175 * Someone wants to shorten the timeout. Let it happen.
177 return;
181 * By how much does the new timeout extend the remaining cache time?
183 additional_time = new_time_left - cache_time_left;
185 if (additional_time * 10 < 0) {
187 * Integer overflow. We extend by so much that we have to write it.
189 return;
193 * The comparison below is essentially equivalent to
195 * new_time_left > cache_time_left * 1.10
197 * but without floating point calculations.
200 if (additional_time * 10 > cache_time_left) {
202 * We extend the cache timeout by more than 10%. Do it.
204 return;
208 * Now the more expensive data compare.
210 if (data_blob_cmp(state->data, &data) != 0) {
212 * Write a new value. Certainly do it.
214 return;
218 * Extending the timeout by less than 10% for the same cache value is
219 * not worth the trouble writing a value into gencache under a
220 * possibly expensive transaction.
222 state->gotit = true;
225 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
226 time_t timeout)
228 struct gencache_have_val_state state;
230 state.new_timeout = timeout;
231 state.data = data;
232 state.gotit = false;
234 if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
235 return false;
237 return state.gotit;
241 * Set an entry in the cache file. If there's no such
242 * one, then add it.
244 * @param keystr string that represents a key of this entry
245 * @param blob DATA_BLOB value being cached
246 * @param timeout time when the value is expired
248 * @retval true when entry is successfuly stored
249 * @retval false on failure
252 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
253 time_t timeout)
255 int ret;
256 TDB_DATA databuf;
257 char* val;
258 time_t last_stabilize;
259 static int writecount;
261 if (tdb_data_cmp(string_term_tdb_data(keystr),
262 last_stabilize_key()) == 0) {
263 DEBUG(10, ("Can't store %s as a key\n", keystr));
264 return false;
267 if ((keystr == NULL) || (blob == NULL)) {
268 return false;
271 if (!gencache_init()) return False;
273 if (gencache_have_val(keystr, blob, timeout)) {
274 DEBUG(10, ("Did not store value for %s, we already got it\n",
275 keystr));
276 return true;
279 val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
280 if (val == NULL) {
281 return False;
283 val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
284 if (val == NULL) {
285 return false;
287 val = (char *)talloc_append_blob(NULL, val, *blob);
288 if (val == NULL) {
289 return false;
292 DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
293 "[%s] (%d seconds %s)\n", keystr,
294 timestring(talloc_tos(), timeout),
295 (int)(timeout - time(NULL)),
296 timeout > time(NULL) ? "ahead" : "in the past"));
298 ret = tdb_store_bystring(
299 cache_notrans, keystr,
300 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
302 TALLOC_FREE(val);
304 if (ret != 0) {
305 return false;
309 * Every 100 writes within a single process, stabilize the cache with
310 * a transaction. This is done to prevent a single transaction to
311 * become huge and chew lots of memory.
313 writecount += 1;
314 if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
315 gencache_stabilize();
316 writecount = 0;
317 goto done;
321 * Every 5 minutes, call gencache_stabilize() to not let grow
322 * gencache_notrans.tdb too large.
325 last_stabilize = 0;
326 databuf = tdb_fetch_compat(cache_notrans, last_stabilize_key());
327 if ((databuf.dptr != NULL)
328 && (databuf.dptr[databuf.dsize-1] == '\0')) {
329 last_stabilize = atoi((char *)databuf.dptr);
330 SAFE_FREE(databuf.dptr);
332 if ((last_stabilize
333 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
334 < time(NULL)) {
335 gencache_stabilize();
338 done:
339 return ret == 0;
343 * Delete one entry from the cache file.
345 * @param keystr string that represents a key of this entry
347 * @retval true upon successful deletion
348 * @retval false in case of failure
351 bool gencache_del(const char *keystr)
353 bool exists, was_expired;
354 bool ret = false;
355 DATA_BLOB value;
357 if (keystr == NULL) {
358 return false;
361 if (!gencache_init()) return False;
363 DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
366 * We delete an element by setting its timeout to 0. This way we don't
367 * have to do a transaction on gencache.tdb every time we delete an
368 * element.
371 exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
373 if (!exists && was_expired) {
375 * gencache_get_data_blob has implicitly deleted this
376 * entry, so we have to return success here.
378 return true;
381 if (exists) {
382 data_blob_free(&value);
383 ret = gencache_set(keystr, "", 0);
385 return ret;
388 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
390 time_t res;
391 char *endptr;
393 if (val == NULL) {
394 return false;
397 res = strtol(val, &endptr, 10);
399 if ((endptr == NULL) || (*endptr != '/')) {
400 DEBUG(2, ("Invalid gencache data format: %s\n", val));
401 return false;
403 if (pres != NULL) {
404 *pres = res;
406 if (pendptr != NULL) {
407 *pendptr = endptr;
409 return true;
412 struct gencache_parse_state {
413 void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
414 void *private_data;
417 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
419 struct gencache_parse_state *state;
420 DATA_BLOB blob;
421 time_t t;
422 char *endptr;
423 bool ret;
425 if (data.dptr == NULL) {
426 return -1;
428 ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
429 if (!ret) {
430 return -1;
432 state = (struct gencache_parse_state *)private_data;
433 blob = data_blob_const(
434 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
435 state->parser(t, blob, state->private_data);
436 return 0;
439 bool gencache_parse(const char *keystr,
440 void (*parser)(time_t timeout, DATA_BLOB blob,
441 void *private_data),
442 void *private_data)
444 struct gencache_parse_state state;
445 TDB_DATA key;
446 int ret;
448 if (keystr == NULL) {
449 return false;
451 if (tdb_data_cmp(string_term_tdb_data(keystr),
452 last_stabilize_key()) == 0) {
453 return false;
455 if (!gencache_init()) {
456 return false;
459 key = string_term_tdb_data(keystr);
460 state.parser = parser;
461 state.private_data = private_data;
463 ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
464 if (ret == 0) {
465 return true;
467 ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
468 return (ret == 0);
471 struct gencache_get_data_blob_state {
472 DATA_BLOB *blob;
473 time_t timeout;
474 bool result;
477 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
478 void *private_data)
480 struct gencache_get_data_blob_state *state =
481 (struct gencache_get_data_blob_state *)private_data;
483 if (timeout == 0) {
484 state->result = false;
485 return;
487 state->timeout = timeout;
489 if (state->blob == NULL) {
490 state->result = true;
491 return;
494 *state->blob = data_blob(blob.data, blob.length);
495 if (state->blob->data == NULL) {
496 state->result = false;
497 return;
499 state->result = true;
503 * Get existing entry from the cache file.
505 * @param keystr string that represents a key of this entry
506 * @param blob DATA_BLOB that is filled with entry's blob
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_data_blob(const char *keystr, DATA_BLOB *blob,
515 time_t *timeout, bool *was_expired)
517 struct gencache_get_data_blob_state state;
518 bool expired = false;
520 state.result = false;
521 state.blob = blob;
523 if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
524 goto fail;
526 if (!state.result) {
527 goto fail;
529 if (state.timeout <= time(NULL)) {
531 * We're expired, delete the entry. We can't use gencache_del
532 * here, because that uses gencache_get_data_blob for checking
533 * the existence of a record. We know the thing exists and
534 * directly store an empty value with 0 timeout.
536 gencache_set(keystr, "", 0);
537 expired = true;
538 goto fail;
540 if (timeout) {
541 *timeout = state.timeout;
544 return True;
546 fail:
547 if (was_expired != NULL) {
548 *was_expired = expired;
550 if (state.result && state.blob) {
551 data_blob_free(state.blob);
553 return false;
556 struct stabilize_state {
557 bool written;
558 bool error;
560 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
561 void *priv);
564 * Stabilize gencache
566 * Migrate the clear-if-first gencache data to the stable,
567 * transaction-based gencache.tdb
570 bool gencache_stabilize(void)
572 struct stabilize_state state;
573 int res;
574 char *now;
576 if (!gencache_init()) {
577 return false;
580 res = tdb_transaction_start_nonblock(cache);
581 if (res != 0) {
582 if (tdb_error(cache) == TDB_ERR_NOLOCK)
585 * Someone else already does the stabilize,
586 * this does not have to be done twice
588 return true;
591 DEBUG(10, ("Could not start transaction on gencache.tdb: "
592 "%s\n", tdb_errorstr_compat(cache)));
593 return false;
595 res = tdb_transaction_start(cache_notrans);
596 if (res != 0) {
597 tdb_transaction_cancel(cache);
598 DEBUG(10, ("Could not start transaction on "
599 "gencache_notrans.tdb: %s\n",
600 tdb_errorstr_compat(cache_notrans)));
601 return false;
604 state.error = false;
605 state.written = false;
607 res = tdb_traverse(cache_notrans, stabilize_fn, &state);
608 if ((res < 0) || state.error) {
609 tdb_transaction_cancel(cache_notrans);
610 tdb_transaction_cancel(cache);
611 return false;
614 if (!state.written) {
615 tdb_transaction_cancel(cache_notrans);
616 tdb_transaction_cancel(cache);
617 return true;
620 res = tdb_transaction_commit(cache);
621 if (res != 0) {
622 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
623 "%s\n", tdb_errorstr_compat(cache)));
624 tdb_transaction_cancel(cache_notrans);
625 return false;
628 res = tdb_transaction_commit(cache_notrans);
629 if (res != 0) {
630 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
631 "%s\n", tdb_errorstr_compat(cache)));
632 return false;
635 now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
636 if (now != NULL) {
637 tdb_store(cache_notrans, last_stabilize_key(),
638 string_term_tdb_data(now), 0);
639 TALLOC_FREE(now);
642 return true;
645 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
646 void *priv)
648 struct stabilize_state *state = (struct stabilize_state *)priv;
649 int res;
650 time_t timeout;
652 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
653 return 0;
656 if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
657 DEBUG(10, ("Ignoring invalid entry\n"));
658 return 0;
660 if ((timeout < time(NULL)) || (val.dsize == 0)) {
661 res = tdb_delete(cache, key);
662 if ((res != 0) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
663 res = 0;
664 } else {
665 state->written = true;
667 } else {
668 res = tdb_store(cache, key, val, 0);
669 if (res == 0) {
670 state->written = true;
674 if (res != 0) {
675 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
676 tdb_errorstr_compat(cache)));
677 state->error = true;
678 return -1;
681 if (tdb_delete(cache_notrans, key) != 0) {
682 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
683 "%s\n", tdb_errorstr_compat(cache_notrans)));
684 state->error = true;
685 return -1;
687 return 0;
691 * Get existing entry from the cache file.
693 * @param keystr string that represents a key of this entry
694 * @param valstr buffer that is allocated and filled with the entry value
695 * buffer's disposing must be done outside
696 * @param timeout pointer to a time_t that is filled with entry's
697 * timeout
699 * @retval true when entry is successfuly fetched
700 * @retval False for failure
703 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
705 DATA_BLOB blob;
706 bool ret = False;
708 ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
709 if (!ret) {
710 return false;
712 if ((blob.data == NULL) || (blob.length == 0)) {
713 SAFE_FREE(blob.data);
714 return false;
716 if (blob.data[blob.length-1] != '\0') {
717 /* Not NULL terminated, can't be a string */
718 SAFE_FREE(blob.data);
719 return false;
721 if (value) {
722 *value = SMB_STRDUP((char *)blob.data);
723 data_blob_free(&blob);
724 if (*value == NULL) {
725 return false;
727 return true;
729 data_blob_free(&blob);
730 return true;
734 * Set an entry in the cache file. If there's no such
735 * one, then add it.
737 * @param keystr string that represents a key of this entry
738 * @param value text representation value being cached
739 * @param timeout time when the value is expired
741 * @retval true when entry is successfuly stored
742 * @retval false on failure
745 bool gencache_set(const char *keystr, const char *value, time_t timeout)
747 DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
748 return gencache_set_data_blob(keystr, &blob, timeout);
751 struct gencache_iterate_blobs_state {
752 void (*fn)(const char *key, DATA_BLOB value,
753 time_t timeout, void *private_data);
754 const char *pattern;
755 void *private_data;
756 bool in_persistent;
759 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
760 TDB_DATA data, void *priv)
762 struct gencache_iterate_blobs_state *state =
763 (struct gencache_iterate_blobs_state *)priv;
764 char *keystr;
765 char *free_key = NULL;
766 time_t timeout;
767 char *endptr;
769 if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
770 return 0;
772 if (state->in_persistent && tdb_exists(cache_notrans, key)) {
773 return 0;
776 if (key.dptr[key.dsize-1] == '\0') {
777 keystr = (char *)key.dptr;
778 } else {
779 /* ensure 0-termination */
780 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
781 free_key = keystr;
784 if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
785 goto done;
787 endptr += 1;
789 if (fnmatch(state->pattern, keystr, 0) != 0) {
790 goto done;
793 DEBUG(10, ("Calling function with arguments "
794 "(key=[%s], timeout=[%s])\n",
795 keystr, timestring(talloc_tos(), timeout)));
797 state->fn(keystr,
798 data_blob_const(endptr,
799 data.dsize - PTR_DIFF(endptr, data.dptr)),
800 timeout, state->private_data);
802 done:
803 SAFE_FREE(free_key);
804 return 0;
807 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
808 time_t timeout, void *private_data),
809 void *private_data, const char *pattern)
811 struct gencache_iterate_blobs_state state;
813 if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
814 return;
817 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
819 state.fn = fn;
820 state.pattern = pattern;
821 state.private_data = private_data;
823 state.in_persistent = false;
824 tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
826 state.in_persistent = true;
827 tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
831 * Iterate through all entries which key matches to specified pattern
833 * @param fn pointer to the function that will be supplied with each single
834 * matching cache entry (key, value and timeout) as an arguments
835 * @param data void pointer to an arbitrary data that is passed directly to the fn
836 * function on each call
837 * @param keystr_pattern pattern the existing entries' keys are matched to
841 struct gencache_iterate_state {
842 void (*fn)(const char *key, const char *value, time_t timeout,
843 void *priv);
844 void *private_data;
847 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
848 time_t timeout, void *private_data)
850 struct gencache_iterate_state *state =
851 (struct gencache_iterate_state *)private_data;
852 char *valstr;
853 char *free_val = NULL;
855 if (value.data[value.length-1] == '\0') {
856 valstr = (char *)value.data;
857 } else {
858 /* ensure 0-termination */
859 valstr = SMB_STRNDUP((char *)value.data, value.length);
860 free_val = valstr;
863 DEBUG(10, ("Calling function with arguments "
864 "(key=[%s], value=[%s], timeout=[%s])\n",
865 key, valstr, timestring(talloc_tos(), timeout)));
867 state->fn(key, valstr, timeout, state->private_data);
869 SAFE_FREE(free_val);
872 void gencache_iterate(void (*fn)(const char *key, const char *value,
873 time_t timeout, void *dptr),
874 void *private_data, const char *pattern)
876 struct gencache_iterate_state state;
878 if (fn == NULL) {
879 return;
881 state.fn = fn;
882 state.private_data = private_data;
883 gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);