67c37f34e73cd9b0d972d630cdf9b818cebab285
[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
28 #undef  DBGC_CLASS
29 #define DBGC_CLASS DBGC_TDB
30
31 #define TIMEOUT_LEN 12
32 #define CACHE_DATA_FMT  "%12u/"
33 #define READ_CACHE_DATA_FMT_TEMPLATE "%%12u/%%%us"
34 #define BLOB_TYPE "DATA_BLOB"
35 #define BLOB_TYPE_LEN 9
36
37 static struct tdb_context *cache;
38 static struct tdb_context *cache_notrans;
39
40 /**
41  * @file gencache.c
42  * @brief Generic, persistent and shared between processes cache mechanism
43  *        for use by various parts of the Samba code
44  *
45  **/
46
47
48 /**
49  * Cache initialisation function. Opens cache tdb file or creates
50  * it if does not exist.
51  *
52  * @return true on successful initialisation of the cache or
53  *         false on failure
54  **/
55
56 static bool gencache_init(void)
57 {
58         char* cache_fname = NULL;
59         int open_flags = O_RDWR|O_CREAT;
60         bool first_try = true;
61
62         /* skip file open if it's already opened */
63         if (cache) return True;
64
65         cache_fname = lock_path("gencache.tdb");
66
67         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
68
69 again:
70         cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
71         if (cache) {
72                 int ret;
73                 ret = tdb_check(cache, NULL, NULL);
74                 if (ret != 0) {
75                         tdb_close(cache);
76                         cache = NULL;
77                         if (!first_try) {
78                                 DEBUG(0, ("gencache_init: tdb_check(%s) failed\n",
79                                           cache_fname));
80                                 return false;
81                         }
82                         first_try = false;
83                         DEBUG(0, ("gencache_init: tdb_check(%s) failed - retry after CLEAR_IF_FIRST\n",
84                                   cache_fname));
85                         cache = tdb_open_log(cache_fname, 0, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, open_flags, 0644);
86                         if (cache) {
87                                 tdb_close(cache);
88                                 cache = NULL;
89                                 goto again;
90                         }
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, TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
113                                      open_flags, 0644);
114         if (cache_notrans == NULL) {
115                 DEBUG(5, ("Opening %s failed: %s\n", cache_fname,
116                           strerror(errno)));
117                 tdb_close(cache);
118                 cache = NULL;
119                 return false;
120         }
121
122         return True;
123 }
124
125 static TDB_DATA last_stabilize_key(void)
126 {
127         TDB_DATA result;
128         result.dptr = (uint8_t *)"@LAST_STABILIZED";
129         result.dsize = 17;
130         return result;
131 }
132
133 /**
134  * Set an entry in the cache file. If there's no such
135  * one, then add it.
136  *
137  * @param keystr string that represents a key of this entry
138  * @param blob DATA_BLOB value being cached
139  * @param timeout time when the value is expired
140  *
141  * @retval true when entry is successfuly stored
142  * @retval false on failure
143  **/
144
145 bool gencache_set_data_blob(const char *keystr, const DATA_BLOB *blob,
146                             time_t timeout)
147 {
148         int ret;
149         TDB_DATA databuf;
150         char* val;
151         time_t last_stabilize;
152         static int writecount;
153
154         if (tdb_data_cmp(string_term_tdb_data(keystr),
155                          last_stabilize_key()) == 0) {
156                 DEBUG(10, ("Can't store %s as a key\n", keystr));
157                 return false;
158         }
159
160         if ((keystr == NULL) || (blob == NULL)) {
161                 return false;
162         }
163
164         if (!gencache_init()) return False;
165
166         val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
167         if (val == NULL) {
168                 return False;
169         }
170         val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
171         if (val == NULL) {
172                 return false;
173         }
174         val = (char *)talloc_append_blob(NULL, val, *blob);
175         if (val == NULL) {
176                 return false;
177         }
178
179         DEBUG(10, ("Adding cache entry with key = %s and timeout ="
180                    " %s (%d seconds %s)\n", keystr, ctime(&timeout),
181                    (int)(timeout - time(NULL)), 
182                    timeout > time(NULL) ? "ahead" : "in the past"));
183
184         ret = tdb_store_bystring(
185                 cache_notrans, keystr,
186                 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
187                 0);
188         TALLOC_FREE(val);
189
190         if (ret != 0) {
191                 return false;
192         }
193
194         /*
195          * Every 100 writes within a single process, stabilize the cache with
196          * a transaction. This is done to prevent a single transaction to
197          * become huge and chew lots of memory.
198          */
199         writecount += 1;
200         if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
201                 gencache_stabilize();
202                 writecount = 0;
203                 goto done;
204         }
205
206         /*
207          * Every 5 minutes, call gencache_stabilize() to not let grow
208          * gencache_notrans.tdb too large.
209          */
210
211         last_stabilize = 0;
212         databuf = tdb_fetch(cache_notrans, last_stabilize_key());
213         if ((databuf.dptr != NULL)
214             && (databuf.dptr[databuf.dsize-1] == '\0')) {
215                 last_stabilize = atoi((char *)databuf.dptr);
216                 SAFE_FREE(databuf.dptr);
217         }
218         if ((last_stabilize
219              + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
220             < time(NULL)) {
221                 gencache_stabilize();
222         }
223
224 done:
225         return ret == 0;
226 }
227
228 /**
229  * Delete one entry from the cache file.
230  *
231  * @param keystr string that represents a key of this entry
232  *
233  * @retval true upon successful deletion
234  * @retval false in case of failure
235  **/
236
237 bool gencache_del(const char *keystr)
238 {
239         bool exists, was_expired;
240         bool ret = false;
241         DATA_BLOB value;
242
243         if (keystr == NULL) {
244                 return false;
245         }
246
247         if (!gencache_init()) return False;     
248
249         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
250
251         /*
252          * We delete an element by setting its timeout to 0. This way we don't
253          * have to do a transaction on gencache.tdb every time we delete an
254          * element.
255          */
256
257         exists = gencache_get_data_blob(keystr, &value, NULL, &was_expired);
258
259         if (!exists && was_expired) {
260                 /*
261                  * gencache_get_data_blob has implicitly deleted this
262                  * entry, so we have to return success here.
263                  */
264                 return true;
265         }
266
267         if (exists) {
268                 data_blob_free(&value);
269                 ret = gencache_set(keystr, "", 0);
270         }
271         return ret;
272 }
273
274 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
275 {
276         time_t res;
277         char *endptr;
278
279         if (val == NULL) {
280                 return false;
281         }
282
283         res = strtol(val, &endptr, 10);
284
285         if ((endptr == NULL) || (*endptr != '/')) {
286                 DEBUG(2, ("Invalid gencache data format: %s\n", val));
287                 return false;
288         }
289         if (pres != NULL) {
290                 *pres = res;
291         }
292         if (pendptr != NULL) {
293                 *pendptr = endptr;
294         }
295         return true;
296 }
297
298 struct gencache_parse_state {
299         void (*parser)(time_t timeout, DATA_BLOB blob, void *private_data);
300         void *private_data;
301 };
302
303 static int gencache_parse_fn(TDB_DATA key, TDB_DATA data, void *private_data)
304 {
305         struct gencache_parse_state *state;
306         DATA_BLOB blob;
307         time_t t;
308         char *endptr;
309         bool ret;
310
311         if (data.dptr == NULL) {
312                 return -1;
313         }
314         ret = gencache_pull_timeout((char *)data.dptr, &t, &endptr);
315         if (!ret) {
316                 return -1;
317         }
318         state = (struct gencache_parse_state *)private_data;
319         blob = data_blob_const(
320                 endptr+1, data.dsize - PTR_DIFF(endptr+1, data.dptr));
321         state->parser(t, blob, state->private_data);
322         return 0;
323 }
324
325 bool gencache_parse(const char *keystr,
326                     void (*parser)(time_t timeout, DATA_BLOB blob,
327                                    void *private_data),
328                     void *private_data)
329 {
330         struct gencache_parse_state state;
331         TDB_DATA key;
332         int ret;
333
334         if (keystr == NULL) {
335                 return false;
336         }
337         if (tdb_data_cmp(string_term_tdb_data(keystr),
338                          last_stabilize_key()) == 0) {
339                 return false;
340         }
341         if (!gencache_init()) {
342                 return false;
343         }
344
345         key = string_term_tdb_data(keystr);
346         state.parser = parser;
347         state.private_data = private_data;
348
349         ret = tdb_parse_record(cache_notrans, key, gencache_parse_fn, &state);
350         if (ret != -1) {
351                 return true;
352         }
353         ret = tdb_parse_record(cache, key, gencache_parse_fn, &state);
354         return (ret != -1);
355 }
356
357 struct gencache_get_data_blob_state {
358         DATA_BLOB *blob;
359         time_t timeout;
360         bool result;
361 };
362
363 static void gencache_get_data_blob_parser(time_t timeout, DATA_BLOB blob,
364                                           void *private_data)
365 {
366         struct gencache_get_data_blob_state *state =
367                 (struct gencache_get_data_blob_state *)private_data;
368
369         if (timeout == 0) {
370                 state->result = false;
371                 return;
372         }
373         state->timeout = timeout;
374
375         if (state->blob == NULL) {
376                 state->result = true;
377                 return;
378         }
379
380         *state->blob = data_blob(blob.data, blob.length);
381         if (state->blob->data == NULL) {
382                 state->result = false;
383                 return;
384         }
385         state->result = true;
386 }
387
388 /**
389  * Get existing entry from the cache file.
390  *
391  * @param keystr string that represents a key of this entry
392  * @param blob DATA_BLOB that is filled with entry's blob
393  * @param timeout pointer to a time_t that is filled with entry's
394  *        timeout
395  *
396  * @retval true when entry is successfuly fetched
397  * @retval False for failure
398  **/
399
400 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
401                             time_t *timeout, bool *was_expired)
402 {
403         struct gencache_get_data_blob_state state;
404         bool expired = false;
405
406         state.result = false;
407         state.blob = blob;
408
409         if (!gencache_parse(keystr, gencache_get_data_blob_parser, &state)) {
410                 goto fail;
411         }
412         if (!state.result) {
413                 goto fail;
414         }
415         if (state.timeout <= time(NULL)) {
416                 /*
417                  * We're expired, delete the entry. We can't use gencache_del
418                  * here, because that uses gencache_get_data_blob for checking
419                  * the existence of a record. We know the thing exists and
420                  * directly store an empty value with 0 timeout.
421                  */
422                 gencache_set(keystr, "", 0);
423                 expired = true;
424                 goto fail;
425         }
426         if (timeout) {
427                 *timeout = state.timeout;
428         }
429
430         return True;
431
432 fail:
433         if (was_expired != NULL) {
434                 *was_expired = expired;
435         }
436         if (state.result && state.blob) {
437                 data_blob_free(state.blob);
438         }
439         return false;
440
441
442 struct stabilize_state {
443         bool written;
444         bool error;
445 };
446 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
447                         void *priv);
448
449 /**
450  * Stabilize gencache
451  *
452  * Migrate the clear-if-first gencache data to the stable,
453  * transaction-based gencache.tdb
454  */
455
456 bool gencache_stabilize(void)
457 {
458         struct stabilize_state state;
459         int res;
460         char *now;
461
462         if (!gencache_init()) {
463                 return false;
464         }
465
466         res = tdb_transaction_start_nonblock(cache);
467         if (res == -1) {
468
469                 if (tdb_error(cache) == TDB_ERR_NOLOCK) {
470                         /*
471                          * Someone else already does the stabilize,
472                          * this does not have to be done twice
473                          */
474                         return true;
475                 }
476
477                 DEBUG(10, ("Could not start transaction on gencache.tdb: "
478                            "%s\n", tdb_errorstr(cache)));
479                 return false;
480         }
481         res = tdb_transaction_start(cache_notrans);
482         if (res == -1) {
483                 tdb_transaction_cancel(cache);
484                 DEBUG(10, ("Could not start transaction on "
485                            "gencache_notrans.tdb: %s\n",
486                            tdb_errorstr(cache_notrans)));
487                 return false;
488         }
489
490         state.error = false;
491         state.written = false;
492
493         res = tdb_traverse(cache_notrans, stabilize_fn, &state);
494         if ((res == -1) || state.error) {
495                 if ((tdb_transaction_cancel(cache_notrans) == -1)
496                     || (tdb_transaction_cancel(cache) == -1)) {
497                         smb_panic("tdb_transaction_cancel failed\n");
498                 }
499                 return false;
500         }
501
502         if (!state.written) {
503                 if ((tdb_transaction_cancel(cache_notrans) == -1)
504                     || (tdb_transaction_cancel(cache) == -1)) {
505                         smb_panic("tdb_transaction_cancel failed\n");
506                 }
507                 return true;
508         }
509
510         res = tdb_transaction_commit(cache);
511         if (res == -1) {
512                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
513                            "%s\n", tdb_errorstr(cache)));
514                 if (tdb_transaction_cancel(cache_notrans) == -1) {
515                         smb_panic("tdb_transaction_cancel failed\n");
516                 }
517                 return false;
518         }
519
520         res = tdb_transaction_commit(cache_notrans);
521         if (res == -1) {
522                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
523                            "%s\n", tdb_errorstr(cache)));
524                 return false;
525         }
526
527         now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
528         if (now != NULL) {
529                 tdb_store(cache_notrans, last_stabilize_key(),
530                           string_term_tdb_data(now), 0);
531                 TALLOC_FREE(now);
532         }
533
534         return true;
535 }
536
537 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
538                         void *priv)
539 {
540         struct stabilize_state *state = (struct stabilize_state *)priv;
541         int res;
542         time_t timeout;
543
544         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
545                 return 0;
546         }
547
548         if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
549                 DEBUG(10, ("Ignoring invalid entry\n"));
550                 return 0;
551         }
552         if ((timeout < time(NULL)) || (val.dsize == 0)) {
553                 res = tdb_delete(cache, key);
554                 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
555                         res = 0;
556                 } else {
557                         state->written = true;
558                 }
559         } else {
560                 res = tdb_store(cache, key, val, 0);
561                 if (res == 0) {
562                         state->written = true;
563                 }
564         }
565
566         if (res == -1) {
567                 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
568                            tdb_errorstr(cache)));
569                 state->error = true;
570                 return -1;
571         }
572
573         if (tdb_delete(cache_notrans, key) == -1) {
574                 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
575                            "%s\n", tdb_errorstr(cache_notrans)));
576                 state->error = true;
577                 return -1;
578         }
579         return 0;
580 }
581
582 /**
583  * Get existing entry from the cache file.
584  *
585  * @param keystr string that represents a key of this entry
586  * @param valstr buffer that is allocated and filled with the entry value
587  *        buffer's disposing must be done outside
588  * @param timeout pointer to a time_t that is filled with entry's
589  *        timeout
590  *
591  * @retval true when entry is successfuly fetched
592  * @retval False for failure
593  **/
594
595 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
596 {
597         DATA_BLOB blob;
598         bool ret = False;
599
600         ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
601         if (!ret) {
602                 return false;
603         }
604         if ((blob.data == NULL) || (blob.length == 0)) {
605                 SAFE_FREE(blob.data);
606                 return false;
607         }
608         if (blob.data[blob.length-1] != '\0') {
609                 /* Not NULL terminated, can't be a string */
610                 SAFE_FREE(blob.data);
611                 return false;
612         }
613         if (value) {
614                 *value = SMB_STRDUP((char *)blob.data);
615                 data_blob_free(&blob);
616                 if (*value == NULL) {
617                         return false;
618                 }
619                 return true;
620         }
621         data_blob_free(&blob);
622         return true;
623 }
624
625 /**
626  * Set an entry in the cache file. If there's no such
627  * one, then add it.
628  *
629  * @param keystr string that represents a key of this entry
630  * @param value text representation value being cached
631  * @param timeout time when the value is expired
632  *
633  * @retval true when entry is successfuly stored
634  * @retval false on failure
635  **/
636
637 bool gencache_set(const char *keystr, const char *value, time_t timeout)
638 {
639         DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
640         return gencache_set_data_blob(keystr, &blob, timeout);
641 }
642
643 struct gencache_iterate_blobs_state {
644         void (*fn)(const char *key, DATA_BLOB value,
645                    time_t timeout, void *private_data);
646         const char *pattern;
647         void *private_data;
648         bool in_persistent;
649 };
650
651 static int gencache_iterate_blobs_fn(struct tdb_context *tdb, TDB_DATA key,
652                                      TDB_DATA data, void *priv)
653 {
654         struct gencache_iterate_blobs_state *state =
655                 (struct gencache_iterate_blobs_state *)priv;
656         char *keystr;
657         char *free_key = NULL;
658         time_t timeout;
659         char *endptr;
660
661         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
662                 return 0;
663         }
664         if (state->in_persistent && tdb_exists(cache_notrans, key)) {
665                 return 0;
666         }
667
668         if (key.dptr[key.dsize-1] == '\0') {
669                 keystr = (char *)key.dptr;
670         } else {
671                 /* ensure 0-termination */
672                 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
673                 free_key = keystr;
674         }
675
676         if (!gencache_pull_timeout((char *)data.dptr, &timeout, &endptr)) {
677                 goto done;
678         }
679         endptr += 1;
680
681         if (fnmatch(state->pattern, keystr, 0) != 0) {
682                 goto done;
683         }
684
685         DEBUG(10, ("Calling function with arguments (key=%s, timeout=%s)\n",
686                    keystr, ctime(&timeout)));
687
688         state->fn(keystr,
689                   data_blob_const(endptr,
690                                   data.dsize - PTR_DIFF(endptr, data.dptr)),
691                   timeout, state->private_data);
692
693  done:
694         SAFE_FREE(free_key);
695         return 0;
696 }
697
698 void gencache_iterate_blobs(void (*fn)(const char *key, DATA_BLOB value,
699                                        time_t timeout, void *private_data),
700                             void *private_data, const char *pattern)
701 {
702         struct gencache_iterate_blobs_state state;
703
704         if ((fn == NULL) || (pattern == NULL) || !gencache_init()) {
705                 return;
706         }
707
708         DEBUG(5, ("Searching cache keys with pattern %s\n", pattern));
709
710         state.fn = fn;
711         state.pattern = pattern;
712         state.private_data = private_data;
713
714         state.in_persistent = false;
715         tdb_traverse(cache_notrans, gencache_iterate_blobs_fn, &state);
716
717         state.in_persistent = true;
718         tdb_traverse(cache, gencache_iterate_blobs_fn, &state);
719 }
720
721 /**
722  * Iterate through all entries which key matches to specified pattern
723  *
724  * @param fn pointer to the function that will be supplied with each single
725  *        matching cache entry (key, value and timeout) as an arguments
726  * @param data void pointer to an arbitrary data that is passed directly to the fn
727  *        function on each call
728  * @param keystr_pattern pattern the existing entries' keys are matched to
729  *
730  **/
731
732 struct gencache_iterate_state {
733         void (*fn)(const char *key, const char *value, time_t timeout,
734                    void *priv);
735         void *private_data;
736 };
737
738 static void gencache_iterate_fn(const char *key, DATA_BLOB value,
739                                 time_t timeout, void *private_data)
740 {
741         struct gencache_iterate_state *state =
742                 (struct gencache_iterate_state *)private_data;
743         char *valstr;
744         char *free_val = NULL;
745
746         if (value.data[value.length-1] == '\0') {
747                 valstr = (char *)value.data;
748         } else {
749                 /* ensure 0-termination */
750                 valstr = SMB_STRNDUP((char *)value.data, value.length);
751                 free_val = valstr;
752         }
753
754         DEBUG(10, ("Calling function with arguments "
755                    "(key = %s, value = %s, timeout = %s)\n",
756                    key, valstr, ctime(&timeout)));
757
758         state->fn(key, valstr, timeout, state->private_data);
759
760         SAFE_FREE(free_val);
761 }
762
763 void gencache_iterate(void (*fn)(const char *key, const char *value,
764                                  time_t timeout, void *dptr),
765                       void *private_data, const char *pattern)
766 {
767         struct gencache_iterate_state state;
768
769         if (fn == NULL) {
770                 return;
771         }
772         state.fn = fn;
773         state.private_data = private_data;
774         gencache_iterate_blobs(gencache_iterate_fn, &state, pattern);
775 }