summaryrefslogtreecommitdiff
path: root/source3/lib/gencache.c
blob: 2c5e9ab4245635cff14a153a66a98decd6aae81d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/* 
   Unix SMB/CIFS implementation.

   Generic, persistent and shared between processes cache mechanism for use
   by various parts of the Samba code

   Copyright (C) Rafal Szczesniak    2002
   Copyright (C) Volker Lendecke     2009

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "system/filesys.h"
#include "system/glob.h"
#include "util_tdb.h"

#undef  DBGC_CLASS
#define DBGC_CLASS DBGC_TDB

#define TIMEOUT_LEN 12
#define CACHE_DATA_FMT	"%12u/"
#define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
#define BLOB_TYPE "DATA_BLOB"
#define BLOB_TYPE_LEN 9

static struct tdb_context *cache;
static struct tdb_context *cache_notrans;

/**
 * @file gencache.c
 * @brief Generic, persistent and shared between processes cache mechanism
 *        for use by various parts of the Samba code
 *
 **/


/**
 * Cache initialisation function. Opens cache tdb file or creates
 * it if does not exist.
 *
 * @return true on successful initialisation of the cache or
 *         false on failure
 **/

static bool gencache_init(void)
{
	char* cache_fname = NULL;
	int open_flags = O_RDWR|O_CREAT;

	/* skip file open if it's already opened */
	if (cache) return True;

	cache_fname = cache_path("gencache.tdb");

	DEBUG(5, ("Opening cache file at %s\n", cache_fname));

	cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
	if (cache) {
		int ret;
		ret = tdb_check(cache, NULL, NULL);
		if (ret != 0) {
			tdb_close(cache);

			/*
			 * Retry with CLEAR_IF_FIRST.
			 *
			 * Warning: Converting this to dbwrap won't work
			 * directly. gencache.c does transactions on this tdb,
			 * and dbwrap forbids this for CLEAR_IF_FIRST
			 * databases. tdb does allow transactions on
			 * CLEAR_IF_FIRST databases, so lets use it here to
			 * clean up a broken database.
			 */
			cache = tdb_open_log(cache_fname, 0,
					     TDB_DEFAULT|
					     TDB_INCOMPATIBLE_HASH|
					     TDB_CLEAR_IF_FIRST,
					     open_flags, 0644);
		}
	}

	if (!cache && (errno == EACCES)) {
		open_flags = O_RDONLY;
		cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags,
				     0644);
		if (cache) {
			DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
		}
	}

	if (!cache) {
		DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
		return False;
	}

	cache_fname = lock_path("gencache_notrans.tdb");

	DEBUG(5, ("Opening cache file at %s\n", cache_fname));

	cache_notrans = tdb_open_log(cache_fname, 0,
				     TDB_CLEAR_IF_FIRST|
				     TDB_INCOMPATIBLE_HASH|
				     TDB_NOSYNC,
				     open_flags, 0644);
	if (cache_notrans == NULL) {
		DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
			  strerror(errno)));
		tdb_close(cache);
		cache = NULL;
		return false;
	}

	return True;
}

static TDB_DATA last_stabilize_key(void)
{
	TDB_DATA result;
	result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
	result.dsize = 17;
	return result;
}

struct gencache_have_val_state {
	time_t new_timeout;
	const DATA_BLOB *data;
	bool gotit;
};

