source code fix for bug 1095 -- honor the '-l' option
[tprouty/samba.git] / source / 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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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/%s"
31
32 static TDB_CONTEXT *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_open_log(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         /* tdb_close routine returns -1 on error */
87         if (!cache) return False;
88         DEBUG(5, ("Closing cache file\n"));
89         return tdb_close(cache) != -1;
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 = strdup(keystr);
121         keybuf.dsize = strlen(keystr)+1;
122         databuf.dptr = 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)), 
127                    timeout > time(NULL) ? "ahead" : "in the past"));
128
129         ret = tdb_store(cache, 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 = strdup(keystr);
174         keybuf.dsize = strlen(keystr)+1;
175         databuf.dptr = 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, 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 = strdup(keystr);
213         keybuf.dsize = strlen(keystr)+1;
214         DEBUG(10, ("Deleting cache entry (key = %s)\n", keystr));
215         ret = tdb_delete(cache, 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 = strdup(keystr);
246         keybuf.dsize = strlen(keystr)+1;
247         databuf = tdb_fetch(cache, keybuf);
248         SAFE_FREE(keybuf.dptr);
249         
250         if (databuf.dptr && databuf.dsize > TIMEOUT_LEN) {
251                 char* entry_buf = strndup(databuf.dptr, databuf.dsize);
252                 char *v;
253                 time_t t;
254
255                 v = (char*)malloc(sizeof(char) * 
256                                   (databuf.dsize - TIMEOUT_LEN));
257                                 
258                 SAFE_FREE(databuf.dptr);
259                 sscanf(entry_buf, CACHE_DATA_FMT, (int*)&t, v);
260                 SAFE_FREE(entry_buf);
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
312         /* fail completely if get null pointers passed */
313         SMB_ASSERT(fn && keystr_pattern);
314
315         if (!gencache_init()) return;
316
317         DEBUG(5, ("Searching cache keys with pattern %s\n", keystr_pattern));
318         node = tdb_search_keys(cache, keystr_pattern);
319         first_node = node;
320         
321         while (node) {
322                 /* ensure null termination of the key string */
323                 keystr = strndup(node->node_key.dptr, node->node_key.dsize);
324                 
325                 /* 
326                  * We don't use gencache_get function, because we need to iterate through
327                  * all of the entries. Validity verification is up to fn routine.
328                  */
329                 databuf = tdb_fetch(cache, node->node_key);
330                 if (!databuf.dptr || databuf.dsize <= TIMEOUT_LEN) {
331                         SAFE_FREE(databuf.dptr);
332                         SAFE_FREE(keystr);
333                         node = node->next;
334                         continue;
335                 }
336                 entry = strndup(databuf.dptr, databuf.dsize);
337                 SAFE_FREE(databuf.dptr);
338                 valstr = (char*)malloc(sizeof(char) * (databuf.dsize - TIMEOUT_LEN));
339                 sscanf(entry, CACHE_DATA_FMT, (int*)(&timeout), valstr);
340                 
341                 DEBUG(10, ("Calling function with arguments (key = %s, value = %s, timeout = %s)\n",
342                            keystr, valstr, ctime(&timeout)));
343                 fn(keystr, valstr, timeout, data);
344                 
345                 SAFE_FREE(valstr);
346                 SAFE_FREE(entry);
347                 SAFE_FREE(keystr);
348                 node = node->next;
349         }
350         
351         tdb_search_list_free(first_node);
352 }
353
354 /********************************************************************
355  lock a key
356 ********************************************************************/
357
358 int gencache_lock_entry( const char *key )
359 {
360         if (!gencache_init())
361                 return -1;
362         
363         return tdb_lock_bystring(cache, key, 0);
364 }
365
366 /********************************************************************
367  unlock a key
368 ********************************************************************/
369
370 void gencache_unlock_entry( const char *key )
371 {
372         if (!gencache_init())
373                 return;
374         
375         tdb_unlock_bystring(cache, key);
376         return;
377 }
378
379