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