1ee720cdfdaa8f7161da4bb9aa4baff47ccbf35a
[kamenim/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 TDB_CONTEXT *cache;
35 static BOOL cache_readonly;
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 BOOL gencache_init(void)
54 {
55         char* cache_fname = NULL;
56         
57         /* skip file open if it's already opened */
58         if (cache) return True;
59
60         cache_fname = lock_path("gencache.tdb");
61
62         DEBUG(5, ("Opening cache file at %s\n", cache_fname));
63
64         cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT,
65                              O_RDWR|O_CREAT, 0644);
66
67         if (!cache && (errno == EACCES)) {
68                 cache = tdb_open_log(cache_fname, 0, TDB_DEFAULT, O_RDONLY, 0644);
69                 if (cache) {
70                         cache_readonly = True;
71                         DEBUG(5, ("gencache_init: Opening cache file %s read-only.\n", cache_fname));
72                 }
73         }
74
75         if (!cache) {
76                 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
77                 return False;
78         }
79         return True;
80 }
81
82
83 /**
84  * Cache shutdown function. Closes opened cache tdb file.
85  *
86  * @return true on successful closing the cache or
87  *         false on failure during cache shutdown
88  **/
89  
90 BOOL gencache_shutdown(void)
91 {
92         int ret;
93         /* tdb_close routine returns -1 on error */
94         if (!cache) return False;
95         DEBUG(5, ("Closing cache file\n"));
96         ret = tdb_close(cache);
97         cache = NULL;
98         cache_readonly = False;
99         return ret != -1;
100 }
101
102
103 /**
104  * Set an entry in the cache file. If there's no such
105  * one, then add it.
106  *
107  * @param keystr string that represents a key of this entry
108  * @param value text representation value being cached
109  * @param timeout time when the value is expired
110  *
111  * @retval true when entry is successfuly stored
112  * @retval false on failure
113  **/
114  
115 BOOL gencache_set(const char *keystr, const char *value, time_t timeout)
116 {
117         int ret;
118         TDB_DATA databuf;
119         char* valstr = NULL;
120         
121         /* fail completely if get null pointers passed */
122         SMB_ASSERT(keystr && value);
123
124         if (!gencache_init()) return False;
125         
126         if (cache_readonly) {
127                 return False;
128         }
129
130         asprintf(&valstr, CACHE_DATA_FMT, (int)timeout, value);
131         if (!valstr)
132                 return False;
133
134         databuf = string_term_tdb_data(valstr);
135         DEBUG(10, ("Adding cache entry with key = %s; value = %s and timeout ="
136                    " %s (%d seconds %s)\n", keystr, value,ctime(&timeout),
137                    (int)(timeout - time(NULL)), 
138                    timeout > time(NULL) ? "ahead" : "in the past"));
139
140         ret = tdb_store_bystring(cache, keystr, databuf, 0);
141         SAFE_FREE(valstr);
142         
143         return ret == 0;
144 }
145
146 /**
147  * Delete one entry from the cache file.
148  *
149  * @param keystr string that represents a key of this entry
150  *
151  * @retval true upon successful deletion
152  * @retval false in case of failure
153  **/
154
155 BOOL gencache_del(const char *keystr)
156 {
157         int ret;
158         
159         /* fail completely if get null pointers passed */
160         SMB_ASSERT(keystr);
161
162         if (!gencache_init()) return False;     
163         
164         if (cache_readonly) {
165                 return False;
166         }
167
168         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
169         ret = tdb_delete_bystring(cache, keystr);
170         
171         return ret == 0;
172 }
173
174
175 /**
176  * Get existing entry from the cache file.
177  *
178  * @param keystr string that represents a key of this entry
179  * @param valstr buffer that is allocated and filled with the entry value
180  *        buffer's disposing must be done outside
181  * @param timeout pointer to a time_t that is filled with entry's
182  *        timeout
183  *
184  * @retval true when entry is successfuly fetched
185  * @retval False for failure
186  **/
187
188 BOOL gencache_get(const char *keystr, char **valstr, time_t *timeout)
189 {
190         TDB_DATA databuf;
191         time_t t;
192         char *endptr;
193
194         /* fail completely if get null pointers passed */
195         SMB_ASSERT(keystr);
196
197         if (!gencache_init()) {
198                 return False;
199         }
200
201         databuf = tdb_fetch_bystring(cache, keystr);
202
203         if (databuf.dptr == NULL) {
204                 DEBUG(10, ("Cache entry with key = %s couldn't be found\n",
205                            keystr));
206                 return False;
207         }
208
209         t = strtol((const char *)databuf.dptr, &endptr, 10);
210
211         if ((endptr == NULL) || (*endptr != '/')) {
212                 DEBUG(2, ("Invalid gencache data format: %s\n", databuf.dptr));
213                 SAFE_FREE(databuf.dptr);
214                 return False;
215         }
216
217         DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
218                    "timeout = %s", t > time(NULL) ? "valid" :
219                    "expired", keystr, endptr+1, ctime(&t)));
220
221         if (t <= time(NULL)) {
222
223                 /* We're expired, delete the entry */
224                 tdb_delete_bystring(cache, keystr);
225
226                 SAFE_FREE(databuf.dptr);
227                 return False;
228         }
229
230         if (valstr) {
231                 *valstr = SMB_STRDUP(endptr+1);
232                 if (*valstr == NULL) {
233                         SAFE_FREE(databuf.dptr);
234                         DEBUG(0, ("strdup failed\n"));
235                         return False;
236                 }
237         }
238         
239         SAFE_FREE(databuf.dptr);
240
241         if (timeout) {
242                 *timeout = t;
243         }
244
245         return True;
246
247
248 /**
249  * Get existing entry from the cache file.
250  *
251  * @param keystr string that represents a key of this entry
252  * @param blob DATA_BLOB that is filled with entry's blob
253  * @param expired pointer to a BOOL that indicates whether the entry is expired
254  *
255  * @retval true when entry is successfuly fetched
256  * @retval False for failure
257  **/
258
259 BOOL gencache_get_data_blob(const char *keystr, DATA_BLOB *blob, BOOL *expired)
260 {
261         TDB_DATA databuf;
262         time_t t;
263         char *blob_type;
264         unsigned char *buf = NULL;
265         BOOL ret = False;
266         fstring valstr;
267         int buflen = 0, len = 0, blob_len = 0;
268         unsigned char *blob_buf = NULL;
269
270         /* fail completely if get null pointers passed */
271         SMB_ASSERT(keystr);
272
273         if (!gencache_init()) {
274                 return False;
275         }
276
277         databuf = tdb_fetch_bystring(cache, keystr);
278         if (!databuf.dptr) {
279                 DEBUG(10,("Cache entry with key = %s couldn't be found\n",
280                           keystr));
281                 return False;
282         }
283
284         buf = (unsigned char *)databuf.dptr;
285         buflen = databuf.dsize;
286
287         len += tdb_unpack(buf+len, buflen-len, "fB",
288                           &valstr,
289                           &blob_len, &blob_buf);
290         if (len == -1) {
291                 goto out;
292         }
293
294         t = strtol(valstr, &blob_type, 10);
295
296         if (strcmp(blob_type+1, BLOB_TYPE) != 0) {
297                 goto out;
298         }
299
300         DEBUG(10,("Returning %s cache entry: key = %s, "
301                   "timeout = %s", t > time(NULL) ? "valid" :
302                   "expired", keystr, ctime(&t)));
303
304         if (t <= time(NULL)) {
305                 /* We're expired */
306                 if (expired) {
307                         *expired = True;
308                 }
309         }
310
311         if (blob) {
312                 *blob = data_blob(blob_buf, blob_len);
313                 if (!blob->data) {
314                         goto out;
315                 }
316         }
317
318         ret = True;
319  out:
320         SAFE_FREE(blob_buf);
321         SAFE_FREE(databuf.dptr);
322
323         return ret;
324 }
325
326 /**
327  * Set an entry in the cache file. If there's no such
328  * one, then add it.
329  *
330  * @param keystr string that represents a key of this entry
331  * @param blob DATA_BLOB value being cached
332  * @param timeout time when the value is expired
333  *
334  * @retval true when entry is successfuly stored
335  * @retval false on failure
336  **/
337
338 BOOL gencache_set_data_blob(const char *keystr, DATA_BLOB *blob, time_t timeout)
339 {
340         BOOL ret = False;
341         int tdb_ret;
342         TDB_DATA databuf;
343         char *valstr = NULL;
344         unsigned char *buf = NULL;
345         int len = 0, buflen = 0;
346
347         /* fail completely if get null pointers passed */
348         SMB_ASSERT(keystr && blob);
349
350         if (!gencache_init()) {
351                 return False;
352         }
353
354         if (cache_readonly) {
355                 return False;
356         }
357
358         asprintf(&valstr, "%12u/%s", (int)timeout, BLOB_TYPE);
359         if (!valstr) {
360                 return False;
361         }
362
363  again:
364         len = 0;
365
366         len += tdb_pack(buf+len, buflen-len, "fB",
367                         valstr,
368                         blob->length, blob->data);
369
370         if (len == -1) {
371                 goto out;
372         }
373
374         if (buflen < len) {
375                 SAFE_FREE(buf);
376                 buf = SMB_MALLOC_ARRAY(unsigned char, len);
377                 if (!buf) {
378                         goto out;
379                 }
380                 buflen = len;
381                 goto again;
382         }
383
384         databuf = make_tdb_data(buf, len);
385
386         DEBUG(10,("Adding cache entry with key = %s; "
387                   "blob size = %d and timeout = %s"
388                   "(%d seconds %s)\n", keystr, (int)databuf.dsize,
389                   ctime(&timeout), (int)(timeout - time(NULL)),
390                   timeout > time(NULL) ? "ahead" : "in the past"));
391
392         tdb_ret = tdb_store_bystring(cache, keystr, databuf, 0);
393         if (tdb_ret == 0) {
394                 ret = True;
395         }
396
397  out:
398         SAFE_FREE(valstr);
399         SAFE_FREE(buf);
400
401         return ret;
402 }
403
404 /**
405  * Iterate through all entries which key matches to specified pattern
406  *
407  * @param fn pointer to the function that will be supplied with each single
408  *        matching cache entry (key, value and timeout) as an arguments
409  * @param data void pointer to an arbitrary data that is passed directly to the fn
410  *        function on each call
411  * @param keystr_pattern pattern the existing entries' keys are matched to
412  *
413  **/
414
415 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
416                       void* data, const char* keystr_pattern)
417 {
418         TDB_LIST_NODE *node, *first_node;
419         TDB_DATA databuf;
420         char *keystr = NULL, *valstr = NULL, *entry = NULL;
421         time_t timeout = 0;
422         int status;
423         unsigned u;
424
425         /* fail completely if get null pointers passed */
426         SMB_ASSERT(fn && keystr_pattern);
427
428         if (!gencache_init()) return;
429
430         DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
431         node = tdb_search_keys(cache, keystr_pattern);
432         first_node = node;
433         
434         while (node) {
435                 char *fmt;
436
437                 /* ensure null termination of the key string */
438                 keystr = SMB_STRNDUP((const char *)node->node_key.dptr, node->node_key.dsize);
439                 if (!keystr) {
440                         break;
441                 }
442                 
443                 /* 
444                  * We don't use gencache_get function, because we need to iterate through
445                  * all of the entries. Validity verification is up to fn routine.
446                  */
447                 databuf = tdb_fetch(cache, node->node_key);
448                 if (!databuf.dptr || databuf.dsize <= TIMEOUT_LEN) {
449                         SAFE_FREE(databuf.dptr);
450                         SAFE_FREE(keystr);
451                         node = node->next;
452                         continue;
453                 }
454                 entry = SMB_STRNDUP((const char *)databuf.dptr, databuf.dsize);
455                 if (!entry) {
456                         SAFE_FREE(databuf.dptr);
457                         SAFE_FREE(keystr);
458                         break;
459                 }
460
461                 SAFE_FREE(databuf.dptr);
462
463                 valstr = (char *)SMB_MALLOC(databuf.dsize + 1 - TIMEOUT_LEN);
464                 if (!valstr) {
465                         SAFE_FREE(entry);
466                         SAFE_FREE(keystr);
467                         break;
468                 }
469
470                 asprintf(&fmt, READ_CACHE_DATA_FMT_TEMPLATE, (unsigned int)databuf.dsize - TIMEOUT_LEN);
471                 if (!fmt) {
472                         SAFE_FREE(valstr);
473                         SAFE_FREE(entry);
474                         SAFE_FREE(keystr);
475                         break;
476                 }
477                 status = sscanf(entry, fmt, &u, valstr);
478                 SAFE_FREE(fmt);
479
480                 if ( status != 2 ) {
481                         DEBUG(0,("gencache_iterate: invalid return from sscanf %d\n",status));
482                 }
483                 timeout = u;
484                 
485                 DEBUG(10, ("Calling function with arguments (key = %s, value = %s, timeout = %s)\n",
486                            keystr, valstr, ctime(&timeout)));
487                 fn(keystr, valstr, timeout, data);
488                 
489                 SAFE_FREE(valstr);
490                 SAFE_FREE(entry);
491                 SAFE_FREE(keystr);
492                 node = node->next;
493         }
494         
495         tdb_search_list_free(first_node);
496 }
497
498 /********************************************************************
499  lock a key
500 ********************************************************************/
501
502 int gencache_lock_entry( const char *key )
503 {
504         if (!gencache_init())
505                 return -1;
506         
507         return tdb_lock_bystring(cache, key);
508 }
509
510 /********************************************************************
511  unlock a key
512 ********************************************************************/
513
514 void gencache_unlock_entry( const char *key )
515 {
516         if (!gencache_init())
517                 return;
518         
519         tdb_unlock_bystring(cache, key);
520         return;
521 }