static void gencache_have_val_parser(time_t old_timeout, DATA_BLOB data,
				     void *private_data)
{
	struct gencache_have_val_state *state =
		(struct gencache_have_val_state *)private_data;
	time_t now = time(NULL);
	int cache_time_left, new_time_left, additional_time;

	/*
	 * Excuse the many variables, but these time calculations are
	 * confusing to me. We do not want to write to gencache with a
	 * possibly expensive transaction if we are about to write the same
	 * value, just extending the remaining timeout by less than 10%.
	 */

	cache_time_left = old_timeout - now;
	if (cache_time_left <= 0) {
		/*
		 * timed out, write new value
		 */
		return;
	}

	new_time_left = state->new_timeout - now;
	if (new_time_left <= 0) {
		/*
		 * Huh -- no new timeout?? Write it.
		 */
		return;
	}

	if (new_time_left < cache_time_left) {
		/*
		 * Someone wants to shorten the timeout. Let it happen.
		 */
		return;
	}

	/*
	 * By how much does the new timeout extend the remaining cache time?
	 */
	additional_time = new_time_left - cache_time_left;

	if (additional_time * 10 < 0) {
		/*
		 * Integer overflow. We extend by so much that we have to write it.
		 */
		return;
	}

	/*
	 * The comparison below is essentially equivalent to
	 *
	 *    new_time_left > cache_time_left * 1.10
	 *
	 * but without floating point calculations.
	 */

	if (additional_time * 10 > cache_time_left) {
		/*
		 * We extend the cache timeout by more than 10%. Do it.
		 */
		return;
	}

	/*
	 * Now the more expensive data compare.
	 */
	if (data_blob_cmp(state->data, &data) != 0) {
		/*
		 * Write a new value. Certainly do it.
		 */
		return;
	}

	/*
	 * Extending the timeout by less than 10% for the same cache value is
	 * not worth the trouble writing a value into gencache under a
	 * possibly expensive transaction.
	 */
	state->gotit = true;
}

static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
			      time_t timeout)
{
	struct gencache_have_val_state state;

	state.new_timeout = timeout;
	state.data = data;
	state.gotit = false;

	if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
		return false;
	}
	return state.gotit;
}

/**
 * Set an entry in the cache file. If there's no such
 * one, then add it.
 *
 * @param keystr string that represents a key of this entry
 * @param blob DATA_BLOB value being cached
 * @param timeout time when the value is expired
 *
 * @retval true when entry is successfuly stored
 * @retval false on failure
 **/

bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
			    time_t timeout)
{
	int ret;
	TDB_DATA databuf;
	char* val;
	time_t last_stabilize;
	static int writecount;

	if (tdb_data_cmp(string_term_tdb_data(keystr),
			 last_stabilize_key()) == 0) {
		DEBUG(10, ("Can't store %s as a key\n", keystr));
		return false;
	}

	if ((keystr == NULL) || (blob == NULL)) {
		return false;
	}

	if (!gencache_init()) return False;

	if (gencache_have_val(keystr, blob, timeout)) {
		DEBUG(10, ("Did not store value for %s, we already got it\n",
			   keystr));
		return true;
	}

	val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
	if (val == NULL) {
		return False;
	}
	val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
	if (val == NULL) {
		return false;
	}
	val = (char *)talloc_append_blob(NULL, val, *blob);
	if (val == NULL) {
		return false;
	}

	DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
	           "[%s] (%d seconds %s)\n", keystr,
		   timestring(talloc_tos(), timeout),
		   (int)(timeout - time(NULL)), 
		   timeout > time(NULL) ? "ahead" : "in the past"));

	ret = tdb_store_bystring(
		cache_notrans, keystr,
		make_tdb_data((uint8_t *)val, talloc_array_length(val)),
		0);
	TALLOC_FREE(val);

	if (ret != 0) {
		return false;
	}

	/*
	 * Every 100 writes within a single process, stabilize the cache with
	 * a transaction. This is done to prevent a single transaction to
	 * become huge and chew lots of memory.
	 */
	writecount += 1;
	if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
		gencache_stabilize();
		writecount = 0;
		goto done;
	}

	/*
	 * Every 5 minutes, call gencache_stabilize() to not let grow
	 * gencache_notrans.tdb too large.
	 */

	last_stabilize = 0;
	databuf = tdb_fetch_compat(cache_notrans, last_stabilize_key());
	if ((databuf.dptr != NULL)
	    && (databuf.dptr[databuf.dsize-1] == '\0')) {
		last_stabilize = atoi((char *)databuf.dptr);
		SAFE_FREE(databuf.dptr);
	}
	if ((last_stabilize
	     + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
	    < time(NULL)) {
		gencache_stabilize();
	}

done:
	return ret == 0;
}

