lib: Pass mem_ctx to lock_path()
[samba.git] / source3 / lib / gencache.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Generic, persistent and shared between processes cache mechanism for use
5    by various parts of the Samba code
6
7    Copyright (C) Rafal Szczesniak    2002
8    Copyright (C) Volker Lendecke     2009
9
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.
14
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.
19
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/>.
22 */
23
24 #include "includes.h"
25 #include "system/filesys.h"
26 #include "system/glob.h"
27 #include "util_tdb.h"
28 #include "tdb_wrap/tdb_wrap.h"
29
30 #undef  DBGC_CLASS
31 #define DBGC_CLASS DBGC_TDB
32
33 #define CACHE_DATA_FMT  "%12u/"
34
35 static struct tdb_wrap *cache;
36 static struct tdb_wrap *cache_notrans;
37
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
42  *
43  **/
44
45
46 /**
47  * Cache initialisation function. Opens cache tdb file or creates
48  * it if does not exist.
49  *
50  * @return true on successful initialisation of the cache or
51  *         false on failure
52  **/
53
54 static bool gencache_init(void)
55 {
56         char* cache_fname = NULL;
57         int open_flags = O_RDWR|O_CREAT;
58         int hash_size;
59
60         /* skip file open if it's already opened */
61         if (cache) {
62                 return true;
63         }
64
65         hash_size = lp_parm_int(-1, "gencache", "hash_size", 10000);
66
67         cache_fname = cache_path("gencache.tdb");
68         if (cache_fname == NULL) {
69                 return false;
70         }
71
72         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
73
74         cache = tdb_wrap_open(NULL, cache_fname, hash_size,
75                               TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
76                               open_flags, 0644);
77
78         if (!cache && (errno == EACCES)) {
79                 open_flags = O_RDONLY;
80                 cache = tdb_wrap_open(NULL, cache_fname, hash_size,
81                                       TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
82                                       open_flags, 0644);
83                 if (cache) {
84                         DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
85                 }
86         }
87         TALLOC_FREE(cache_fname);
88
89         if (!cache) {
90                 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
91                 return false;
92         }
93
94         cache_fname = lock_path(talloc_tos(), "gencache_notrans.tdb");
95         if (cache_fname == NULL) {
96                 TALLOC_FREE(cache);
97                 return false;
98         }
99
100         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
101
102         cache_notrans = tdb_wrap_open(NULL, cache_fname, hash_size,
103                                       TDB_CLEAR_IF_FIRST|
104                                       TDB_INCOMPATIBLE_HASH|
105                                       TDB_NOSYNC|
106                                       TDB_MUTEX_LOCKING,
107                                       open_flags, 0644);
108         if (cache_notrans == NULL) {
109                 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
110                           strerror(errno)));
111                 TALLOC_FREE(cache_fname);
112                 TALLOC_FREE(cache);
113                 return false;
114         }
115         TALLOC_FREE(cache_fname);
116
117         return true;
118 }
119
120 static TDB_DATA last_stabilize_key(void)
121 {
122         TDB_DATA result;
123         result.dptr = discard_const_p(uint8_t, "@LAST_STABILIZED");
124         result.dsize = 17;
125         return result;
126 }
127
128 struct gencache_have_val_state {
129         time_t new_timeout;
130         const DATA_BLOB *data;
131         bool gotit;
132 };
133
134 static void gencache_have_val_parser(time_t old_timeout, DATA_BLOB data,
135                                      void *private_data)
136 {
137         struct gencache_have_val_state *state =
138                 (struct gencache_have_val_state *)private_data;
139         time_t now = time(NULL);
140         int cache_time_left, new_time_left, additional_time;
141
142         /*
143          * Excuse the many variables, but these time calculations are
144          * confusing to me. We do not want to write to gencache with a
145          * possibly expensive transaction if we are about to write the same
146          * value, just extending the remaining timeout by less than 10%.
147          */
148
149         cache_time_left = old_timeout - now;
150         if (cache_time_left <= 0) {
151                 /*
152                  * timed out, write new value
153                  */
154                 return;
155         }
156
157         new_time_left = state->new_timeout - now;
158         if (new_time_left <= 0) {
159                 /*
160                  * Huh -- no new timeout?? Write it.
161                  */
162                 return;
163         }
164
165         if (new_time_left < cache_time_left) {
166                 /*
167                  * Someone wants to shorten the timeout. Let it happen.
168                  */
169                 return;
170         }
171
172         /*
173          * By how much does the new timeout extend the remaining cache time?
174          */
175         additional_time = new_time_left - cache_time_left;
176
177         if (additional_time * 10 < 0) {
178                 /*
179                  * Integer overflow. We extend by so much that we have to write it.
180                  */
181                 return;
182         }
183
184         /*
185          * The comparison below is essentially equivalent to
186          *
187          *    new_time_left > cache_time_left * 1.10
188          *
189          * but without floating point calculations.
190          */
191
192         if (additional_time * 10 > cache_time_left) {
193                 /*
194                  * We extend the cache timeout by more than 10%. Do it.
195                  */
196                 return;
197         }
198
199         /*
200          * Now the more expensive data compare.
201          */
202         if (data_blob_cmp(state->data, &data) != 0) {
203                 /*
204                  * Write a new value. Certainly do it.
205                  */
206                 return;
207         }
208
209         /*
210          * Extending the timeout by less than 10% for the same cache value is
211          * not worth the trouble writing a value into gencache under a
212          * possibly expensive transaction.
213          */
214         state->gotit = true;
215 }
216
217 static bool gencache_have_val(const char *keystr, const DATA_BLOB *data,
218                               time_t timeout)
219 {
220         struct gencache_have_val_state state;
221
222         state.new_timeout = timeout;
223         state.data = data;
224         state.gotit = false;
225
226         if (!gencache_parse(keystr, gencache_have_val_parser, &state)) {
227                 return false;
228         }
229         return state.gotit;
230 }
231
232 static int last_stabilize_parser(TDB_DATA key, TDB_DATA data,
233                                  void *private_data)
234 {
235         time_t *last_stabilize = private_data;
236
237         if ((data.dsize != 0) && (data.dptr[data.dsize-1] == '\0')) {
238                 *last_stabilize = atoi((char *)data.dptr);
239         }
240         return 0;
241 }
242
243 /**
244  * Set an entry in the cache file. If there's no such
245  * one, then add it.
246  *
247  * @param keystr string that represents a key of this entry
248  * @param blob DATA_BLOB value being cached
249  * @param timeout time when the value is expired
250  *
251  * @retval true when entry is successfully stored
252  * @retval false on failure
253  **/
254
255 bool gencache_set_data_blob(const char *keystr, DATA_BLOB blob,
256                             time_t timeout)
257 {
258         int ret;
259         fstring hdr;
260         int hdr_len;
261         time_t last_stabilize;
262         static int writecount;
263         TDB_DATA dbufs[2];
264
265         if (tdb_data_cmp(string_term_tdb_data(keystr),
266                          last_stabilize_key()) == 0) {
267                 DEBUG(10, ("Can't store %s as a key\n", keystr));
268                 return false;
269         }
270
271         if ((keystr == NULL) || (blob.data == NULL)) {
272                 return false;
273         }
274
275         if (!gencache_init()) {
276                 return false;
277         }
278
279         if ((timeout != 0) && gencache_have_val(keystr, &blob, timeout)) {
280                 DEBUG(10, ("Did not store value for %s, we already got it\n",
281                            keystr));
282                 return true;
283         }
284
285         hdr_len = fstr_sprintf(hdr, CACHE_DATA_FMT, (int)timeout);
286
287         if (hdr_len == -1) {
288                 return false;
289         }
290         if ((blob.length + (size_t)hdr_len) < blob.length) {
291                 return false;
292         }
293
294         dbufs[0] = (TDB_DATA) { .dptr = (uint8_t *)hdr, .dsize = hdr_len };
295         dbufs[1] = (TDB_DATA) { .dptr = blob.data, .dsize = blob.length };
296
297         DEBUG(10, ("Adding cache entry with key=[%s] and timeout="
298                    "[%s] (%d seconds %s)\n", keystr,
299                    timestring(talloc_tos(), timeout),
300                    (int)(timeout - time(NULL)), 
301                    timeout > time(NULL) ? "ahead" : "in the past"));
302
303         ret = tdb_storev(cache_notrans->tdb, string_term_tdb_data(keystr),
304                          dbufs, 2, 0);
305         if (ret != 0) {
306                 return false;
307         }
308
309         /*
310          * Every 100 writes within a single process, stabilize the cache with
311          * a transaction. This is done to prevent a single transaction to
312          * become huge and chew lots of memory.
313          */
314         writecount += 1;
315         if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
316                 gencache_stabilize();
317                 writecount = 0;
318                 goto done;
319         }
320
321         /*
322          * Every 5 minutes, call gencache_stabilize() to not let grow
323          * gencache_notrans.tdb too large.
324          */
325
326         last_stabilize = 0;
327
328         tdb_parse_record(cache_notrans->tdb, last_stabilize_key(),
329                          last_stabilize_parser, &last_stabilize);
330
331         if ((last_stabilize
332              + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
333             < time(NULL)) {
334                 gencache_stabilize();
335         }
336
337 done:
338         return ret == 0;
339 }
340
341 static void gencache_del_parser(time_t timeout, DATA_BLOB blob,
342                                 void *private_data)
343 {
344         if (timeout != 0) {
345                 bool *exists = private_data;
346                 *exists = true;
347         }
348 }
349
350 /**
351  * Delete one entry from the cache file.
352  *
353  * @param keystr string that represents a key of this entry
354  *
355  * @retval true upon successful deletion
356  * @retval false in case of failure
357  **/
358
359 bool gencache_del(const char *keystr)
360 {
361         TDB_DATA key = string_term_tdb_data(keystr);
362         bool exists = false;
363         bool result = false;
364         int ret;
365
366         if (keystr == NULL) {
367                 return false;
368         }
369
370         if (!gencache_init()) {
371                 return false;
372         }
373
374         DEBUG(10, ("Deleting cache entry (key=[%s])\n", keystr));
375
376         ret = tdb_chainlock(cache_notrans->tdb, key);
377         if (ret == -1) {
378                 return false;
379         }
380
381         gencache_parse(keystr, gencache_del_parser, &exists);
382
383         if (exists) {
384                 /*
385                  * We delete an element by setting its timeout to
386                  * 0. This way we don't have to do a transaction on
387                  * gencache.tdb every time we delete an element.
388                  */
389                 result = gencache_set(keystr, "", 0);
390         }
391
392         tdb_chainunlock(cache_notrans->tdb, key);
393
394         return result;
395 }
396
397 static bool gencache_pull_timeout(uint8_t *val, time_t *pres, char **payload)
398 {
399         time_t res;
400         char *endptr;
401
402         if (val == NULL) {
403                 return false;
404         }
405
406         res = strtol((char *)val, &endptr, 10);
407
408         if ((endptr == NULL) || (*endptr != '/')) {
409                 DEBUG(2, ("Invalid gencache data format: %s\n", (char *)val));
410                 return false;
411         }
412         if (pres != NULL) {
413                 *pres = res;
414         }
415         if (payload != NULL) {
416                 *payload = endptr+1;
417         }
418         return true;
419 }
420
421 struct gencache_parse_state {
422         void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
423         void *private_data;
424         bool copy_to_notrans;
425 };
426
427 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
428 {
429         struct gencache_parse_state *state;
430         DATA_BLOB blob;
431         time_t t;
432         char *payload;
433         bool ret;
434
435         if (data.dptr == NULL) {
436                 return -1;
437         }
438         ret = gencache_pull_timeout(data.dptr, &t, &payload);
439         if (!ret) {
440                 return -1;
441         }
442         state = (struct gencache_parse_state *)private_data;
443         blob = data_blob_const(
444                 payload, data.dsize - PTR_DIFF(payload, data.dptr));
445         state->parser(t, blob, state->private_data);
446
447         if (state->copy_to_notrans) {
448                 tdb_store(cache_notrans->tdb, key, data, 0);
449         }
450
451         return 0;
452 }
453
454 bool gencache_parse(const char *keystr,
455                     void (*parser)(time_t timeout, DATA_BLOB blob,
456                                    void *private_data),
457                     void *private_data)
458 {
459         struct gencache_parse_state state;
460         TDB_DATA key = string_term_tdb_data(keystr);
461         int ret;
462
463         if (keystr == NULL) {
464                 return false;
465         }
466         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
467                 return false;
468         }
469         if (!gencache_init()) {
470                 return false;
471         }
472
473         state.parser = parser;
474         state.private_data = private_data;
475         state.copy_to_notrans = false;
476
477         ret = tdb_chainlock(cache_notrans->tdb, key);
478         if (ret != 0) {
479                 return false;
480         }
481
482         ret = tdb_parse_record(cache_notrans->tdb, key,
483                                gencache_parse_fn, &state);
484         if (ret == 0) {
485                 tdb_chainunlock(cache_notrans->tdb, key);
486                 return true;
487         }
488
489         state.copy_to_notrans = true;
490
491         ret = tdb_parse_record(cache->tdb, key, gencache_parse_fn, &state);
492
493         if ((ret == -1) && (tdb_error(cache->tdb) == TDB_ERR_NOEXIST)) {
494                 /*
495                  * The record does not exist. Set a delete-marker in
496                  * gencache_notrans, so that we don't have to look at
497                  * the fcntl-based cache again.
498                  */
499                 gencache_set(keystr, "", 0);
500         }
501
502         tdb_chainunlock(cache_notrans->tdb, key);
503
504         return (ret == 0);
505 }
506
507 struct gencache_get_data_blob_state {
508         TALLOC_CTX *mem_ctx;
509         DATA_BLOB *blob;
510         time_t timeout;
511         bool result;
512 };
513
514 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
515                                           void *private_data)
516 {
517         struct gencache_get_data_blob_state *state =
518                 (struct gencache_get_data_blob_state *)private_data;
519
520         if (timeout == 0) {
521                 state->result = false;
522                 return;
523         }
524         state->timeout = timeout;
525
526         if (state->blob == NULL) {
527                 state->result = true;
528                 return;
529         }
530
531         *state->blob = data_blob_talloc(state->mem_ctx, blob.data,
532                                         blob.length);
533         if (state->blob->data == NULL) {
534                 state->result = false;
535                 return;
536         }
537         state->result = true;
538 }
539
540 /**
541  * Get existing entry from the cache file.
542  *
543  * @param keystr string that represents a key of this entry
544  * @param blob DATA_BLOB that is filled with entry's blob
545  * @param timeout pointer to a time_t that is filled with entry's
546  *        timeout
547  *
548  * @retval true when entry is successfully fetched
549  * @retval false for failure
550  **/
551
552 bool gencache_get_data_blob(const char *keystr, TALLOC_CTX *mem_ctx,
553                             DATA_BLOB *blob,
554                             time_t *timeout, bool *was_expired)
555 {
556         struct gencache_get_data_blob_state state;
557         bool expired = false;
558
559         state.result = false;
560         state.mem_ctx = mem_ctx;
561         state.blob = blob;
562
563         if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
564                 goto fail;
565         }
566         if (!state.result) {
567                 goto fail;
568         }
569         if (state.timeout <= time(NULL)) {
570                 /*
571                  * We're expired, delete the entry. We can't use gencache_del
572                  * here, because that uses gencache_get_data_blob for checking
573                  * the existence of a record. We know the thing exists and
574                  * directly store an empty value with 0 timeout.
575                  */
576                 gencache_set(keystr, "", 0);
577                 expired = true;
578                 goto fail;
579         }
580         if (timeout) {
581                 *timeout = state.timeout;
582         }
583
584         return true;
585
586 fail:
587         if (was_expired != NULL) {
588                 *was_expired = expired;
589         }
590         if (state.result && state.blob) {
591                 data_blob_free(state.blob);
592         }
593         return false;
594
595
596 struct stabilize_state {
597         bool written;
598 };
599 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
600                         void *priv);
601
602 /**
603  * Stabilize gencache
604  *
605  * Migrate the clear-if-first gencache data to the stable,
606  * transaction-based gencache.tdb
607  */
608
609 bool gencache_stabilize(void)
610 {
611         struct stabilize_state state;
612         int res;
613         char *now;
614
615         if (!gencache_init()) {
616                 return false;
617         }
618
619         res = tdb_transaction_start_nonblock(cache->tdb);
620         if (res != 0) {
621                 if (tdb_error(cache->tdb) == TDB_ERR_NOLOCK)
622                 {
623                         /*
624                          * Someone else already does the stabilize,
625                          * this does not have to be done twice
626                          */
627                         return true;
628                 }
629
630                 DEBUG(10, ("Could not start transaction on gencache.tdb: "
631                            "%s\n", tdb_errorstr(cache->tdb)));
632                 return false;
633         }
634
635         res = tdb_lockall_nonblock(cache_notrans->tdb);
636         if (res != 0) {
637                 tdb_transaction_cancel(cache->tdb);
638                 DEBUG(10, ("Could not get allrecord lock on "
639                            "gencache_notrans.tdb: %s\n",
640                            tdb_errorstr(cache_notrans->tdb)));
641                 return false;
642         }
643
644         state.written = false;
645
646         res = tdb_traverse(cache_notrans->tdb, stabilize_fn, &state);
647         if (res < 0) {
648                 tdb_unlockall(cache_notrans->tdb);
649                 tdb_transaction_cancel(cache->tdb);
650                 return false;
651         }
652
653         if (!state.written) {
654                 tdb_unlockall(cache_notrans->tdb);
655                 tdb_transaction_cancel(cache->tdb);
656                 return true;
657         }
658
659         res = tdb_transaction_commit(cache->tdb);
660         if (res != 0) {
661                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
662                            "%s\n", tdb_errorstr(cache->tdb)));
663                 tdb_unlockall(cache_notrans->tdb);
664                 return false;
665         }
666
667         res = tdb_wipe_all(cache_notrans->tdb);
668         if (res < 0) {
669                 DBG_DEBUG("tdb_wipe_all on gencache_notrans.tdb failed: %s\n",
670                           tdb_errorstr(cache_notrans->tdb));
671         }
672
673         now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
674         if (now != NULL) {
675                 tdb_store(cache_notrans->tdb, last_stabilize_key(),
676                           string_term_tdb_data(now), 0);
677                 TALLOC_FREE(now);
678         }
679
680         res = tdb_unlockall(cache_notrans->tdb);
681         if (res != 0) {
682                 DEBUG(10, ("tdb_unlockall on gencache.tdb failed: "
683                            "%s\n", tdb_errorstr(cache->tdb)));
684                 return false;
685         }
686
687         return true;
688 }
689
690 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
691                         void *priv)
692 {
693         struct stabilize_state *state = (struct stabilize_state *)priv;
694         int res;
695         time_t timeout;
696
697         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
698                 return 0;
699         }
700
701         if (!gencache_pull_timeout(val.dptr, &timeout, NULL)) {
702                 DEBUG(10, ("Ignoring invalid entry\n"));
703                 return 0;
704         }
705         if ((timeout < time(NULL)) || (val.dsize == 0)) {
706                 res = tdb_delete(cache->tdb, key);
707                 if (res == 0) {
708                         state->written = true;
709                 } else if (tdb_error(cache->tdb) == TDB_ERR_NOEXIST) {
710                         res = 0;
711                 }
712         } else {
713                 res = tdb_store(cache->tdb, key, val, 0);
714                 if (res == 0) {
715                         state->written = true;
716                 }
717         }
718
719         if (res != 0) {
720                 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
721                            tdb_errorstr(cache->tdb)));
722                 return -1;
723         }
724
725         return 0;
726 }
727
728 /**
729  * Get existing entry from the cache file.
730  *
731  * @param keystr string that represents a key of this entry
732  * @param valstr buffer that is allocated and filled with the entry value
733  *        buffer's disposing must be done outside
734  * @param timeout pointer to a time_t that is filled with entry's
735  *        timeout
736  *
737  * @retval true when entry is successfully fetched
738  * @retval false for failure
739  **/
740
741 bool gencache_get(const char *keystr, TALLOC_CTX *mem_ctx, char **value,
742                   time_t *ptimeout)
743 {
744         DATA_BLOB blob;
745         bool ret = false;
746
747         ret = gencache_get_data_blob(keystr, mem_ctx, &blob, ptimeout, NULL);
748         if (!ret) {
749                 return false;
750         }
751         if ((blob.data == NULL) || (blob.length == 0)) {
752                 data_blob_free(&blob);
753                 return false;
754         }
755         if (blob.data[blob.length-1] != '\0') {
756                 /* Not NULL terminated, can't be a string */
757                 data_blob_free(&blob);
758                 return false;
759         }
760         if (value) {
761                 /*
762                  * talloc_move generates a type-punned warning here. As we
763                  * leave the function immediately, do a simple talloc_steal.
764                  */
765                 *value = (char *)talloc_steal(mem_ctx, blob.data);
766                 return true;
767         }
768         data_blob_free(&blob);
769         return true;
770 }
771
772 /**
773  * Set an entry in the cache file. If there's no such
774  * one, then add it.
775  *
776  * @param keystr string that represents a key of this entry
777  * @param value text representation value being cached
778  * @param timeout time when the value is expired
779  *
780  * @retval true when entry is successfully stored
781  * @retval false on failure
782  **/
783
784 bool gencache_set(const char *keystr, const char *value, time_t timeout)
785 {
786         DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
787         return gencache_set_data_blob(keystr, blob, timeout);
788 }
789
790 struct gencache_iterate_blobs_state {
791         void (*fn)(const char *key, DATA_BLOB value,
792                    time_t timeout, void *private_data);
793         const char *pattern;
794         void *private_data;
795         bool in_persistent;
796 };
797
798 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
799                                      TDB_DATA data, void *priv)
800 {
801         struct gencache_iterate_blobs_state *state =
802                 (struct gencache_iterate_blobs_state *)priv;
803         char *keystr;
804         char *free_key = NULL;
805         time_t timeout;
806         char *payload;
807
808         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
809                 return 0;
810         }
811         if (state->in_persistent && tdb_exists(cache_notrans->tdb, key)) {
812                 return 0;
813         }
814
815         if (key.dptr[key.dsize-1] == '\0') {
816                 keystr = (char *)key.dptr;
817         } else {
818                 /* ensure 0-termination */
819                 keystr = talloc_strndup(talloc_tos(), (char *)key.dptr, key.dsize);
820                 free_key = keystr;
821                 if (keystr == NULL) {
822                         goto done;
823                 }
824         }
825
826         if (!gencache_pull_timeout(data.dptr, &timeout, &payload)) {
827                 goto done;
828         }
829
830         if (timeout == 0) {
831                 /* delete marker */
832                 goto done;
833         }
834
835         if (fnmatch(state->pattern, keystr, 0) != 0) {
836                 goto done;
837         }
838
839         DEBUG(10, ("Calling function with arguments "
840                    "(key=[%s], timeout=[%s])\n",
841                    keystr, timestring(talloc_tos(), timeout)));
842
843         state->fn(keystr,
844                   data_blob_const(payload,
845                                   data.dsize - PTR_DIFF(payload, data.dptr)),
846                   timeout, state->private_data);
847
848  done:
849         TALLOC_FREE(free_key);
850         return 0;
851 }
852
853 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
854                                        time_t timeout, void *private_data),
855                             void *private_data, const char *pattern)
856 {
857         struct gencache_iterate_blobs_state state;
858
859         if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
860                 return;
861         }
862
863         DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
864
865         state.fn = fn;
866         state.pattern = pattern;
867         state.private_data = private_data;
868
869         state.in_persistent = false;
870         tdb_traverse(cache_notrans->tdb, gencache_iterate_blobs_fn, &state);
871
872         state.in_persistent = true;
873         tdb_traverse(cache->tdb, gencache_iterate_blobs_fn, &state);
874 }
875
876 /**
877  * Iterate through all entries which key matches to specified pattern
878  *
879  * @param fn pointer to the function that will be supplied with each single
880  *        matching cache entry (key, value and timeout) as an arguments
881  * @param data void pointer to an arbitrary data that is passed directly to the fn
882  *        function on each call
883  * @param keystr_pattern pattern the existing entries' keys are matched to
884  *
885  **/
886
887 struct gencache_iterate_state {
888         void (*fn)(const char *key, const char *value, time_t timeout,
889                    void *priv);
890         void *private_data;
891 };
892
893 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
894                                 time_t timeout, void *private_data)
895 {
896         struct gencache_iterate_state *state =
897                 (struct gencache_iterate_state *)private_data;
898         char *valstr;
899         char *free_val = NULL;
900
901         if (value.data[value.length-1] == '\0') {
902                 valstr = (char *)value.data;
903         } else {
904                 /* ensure 0-termination */
905                 valstr = talloc_strndup(talloc_tos(), (char *)value.data, value.length);
906                 free_val = valstr;
907                 if (valstr == NULL) {
908                         goto done;
909                 }
910         }
911
912         DEBUG(10, ("Calling function with arguments "
913                    "(key=[%s], value=[%s], timeout=[%s])\n",
914                    key, valstr, timestring(talloc_tos(), timeout)));
915
916         state->fn(key, valstr, timeout, state->private_data);
917
918   done:
919
920         TALLOC_FREE(free_val);
921 }
922
923 void gencache_iterate(void (*fn)(const char *key, const char *value,
924                                  time_t timeout, void *dptr),
925                       void *private_data, const char *pattern)
926 {
927         struct gencache_iterate_state state;
928
929         if (fn == NULL) {
930                 return;
931         }
932         state.fn = fn;
933         state.private_data = private_data;
934         gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);
935 }