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