/**
 * Delete one entry from the cache file.
 *
 * @param keystr string that represents a key of this entry
 *
 * @retval true upon successful deletion
 * @retval false in case of failure
 **/

bool gencache_del(const char *keystr)
{
	bool exists, was_expired;
	bool ret = false;
	DATA_BLOB value;

	if (keystr == NULL) {
		return false;
	}

	if (!gencache_init()) return False;	

	DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));

	/*
	 * We delete an element by setting its timeout to 0. This way we don't
	 * have to do a transaction on gencache.tdb every time we delete an
	 * element.
	 */

	exists = gencache_get_data_blob(keystr, NULL, &value, NULL,
					&was_expired);

	if (!exists && was_expired) {
		/*
		 * gencache_get_data_blob has implicitly deleted this
		 * entry, so we have to return success here.
		 */
		return true;
	}

	if (exists) {
		data_blob_free(&value);
		ret = gencache_set(keystr, "", 0);
	}
	return ret;
}

static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
{
	time_t res;
	char *endptr;

	if (val == NULL) {
		return false;
	}

	res = strtol(val, &endptr, 10);

	if ((endptr == NULL) || (*endptr != '/')) {
		DEBUG(2, ("Invalid gencache data format: %s\n", val));
		return false;
	}
	if (pres != NULL) {
		*pres = res;
	}
	if (pendptr != NULL) {
		*pendptr = endptr;
	}
	return true;
}

struct gencache_parse_state {
	void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
	void *private_data;
};

static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
{
	struct gencache_parse_state *state;
	DATA_BLOB blob;
	time_t t;
	char *endptr;
	bool ret;

	if (data.dptr == NULL) {
		return -1;
	}
	ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
	if (!ret) {
		return -1;
	}
	state = (struct gencache_parse_state *)private_data;
	blob = data_blob_const(
		endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
	state->parser(t, blob, state->private_data);
	return 0;
}

bool gencache_parse(const char *keystr,
		    void (*parser)(time_t timeout, DATA_BLOB blob,
				   void *private_data),
		    void *private_data)
{
	struct gencache_parse_state state;
	TDB_DATA key;
	int ret;

	if (keystr == NULL) {
		return false;
	}
	if (tdb_data_cmp(string_term_tdb_data(keystr),
			 last_stabilize_key()) == 0) {
		return false;
	}
	if (!gencache_init()) {
		return false;
	}

	key = string_term_tdb_data(keystr);
	state.parser = parser;
	state.private_data = private_data;

	ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
	if (ret == 0) {
		return true;
	}
	ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
	return (ret == 0);
}

struct gencache_get_data_blob_state {
	TALLOC_CTX *mem_ctx;
	DATA_BLOB *blob;
	time_t timeout;
	bool result;
};

static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
					  void *private_data)
{
	struct gencache_get_data_blob_state *state =
		(struct gencache_get_data_blob_state *)private_data;

	if (timeout == 0) {
		state->result = false;
		return;
	}
	state->timeout = timeout;

	if (state->blob == NULL) {
		state->result = true;
		return;
	}

	*state->blob = data_blob_talloc(state->mem_ctx, blob.data,
					blob.length);
	if (state->blob->data == NULL) {
		state->result = false;
		return;
	}
	state->result = true;
}

/**
 * Get existing entry from the cache file.
 *
 * @param keystr string that represents a key of this entry
 * @param blob DATA_BLOB that is filled with entry's blob
 * @param timeout pointer to a time_t that is filled with entry's
 *        timeout
 *
 * @retval true when entry is successfuly fetched
 * @retval False for failure
 **/

bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
			    DATA_BLOB *blob,
			    time_t *timeout, bool *was_expired)
{
	struct gencache_get_data_blob_state state;
	bool expired = false;

	state.result = false;
	state.mem_ctx = mem_ctx;
	state.blob = blob;

	if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
		goto fail;
	}
	if (!state.result) {
		goto fail;
	}
	if (state.timeout <= time(NULL)) {
		/*
		 * We're expired, delete the entry. We can't use gencache_del
		 * here, because that uses gencache_get_data_blob for checking
		 * the existence of a record. We know the thing exists and
		 * directly store an empty value with 0 timeout.
		 */
		gencache_set(keystr, "", 0);
		expired = true;
		goto fail;
	}
	if (timeout) {
		*timeout = state.timeout;
	}

	return True;

