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