s3:gencache: Add a "was_expired" argument to gencache_get_data_blob
[mat/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/"
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 blob DATA_BLOB 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_data_blob(const char *keystr, const DATA_BLOB *blob,
118                             time_t timeout)
119 {
120         int ret;
121         TDB_DATA databuf;
122         char* val;
123         time_t last_stabilize;
124         static int writecount;
125
126         if (tdb_data_cmp(string_term_tdb_data(keystr),
127                          last_stabilize_key()) == 0) {
128                 DEBUG(10, ("Can't store %s as a key\n", keystr));
129                 return false;
130         }
131
132         if ((keystr == NULL) || (blob == NULL)) {
133                 return false;
134         }
135
136         if (!gencache_init()) return False;
137
138         val = talloc_asprintf(talloc_tos(), CACHE_DATA_FMT, (int)timeout);
139         if (val == NULL) {
140                 return False;
141         }
142         val = talloc_realloc(NULL, val, char, talloc_array_length(val)-1);
143         if (val == NULL) {
144                 return false;
145         }
146         val = (char *)talloc_append_blob(NULL, val, *blob);
147         if (val == NULL) {
148                 return false;
149         }
150
151         DEBUG(10, ("Adding cache entry with key = %s and timeout ="
152                    " %s (%d seconds %s)\n", keystr, ctime(&timeout),
153                    (int)(timeout - time(NULL)), 
154                    timeout > time(NULL) ? "ahead" : "in the past"));
155
156         ret = tdb_store_bystring(
157                 cache_notrans, keystr,
158                 make_tdb_data((uint8_t *)val, talloc_array_length(val)),
159                 0);
160         TALLOC_FREE(val);
161
162         if (ret != 0) {
163                 return false;
164         }
165
166         /*
167          * Every 100 writes within a single process, stabilize the cache with
168          * a transaction. This is done to prevent a single transaction to
169          * become huge and chew lots of memory.
170          */
171         writecount += 1;
172         if (writecount > lp_parm_int(-1, "gencache", "stabilize_count", 100)) {
173                 gencache_stabilize();
174                 writecount = 0;
175                 goto done;
176         }
177
178         /*
179          * Every 5 minutes, call gencache_stabilize() to not let grow
180          * gencache_notrans.tdb too large.
181          */
182
183         last_stabilize = 0;
184         databuf = tdb_fetch(cache_notrans, last_stabilize_key());
185         if ((databuf.dptr != NULL)
186             && (databuf.dptr[databuf.dsize-1] == '\0')) {
187                 last_stabilize = atoi((char *)databuf.dptr);
188                 SAFE_FREE(databuf.dptr);
189         }
190         if ((last_stabilize
191              + lp_parm_int(-1, "gencache", "stabilize_interval", 300))
192             < time(NULL)) {
193                 gencache_stabilize();
194         }
195
196 done:
197         return ret == 0;
198 }
199
200 /**
201  * Delete one entry from the cache file.
202  *
203  * @param keystr string that represents a key of this entry
204  *
205  * @retval true upon successful deletion
206  * @retval false in case of failure
207  **/
208
209 bool gencache_del(const char *keystr)
210 {
211         bool exists;
212         bool ret = false;
213         char *value;
214
215         if (keystr == NULL) {
216                 return false;
217         }
218
219         if (!gencache_init()) return False;     
220
221         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
222
223         if (tdb_lock_bystring(cache_notrans, keystr) == -1) {
224                 DEBUG(5, ("Could not lock key for %s\n", keystr));
225                 return false;
226         }
227
228         /*
229          * We delete an element by setting its timeout to 0. This way we don't
230          * have to do a transaction on gencache.tdb every time we delete an
231          * element.
232          */
233
234         exists = gencache_get(keystr, &value, NULL);
235         if (exists) {
236                 SAFE_FREE(value);
237                 ret = gencache_set(keystr, "", 0);
238         }
239         tdb_unlock_bystring(cache_notrans, keystr);
240         return ret;
241 }
242
243 static bool gencache_pull_timeout(char *val, time_t *pres, char **pendptr)
244 {
245         time_t res;
246         char *endptr;
247
248         res = strtol(val, &endptr, 10);
249
250         if ((endptr == NULL) || (*endptr != '/')) {
251                 DEBUG(2, ("Invalid gencache data format: %s\n", val));
252                 return false;
253         }
254         if (pres != NULL) {
255                 *pres = res;
256         }
257         if (pendptr != NULL) {
258                 *pendptr = endptr;
259         }
260         return true;
261 }
262
263 /**
264  * Get existing entry from the cache file.
265  *
266  * @param keystr string that represents a key of this entry
267  * @param blob DATA_BLOB that is filled with entry's blob
268  * @param timeout pointer to a time_t that is filled with entry's
269  *        timeout
270  *
271  * @retval true when entry is successfuly fetched
272  * @retval False for failure
273  **/
274
275 bool gencache_get_data_blob(const char *keystr, DATA_BLOB *blob,
276                             time_t *timeout, bool *was_expired)
277 {
278         TDB_DATA databuf;
279         time_t t;
280         char *endptr;
281         bool expired = false;
282
283         if (keystr == NULL) {
284                 goto fail;
285         }
286
287         if (tdb_data_cmp(string_term_tdb_data(keystr),
288                          last_stabilize_key()) == 0) {
289                 DEBUG(10, ("Can't get %s as a key\n", keystr));
290                 goto fail;
291         }
292
293         if (!gencache_init()) {
294                 goto fail;
295         }
296
297         databuf = tdb_fetch_bystring(cache_notrans, keystr);
298
299         if (databuf.dptr == NULL) {
300                 databuf = tdb_fetch_bystring(cache, keystr);
301         }
302
303         if (databuf.dptr == NULL) {
304                 DEBUG(10, ("Cache entry with key = %s couldn't be found \n",
305                            keystr));
306                 goto fail;
307         }
308
309         if (!gencache_pull_timeout((char *)databuf.dptr, &t, &endptr)) {
310                 SAFE_FREE(databuf.dptr);
311                 goto fail;
312         }
313
314         DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
315                    "timeout = %s", t > time(NULL) ? "valid" :
316                    "expired", keystr, endptr+1, ctime(&t)));
317
318         if (t == 0) {
319                 /* Deleted */
320                 SAFE_FREE(databuf.dptr);
321                 goto fail;
322         }
323
324         if (t <= time(NULL)) {
325
326                 /*
327                  * We're expired, delete the entry. We can't use gencache_del
328                  * here, because that uses gencache_get_data_blob for checking
329                  * the existence of a record. We know the thing exists and
330                  * directly store an empty value with 0 timeout.
331                  */
332                 gencache_set(keystr, "", 0);
333
334                 SAFE_FREE(databuf.dptr);
335
336                 expired = true;
337                 goto fail;
338         }
339
340         if (blob != NULL) {
341                 *blob = data_blob(
342                         endptr+1,
343                         databuf.dsize - PTR_DIFF(endptr+1, databuf.dptr));
344                 if (blob->data == NULL) {
345                         SAFE_FREE(databuf.dptr);
346                         DEBUG(0, ("memdup failed\n"));
347                         goto fail;
348                 }
349         }
350
351         SAFE_FREE(databuf.dptr);
352
353         if (timeout) {
354                 *timeout = t;
355         }
356
357         return True;
358
359 fail:
360         if (was_expired != NULL) {
361                 *was_expired = expired;
362         }
363         return false;
364
365
366 struct stabilize_state {
367         bool written;
368         bool error;
369 };
370 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
371                         void *priv);
372
373 /**
374  * Stabilize gencache
375  *
376  * Migrate the clear-if-first gencache data to the stable,
377  * transaction-based gencache.tdb
378  */
379
380 bool gencache_stabilize(void)
381 {
382         struct stabilize_state state;
383         int res;
384         char *now;
385
386         if (!gencache_init()) {
387                 return false;
388         }
389
390         res = tdb_transaction_start(cache);
391         if (res == -1) {
392                 DEBUG(10, ("Could not start transaction on gencache.tdb: "
393                            "%s\n", tdb_errorstr(cache)));
394                 return false;
395         }
396         res = tdb_transaction_start(cache_notrans);
397         if (res == -1) {
398                 tdb_transaction_cancel(cache);
399                 DEBUG(10, ("Could not start transaction on "
400                            "gencache_notrans.tdb: %s\n",
401                            tdb_errorstr(cache_notrans)));
402                 return false;
403         }
404
405         state.error = false;
406         state.written = false;
407
408         res = tdb_traverse(cache_notrans, stabilize_fn, &state);
409         if ((res == -1) || state.error) {
410                 if ((tdb_transaction_cancel(cache_notrans) == -1)
411                     || (tdb_transaction_cancel(cache) == -1)) {
412                         smb_panic("tdb_transaction_cancel failed\n");
413                 }
414                 return false;
415         }
416
417         if (!state.written) {
418                 if ((tdb_transaction_cancel(cache_notrans) == -1)
419                     || (tdb_transaction_cancel(cache) == -1)) {
420                         smb_panic("tdb_transaction_cancel failed\n");
421                 }
422                 return true;
423         }
424
425         res = tdb_transaction_commit(cache);
426         if (res == -1) {
427                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
428                            "%s\n", tdb_errorstr(cache)));
429                 if (tdb_transaction_cancel(cache_notrans) == -1) {
430                         smb_panic("tdb_transaction_cancel failed\n");
431                 }
432                 return false;
433         }
434
435         res = tdb_transaction_commit(cache_notrans);
436         if (res == -1) {
437                 DEBUG(10, ("tdb_transaction_commit on gencache.tdb failed: "
438                            "%s\n", tdb_errorstr(cache)));
439                 return false;
440         }
441
442         now = talloc_asprintf(talloc_tos(), "%d", (int)time(NULL));
443         if (now != NULL) {
444                 tdb_store(cache_notrans, last_stabilize_key(),
445                           string_term_tdb_data(now), 0);
446                 TALLOC_FREE(now);
447         }
448
449         return true;
450 }
451
452 static int stabilize_fn(struct tdb_context *tdb, TDB_DATA key, TDB_DATA val,
453                         void *priv)
454 {
455         struct stabilize_state *state = (struct stabilize_state *)priv;
456         int res;
457         time_t timeout;
458
459         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
460                 return 0;
461         }
462
463         if (!gencache_pull_timeout((char *)val.dptr, &timeout, NULL)) {
464                 DEBUG(10, ("Ignoring invalid entry\n"));
465                 return 0;
466         }
467         if ((timeout < time(NULL)) || (val.dsize == 0)) {
468                 res = tdb_delete(cache, key);
469                 if ((res == -1) && (tdb_error(cache) == TDB_ERR_NOEXIST)) {
470                         res = 0;
471                 } else {
472                         state->written = true;
473                 }
474         } else {
475                 res = tdb_store(cache, key, val, 0);
476                 if (res == 0) {
477                         state->written = true;
478                 }
479         }
480
481         if (res == -1) {
482                 DEBUG(10, ("Transfer to gencache.tdb failed: %s\n",
483                            tdb_errorstr(cache)));
484                 state->error = true;
485                 return -1;
486         }
487
488         if (tdb_delete(cache_notrans, key) == -1) {
489                 DEBUG(10, ("tdb_delete from gencache_notrans.tdb failed: "
490                            "%s\n", tdb_errorstr(cache_notrans)));
491                 state->error = true;
492                 return -1;
493         }
494         return 0;
495 }
496
497 /**
498  * Get existing entry from the cache file.
499  *
500  * @param keystr string that represents a key of this entry
501  * @param valstr buffer that is allocated and filled with the entry value
502  *        buffer's disposing must be done outside
503  * @param timeout pointer to a time_t that is filled with entry's
504  *        timeout
505  *
506  * @retval true when entry is successfuly fetched
507  * @retval False for failure
508  **/
509
510 bool gencache_get(const char *keystr, char **value, time_t *ptimeout)
511 {
512         DATA_BLOB blob;
513         bool ret = False;
514
515         ret = gencache_get_data_blob(keystr, &blob, ptimeout, NULL);
516         if (!ret) {
517                 return false;
518         }
519         if ((blob.data == NULL) || (blob.length == 0)) {
520                 SAFE_FREE(blob.data);
521                 return false;
522         }
523         if (blob.data[blob.length-1] != '\0') {
524                 /* Not NULL terminated, can't be a string */
525                 SAFE_FREE(blob.data);
526                 return false;
527         }
528         *value = SMB_STRDUP((char *)blob.data);
529         data_blob_free(&blob);
530         if (*value == NULL) {
531                 return false;
532         }
533         return true;
534 }
535
536 /**
537  * Set an entry in the cache file. If there's no such
538  * one, then add it.
539  *
540  * @param keystr string that represents a key of this entry
541  * @param value text representation value being cached
542  * @param timeout time when the value is expired
543  *
544  * @retval true when entry is successfuly stored
545  * @retval false on failure
546  **/
547
548 bool gencache_set(const char *keystr, const char *value, time_t timeout)
549 {
550         DATA_BLOB blob = data_blob_const(value, strlen(value)+1);
551         return gencache_set_data_blob(keystr, &blob, timeout);
552 }
553
554 /**
555  * Iterate through all entries which key matches to specified pattern
556  *
557  * @param fn pointer to the function that will be supplied with each single
558  *        matching cache entry (key, value and timeout) as an arguments
559  * @param data void pointer to an arbitrary data that is passed directly to the fn
560  *        function on each call
561  * @param keystr_pattern pattern the existing entries' keys are matched to
562  *
563  **/
564
565 struct gencache_iterate_state {
566         void (*fn)(const char *key, const char *value, time_t timeout,
567                    void *priv);
568         const char *pattern;
569         void *priv;
570         bool in_persistent;
571 };
572
573 static int gencache_iterate_fn(struct tdb_context *tdb, TDB_DATA key,
574                                TDB_DATA value, void *priv)
575 {
576         struct gencache_iterate_state *state =
577                 (struct gencache_iterate_state *)priv;
578         char *keystr;
579         char *free_key = NULL;
580         char *valstr;
581         char *free_val = NULL;
582         unsigned long u;
583         time_t timeout;
584         char *timeout_endp;
585
586         if (tdb_data_cmp(key, last_stabilize_key()) == 0) {
587                 return 0;
588         }
589
590         if (state->in_persistent && tdb_exists(cache_notrans, key)) {
591                 return 0;
592         }
593
594         if (key.dptr[key.dsize-1] == '\0') {
595                 keystr = (char *)key.dptr;
596         } else {
597                 /* ensure 0-termination */
598                 keystr = SMB_STRNDUP((char *)key.dptr, key.dsize);
599                 free_key = keystr;
600         }
601
602         if ((value.dptr == NULL) || (value.dsize <= TIMEOUT_LEN)) {
603                 goto done;
604         }
605
606         if (fnmatch(state->pattern, keystr, 0) != 0) {
607                 goto done;
608         }
609
610         if (value.dptr[value.dsize-1] == '\0') {
611                 valstr = (char *)value.dptr;
612         } else {
613                 /* ensure 0-termination */
614                 valstr = SMB_STRNDUP((char *)value.dptr, value.dsize);
615                 free_val = valstr;
616         }
617
618         u = strtoul(valstr, &timeout_endp, 10);
619
620         if ((*timeout_endp != '/') || ((timeout_endp-valstr) != TIMEOUT_LEN)) {
621                 goto done;
622         }
623
624         timeout = u;
625         timeout_endp += 1;
626
627         DEBUG(10, ("Calling function with arguments "
628                    "(key = %s, value = %s, timeout = %s)\n",
629                    keystr, timeout_endp, ctime(&timeout)));
630         state->fn(keystr, timeout_endp, timeout, state->priv);
631
632  done:
633         SAFE_FREE(free_key);
634         SAFE_FREE(free_val);
635         return 0;
636 }
637
638 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
639                       void* data, const char* keystr_pattern)
640 {
641         struct gencache_iterate_state state;
642
643         if ((fn == NULL) || (keystr_pattern == NULL)) {
644                 return;
645         }
646
647         if (!gencache_init()) return;
648
649         DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
650
651         state.fn = fn;
652         state.pattern = keystr_pattern;
653         state.priv = data;
654
655         state.in_persistent = false;
656         tdb_traverse(cache_notrans, gencache_iterate_fn, &state);
657
658         state.in_persistent = true;
659         tdb_traverse(cache, gencache_iterate_fn, &state);
660 }