fail:
	if (was_expired != NULL) {
		*was_expired = expired;
	}
	if (state.result && state.blob) {
		data_blob_free(state.blob);
	}
	return false;
} 

struct stabilize_state {
	bool written;
	bool error;
};
static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
			void *priv);

/**
 * Stabilize gencache
 *
 * Migrate the clear-if-first gencache data to the stable,
 * transaction-based gencache.tdb
 */

bool gencache_stabilize(void)
{
	struct stabilize_state state;
	int res;
	char *now;

	if (!gencache_init()) {
		return false;
	}

	res = tdb_transaction_start_nonblock(cache);
	if (res != 0) {
		if (tdb_error(cache) == TDB_ERR_NOLOCK)
		{
			/*
			 * Someone else already does the stabilize,
			 * this does not have to be done twice
			 */
			return true;
		}

		DEBUG(10, ("Could not start transaction on gencache.tdb: "
			   "%s\n", tdb_errorstr_compat(cache)));
		return false;
	}
	res = tdb_transaction_start(cache_notrans);
	if (res != 0) {
		tdb_transaction_cancel(cache);
		DEBUG(10, ("Could not start transaction on "
			   "gencache_notrans.tdb: %s\n",
			   tdb_errorstr_compat(cache_notrans)));
		return false;
	}

	state.error = false;
	state.written = false;

	res = tdb_traverse(cache_notrans, stabilize_fn, &state);
	if ((res < 0) || state.error) {
		tdb_transaction_cancel(cache_notrans);
		tdb_transaction_cancel(cache);
		return false;
	}

	if (!state.written) {
		tdb_transaction_cancel(cache_notrans);
		tdb_transaction_cancel(cache);
		return true;
	}

	res = tdb_transaction_commit(cache);
	if (res != 0) {
		DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
			   "%s\n", tdb_errorstr_compat(cache)));
		tdb_transaction_cancel(cache_notrans);
		return false;
	}

	res = tdb_transaction_commit(cache_notrans);
	if (res != 0) {
		DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
			   "%s\n", tdb_errorstr_compat(cache)));
		return false;
	}

	now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
	if (now != NULL) {
		tdb_store(cache_notrans, last_stabilize_key(),
			  string_term_tdb_data(now), 0);
		TALLOC_FREE(now);
	}

	return true;
}

static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
			void *priv)
{
	struct stabilize_state *state = (struct stabilize_state *)priv;
	int res;
	time_t timeout;

	if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
		return 0;
	}

	if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
		DEBUG(10, ("Ignoring invalid entry\n"));
		return 0;
	}
	if ((timeout < time(NULL)) || (val.dsize == 0)) {
		res = tdb_delete(cache, key);
		if ((res != 0) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
			res = 0;
		} else {
			state->written = true;
		}
	} else {
		res = tdb_store(cache, key, val, 0);
		if (res == 0) {
			state->written = true;
		}
	}

	if (res != 0) {
		DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
			   tdb_errorstr_compat(cache)));
		state->error = true;
		return -1;
	}

	if (tdb_delete(cache_notrans, key) != 0) {
		DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
			   "%s\n", tdb_errorstr_compat(cache_notrans)));
		state->error = true;
		return -1;
	}
	return 0;
}

/**
 * Get existing entry from the cache file.
 *
 * @param keystr string that represents a key of this entry
 * @param valstr buffer that is allocated and filled with the entry value
 *        buffer's disposing must be done outside
 * @param timeout pointer to a time_t that is filled with entry's
 *        timeout
 *
 * @retval true when entry is successfuly fetched
 * @retval False for failure
 **/

bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
		  time_t *ptimeout)
{
	DATA_BLOB blob;
	bool ret = False;

	ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
	if (!ret) {
		return false;
	}
	if ((blob.data == NULL) || (blob.length == 0)) {
		data_blob_free(&blob);
		return false;
	}
	if (blob.data[blob.length-1] != '\0') {
		/* Not NULL terminated, can't be a string */
		data_blob_free(&blob);
		return false;
	}
	if (value) {
		*value = talloc_move(mem_ctx, (char **)&blob.data);
		return true;
	}
	data_blob_free(&blob);
	return true;
}

