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/filesys.h"
26 #include "system/glob.h"
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
;
43 * @brief Generic, persistent and shared between processes cache mechanism
44 * for use by various parts of the Samba code
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
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);
72 ret
= tdb_check(cache
, NULL
, NULL
);
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,
88 TDB_INCOMPATIBLE_HASH
|
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
,
99 DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname
));
104 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
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,
114 TDB_INCOMPATIBLE_HASH
|
117 if (cache_notrans
== NULL
) {
118 DEBUG(5, ("Opening %s failed: %s\n", cache_fname
,
128 static TDB_DATA
last_stabilize_key(void)
131 result
.dptr
= discard_const_p(uint8_t, "@LAST_STABILIZED");
136 struct gencache_have_val_state
{
138 const DATA_BLOB
*data
;
142 static void gencache_have_val_parser(time_t old_timeout
, DATA_BLOB 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
165 new_time_left
= state
->new_timeout
- now
;
166 if (new_time_left
<= 0) {
168 * Huh -- no new timeout?? Write it.
173 if (new_time_left
< cache_time_left
) {
175 * Someone wants to shorten the timeout. Let it happen.
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.
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.
208 * Now the more expensive data compare.
210 if (data_blob_cmp(state
->data
, &data
) != 0) {
212 * Write a new value. Certainly do it.
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.
225 static bool gencache_have_val(const char *keystr
, const DATA_BLOB
*data
,
228 struct gencache_have_val_state state
;
230 state
.new_timeout
= timeout
;
234 if (!gencache_parse(keystr
, gencache_have_val_parser
, &state
)) {
241 * Set an entry in the cache file. If there's no such
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
,
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
));
267 if ((keystr
== NULL
) || (blob
== NULL
)) {
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",
279 val
= talloc_asprintf(talloc_tos(), CACHE_DATA_FMT
, (int)timeout
);
283 val
= talloc_realloc(NULL
, val
, char, talloc_array_length(val
)-1);
287 val
= (char *)talloc_append_blob(NULL
, val
, *blob
);
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
)),
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.
314 if (writecount
> lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
315 gencache_stabilize();
321 * Every 5 minutes, call gencache_stabilize() to not let grow
322 * gencache_notrans.tdb too large.
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
);
333 + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
335 gencache_stabilize();
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
;
357 if (keystr
== NULL
) {
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
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.
382 data_blob_free(&value
);
383 ret
= gencache_set(keystr
, "", 0);
388 static bool gencache_pull_timeout(char *val
, time_t *pres
, char **pendptr
)
397 res
= strtol(val
, &endptr
, 10);
399 if ((endptr
== NULL
) || (*endptr
!= '/')) {
400 DEBUG(2, ("Invalid gencache data format: %s\n", val
));
406 if (pendptr
!= NULL
) {
412 struct gencache_parse_state
{
413 void (*parser
)(time_t timeout
, DATA_BLOB blob
, void *private_data
);
417 static int gencache_parse_fn(TDB_DATA key
, TDB_DATA data
, void *private_data
)
419 struct gencache_parse_state
*state
;
425 if (data
.dptr
== NULL
) {
428 ret
= gencache_pull_timeout((char *)data
.dptr
, &t
, &endptr
);
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
);
439 bool gencache_parse(const char *keystr
,
440 void (*parser
)(time_t timeout
, DATA_BLOB blob
,
444 struct gencache_parse_state state
;
448 if (keystr
== NULL
) {
451 if (tdb_data_cmp(string_term_tdb_data(keystr
),
452 last_stabilize_key()) == 0) {
455 if (!gencache_init()) {
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
);
467 ret
= tdb_parse_record(cache
, key
, gencache_parse_fn
, &state
);
471 struct gencache_get_data_blob_state
{
477 static void gencache_get_data_blob_parser(time_t timeout
, DATA_BLOB blob
,
480 struct gencache_get_data_blob_state
*state
=
481 (struct gencache_get_data_blob_state
*)private_data
;
484 state
->result
= false;
487 state
->timeout
= timeout
;
489 if (state
->blob
== NULL
) {
490 state
->result
= true;
494 *state
->blob
= data_blob(blob
.data
, blob
.length
);
495 if (state
->blob
->data
== NULL
) {
496 state
->result
= false;
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
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;
523 if (!gencache_parse(keystr
, gencache_get_data_blob_parser
, &state
)) {
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);
541 *timeout
= state
.timeout
;
547 if (was_expired
!= NULL
) {
548 *was_expired
= expired
;
550 if (state
.result
&& state
.blob
) {
551 data_blob_free(state
.blob
);
556 struct stabilize_state
{
560 static int stabilize_fn(struct tdb_context
*tdb
, TDB_DATA key
, TDB_DATA val
,
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
;
576 if (!gencache_init()) {
580 res
= tdb_transaction_start_nonblock(cache
);
582 if (tdb_error(cache
) == TDB_ERR_NOLOCK
)
585 * Someone else already does the stabilize,
586 * this does not have to be done twice
591 DEBUG(10, ("Could not start transaction on gencache.tdb: "
592 "%s\n", tdb_errorstr_compat(cache
)));
595 res
= tdb_transaction_start(cache_notrans
);
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
)));
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
);
614 if (!state
.written
) {
615 tdb_transaction_cancel(cache_notrans
);
616 tdb_transaction_cancel(cache
);
620 res
= tdb_transaction_commit(cache
);
622 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
623 "%s\n", tdb_errorstr_compat(cache
)));
624 tdb_transaction_cancel(cache_notrans
);
628 res
= tdb_transaction_commit(cache_notrans
);
630 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
631 "%s\n", tdb_errorstr_compat(cache
)));
635 now
= talloc_asprintf(talloc_tos(), "%d", (int)time(NULL
));
637 tdb_store(cache_notrans
, last_stabilize_key(),
638 string_term_tdb_data(now
), 0);
645 static int stabilize_fn(struct tdb_context
*tdb
, TDB_DATA key
, TDB_DATA val
,
648 struct stabilize_state
*state
= (struct stabilize_state
*)priv
;
652 if (tdb_data_cmp(key
, last_stabilize_key()) == 0) {
656 if (!gencache_pull_timeout((char *)val
.dptr
, &timeout
, NULL
)) {
657 DEBUG(10, ("Ignoring invalid entry\n"));
660 if ((timeout
< time(NULL
)) || (val
.dsize
== 0)) {
661 res
= tdb_delete(cache
, key
);
662 if ((res
!= 0) && (tdb_error(cache
) == TDB_ERR_NOEXIST
)) {
665 state
->written
= true;
668 res
= tdb_store(cache
, key
, val
, 0);
670 state
->written
= true;
675 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
676 tdb_errorstr_compat(cache
)));
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
)));
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
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
)
708 ret
= gencache_get_data_blob(keystr
, &blob
, ptimeout
, NULL
);
712 if ((blob
.data
== NULL
) || (blob
.length
== 0)) {
713 SAFE_FREE(blob
.data
);
716 if (blob
.data
[blob
.length
-1] != '\0') {
717 /* Not NULL terminated, can't be a string */
718 SAFE_FREE(blob
.data
);
722 *value
= SMB_STRDUP((char *)blob
.data
);
723 data_blob_free(&blob
);
724 if (*value
== NULL
) {
729 data_blob_free(&blob
);
734 * Set an entry in the cache file. If there's no such
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
);
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
;
765 char *free_key
= NULL
;
769 if (tdb_data_cmp(key
, last_stabilize_key()) == 0) {
772 if (state
->in_persistent
&& tdb_exists(cache_notrans
, key
)) {
776 if (key
.dptr
[key
.dsize
-1] == '\0') {
777 keystr
= (char *)key
.dptr
;
779 /* ensure 0-termination */
780 keystr
= SMB_STRNDUP((char *)key
.dptr
, key
.dsize
);
784 if (!gencache_pull_timeout((char *)data
.dptr
, &timeout
, &endptr
)) {
789 if (fnmatch(state
->pattern
, keystr
, 0) != 0) {
793 DEBUG(10, ("Calling function with arguments "
794 "(key=[%s], timeout=[%s])\n",
795 keystr
, timestring(talloc_tos(), timeout
)));
798 data_blob_const(endptr
,
799 data
.dsize
- PTR_DIFF(endptr
, data
.dptr
)),
800 timeout
, state
->private_data
);
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()) {
817 DEBUG(5, ("Searching cache keys with pattern %s\n", pattern
));
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
,
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
;
853 char *free_val
= NULL
;
855 if (value
.data
[value
.length
-1] == '\0') {
856 valstr
= (char *)value
.data
;
858 /* ensure 0-termination */
859 valstr
= SMB_STRNDUP((char *)value
.data
, value
.length
);
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
);
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
;
882 state
.private_data
= private_data
;
883 gencache_iterate_blobs(gencache_iterate_fn
, &state
, pattern
);