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