/**
 * Set an entry in the cache file. If there's no such
 * one, then add it.
 *
 * @param keystr string that represents a key of this entry
 * @param value text representation value being cached
 * @param timeout time when the value is expired
 *
 * @retval true when entry is successfuly stored
 * @retval false on failure
 **/

bool gencache_set(const char *keystr, const char *value, time_t timeout)
{
	DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
	return gencache_set_data_blob(keystr, &blob, timeout);
}

struct gencache_iterate_blobs_state {
	void (*fn)(const char *key, DATA_BLOB value,
		   time_t timeout, void *private_data);
	const char *pattern;
	void *private_data;
	bool in_persistent;
};

static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
				     TDB_DATA data, void *priv)
{
	struct gencache_iterate_blobs_state *state =
		(struct gencache_iterate_blobs_state *)priv;
	char *keystr;
	char *free_key = NULL;
	time_t timeout;
	char *endptr;

	if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
		return 0;
	}
	if (state->in_persistent && tdb_exists(cache_notrans, key)) {
		return 0;
	}

	if (key.dptr[key.dsize-1] == '\0') {
		keystr = (char *)key.dptr;
	} else {
		/* ensure 0-termination */
		keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
		free_key = keystr;
		if (keystr == NULL) {
			goto done;
		}
	}

	if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
		goto done;
	}
	endptr += 1;

	if (fnmatch(state->pattern, keystr, 0) != 0) {
		goto done;
	}

	DEBUG(10, ("Calling function with arguments "
		   "(key=[%s], timeout=[%s])\n",
		   keystr, timestring(talloc_tos(), timeout)));

	state->fn(keystr,
		  data_blob_const(endptr,
				  data.dsize - PTR_DIFF(endptr, data.dptr)),
		  timeout, state->private_data);

 done:
	TALLOC_FREE(free_key);
	return 0;
}

void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
				       time_t timeout, void *private_data),
			    void *private_data, const char *pattern)
{
	struct gencache_iterate_blobs_state state;

	if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
		return;
	}

	DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));

	state.fn = fn;
	state.pattern = pattern;
	state.private_data = private_data;

	state.in_persistent = false;
	tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);

	state.in_persistent = true;
	tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
}

/**
 * Iterate through all entries which key matches to specified pattern
 *
 * @param fn pointer to the function that will be supplied with each single
 *        matching cache entry (key, value and timeout) as an arguments
 * @param data void pointer to an arbitrary data that is passed directly to the fn
 *        function on each call
 * @param keystr_pattern pattern the existing entries' keys are matched to
 *
 **/

struct gencache_iterate_state {
	void (*fn)(const char *key, const char *value, time_t timeout,
		   void *priv);
	void *private_data;
};

static void gencache_iterate_fn(const char *key, DATA_BLOB value,
				time_t timeout, void *private_data)
{
	struct gencache_iterate_state *state =
		(struct gencache_iterate_state *)private_data;
	char *valstr;
	char *free_val = NULL;

	if (value.data[value.length-1] == '\0') {
		valstr = (char *)value.data;
	} else {
		/* ensure 0-termination */
		valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
		free_val = valstr;
		if (valstr == NULL) {
			goto done;
		}
	}

	DEBUG(10, ("Calling function with arguments "
		   "(key=[%s], value=[%s], timeout=[%s])\n",
		   key, valstr, timestring(talloc_tos(), timeout)));

	state->fn(key, valstr, timeout, state->private_data);

  done:

	TALLOC_FREE(free_val);
}

void gencache_iterate(void (*fn)(const char *key, const char *value,
				 time_t timeout, void *dptr),
                      void *private_data, const char *pattern)
{
	struct gencache_iterate_state state;

	if (fn == NULL) {
		return;
	}
	state.fn = fn;
	state.private_data = private_data;
	gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);
}