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