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