This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[samba.git] / source / tdb / tdbutil.c
1 /* 
2    Unix SMB/CIFS implementation.
3    tdb utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "includes.h"
22 #include <fnmatch.h>
23
24 /* these are little tdb utility functions that are meant to make
25    dealing with a tdb database a little less cumbersome in Samba */
26
27 static SIG_ATOMIC_T gotalarm;
28
29 /***************************************************************
30  Signal function to tell us we timed out.
31 ****************************************************************/
32
33 static void gotalarm_sig(void)
34 {
35         gotalarm = 1;
36 }
37
38 /***************************************************************
39  Make a TDB_DATA and keep the const warning in one place
40 ****************************************************************/
41
42 static TDB_DATA make_tdb_data(const char *dptr, size_t dsize)
43 {
44         TDB_DATA ret;
45         ret.dptr = dptr;
46         ret.dsize = dsize;
47         return ret;
48 }
49
50 /****************************************************************************
51  Lock a chain with timeout (in seconds).
52 ****************************************************************************/
53
54 static int tdb_chainlock_with_timeout( TDB_CONTEXT *tdb, TDB_DATA key, unsigned int timeout, int rw_type)
55 {
56         /* Allow tdb_chainlock to be interrupted by an alarm. */
57         int ret;
58         gotalarm = 0;
59         tdb_set_lock_alarm(&gotalarm);
60
61         if (timeout) {
62                 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
63                 alarm(timeout);
64         }
65
66         if (rw_type == F_RDLCK)
67                 ret = tdb_chainlock_read(tdb, key);
68         else
69                 ret = tdb_chainlock(tdb, key);
70
71         if (timeout) {
72                 alarm(0);
73                 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
74                 if (gotalarm) {
75                         DEBUG(0,("tdb_chainlock_with_timeout: alarm (%u) timed out for key %s in tdb %s\n",
76                                 timeout, key.dptr, tdb->name ));
77                         return -1;
78                 }
79         }
80
81         return ret;
82 }
83
84 /****************************************************************************
85  Lock a chain by string. Return -1 if timeout or lock failed.
86 ****************************************************************************/
87
88 int tdb_lock_bystring(TDB_CONTEXT *tdb, const char *keyval, unsigned int timeout)
89 {
90         TDB_DATA key = make_tdb_data(keyval, strlen(keyval)+1);
91         
92         return tdb_chainlock_with_timeout(tdb, key, timeout, F_WRLCK);
93 }
94
95 /****************************************************************************
96  Unlock a chain by string.
97 ****************************************************************************/
98
99 void tdb_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
100 {
101         TDB_DATA key = make_tdb_data(keyval, strlen(keyval)+1);
102         
103         tdb_chainunlock(tdb, key);
104 }
105
106 /****************************************************************************
107  Read lock a chain by string. Return -1 if timeout or lock failed.
108 ****************************************************************************/
109
110 int tdb_read_lock_bystring(TDB_CONTEXT *tdb, const char *keyval, unsigned int timeout)
111 {
112         TDB_DATA key = make_tdb_data(keyval, strlen(keyval)+1);
113         
114         return tdb_chainlock_with_timeout(tdb, key, timeout, F_RDLCK);
115 }
116
117 /****************************************************************************
118  Read unlock a chain by string.
119 ****************************************************************************/
120
121 void tdb_read_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
122 {
123         TDB_DATA key = make_tdb_data(keyval, strlen(keyval)+1);
124         
125         tdb_chainunlock_read(tdb, key);
126 }
127
128
129 /****************************************************************************
130  Fetch a int32 value by a arbitrary blob key, return -1 if not found.
131  Output is int32 in native byte order.
132 ****************************************************************************/
133
134 int32 tdb_fetch_int32_byblob(TDB_CONTEXT *tdb, const char *keyval, size_t len)
135 {
136         TDB_DATA key = make_tdb_data(keyval, len);
137         TDB_DATA data;
138         int32 ret;
139
140         data = tdb_fetch(tdb, key);
141         if (!data.dptr || data.dsize != sizeof(int32)) {
142                 SAFE_FREE(data.dptr);
143                 return -1;
144         }
145
146         ret = IVAL(data.dptr,0);
147         SAFE_FREE(data.dptr);
148         return ret;
149 }
150
151 /****************************************************************************
152  Fetch a int32 value by string key, return -1 if not found.
153  Output is int32 in native byte order.
154 ****************************************************************************/
155
156 int32 tdb_fetch_int32(TDB_CONTEXT *tdb, const char *keystr)
157 {
158         return tdb_fetch_int32_byblob(tdb, keystr, strlen(keystr) + 1);
159 }
160
161 /****************************************************************************
162  Store a int32 value by an arbitary blob key, return 0 on success, -1 on failure.
163  Input is int32 in native byte order. Output in tdb is in little-endian.
164 ****************************************************************************/
165
166 int tdb_store_int32_byblob(TDB_CONTEXT *tdb, const char *keystr, size_t len, int32 v)
167 {
168         TDB_DATA key = make_tdb_data(keystr, len);
169         TDB_DATA data;
170         int32 v_store;
171
172         SIVAL(&v_store,0,v);
173         data.dptr = (void *)&v_store;
174         data.dsize = sizeof(int32);
175
176         return tdb_store(tdb, key, data, TDB_REPLACE);
177 }
178
179 /****************************************************************************
180  Store a int32 value by string key, return 0 on success, -1 on failure.
181  Input is int32 in native byte order. Output in tdb is in little-endian.
182 ****************************************************************************/
183
184 int tdb_store_int32(TDB_CONTEXT *tdb, const char *keystr, int32 v)
185 {
186         return tdb_store_int32_byblob(tdb, keystr, strlen(keystr) + 1, v);
187 }
188
189 /****************************************************************************
190  Fetch a uint32 value by a arbitrary blob key, return -1 if not found.
191  Output is uint32 in native byte order.
192 ****************************************************************************/
193
194 BOOL tdb_fetch_uint32_byblob(TDB_CONTEXT *tdb, const char *keyval, size_t len, uint32 *value)
195 {
196         TDB_DATA key = make_tdb_data(keyval, len);
197         TDB_DATA data;
198
199         data = tdb_fetch(tdb, key);
200         if (!data.dptr || data.dsize != sizeof(uint32)) {
201                 SAFE_FREE(data.dptr);
202                 return False;
203         }
204
205         *value = IVAL(data.dptr,0);
206         SAFE_FREE(data.dptr);
207         return True;
208 }
209
210 /****************************************************************************
211  Fetch a uint32 value by string key, return -1 if not found.
212  Output is uint32 in native byte order.
213 ****************************************************************************/
214
215 BOOL tdb_fetch_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 *value)
216 {
217         return tdb_fetch_uint32_byblob(tdb, keystr, strlen(keystr) + 1, value);
218 }
219
220 /****************************************************************************
221  Store a uint32 value by an arbitary blob key, return 0 on success, -1 on failure.
222  Input is uint32 in native byte order. Output in tdb is in little-endian.
223 ****************************************************************************/
224
225 BOOL tdb_store_uint32_byblob(TDB_CONTEXT *tdb, const char *keystr, size_t len, uint32 value)
226 {
227         TDB_DATA key = make_tdb_data(keystr, len);
228         TDB_DATA data;
229         uint32 v_store;
230         BOOL ret = True;
231
232         SIVAL(&v_store, 0, value);
233         data.dptr = (void *)&v_store;
234         data.dsize = sizeof(uint32);
235
236         if (tdb_store(tdb, key, data, TDB_REPLACE) == -1)
237                 ret = False;
238
239         return ret;
240 }
241
242 /****************************************************************************
243  Store a uint32 value by string key, return 0 on success, -1 on failure.
244  Input is uint32 in native byte order. Output in tdb is in little-endian.
245 ****************************************************************************/
246
247 BOOL tdb_store_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 value)
248 {
249         return tdb_store_uint32_byblob(tdb, keystr, strlen(keystr) + 1, value);
250 }
251 /****************************************************************************
252  Store a buffer by a null terminated string key.  Return 0 on success, -1
253  on failure.
254 ****************************************************************************/
255
256 int tdb_store_by_string(TDB_CONTEXT *tdb, const char *keystr, TDB_DATA data, int flags)
257 {
258         TDB_DATA key = make_tdb_data(keystr, strlen(keystr)+1);
259
260     return tdb_store(tdb, key, data, flags);
261 }
262
263 /****************************************************************************
264  Fetch a buffer using a null terminated string key.  Don't forget to call
265  free() on the result dptr.
266 ****************************************************************************/
267
268 TDB_DATA tdb_fetch_by_string(TDB_CONTEXT *tdb, const char *keystr)
269 {
270         TDB_DATA key = make_tdb_data(keystr, strlen(keystr)+1);
271
272     return tdb_fetch(tdb, key);
273 }
274
275 /****************************************************************************
276  Delete an entry using a null terminated string key. 
277 ****************************************************************************/
278
279 int tdb_delete_by_string(TDB_CONTEXT *tdb, const char *keystr)
280 {
281         TDB_DATA key = make_tdb_data(keystr, strlen(keystr)+1);
282
283     return tdb_delete(tdb, key);
284 }
285
286 /****************************************************************************
287  Atomic integer change. Returns old value. To create, set initial value in *oldval. 
288 ****************************************************************************/
289
290 int32 tdb_change_int32_atomic(TDB_CONTEXT *tdb, const char *keystr, int32 *oldval, int32 change_val)
291 {
292         int32 val;
293         int32 ret = -1;
294
295         if (tdb_lock_bystring(tdb, keystr,0) == -1)
296                 return -1;
297
298         if ((val = tdb_fetch_int32(tdb, keystr)) == -1) {
299                 /* The lookup failed */
300                 if (tdb_error(tdb) != TDB_ERR_NOEXIST) {
301                         /* but not becouse it didn't exist */
302                         goto err_out;
303                 }
304                 
305                 /* Start with 'old' value */
306                 val = *oldval;
307
308         } else {
309                 /* It worked, set return value (oldval) to tdb data */
310                 *oldval = val;
311         }
312
313         /* Increment value for storage and return next time */
314         val += change_val;
315                 
316         if (tdb_store_int32(tdb, keystr, val) == -1)
317                 goto err_out;
318
319         ret = 0;
320
321   err_out:
322
323         tdb_unlock_bystring(tdb, keystr);
324         return ret;
325 }
326
327 /****************************************************************************
328  Atomic unsigned integer change. Returns old value. To create, set initial value in *oldval. 
329 ****************************************************************************/
330
331 BOOL tdb_change_uint32_atomic(TDB_CONTEXT *tdb, const char *keystr, uint32 *oldval, uint32 change_val)
332 {
333         uint32 val;
334         BOOL ret = False;
335
336         if (tdb_lock_bystring(tdb, keystr,0) == -1)
337                 return False;
338
339         if (!tdb_fetch_uint32(tdb, keystr, &val)) {
340                 /* It failed */
341                 if (tdb_error(tdb) != TDB_ERR_NOEXIST) { 
342                         /* and not becouse it didn't exist */
343                         goto err_out;
344                 }
345
346                 /* Start with 'old' value */
347                 val = *oldval;
348
349         } else {
350                 /* it worked, set return value (oldval) to tdb data */
351                 *oldval = val;
352
353         }
354
355         /* get a new value to store */
356         val += change_val;
357                 
358         if (!tdb_store_uint32(tdb, keystr, val))
359                 goto err_out;
360
361         ret = True;
362
363   err_out:
364
365         tdb_unlock_bystring(tdb, keystr);
366         return ret;
367 }
368
369 /****************************************************************************
370  Useful pair of routines for packing/unpacking data consisting of
371  integers and strings.
372 ****************************************************************************/
373
374 size_t tdb_pack(char *buf, int bufsize, const char *fmt, ...)
375 {
376         va_list ap;
377         uint16 w;
378         uint32 d;
379         int i;
380         void *p;
381         int len;
382         char *s;
383         char c;
384         char *buf0 = buf;
385         const char *fmt0 = fmt;
386         int bufsize0 = bufsize;
387
388         va_start(ap, fmt);
389
390         while (*fmt) {
391                 switch ((c = *fmt++)) {
392                 case 'w':
393                         len = 2;
394                         w = (uint16)va_arg(ap, int);
395                         if (bufsize >= len)
396                                 SSVAL(buf, 0, w);
397                         break;
398                 case 'd':
399                         len = 4;
400                         d = va_arg(ap, uint32);
401                         if (bufsize >= len)
402                                 SIVAL(buf, 0, d);
403                         break;
404                 case 'p':
405                         len = 4;
406                         p = va_arg(ap, void *);
407                         d = p?1:0;
408                         if (bufsize >= len)
409                                 SIVAL(buf, 0, d);
410                         break;
411                 case 'P':
412                         s = va_arg(ap,char *);
413                         w = strlen(s);
414                         len = w + 1;
415                         if (bufsize >= len)
416                                 memcpy(buf, s, len);
417                         break;
418                 case 'f':
419                         s = va_arg(ap,char *);
420                         w = strlen(s);
421                         len = w + 1;
422                         if (bufsize >= len)
423                                 memcpy(buf, s, len);
424                         break;
425                 case 'B':
426                         i = va_arg(ap, int);
427                         s = va_arg(ap, char *);
428                         len = 4+i;
429                         if (bufsize >= len) {
430                                 SIVAL(buf, 0, i);
431                                 memcpy(buf+4, s, i);
432                         }
433                         break;
434                 default:
435                         DEBUG(0,("Unknown tdb_pack format %c in %s\n", 
436                                  c, fmt));
437                         len = 0;
438                         break;
439                 }
440
441                 buf += len;
442                 bufsize -= len;
443         }
444
445         va_end(ap);
446
447         DEBUG(18,("tdb_pack(%s, %d) -> %d\n", 
448                  fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
449         
450         return PTR_DIFF(buf, buf0);
451 }
452
453 /****************************************************************************
454  Useful pair of routines for packing/unpacking data consisting of
455  integers and strings.
456 ****************************************************************************/
457
458 int tdb_unpack(char *buf, int bufsize, const char *fmt, ...)
459 {
460         va_list ap;
461         uint16 *w;
462         uint32 *d;
463         int len;
464         int *i;
465         void **p;
466         char *s, **b;
467         char c;
468         char *buf0 = buf;
469         const char *fmt0 = fmt;
470         int bufsize0 = bufsize;
471
472         va_start(ap, fmt);
473         
474         while (*fmt) {
475                 switch ((c=*fmt++)) {
476                 case 'w':
477                         len = 2;
478                         w = va_arg(ap, uint16 *);
479                         if (bufsize < len)
480                                 goto no_space;
481                         *w = SVAL(buf, 0);
482                         break;
483                 case 'd':
484                         len = 4;
485                         d = va_arg(ap, uint32 *);
486                         if (bufsize < len)
487                                 goto no_space;
488                         *d = IVAL(buf, 0);
489                         break;
490                 case 'p':
491                         len = 4;
492                         p = va_arg(ap, void **);
493                         if (bufsize < len)
494                                 goto no_space;
495                         *p = (void *)IVAL(buf, 0);
496                         break;
497                 case 'P':
498                         s = va_arg(ap,char *);
499                         len = strlen(buf) + 1;
500                         if (bufsize < len || len > sizeof(pstring))
501                                 goto no_space;
502                         memcpy(s, buf, len);
503                         break;
504                 case 'f':
505                         s = va_arg(ap,char *);
506                         len = strlen(buf) + 1;
507                         if (bufsize < len || len > sizeof(fstring))
508                                 goto no_space;
509                         memcpy(s, buf, len);
510                         break;
511                 case 'B':
512                         i = va_arg(ap, int *);
513                         b = va_arg(ap, char **);
514                         len = 4;
515                         if (bufsize < len)
516                                 goto no_space;
517                         *i = IVAL(buf, 0);
518                         if (! *i) {
519                                 *b = NULL;
520                                 break;
521                         }
522                         len += *i;
523                         if (bufsize < len)
524                                 goto no_space;
525                         *b = (char *)malloc(*i);
526                         if (! *b)
527                                 goto no_space;
528                         memcpy(*b, buf+4, *i);
529                         break;
530                 default:
531                         DEBUG(0,("Unknown tdb_unpack format %c in %s\n", 
532                                  c, fmt));
533
534                         len = 0;
535                         break;
536                 }
537
538                 buf += len;
539                 bufsize -= len;
540         }
541
542         va_end(ap);
543
544         DEBUG(18,("tdb_unpack(%s, %d) -> %d\n", 
545                  fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
546
547         return PTR_DIFF(buf, buf0);
548
549  no_space:
550         return -1;
551 }
552
553 /****************************************************************************
554  Log tdb messages via DEBUG().
555 ****************************************************************************/
556
557 static void tdb_log(TDB_CONTEXT *tdb, int level, const char *format, ...)
558 {
559         va_list ap;
560         char *ptr = NULL;
561
562         va_start(ap, format);
563         vasprintf(&ptr, format, ap);
564         va_end(ap);
565         
566         if (!ptr || !*ptr)
567                 return;
568
569         DEBUG(level, ("tdb(%s): %s", tdb->name ? tdb->name : "unnamed", ptr));
570         SAFE_FREE(ptr);
571 }
572
573 /****************************************************************************
574  Like tdb_open() but also setup a logging function that redirects to
575  the samba DEBUG() system.
576 ****************************************************************************/
577
578 TDB_CONTEXT *tdb_open_log(const char *name, int hash_size, int tdb_flags,
579                           int open_flags, mode_t mode)
580 {
581         TDB_CONTEXT *tdb;
582
583         if (!lp_use_mmap())
584                 tdb_flags |= TDB_NOMMAP;
585
586         tdb = tdb_open_ex(name, hash_size, tdb_flags, 
587                                     open_flags, mode, tdb_log);
588         if (!tdb)
589                 return NULL;
590
591         return tdb;
592 }
593
594
595 /****************************************************************************
596  Allow tdb_delete to be used as a tdb_traversal_fn.
597 ****************************************************************************/
598
599 int tdb_traverse_delete_fn(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf,
600                      void *state)
601 {
602     return tdb_delete(the_tdb, key);
603 }
604
605
606
607 /**
608  * Search across the whole tdb for keys that match the given pattern
609  * return the result as a list of keys
610  *
611  * @param tdb pointer to opened tdb file context
612  * @param pattern searching pattern used by fnmatch(3) functions
613  *
614  * @return list of keys found by looking up with given pattern
615  **/
616 TDB_LIST_NODE *tdb_search_keys(TDB_CONTEXT *tdb, const char* pattern)
617 {
618         TDB_DATA key, next;
619         TDB_LIST_NODE *list = NULL;
620         TDB_LIST_NODE *rec = NULL;
621         TDB_LIST_NODE *tmp = NULL;
622         
623         for (key = tdb_firstkey(tdb); key.dptr; key = next) {
624                 /* duplicate key string to ensure null-termination */
625                 char *key_str = (char*) strndup(key.dptr, key.dsize);
626                 if (!key_str) {
627                         DEBUG(0, ("tdb_search_keys: strndup() failed!\n"));
628                         smb_panic("strndup failed!\n");
629                 }
630                 
631                 DEBUG(18, ("checking %s for match to pattern %s\n", key_str, pattern));
632                 
633                 next = tdb_nextkey(tdb, key);
634
635                 /* do the pattern checking */
636                 if (fnmatch(pattern, key_str, 0) == 0) {
637                         rec = (TDB_LIST_NODE*) malloc(sizeof(*rec));
638                         ZERO_STRUCTP(rec);
639
640                         rec->node_key = key;
641         
642                         DLIST_ADD_END(list, rec, tmp);
643                 
644                         DEBUG(18, ("checking %s matched pattern %s\n", key_str, pattern));
645                 } else {
646                         free(key.dptr);
647                 }
648                 
649                 /* free duplicated key string */
650                 free(key_str);
651         }
652         
653         return list;
654
655 };
656
657
658 /**
659  * Free the list returned by tdb_search_keys
660  *
661  * @param node list of results found by tdb_search_keys
662  **/
663 void tdb_search_list_free(TDB_LIST_NODE* node)
664 {
665         TDB_LIST_NODE *next_node;
666         
667         while (node) {
668                 next_node = node->next;
669                 SAFE_FREE(node);
670                 node = next_node;
671         };
672 };
673
674