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