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