r23792: convert Samba4 to GPLv3
[amitay/samba.git] / source4 / lib / gencache / 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 #include "system/time.h"
25 #include "system/filesys.h"
26 #include "db_wrap.h"
27 #include "lib/gencache/gencache.h"
28
29 #define TIMEOUT_LEN 12
30 #define CACHE_DATA_FMT  "%12u/%s"
31
32 static struct tdb_wrap *cache;
33
34 /**
35  * @file gencache.c
36  * @brief Generic, persistent and shared between processes cache mechanism
37  *        for use by various parts of the Samba code
38  *
39  **/
40
41
42 /**
43  * Cache initialisation function. Opens cache tdb file or creates
44  * it if does not exist.
45  *
46  * @return true on successful initialisation of the cache or
47  *         false on failure
48  **/
49
50 BOOL gencache_init(void)
51 {
52         char* cache_fname = NULL;
53         
54         /* skip file open if it's already opened */
55         if (cache) return True;
56
57         asprintf(&cache_fname, "%s/%s", lp_lockdir(), "gencache.tdb");
58         if (cache_fname)
59                 DEBUG(5, ("Opening cache file at %s\n", cache_fname));
60         else {
61                 DEBUG(0, ("Filename allocation failed.\n"));
62                 return False;
63         }
64
65         cache = tdb_wrap_open(NULL, cache_fname, 0, TDB_DEFAULT,
66                               O_RDWR|O_CREAT, 0644);
67
68         SAFE_FREE(cache_fname);
69         if (!cache) {
70                 DEBUG(5, ("Attempt to open gencache.tdb has failed.\n"));
71                 return False;
72         }
73         return True;
74 }
75
76
77 /**
78  * Cache shutdown function. Closes opened cache tdb file.
79  *
80  * @return true on successful closing the cache or
81  *         false on failure during cache shutdown
82  **/
83  
84 BOOL gencache_shutdown(void)
85 {
86         if (!cache) return False;
87         DEBUG(5, ("Closing cache file\n"));
88         talloc_free(cache);
89         return True;
90 }
91
92
93 /**
94  * Set an entry in the cache file. If there's no such
95  * one, then add it.
96  *
97  * @param keystr string that represents a key of this entry
98  * @param value text representation value being cached
99  * @param timeout time when the value is expired
100  *
101  * @retval true when entry is successfuly stored
102  * @retval false on failure
103  **/
104  
105 BOOL gencache_set(const char *keystr, const char *value, time_t timeout)
106 {
107         int ret;
108         TDB_DATA keybuf, databuf;
109         char* valstr = NULL;
110         
111         /* fail completely if get null pointers passed */
112         SMB_ASSERT(keystr && value);
113
114         if (!gencache_init()) return False;
115         
116         asprintf(&valstr, CACHE_DATA_FMT, (int)timeout, value);
117         if (!valstr)
118                 return False;
119
120         keybuf.dptr = (uint8_t *)strdup(keystr);
121         keybuf.dsize = strlen(keystr)+1;
122         databuf.dptr = (uint8_t *)strdup(valstr);
123         databuf.dsize = strlen(valstr)+1;
124         DEBUG(10, ("Adding cache entry with key = %s; value = %s and timeout \
125                    = %s (%d seconds %s)\n", keybuf.dptr, value, ctime(&timeout),
126                    (int)(timeout - time(NULL)), timeout > time(NULL) ? "ahead" : "in the past"));
127                 
128         ret = tdb_store(cache->tdb, keybuf, databuf, 0);
129         SAFE_FREE(valstr);
130         SAFE_FREE(keybuf.dptr);
131         SAFE_FREE(databuf.dptr);
132         
133         return ret == 0;
134 }
135
136
137 /**
138  * Set existing entry to the cache file.
139  *
140  * @param keystr string that represents a key of this entry
141  * @param valstr text representation value being cached
142  * @param timeout time when the value is expired
143  *
144  * @retval true when entry is successfuly set
145  * @retval false on failure
146  **/
147
148 BOOL gencache_set_only(const char *keystr, const char *valstr, time_t timeout)
149 {
150         int ret = -1;
151         TDB_DATA keybuf, databuf;
152         char *old_valstr, *datastr;
153         time_t old_timeout;
154         
155         /* fail completely if get null pointers passed */
156         SMB_ASSERT(keystr && valstr);
157
158         if (!gencache_init()) return False;
159                         
160         /* 
161          * Check whether entry exists in the cache
162          * Don't verify gencache_get exit code, since the entry may be expired
163          */     
164         gencache_get(keystr, &old_valstr, &old_timeout);
165         
166         if (!(old_valstr && old_timeout)) return False;
167                 
168         DEBUG(10, ("Setting cache entry with key = %s; old value = %s and old timeout \
169                    = %s\n", keystr, old_valstr, ctime(&old_timeout)));
170
171         asprintf(&datastr, CACHE_DATA_FMT, (int)timeout, valstr);
172         keybuf.dptr = (uint8_t *)strdup(keystr);
173         keybuf.dsize = strlen(keystr)+1;
174         databuf.dptr = (uint8_t *)strdup(datastr);
175         databuf.dsize = strlen(datastr)+1;
176         DEBUGADD(10, ("New value = %s, new timeout = %s (%d seconds %s)", valstr,
177                       ctime(&timeout), (int)(timeout - time(NULL)),
178                       timeout > time(NULL) ? "ahead" : "in the past"));
179
180                 
181         ret = tdb_store(cache->tdb, keybuf, databuf, TDB_REPLACE);
182
183         SAFE_FREE(datastr);
184         SAFE_FREE(old_valstr);
185         SAFE_FREE(keybuf.dptr);
186         SAFE_FREE(databuf.dptr);
187         
188         return ret == 0;
189 }
190  
191
192 /**
193  * Delete one entry from the cache file.
194  *
195  * @param keystr string that represents a key of this entry
196  *
197  * @retval true upon successful deletion
198  * @retval false in case of failure
199  **/
200
201 BOOL gencache_del(const char *keystr)
202 {
203         int ret;
204         TDB_DATA keybuf;
205         
206         /* fail completely if get null pointers passed */
207         SMB_ASSERT(keystr);
208
209         if (!gencache_init()) return False;     
210         
211         keybuf.dptr = (uint8_t *)strdup(keystr);
212         keybuf.dsize = strlen(keystr)+1;
213         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
214         ret = tdb_delete(cache->tdb, keybuf);
215         
216         SAFE_FREE(keybuf.dptr);
217         return ret == 0;
218 }
219
220
221 /**
222  * Get existing entry from the cache file.
223  *
224  * @param keystr string that represents a key of this entry
225  * @param valstr buffer that is allocated and filled with the entry value
226  *        buffer's disposing must be done outside
227  * @param timeout pointer to a time_t that is filled with entry's
228  *        timeout
229  *
230  * @retval true when entry is successfuly fetched
231  * @retval False for failure
232  **/
233
234 BOOL gencache_get(const char *keystr, char **valstr, time_t *timeout)
235 {
236         TDB_DATA keybuf, databuf;
237
238         /* fail completely if get null pointers passed */
239         SMB_ASSERT(keystr);
240
241         if (!gencache_init())
242                 return False;
243         
244         keybuf.dptr = (uint8_t *)strdup(keystr);
245         keybuf.dsize = strlen(keystr)+1;
246         databuf = tdb_fetch(cache->tdb, keybuf);
247         SAFE_FREE(keybuf.dptr);
248         
249         if (databuf.dptr && databuf.dsize > TIMEOUT_LEN) {
250                 char* entry_buf = strndup((char *)databuf.dptr, databuf.dsize);
251                 char *v;
252                 time_t t;
253                 unsigned i;
254
255                 v = malloc_array_p(char, databuf.dsize - TIMEOUT_LEN);
256                                 
257                 SAFE_FREE(databuf.dptr);
258                 sscanf(entry_buf, CACHE_DATA_FMT, (int*)&i, v);
259                 SAFE_FREE(entry_buf);
260                 t = i;
261
262                 DEBUG(10, ("Returning %s cache entry: key = %s, value = %s, "
263                            "timeout = %s\n", t > time(NULL) ? "valid" :
264                            "expired", keystr, v, ctime(&t)));
265
266                 if (valstr)
267                         *valstr = v;
268                 else
269                         SAFE_FREE(v);
270
271                 if (timeout)
272                         *timeout = t;
273
274                 return t > time(NULL);
275
276         } else {
277                 SAFE_FREE(databuf.dptr);
278
279                 if (valstr)
280                         *valstr = NULL;
281
282                 if (timeout)
283                         timeout = NULL;
284
285                 DEBUG(10, ("Cache entry with key = %s couldn't be found\n", 
286                            keystr));
287
288                 return False;
289         }
290 }
291
292
293 /**
294  * Iterate through all entries which key matches to specified pattern
295  *
296  * @param fn pointer to the function that will be supplied with each single
297  *        matching cache entry (key, value and timeout) as an arguments
298  * @param data void pointer to an arbitrary data that is passed directly to the fn
299  *        function on each call
300  * @param keystr_pattern pattern the existing entries' keys are matched to
301  *
302  **/
303
304 void gencache_iterate(void (*fn)(const char* key, const char *value, time_t timeout, void* dptr),
305                       void* data, const char* keystr_pattern)
306 {
307         TDB_LIST_NODE *node, *first_node;
308         TDB_DATA databuf;
309         char *keystr = NULL, *valstr = NULL, *entry = NULL;
310         time_t timeout = 0;
311         unsigned i;
312
313         /* fail completely if get null pointers passed */
314         SMB_ASSERT(fn && keystr_pattern);
315
316         if (!gencache_init()) return;
317
318         DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
319         node = tdb_search_keys(cache->tdb, keystr_pattern);
320         first_node = node;
321         
322         while (node) {
323                 /* ensure null termination of the key string */
324                 keystr = strndup((char *)node->node_key.dptr, node->node_key.dsize);
325                 
326                 /* 
327                  * We don't use gencache_get function, because we need to iterate through
328                  * all of the entries. Validity verification is up to fn routine.
329                  */
330                 databuf = tdb_fetch(cache->tdb, node->node_key);
331                 if (!databuf.dptr || databuf.dsize <= TIMEOUT_LEN) {
332                         SAFE_FREE(databuf.dptr);
333                         SAFE_FREE(keystr);
334                         node = node->next;
335                         continue;
336                 }
337                 entry = strndup((char *)databuf.dptr, databuf.dsize);
338                 SAFE_FREE(databuf.dptr);
339                 valstr = malloc_array_p(char, databuf.dsize - TIMEOUT_LEN);
340                 sscanf(entry, CACHE_DATA_FMT, (int*)(&i), valstr);
341                 timeout = i;
342                 
343                 DEBUG(10, ("Calling function with arguments (key = %s, value = %s, timeout = %s)\n",
344                            keystr, valstr, ctime(&timeout)));
345                 fn(keystr, valstr, timeout, data);
346                 
347                 SAFE_FREE(valstr);
348                 SAFE_FREE(entry);
349                 SAFE_FREE(keystr);
350                 node = node->next;
351         }
352         
353         tdb_search_list_free(first_node);
354 }
355
356 /********************************************************************
357  lock a key
358 ********************************************************************/
359
360 int gencache_lock_entry( const char *key )
361 {
362         return tdb_lock_bystring(cache->tdb, key);
363 }
364
365 /********************************************************************
366  unlock a key
367 ********************************************************************/
368
369 void gencache_unlock_entry( const char *key )
370 {
371         tdb_unlock_bystring(cache->tdb, key);
372 }
373
374