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