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