RIP BOOL. Convert BOOL -> bool. I found a few interesting
[nivanova/samba-autobuild/.git] / source3 / lib / util_tdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3    tdb utility functions
4    Copyright (C) Andrew Tridgell   1992-1998
5    Copyright (C) Rafal Szczesniak  2002
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #undef malloc
23 #undef realloc
24 #undef calloc
25 #undef strdup
26
27 /* these are little tdb utility functions that are meant to make
28    dealing with a tdb database a little less cumbersome in Samba */
29
30 static SIG_ATOMIC_T gotalarm;
31
32 /***************************************************************
33  Signal function to tell us we timed out.
34 ****************************************************************/
35
36 static void gotalarm_sig(void)
37 {
38         gotalarm = 1;
39 }
40
41 /***************************************************************
42  Make a TDB_DATA and keep the const warning in one place
43 ****************************************************************/
44
45 TDB_DATA make_tdb_data(const uint8 *dptr, size_t dsize)
46 {
47         TDB_DATA ret;
48         ret.dptr = CONST_DISCARD(uint8 *, dptr);
49         ret.dsize = dsize;
50         return ret;
51 }
52
53 TDB_DATA string_tdb_data(const char *string)
54 {
55         return make_tdb_data((const uint8 *)string, string ? strlen(string) : 0 );
56 }
57
58 TDB_DATA string_term_tdb_data(const char *string)
59 {
60         return make_tdb_data((const uint8 *)string, string ? strlen(string) + 1 : 0);
61 }
62
63 /****************************************************************************
64  Lock a chain with timeout (in seconds).
65 ****************************************************************************/
66
67 static int tdb_chainlock_with_timeout_internal( TDB_CONTEXT *tdb, TDB_DATA key, unsigned int timeout, int rw_type)
68 {
69         /* Allow tdb_chainlock to be interrupted by an alarm. */
70         int ret;
71         gotalarm = 0;
72
73         if (timeout) {
74                 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
75                 alarm(timeout);
76         }
77
78         if (rw_type == F_RDLCK)
79                 ret = tdb_chainlock_read(tdb, key);
80         else
81                 ret = tdb_chainlock(tdb, key);
82
83         if (timeout) {
84                 alarm(0);
85                 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
86                 if (gotalarm) {
87                         DEBUG(0,("tdb_chainlock_with_timeout_internal: alarm (%u) timed out for key %s in tdb %s\n",
88                                 timeout, key.dptr, tdb_name(tdb)));
89                         /* TODO: If we time out waiting for a lock, it might
90                          * be nice to use F_GETLK to get the pid of the
91                          * process currently holding the lock and print that
92                          * as part of the debugging message. -- mbp */
93                         return -1;
94                 }
95         }
96
97         return ret;
98 }
99
100 /****************************************************************************
101  Write lock a chain. Return -1 if timeout or lock failed.
102 ****************************************************************************/
103
104 int tdb_chainlock_with_timeout( TDB_CONTEXT *tdb, TDB_DATA key, unsigned int timeout)
105 {
106         return tdb_chainlock_with_timeout_internal(tdb, key, timeout, F_WRLCK);
107 }
108
109 /****************************************************************************
110  Lock a chain by string. Return -1 if timeout or lock failed.
111 ****************************************************************************/
112
113 int tdb_lock_bystring(TDB_CONTEXT *tdb, const char *keyval)
114 {
115         TDB_DATA key = string_term_tdb_data(keyval);
116         
117         return tdb_chainlock(tdb, key);
118 }
119
120 int tdb_lock_bystring_with_timeout(TDB_CONTEXT *tdb, const char *keyval,
121                                    int timeout)
122 {
123         TDB_DATA key = string_term_tdb_data(keyval);
124         
125         return tdb_chainlock_with_timeout(tdb, key, timeout);
126 }
127
128 /****************************************************************************
129  Unlock a chain by string.
130 ****************************************************************************/
131
132 void tdb_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
133 {
134         TDB_DATA key = string_term_tdb_data(keyval);
135
136         tdb_chainunlock(tdb, key);
137 }
138
139 /****************************************************************************
140  Read lock a chain by string. Return -1 if timeout or lock failed.
141 ****************************************************************************/
142
143 int tdb_read_lock_bystring_with_timeout(TDB_CONTEXT *tdb, const char *keyval, unsigned int timeout)
144 {
145         TDB_DATA key = string_term_tdb_data(keyval);
146         
147         return tdb_chainlock_with_timeout_internal(tdb, key, timeout, F_RDLCK);
148 }
149
150 /****************************************************************************
151  Read unlock a chain by string.
152 ****************************************************************************/
153
154 void tdb_read_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
155 {
156         TDB_DATA key = string_term_tdb_data(keyval);
157         
158         tdb_chainunlock_read(tdb, key);
159 }
160
161
162 /****************************************************************************
163  Fetch a int32 value by a arbitrary blob key, return -1 if not found.
164  Output is int32 in native byte order.
165 ****************************************************************************/
166
167 int32 tdb_fetch_int32_byblob(TDB_CONTEXT *tdb, TDB_DATA key)
168 {
169         TDB_DATA data;
170         int32 ret;
171
172         data = tdb_fetch(tdb, key);
173         if (!data.dptr || data.dsize != sizeof(int32)) {
174                 SAFE_FREE(data.dptr);
175                 return -1;
176         }
177
178         ret = IVAL(data.dptr,0);
179         SAFE_FREE(data.dptr);
180         return ret;
181 }
182
183 /****************************************************************************
184  Fetch a int32 value by string key, return -1 if not found.
185  Output is int32 in native byte order.
186 ****************************************************************************/
187
188 int32 tdb_fetch_int32(TDB_CONTEXT *tdb, const char *keystr)
189 {
190         TDB_DATA key = string_term_tdb_data(keystr);
191
192         return tdb_fetch_int32_byblob(tdb, key);
193 }
194
195 /****************************************************************************
196  Store a int32 value by an arbitary blob key, return 0 on success, -1 on failure.
197  Input is int32 in native byte order. Output in tdb is in little-endian.
198 ****************************************************************************/
199
200 int tdb_store_int32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, int32 v)
201 {
202         TDB_DATA data;
203         int32 v_store;
204
205         SIVAL(&v_store,0,v);
206         data.dptr = (uint8 *)&v_store;
207         data.dsize = sizeof(int32);
208
209         return tdb_store(tdb, key, data, TDB_REPLACE);
210 }
211
212 /****************************************************************************
213  Store a int32 value by string key, return 0 on success, -1 on failure.
214  Input is int32 in native byte order. Output in tdb is in little-endian.
215 ****************************************************************************/
216
217 int tdb_store_int32(TDB_CONTEXT *tdb, const char *keystr, int32 v)
218 {
219         TDB_DATA key = string_term_tdb_data(keystr);
220
221         return tdb_store_int32_byblob(tdb, key, v);
222 }
223
224 /****************************************************************************
225  Fetch a uint32 value by a arbitrary blob key, return -1 if not found.
226  Output is uint32 in native byte order.
227 ****************************************************************************/
228
229 bool tdb_fetch_uint32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, uint32 *value)
230 {
231         TDB_DATA data;
232
233         data = tdb_fetch(tdb, key);
234         if (!data.dptr || data.dsize != sizeof(uint32)) {
235                 SAFE_FREE(data.dptr);
236                 return False;
237         }
238
239         *value = IVAL(data.dptr,0);
240         SAFE_FREE(data.dptr);
241         return True;
242 }
243
244 /****************************************************************************
245  Fetch a uint32 value by string key, return -1 if not found.
246  Output is uint32 in native byte order.
247 ****************************************************************************/
248
249 bool tdb_fetch_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 *value)
250 {
251         TDB_DATA key = string_term_tdb_data(keystr);
252
253         return tdb_fetch_uint32_byblob(tdb, key, value);
254 }
255
256 /****************************************************************************
257  Store a uint32 value by an arbitary blob key, return 0 on success, -1 on failure.
258  Input is uint32 in native byte order. Output in tdb is in little-endian.
259 ****************************************************************************/
260
261 bool tdb_store_uint32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, uint32 value)
262 {
263         TDB_DATA data;
264         uint32 v_store;
265         bool ret = True;
266
267         SIVAL(&v_store, 0, value);
268         data.dptr = (uint8 *)&v_store;
269         data.dsize = sizeof(uint32);
270
271         if (tdb_store(tdb, key, data, TDB_REPLACE) == -1)
272                 ret = False;
273
274         return ret;
275 }
276
277 /****************************************************************************
278  Store a uint32 value by string key, return 0 on success, -1 on failure.
279  Input is uint32 in native byte order. Output in tdb is in little-endian.
280 ****************************************************************************/
281
282 bool tdb_store_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 value)
283 {
284         TDB_DATA key = string_term_tdb_data(keystr);
285
286         return tdb_store_uint32_byblob(tdb, key, value);
287 }
288 /****************************************************************************
289  Store a buffer by a null terminated string key.  Return 0 on success, -1
290  on failure.
291 ****************************************************************************/
292
293 int tdb_store_bystring(TDB_CONTEXT *tdb, const char *keystr, TDB_DATA data, int flags)
294 {
295         TDB_DATA key = string_term_tdb_data(keystr);
296
297         return tdb_store(tdb, key, data, flags);
298 }
299
300 int tdb_trans_store_bystring(TDB_CONTEXT *tdb, const char *keystr,
301                              TDB_DATA data, int flags)
302 {
303         TDB_DATA key = string_term_tdb_data(keystr);
304         
305         return tdb_trans_store(tdb, key, data, flags);
306 }
307
308 /****************************************************************************
309  Fetch a buffer using a null terminated string key.  Don't forget to call
310  free() on the result dptr.
311 ****************************************************************************/
312
313 TDB_DATA tdb_fetch_bystring(TDB_CONTEXT *tdb, const char *keystr)
314 {
315         TDB_DATA key = string_term_tdb_data(keystr);
316
317         return tdb_fetch(tdb, key);
318 }
319
320 /****************************************************************************
321  Delete an entry using a null terminated string key. 
322 ****************************************************************************/
323
324 int tdb_delete_bystring(TDB_CONTEXT *tdb, const char *keystr)
325 {
326         TDB_DATA key = string_term_tdb_data(keystr);
327
328         return tdb_delete(tdb, key);
329 }
330
331 /****************************************************************************
332  Atomic integer change. Returns old value. To create, set initial value in *oldval. 
333 ****************************************************************************/
334
335 int32 tdb_change_int32_atomic(TDB_CONTEXT *tdb, const char *keystr, int32 *oldval, int32 change_val)
336 {
337         int32 val;
338         int32 ret = -1;
339
340         if (tdb_lock_bystring(tdb, keystr) == -1)
341                 return -1;
342
343         if ((val = tdb_fetch_int32(tdb, keystr)) == -1) {
344                 /* The lookup failed */
345                 if (tdb_error(tdb) != TDB_ERR_NOEXIST) {
346                         /* but not because it didn't exist */
347                         goto err_out;
348                 }
349                 
350                 /* Start with 'old' value */
351                 val = *oldval;
352
353         } else {
354                 /* It worked, set return value (oldval) to tdb data */
355                 *oldval = val;
356         }
357
358         /* Increment value for storage and return next time */
359         val += change_val;
360                 
361         if (tdb_store_int32(tdb, keystr, val) == -1)
362                 goto err_out;
363
364         ret = 0;
365
366   err_out:
367
368         tdb_unlock_bystring(tdb, keystr);
369         return ret;
370 }
371
372 /****************************************************************************
373  Atomic unsigned integer change. Returns old value. To create, set initial value in *oldval. 
374 ****************************************************************************/
375
376 bool tdb_change_uint32_atomic(TDB_CONTEXT *tdb, const char *keystr, uint32 *oldval, uint32 change_val)
377 {
378         uint32 val;
379         bool ret = False;
380
381         if (tdb_lock_bystring(tdb, keystr) == -1)
382                 return False;
383
384         if (!tdb_fetch_uint32(tdb, keystr, &val)) {
385                 /* It failed */
386                 if (tdb_error(tdb) != TDB_ERR_NOEXIST) { 
387                         /* and not because it didn't exist */
388                         goto err_out;
389                 }
390
391                 /* Start with 'old' value */
392                 val = *oldval;
393
394         } else {
395                 /* it worked, set return value (oldval) to tdb data */
396                 *oldval = val;
397
398         }
399
400         /* get a new value to store */
401         val += change_val;
402                 
403         if (!tdb_store_uint32(tdb, keystr, val))
404                 goto err_out;
405
406         ret = True;
407
408   err_out:
409
410         tdb_unlock_bystring(tdb, keystr);
411         return ret;
412 }
413
414 /****************************************************************************
415  Useful pair of routines for packing/unpacking data consisting of
416  integers and strings.
417 ****************************************************************************/
418
419 size_t tdb_pack_va(uint8 *buf, int bufsize, const char *fmt, va_list ap)
420 {
421         uint8 bt;
422         uint16 w;
423         uint32 d;
424         int i;
425         void *p;
426         int len;
427         char *s;
428         char c;
429         uint8 *buf0 = buf;
430         const char *fmt0 = fmt;
431         int bufsize0 = bufsize;
432
433         while (*fmt) {
434                 switch ((c = *fmt++)) {
435                 case 'b': /* unsigned 8-bit integer */
436                         len = 1;
437                         bt = (uint8)va_arg(ap, int);
438                         if (bufsize && bufsize >= len)
439                                 SSVAL(buf, 0, bt);
440                         break;
441                 case 'w': /* unsigned 16-bit integer */
442                         len = 2;
443                         w = (uint16)va_arg(ap, int);
444                         if (bufsize && bufsize >= len)
445                                 SSVAL(buf, 0, w);
446                         break;
447                 case 'd': /* signed 32-bit integer (standard int in most systems) */
448                         len = 4;
449                         d = va_arg(ap, uint32);
450                         if (bufsize && bufsize >= len)
451                                 SIVAL(buf, 0, d);
452                         break;
453                 case 'p': /* pointer */
454                         len = 4;
455                         p = va_arg(ap, void *);
456                         d = p?1:0;
457                         if (bufsize && bufsize >= len)
458                                 SIVAL(buf, 0, d);
459                         break;
460                 case 'P': /* null-terminated string */
461                         s = va_arg(ap,char *);
462                         w = strlen(s);
463                         len = w + 1;
464                         if (bufsize && bufsize >= len)
465                                 memcpy(buf, s, len);
466                         break;
467                 case 'f': /* null-terminated string */
468                         s = va_arg(ap,char *);
469                         w = strlen(s);
470                         len = w + 1;
471                         if (bufsize && bufsize >= len)
472                                 memcpy(buf, s, len);
473                         break;
474                 case 'B': /* fixed-length string */
475                         i = va_arg(ap, int);
476                         s = va_arg(ap, char *);
477                         len = 4+i;
478                         if (bufsize && bufsize >= len) {
479                                 SIVAL(buf, 0, i);
480                                 memcpy(buf+4, s, i);
481                         }
482                         break;
483                 default:
484                         DEBUG(0,("Unknown tdb_pack format %c in %s\n", 
485                                  c, fmt));
486                         len = 0;
487                         break;
488                 }
489
490                 buf += len;
491                 if (bufsize)
492                         bufsize -= len;
493                 if (bufsize < 0)
494                         bufsize = 0;
495         }
496
497         DEBUG(18,("tdb_pack_va(%s, %d) -> %d\n", 
498                  fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
499         
500         return PTR_DIFF(buf, buf0);
501 }
502
503 size_t tdb_pack(uint8 *buf, int bufsize, const char *fmt, ...)
504 {
505         va_list ap;
506         size_t result;
507
508         va_start(ap, fmt);
509         result = tdb_pack_va(buf, bufsize, fmt, ap);
510         va_end(ap);
511         return result;
512 }
513
514 bool tdb_pack_append(TALLOC_CTX *mem_ctx, uint8 **buf, size_t *len,
515                      const char *fmt, ...)
516 {
517         va_list ap;
518         size_t len1, len2;
519
520         va_start(ap, fmt);
521         len1 = tdb_pack_va(NULL, 0, fmt, ap);
522         va_end(ap);
523
524         if (mem_ctx != NULL) {
525                 *buf = TALLOC_REALLOC_ARRAY(mem_ctx, *buf, uint8,
526                                             (*len) + len1);
527         } else {
528                 *buf = SMB_REALLOC_ARRAY(*buf, uint8, (*len) + len1);
529         }
530
531         if (*buf == NULL) {
532                 return False;
533         }
534
535         va_start(ap, fmt);
536         len2 = tdb_pack_va((*buf)+(*len), len1, fmt, ap);
537         va_end(ap);
538
539         if (len1 != len2) {
540                 return False;
541         }
542
543         *len += len2;
544
545         return True;
546 }
547
548 /****************************************************************************
549  Useful pair of routines for packing/unpacking data consisting of
550  integers and strings.
551 ****************************************************************************/
552
553 int tdb_unpack(const uint8 *buf, int bufsize, const char *fmt, ...)
554 {
555         va_list ap;
556         uint8 *bt;
557         uint16 *w;
558         uint32 *d;
559         int len;
560         int *i;
561         void **p;
562         char *s, **b;
563         char c;
564         const uint8 *buf0 = buf;
565         const char *fmt0 = fmt;
566         int bufsize0 = bufsize;
567
568         va_start(ap, fmt);
569         
570         while (*fmt) {
571                 switch ((c=*fmt++)) {
572                 case 'b':
573                         len = 1;
574                         bt = va_arg(ap, uint8 *);
575                         if (bufsize < len)
576                                 goto no_space;
577                         *bt = SVAL(buf, 0);
578                         break;
579                 case 'w':
580                         len = 2;
581                         w = va_arg(ap, uint16 *);
582                         if (bufsize < len)
583                                 goto no_space;
584                         *w = SVAL(buf, 0);
585                         break;
586                 case 'd':
587                         len = 4;
588                         d = va_arg(ap, uint32 *);
589                         if (bufsize < len)
590                                 goto no_space;
591                         *d = IVAL(buf, 0);
592                         break;
593                 case 'p':
594                         len = 4;
595                         p = va_arg(ap, void **);
596                         if (bufsize < len)
597                                 goto no_space;
598                         /* 
599                          * This isn't a real pointer - only a token (1 or 0)
600                          * to mark the fact a pointer is present.
601                          */
602
603                         *p = (void *)(IVAL(buf, 0) ? (void *)1 : NULL);
604                         break;
605                 case 'P':
606                         s = va_arg(ap,char *);
607                         len = strlen((const char *)buf) + 1;
608                         if (bufsize < len || len > sizeof(pstring))
609                                 goto no_space;
610                         memcpy(s, buf, len);
611                         break;
612                 case 'f':
613                         s = va_arg(ap,char *);
614                         len = strlen((const char *)buf) + 1;
615                         if (bufsize < len || len > sizeof(fstring))
616                                 goto no_space;
617                         memcpy(s, buf, len);
618                         break;
619                 case 'B':
620                         i = va_arg(ap, int *);
621                         b = va_arg(ap, char **);
622                         len = 4;
623                         if (bufsize < len)
624                                 goto no_space;
625                         *i = IVAL(buf, 0);
626                         if (! *i) {
627                                 *b = NULL;
628                                 break;
629                         }
630                         len += *i;
631                         if (bufsize < len)
632                                 goto no_space;
633                         *b = (char *)SMB_MALLOC(*i);
634                         if (! *b)
635                                 goto no_space;
636                         memcpy(*b, buf+4, *i);
637                         break;
638                 default:
639                         DEBUG(0,("Unknown tdb_unpack format %c in %s\n", 
640                                  c, fmt));
641
642                         len = 0;
643                         break;
644                 }
645
646                 buf += len;
647                 bufsize -= len;
648         }
649
650         va_end(ap);
651
652         DEBUG(18,("tdb_unpack(%s, %d) -> %d\n", 
653                  fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
654
655         return PTR_DIFF(buf, buf0);
656
657  no_space:
658         return -1;
659 }
660
661
662 /****************************************************************************
663  Log tdb messages via DEBUG().
664 ****************************************************************************/
665
666 static void tdb_log(TDB_CONTEXT *tdb, enum tdb_debug_level level, const char *format, ...)
667 {
668         va_list ap;
669         char *ptr = NULL;
670
671         va_start(ap, format);
672         vasprintf(&ptr, format, ap);
673         va_end(ap);
674         
675         if (!ptr || !*ptr)
676                 return;
677
678         DEBUG((int)level, ("tdb(%s): %s", tdb_name(tdb) ? tdb_name(tdb) : "unnamed", ptr));
679         SAFE_FREE(ptr);
680 }
681
682 /****************************************************************************
683  Like tdb_open() but also setup a logging function that redirects to
684  the samba DEBUG() system.
685 ****************************************************************************/
686
687 TDB_CONTEXT *tdb_open_log(const char *name, int hash_size, int tdb_flags,
688                           int open_flags, mode_t mode)
689 {
690         TDB_CONTEXT *tdb;
691         struct tdb_logging_context log_ctx;
692
693         if (!lp_use_mmap())
694                 tdb_flags |= TDB_NOMMAP;
695
696         log_ctx.log_fn = tdb_log;
697         log_ctx.log_private = NULL;
698
699         if ((hash_size == 0) && (name != NULL)) {
700                 const char *base = strrchr_m(name, '/');
701                 if (base != NULL) {
702                         base += 1;
703                 }
704                 else {
705                         base = name;
706                 }
707                 hash_size = lp_parm_int(-1, "tdb_hashsize", base, 0);
708         }
709
710         tdb = tdb_open_ex(name, hash_size, tdb_flags, 
711                           open_flags, mode, &log_ctx, NULL);
712         if (!tdb)
713                 return NULL;
714
715         return tdb;
716 }
717
718 /****************************************************************************
719  Allow tdb_delete to be used as a tdb_traversal_fn.
720 ****************************************************************************/
721
722 int tdb_traverse_delete_fn(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf,
723                      void *state)
724 {
725     return tdb_delete(the_tdb, key);
726 }
727
728
729
730 /**
731  * Search across the whole tdb for keys that match the given pattern
732  * return the result as a list of keys
733  *
734  * @param tdb pointer to opened tdb file context
735  * @param pattern searching pattern used by fnmatch(3) functions
736  *
737  * @return list of keys found by looking up with given pattern
738  **/
739 TDB_LIST_NODE *tdb_search_keys(TDB_CONTEXT *tdb, const char* pattern)
740 {
741         TDB_DATA key, next;
742         TDB_LIST_NODE *list = NULL;
743         TDB_LIST_NODE *rec = NULL;
744         
745         for (key = tdb_firstkey(tdb); key.dptr; key = next) {
746                 /* duplicate key string to ensure null-termination */
747                 char *key_str = SMB_STRNDUP((const char *)key.dptr, key.dsize);
748                 if (!key_str) {
749                         DEBUG(0, ("tdb_search_keys: strndup() failed!\n"));
750                         smb_panic("strndup failed!\n");
751                 }
752                 
753                 DEBUG(18, ("checking %s for match to pattern %s\n", key_str, pattern));
754                 
755                 next = tdb_nextkey(tdb, key);
756
757                 /* do the pattern checking */
758                 if (fnmatch(pattern, key_str, 0) == 0) {
759                         rec = SMB_MALLOC_P(TDB_LIST_NODE);
760                         ZERO_STRUCTP(rec);
761
762                         rec->node_key = key;
763         
764                         DLIST_ADD_END(list, rec, TDB_LIST_NODE *);
765                 
766                         DEBUG(18, ("checking %s matched pattern %s\n", key_str, pattern));
767                 } else {
768                         free(key.dptr);
769                 }
770                 
771                 /* free duplicated key string */
772                 free(key_str);
773         }
774         
775         return list;
776
777 }
778
779
780 /**
781  * Free the list returned by tdb_search_keys
782  *
783  * @param node list of results found by tdb_search_keys
784  **/
785 void tdb_search_list_free(TDB_LIST_NODE* node)
786 {
787         TDB_LIST_NODE *next_node;
788         
789         while (node) {
790                 next_node = node->next;
791                 SAFE_FREE(node->node_key.dptr);
792                 SAFE_FREE(node);
793                 node = next_node;
794         };
795 }
796
797 /****************************************************************************
798  tdb_store, wrapped in a transaction. This way we make sure that a process
799  that dies within writing does not leave a corrupt tdb behind.
800 ****************************************************************************/
801
802 int tdb_trans_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf,
803                     int flag)
804 {
805         int res;
806
807         if ((res = tdb_transaction_start(tdb)) != 0) {
808                 DEBUG(5, ("tdb_transaction_start failed\n"));
809                 return res;
810         }
811
812         if ((res = tdb_store(tdb, key, dbuf, flag)) != 0) {
813                 DEBUG(10, ("tdb_store failed\n"));
814                 if (tdb_transaction_cancel(tdb) != 0) {
815                         smb_panic("Cancelling transaction failed");
816                 }
817                 return res;
818         }
819
820         if ((res = tdb_transaction_commit(tdb)) != 0) {
821                 DEBUG(5, ("tdb_transaction_commit failed\n"));
822         }
823
824         return res;
825 }
826
827 /****************************************************************************
828  tdb_delete, wrapped in a transaction. This way we make sure that a process
829  that dies within deleting does not leave a corrupt tdb behind.
830 ****************************************************************************/
831
832 int tdb_trans_delete(struct tdb_context *tdb, TDB_DATA key)
833 {
834         int res;
835
836         if ((res = tdb_transaction_start(tdb)) != 0) {
837                 DEBUG(5, ("tdb_transaction_start failed\n"));
838                 return res;
839         }
840
841         if ((res = tdb_delete(tdb, key)) != 0) {
842                 DEBUG(10, ("tdb_delete failed\n"));
843                 if (tdb_transaction_cancel(tdb) != 0) {
844                         smb_panic("Cancelling transaction failed");
845                 }
846                 return res;
847         }
848
849         if ((res = tdb_transaction_commit(tdb)) != 0) {
850                 DEBUG(5, ("tdb_transaction_commit failed\n"));
851         }
852
853         return res;
854 }
855
856 /*
857  Log tdb messages via DEBUG().
858 */
859 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level, 
860                          const char *format, ...) PRINTF_ATTRIBUTE(3,4);
861
862 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level, 
863                          const char *format, ...)
864 {
865         va_list ap;
866         char *ptr = NULL;
867         int debuglevel = 0;
868
869         va_start(ap, format);
870         vasprintf(&ptr, format, ap);
871         va_end(ap);
872         
873         switch (level) {
874         case TDB_DEBUG_FATAL:
875                 debug_level = 0;
876                 break;
877         case TDB_DEBUG_ERROR:
878                 debuglevel = 1;
879                 break;
880         case TDB_DEBUG_WARNING:
881                 debuglevel = 2;
882                 break;
883         case TDB_DEBUG_TRACE:
884                 debuglevel = 5;
885                 break;
886         default:
887                 debuglevel = 0;
888         }               
889
890         if (ptr != NULL) {
891                 const char *name = tdb_name(tdb);
892                 DEBUG(debuglevel, ("tdb(%s): %s", name ? name : "unnamed", ptr));
893                 free(ptr);
894         }
895 }
896
897 static struct tdb_wrap *tdb_list;
898
899 /* destroy the last connection to a tdb */
900 static int tdb_wrap_destructor(struct tdb_wrap *w)
901 {
902         tdb_close(w->tdb);
903         DLIST_REMOVE(tdb_list, w);
904         return 0;
905 }                                
906
907 /*
908   wrapped connection to a tdb database
909   to close just talloc_free() the tdb_wrap pointer
910  */
911 struct tdb_wrap *tdb_wrap_open(TALLOC_CTX *mem_ctx,
912                                const char *name, int hash_size, int tdb_flags,
913                                int open_flags, mode_t mode)
914 {
915         struct tdb_wrap *w;
916         struct tdb_logging_context log_ctx;
917         log_ctx.log_fn = tdb_wrap_log;
918
919         if (!lp_use_mmap())
920                 tdb_flags |= TDB_NOMMAP;
921
922         for (w=tdb_list;w;w=w->next) {
923                 if (strcmp(name, w->name) == 0) {
924                         /*
925                          * Yes, talloc_reference is exactly what we want
926                          * here. Otherwise we would have to implement our own
927                          * reference counting.
928                          */
929                         return talloc_reference(mem_ctx, w);
930                 }
931         }
932
933         w = talloc(mem_ctx, struct tdb_wrap);
934         if (w == NULL) {
935                 return NULL;
936         }
937
938         if (!(w->name = talloc_strdup(w, name))) {
939                 talloc_free(w);
940                 return NULL;
941         }
942
943         if ((hash_size == 0) && (name != NULL)) {
944                 const char *base = strrchr_m(name, '/');
945                 if (base != NULL) {
946                         base += 1;
947                 }
948                 else {
949                         base = name;
950                 }
951                 hash_size = lp_parm_int(-1, "tdb_hashsize", base, 0);
952         }
953
954         w->tdb = tdb_open_ex(name, hash_size, tdb_flags, 
955                              open_flags, mode, &log_ctx, NULL);
956         if (w->tdb == NULL) {
957                 talloc_free(w);
958                 return NULL;
959         }
960
961         talloc_set_destructor(w, tdb_wrap_destructor);
962
963         DLIST_ADD(tdb_list, w);
964
965         return w;
966 }
967
968 NTSTATUS map_nt_error_from_tdb(enum TDB_ERROR err)
969 {
970         struct { enum TDB_ERROR err; NTSTATUS status; } map[] =
971                 { { TDB_SUCCESS,        NT_STATUS_OK },
972                   { TDB_ERR_CORRUPT,    NT_STATUS_INTERNAL_DB_CORRUPTION },
973                   { TDB_ERR_IO,         NT_STATUS_UNEXPECTED_IO_ERROR },
974                   { TDB_ERR_OOM,        NT_STATUS_NO_MEMORY },
975                   { TDB_ERR_EXISTS,     NT_STATUS_OBJECT_NAME_COLLISION },
976
977                   /*
978                    * TDB_ERR_LOCK is very broad, we could for example
979                    * distinguish between fcntl locks and invalid lock
980                    * sequences. So NT_STATUS_FILE_LOCK_CONFLICT is a
981                    * compromise.
982                    */
983                   { TDB_ERR_LOCK,       NT_STATUS_FILE_LOCK_CONFLICT },
984                   /*
985                    * The next two ones in the enum are not actually used
986                    */
987                   { TDB_ERR_NOLOCK,     NT_STATUS_FILE_LOCK_CONFLICT },
988                   { TDB_ERR_LOCK_TIMEOUT, NT_STATUS_FILE_LOCK_CONFLICT },
989                   { TDB_ERR_NOEXIST,    NT_STATUS_NOT_FOUND },
990                   { TDB_ERR_EINVAL,     NT_STATUS_INVALID_PARAMETER },
991                   { TDB_ERR_RDONLY,     NT_STATUS_ACCESS_DENIED }
992                 };
993
994         int i;
995
996         for (i=0; i < sizeof(map) / sizeof(map[0]); i++) {
997                 if (err == map[i].err) {
998                         return map[i].status;
999                 }
1000         }
1001
1002         return NT_STATUS_INTERNAL_ERROR;
1003 }
1004
1005
1006 /*********************************************************************
1007  * the following is a generic validation mechanism for tdbs.
1008  *********************************************************************/
1009
1010 /* 
1011  * internal validation function, executed by the child.  
1012  */
1013 static int tdb_validate_child(struct tdb_context *tdb,
1014                               tdb_validate_data_func validate_fn)
1015 {
1016         int ret = 1;
1017         int num_entries = 0;
1018         struct tdb_validation_status v_status;
1019
1020         v_status.tdb_error = False;
1021         v_status.bad_freelist = False;
1022         v_status.bad_entry = False;
1023         v_status.unknown_key = False;
1024         v_status.success = True;
1025
1026         if (!tdb) {
1027                 v_status.tdb_error = True;
1028                 v_status.success = False;
1029                 goto out;
1030         }
1031
1032         /* Check if the tdb's freelist is good. */
1033         if (tdb_validate_freelist(tdb, &num_entries) == -1) {
1034                 v_status.bad_freelist = True;
1035                 v_status.success = False;
1036                 goto out;
1037         }
1038
1039         DEBUG(10,("tdb_validate_child: tdb %s freelist has %d entries\n",
1040                   tdb_name(tdb), num_entries));
1041
1042         /* Now traverse the tdb to validate it. */
1043         num_entries = tdb_traverse(tdb, validate_fn, (void *)&v_status);
1044         if (!v_status.success) {
1045                 goto out;
1046         } else if (num_entries == -1) {
1047                 v_status.tdb_error = True;
1048                 v_status.success = False;
1049                 goto out;
1050         }
1051
1052         DEBUG(10,("tdb_validate_child: tdb %s is good with %d entries\n",
1053                   tdb_name(tdb), num_entries));
1054         ret = 0; /* Cache is good. */
1055
1056 out:
1057         DEBUG(10,   ("tdb_validate_child: summary of validation status:\n"));
1058         DEBUGADD(10,(" * tdb error: %s\n", v_status.tdb_error ? "yes" : "no"));
1059         DEBUGADD(10,(" * bad freelist: %s\n",v_status.bad_freelist?"yes":"no"));
1060         DEBUGADD(10,(" * bad entry: %s\n", v_status.bad_entry ? "yes" : "no"));
1061         DEBUGADD(10,(" * unknown key: %s\n", v_status.unknown_key?"yes":"no"));
1062         DEBUGADD(10,(" => overall success: %s\n", v_status.success?"yes":"no"));
1063
1064         return ret;
1065 }
1066
1067 /*
1068  * tdb validation function.
1069  * returns 0 if tdb is ok, != 0 if it isn't.
1070  * this function expects an opened tdb.
1071  */
1072 int tdb_validate(struct tdb_context *tdb, tdb_validate_data_func validate_fn)
1073 {
1074         pid_t child_pid = -1;
1075         int child_status = 0;
1076         int wait_pid = 0;
1077         int ret = 1;
1078
1079         if (tdb == NULL) {
1080                 DEBUG(1, ("Error: tdb_validate called with tdb == NULL\n"));
1081                 return ret;
1082         }
1083
1084         DEBUG(5, ("tdb_validate called for tdb '%s'\n", tdb_name(tdb)));
1085
1086         /* fork and let the child do the validation.
1087          * benefit: no need to twist signal handlers and panic functions.
1088          * just let the child panic. we catch the signal. */
1089
1090         DEBUG(10, ("tdb_validate: forking to let child do validation.\n"));
1091         child_pid = sys_fork();
1092         if (child_pid == 0) {
1093                 /* child code */
1094                 DEBUG(10, ("tdb_validate (validation child): created\n"));
1095                 DEBUG(10, ("tdb_validate (validation child): "
1096                            "calling tdb_validate_child\n"));
1097                 exit(tdb_validate_child(tdb, validate_fn));
1098         }
1099         else if (child_pid < 0) {
1100                 DEBUG(1, ("tdb_validate: fork for validation failed.\n"));
1101                 goto done;
1102         }
1103
1104         /* parent */
1105
1106         DEBUG(10, ("tdb_validate: fork succeeded, child PID = %d\n",child_pid));
1107
1108         DEBUG(10, ("tdb_validate: waiting for child to finish...\n"));
1109         while  ((wait_pid = sys_waitpid(child_pid, &child_status, 0)) < 0) {
1110                 if (errno == EINTR) {
1111                         DEBUG(10, ("tdb_validate: got signal during waitpid, "
1112                                    "retrying\n"));
1113                         errno = 0;
1114                         continue;
1115                 }
1116                 DEBUG(1, ("tdb_validate: waitpid failed with error '%s'.\n",
1117                           strerror(errno)));
1118                 goto done;
1119         }
1120         if (wait_pid != child_pid) {
1121                 DEBUG(1, ("tdb_validate: waitpid returned pid %d, "
1122                           "but %d was expected\n", wait_pid, child_pid));
1123                 goto done;
1124         }
1125
1126         DEBUG(10, ("tdb_validate: validating child returned.\n"));
1127         if (WIFEXITED(child_status)) {
1128                 DEBUG(10, ("tdb_validate: child exited, code %d.\n",
1129                            WEXITSTATUS(child_status)));
1130                 ret = WEXITSTATUS(child_status);
1131         }
1132         if (WIFSIGNALED(child_status)) {
1133                 DEBUG(10, ("tdb_validate: child terminated by signal %d\n",
1134                            WTERMSIG(child_status)));
1135 #ifdef WCOREDUMP
1136                 if (WCOREDUMP(child_status)) {
1137                         DEBUGADD(10, ("core dumped\n"));
1138                 }
1139 #endif
1140                 ret = WTERMSIG(child_status);
1141         }
1142         if (WIFSTOPPED(child_status)) {
1143                 DEBUG(10, ("tdb_validate: child was stopped by signal %d\n",
1144                            WSTOPSIG(child_status)));
1145                 ret = WSTOPSIG(child_status);
1146         }
1147
1148 done:
1149         DEBUG(5, ("tdb_validate returning code '%d' for tdb '%s'\n", ret,
1150                   tdb_name(tdb)));
1151
1152         return ret;
1153 }
1154
1155 /*
1156  * tdb validation function.
1157  * returns 0 if tdb is ok, != 0 if it isn't.
1158  * this is a wrapper around the actual validation function that opens and closes
1159  * the tdb.
1160  */
1161 int tdb_validate_open(const char *tdb_path, tdb_validate_data_func validate_fn)
1162 {
1163         TDB_CONTEXT *tdb = NULL;
1164         int ret = 1;
1165
1166         DEBUG(5, ("tdb_validate_open called for tdb '%s'\n", tdb_path));
1167
1168         tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDONLY, 0);
1169         if (!tdb) {
1170                 DEBUG(1, ("Error opening tdb %s\n", tdb_path));
1171                 return ret;
1172         }
1173
1174         ret = tdb_validate(tdb, validate_fn);
1175         tdb_close(tdb);
1176         return ret;
1177 }
1178
1179 /*
1180  * tdb backup function and helpers for tdb_validate wrapper with backup
1181  * handling.
1182  */
1183
1184 /* this structure eliminates the need for a global overall status for
1185  * the traverse-copy */
1186 struct tdb_copy_data {
1187         struct tdb_context *dst;
1188         bool success;
1189 };
1190
1191 static int traverse_copy_fn(struct tdb_context *tdb, TDB_DATA key,
1192                             TDB_DATA dbuf, void *private_data)
1193 {
1194         struct tdb_copy_data *data = (struct tdb_copy_data *)private_data;
1195
1196         if (tdb_store(data->dst, key, dbuf, TDB_INSERT) != 0) {
1197                 DEBUG(4, ("Failed to insert into %s: %s\n", tdb_name(data->dst),
1198                           strerror(errno)));
1199                 data->success = False;
1200                 return 1;
1201         }
1202         return 0;
1203 }
1204
1205 static int tdb_copy(struct tdb_context *src, struct tdb_context *dst)
1206 {
1207         struct tdb_copy_data data;
1208         int count;
1209
1210         data.dst = dst;
1211         data.success = True;
1212
1213         count = tdb_traverse(src, traverse_copy_fn, (void *)(&data));
1214         if ((count < 0) || (data.success == False)) {
1215                 return -1;
1216         }
1217         return count;
1218 }
1219
1220 static int tdb_verify_basic(struct tdb_context *tdb)
1221 {
1222         return tdb_traverse(tdb, NULL, NULL);
1223 }
1224
1225 /* this backup function is essentially taken from lib/tdb/tools/tdbbackup.tdb
1226  */
1227 static int tdb_backup(TALLOC_CTX *ctx, const char *src_path,
1228                       const char *dst_path, int hash_size)
1229 {
1230         struct tdb_context *src_tdb = NULL;
1231         struct tdb_context *dst_tdb = NULL;
1232         char *tmp_path = NULL;
1233         struct stat st;
1234         int count1, count2;
1235         int saved_errno = 0;
1236         int ret = -1;
1237
1238         if (stat(src_path, &st) != 0) {
1239                 DEBUG(3, ("Could not stat '%s': %s\n", src_path,
1240                           strerror(errno)));
1241                 goto done;
1242         }
1243
1244         /* open old tdb RDWR - so we can lock it */
1245         src_tdb = tdb_open_log(src_path, 0, TDB_DEFAULT, O_RDWR, 0);
1246         if (src_tdb == NULL) {
1247                 DEBUG(3, ("Failed to open tdb '%s'\n", src_path));
1248                 goto done;
1249         }
1250
1251         if (tdb_lockall(src_tdb) != 0) {
1252                 DEBUG(3, ("Failed to lock tdb '%s'\n", src_path));
1253                 goto done;
1254         }
1255
1256         tmp_path = talloc_asprintf(ctx, "%s%s", dst_path, ".tmp");
1257         unlink(tmp_path);
1258         dst_tdb = tdb_open_log(tmp_path,
1259                                hash_size ? hash_size : tdb_hash_size(src_tdb),
1260                                TDB_DEFAULT, O_RDWR | O_CREAT | O_EXCL,
1261                                st.st_mode & 0777);
1262         if (dst_tdb == NULL) {
1263                 DEBUG(3, ("Error creating tdb '%s': %s\n", tmp_path,
1264                           strerror(errno)));
1265                 saved_errno = errno;
1266                 unlink(tmp_path);
1267                 goto done;
1268         }
1269
1270         count1 = tdb_copy(src_tdb, dst_tdb);
1271         if (count1 < 0) {
1272                 DEBUG(3, ("Failed to copy tdb '%s': %s\n", src_path,
1273                           strerror(errno)));
1274                 tdb_close(dst_tdb);
1275                 goto done;
1276         }
1277
1278         /* reopen ro and do basic verification */
1279         tdb_close(dst_tdb);
1280         dst_tdb = tdb_open_log(tmp_path, 0, TDB_DEFAULT, O_RDONLY, 0);
1281         if (!dst_tdb) {
1282                 DEBUG(3, ("Failed to reopen tdb '%s': %s\n", tmp_path,
1283                           strerror(errno)));
1284                 goto done;
1285         }
1286         count2 = tdb_verify_basic(dst_tdb);
1287         if (count2 != count1) {
1288                 DEBUG(3, ("Failed to verify result of copying tdb '%s'.\n",
1289                           src_path));
1290                 tdb_close(dst_tdb);
1291                 goto done;
1292         }
1293
1294         DEBUG(10, ("tdb_backup: successfully copied %d entries\n", count1));
1295
1296         /* make sure the new tdb has reached stable storage
1297          * then rename it to its destination */
1298         fsync(tdb_fd(dst_tdb));
1299         tdb_close(dst_tdb);
1300         unlink(dst_path);
1301         if (rename(tmp_path, dst_path) != 0) {
1302                 DEBUG(3, ("Failed to rename '%s' to '%s': %s\n",
1303                           tmp_path, dst_path, strerror(errno)));
1304                 goto done;
1305         }
1306
1307         /* success */
1308         ret = 0;
1309
1310 done:
1311         if (src_tdb != NULL) {
1312                 tdb_close(src_tdb);
1313         }
1314         if (tmp_path != NULL) {
1315                 unlink(tmp_path);
1316                 TALLOC_FREE(tmp_path);
1317         }
1318         if (saved_errno != 0) {
1319                 errno = saved_errno;
1320         }
1321         return ret;
1322 }
1323
1324 static int rename_file_with_suffix(TALLOC_CTX *ctx, const char *path,
1325                                    const char *suffix)
1326 {
1327         int ret = -1;
1328         char *dst_path;
1329
1330         dst_path = talloc_asprintf(ctx, "%s%s", path, suffix);
1331
1332         ret = (rename(path, dst_path) != 0);
1333
1334         if (ret == 0) {
1335                 DEBUG(5, ("moved '%s' to '%s'\n", path, dst_path));
1336         } else if (errno == ENOENT) {
1337                 DEBUG(3, ("file '%s' does not exist - so not moved\n", path));
1338                 ret = 0;
1339         } else {
1340                 DEBUG(3, ("error renaming %s to %s: %s\n", path, dst_path,
1341                           strerror(errno)));
1342         }
1343
1344         TALLOC_FREE(dst_path);
1345         return ret;
1346 }
1347
1348 /*
1349  * do a backup of a tdb, moving the destination out of the way first
1350  */
1351 static int tdb_backup_with_rotate(TALLOC_CTX *ctx, const char *src_path,
1352                                   const char *dst_path, int hash_size,
1353                                   const char *rotate_suffix,
1354                                   bool retry_norotate_if_nospc,
1355                                   bool rename_as_last_resort_if_nospc)
1356 {
1357         int ret;
1358
1359         rename_file_with_suffix(ctx, dst_path, rotate_suffix);
1360
1361         ret = tdb_backup(ctx, src_path, dst_path, hash_size);
1362
1363         if (ret != 0) {
1364                 DEBUG(10, ("backup of %s failed: %s\n", src_path, strerror(errno)));
1365         }
1366         if ((ret != 0) && (errno == ENOSPC) && retry_norotate_if_nospc)
1367         {
1368                 char *rotate_path = talloc_asprintf(ctx, "%s%s", dst_path,
1369                                                     rotate_suffix);
1370                 DEBUG(10, ("backup of %s failed due to lack of space\n",
1371                            src_path));
1372                 DEBUGADD(10, ("trying to free some space by removing rotated "
1373                               "dst %s\n", rotate_path));
1374                 if (unlink(rotate_path) == -1) {
1375                         DEBUG(10, ("unlink of %s failed: %s\n", rotate_path,
1376                                    strerror(errno)));
1377                 } else {
1378                         ret = tdb_backup(ctx, src_path, dst_path, hash_size);
1379                 }
1380                 TALLOC_FREE(rotate_path);
1381         }
1382
1383         if ((ret != 0) && (errno == ENOSPC) && rename_as_last_resort_if_nospc)
1384         {
1385                 DEBUG(10, ("backup of %s failed due to lack of space\n", 
1386                            src_path));
1387                 DEBUGADD(10, ("using 'rename' as a last resort\n"));
1388                 ret = rename(src_path, dst_path);
1389         }
1390
1391         return ret;
1392 }
1393
1394 /*
1395  * validation function with backup handling:
1396  *
1397  *  - calls tdb_validate
1398  *  - if the tdb is ok, create a backup "name.bak", possibly moving
1399  *    existing backup to name.bak.old,
1400  *    return 0 (success) even if the backup fails
1401  *  - if the tdb is corrupt:
1402  *    - move the tdb to "name.corrupt"
1403  *    - check if there is valid backup.
1404  *      if so, restore the backup.
1405  *      if restore is successful, return 0 (success),
1406  *    - otherwise return -1 (failure)
1407  */
1408 int tdb_validate_and_backup(const char *tdb_path,
1409                             tdb_validate_data_func validate_fn)
1410 {
1411         int ret = -1;
1412         const char *backup_suffix = ".bak";
1413         const char *corrupt_suffix = ".corrupt";
1414         const char *rotate_suffix = ".old";
1415         char *tdb_path_backup;
1416         struct stat st;
1417         TALLOC_CTX *ctx = NULL;
1418
1419         ctx = talloc_new(NULL);
1420         if (ctx == NULL) {
1421                 DEBUG(0, ("tdb_validate_and_backup: out of memory\n"));
1422                 goto done;
1423         }
1424
1425         tdb_path_backup = talloc_asprintf(ctx, "%s%s", tdb_path, backup_suffix);
1426
1427         ret = tdb_validate_open(tdb_path, validate_fn);
1428
1429         if (ret == 0) {
1430                 DEBUG(1, ("tdb '%s' is valid\n", tdb_path));
1431                 ret = tdb_backup_with_rotate(ctx, tdb_path, tdb_path_backup, 0,
1432                                              rotate_suffix, True, False);
1433                 if (ret != 0) {
1434                         DEBUG(1, ("Error creating backup of tdb '%s'\n",
1435                                   tdb_path));
1436                         /* the actual validation was successful: */
1437                         ret = 0;
1438                 } else {
1439                         DEBUG(1, ("Created backup '%s' of tdb '%s'\n",
1440                                   tdb_path_backup, tdb_path));
1441                 }
1442         } else {
1443                 DEBUG(1, ("tdb '%s' is invalid\n", tdb_path));
1444
1445                 ret =stat(tdb_path_backup, &st);
1446                 if (ret != 0) {
1447                         DEBUG(5, ("Could not stat '%s': %s\n", tdb_path_backup,
1448                                   strerror(errno)));
1449                         DEBUG(1, ("No backup found.\n"));
1450                 } else {
1451                         DEBUG(1, ("backup '%s' found.\n", tdb_path_backup));
1452                         ret = tdb_validate_open(tdb_path_backup, validate_fn);
1453                         if (ret != 0) {
1454                                 DEBUG(1, ("Backup '%s' is invalid.\n",
1455                                           tdb_path_backup));
1456                         }
1457                 }
1458
1459                 if (ret != 0) {
1460                         int renamed = rename_file_with_suffix(ctx, tdb_path,
1461                                                               corrupt_suffix);
1462                         if (renamed != 0) {
1463                                 DEBUG(1, ("Error moving tdb to '%s%s'\n",
1464                                           tdb_path, corrupt_suffix));
1465                         } else {
1466                                 DEBUG(1, ("Corrupt tdb stored as '%s%s'\n",
1467                                           tdb_path, corrupt_suffix));
1468                         }
1469                         goto done;
1470                 }
1471
1472                 DEBUG(1, ("valid backup '%s' found\n", tdb_path_backup));
1473                 ret = tdb_backup_with_rotate(ctx, tdb_path_backup, tdb_path, 0,
1474                                              corrupt_suffix, True, True);
1475                 if (ret != 0) {
1476                         DEBUG(1, ("Error restoring backup from '%s'\n",
1477                                   tdb_path_backup));
1478                 } else {
1479                         DEBUG(1, ("Restored tdb backup from '%s'\n",
1480                                   tdb_path_backup));
1481                 }
1482         }
1483
1484 done:
1485         TALLOC_FREE(ctx);
1486         return ret;
1487 }