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