2 Unix SMB/CIFS implementation.
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Rafal Szczesniak 2002
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.
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.
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/>.
27 /* these are little tdb utility functions that are meant to make
28 dealing with a tdb database a little less cumbersome in Samba */
30 static SIG_ATOMIC_T gotalarm;
32 /***************************************************************
33 Signal function to tell us we timed out.
34 ****************************************************************/
36 static void gotalarm_sig(void)
41 /***************************************************************
42 Make a TDB_DATA and keep the const warning in one place
43 ****************************************************************/
45 TDB_DATA make_tdb_data(const uint8 *dptr, size_t dsize)
48 ret.dptr = CONST_DISCARD(uint8 *, dptr);
53 TDB_DATA string_tdb_data(const char *string)
55 return make_tdb_data((const uint8 *)string, string ? strlen(string) : 0 );
58 TDB_DATA string_term_tdb_data(const char *string)
60 return make_tdb_data((const uint8 *)string, string ? strlen(string) + 1 : 0);
63 /****************************************************************************
64 Lock a chain with timeout (in seconds).
65 ****************************************************************************/
67 static int tdb_chainlock_with_timeout_internal( TDB_CONTEXT *tdb, TDB_DATA key, unsigned int timeout, int rw_type)
69 /* Allow tdb_chainlock to be interrupted by an alarm. */
74 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
75 tdb_setalarm_sigptr(tdb, &gotalarm);
79 if (rw_type == F_RDLCK)
80 ret = tdb_chainlock_read(tdb, key);
82 ret = tdb_chainlock(tdb, key);
86 tdb_setalarm_sigptr(tdb, NULL);
87 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
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 */
102 /****************************************************************************
103 Write lock a chain. Return -1 if timeout or lock failed.
104 ****************************************************************************/
106 int tdb_chainlock_with_timeout( TDB_CONTEXT *tdb, TDB_DATA key, unsigned int timeout)
108 return tdb_chainlock_with_timeout_internal(tdb, key, timeout, F_WRLCK);
111 /****************************************************************************
112 Lock a chain by string. Return -1 if timeout or lock failed.
113 ****************************************************************************/
115 int tdb_lock_bystring(TDB_CONTEXT *tdb, const char *keyval)
117 TDB_DATA key = string_term_tdb_data(keyval);
119 return tdb_chainlock(tdb, key);
122 int tdb_lock_bystring_with_timeout(TDB_CONTEXT *tdb, const char *keyval,
125 TDB_DATA key = string_term_tdb_data(keyval);
127 return tdb_chainlock_with_timeout(tdb, key, timeout);
130 /****************************************************************************
131 Unlock a chain by string.
132 ****************************************************************************/
134 void tdb_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
136 TDB_DATA key = string_term_tdb_data(keyval);
138 tdb_chainunlock(tdb, key);
141 /****************************************************************************
142 Read lock a chain by string. Return -1 if timeout or lock failed.
143 ****************************************************************************/
145 int tdb_read_lock_bystring_with_timeout(TDB_CONTEXT *tdb, const char *keyval, unsigned int timeout)
147 TDB_DATA key = string_term_tdb_data(keyval);
149 return tdb_chainlock_with_timeout_internal(tdb, key, timeout, F_RDLCK);
152 /****************************************************************************
153 Read unlock a chain by string.
154 ****************************************************************************/
156 void tdb_read_unlock_bystring(TDB_CONTEXT *tdb, const char *keyval)
158 TDB_DATA key = string_term_tdb_data(keyval);
160 tdb_chainunlock_read(tdb, key);
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 ****************************************************************************/
169 int32 tdb_fetch_int32_byblob(TDB_CONTEXT *tdb, TDB_DATA key)
174 data = tdb_fetch(tdb, key);
175 if (!data.dptr || data.dsize != sizeof(int32)) {
176 SAFE_FREE(data.dptr);
180 ret = IVAL(data.dptr,0);
181 SAFE_FREE(data.dptr);
185 /****************************************************************************
186 Fetch a int32 value by string key, return -1 if not found.
187 Output is int32 in native byte order.
188 ****************************************************************************/
190 int32 tdb_fetch_int32(TDB_CONTEXT *tdb, const char *keystr)
192 TDB_DATA key = string_term_tdb_data(keystr);
194 return tdb_fetch_int32_byblob(tdb, key);
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 ****************************************************************************/
202 int tdb_store_int32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, int32 v)
208 data.dptr = (uint8 *)&v_store;
209 data.dsize = sizeof(int32);
211 return tdb_store(tdb, key, data, TDB_REPLACE);
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 ****************************************************************************/
219 int tdb_store_int32(TDB_CONTEXT *tdb, const char *keystr, int32 v)
221 TDB_DATA key = string_term_tdb_data(keystr);
223 return tdb_store_int32_byblob(tdb, key, v);
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 ****************************************************************************/
231 bool tdb_fetch_uint32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, uint32 *value)
235 data = tdb_fetch(tdb, key);
236 if (!data.dptr || data.dsize != sizeof(uint32)) {
237 SAFE_FREE(data.dptr);
241 *value = IVAL(data.dptr,0);
242 SAFE_FREE(data.dptr);
246 /****************************************************************************
247 Fetch a uint32 value by string key, return -1 if not found.
248 Output is uint32 in native byte order.
249 ****************************************************************************/
251 bool tdb_fetch_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 *value)
253 TDB_DATA key = string_term_tdb_data(keystr);
255 return tdb_fetch_uint32_byblob(tdb, key, value);
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 ****************************************************************************/
263 bool tdb_store_uint32_byblob(TDB_CONTEXT *tdb, TDB_DATA key, uint32 value)
269 SIVAL(&v_store, 0, value);
270 data.dptr = (uint8 *)&v_store;
271 data.dsize = sizeof(uint32);
273 if (tdb_store(tdb, key, data, TDB_REPLACE) == -1)
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 ****************************************************************************/
284 bool tdb_store_uint32(TDB_CONTEXT *tdb, const char *keystr, uint32 value)
286 TDB_DATA key = string_term_tdb_data(keystr);
288 return tdb_store_uint32_byblob(tdb, key, value);
290 /****************************************************************************
291 Store a buffer by a null terminated string key. Return 0 on success, -1
293 ****************************************************************************/
295 int tdb_store_bystring(TDB_CONTEXT *tdb, const char *keystr, TDB_DATA data, int flags)
297 TDB_DATA key = string_term_tdb_data(keystr);
299 return tdb_store(tdb, key, data, flags);
302 int tdb_trans_store_bystring(TDB_CONTEXT *tdb, const char *keystr,
303 TDB_DATA data, int flags)
305 TDB_DATA key = string_term_tdb_data(keystr);
307 return tdb_trans_store(tdb, key, data, flags);
310 /****************************************************************************
311 Fetch a buffer using a null terminated string key. Don't forget to call
312 free() on the result dptr.
313 ****************************************************************************/
315 TDB_DATA tdb_fetch_bystring(TDB_CONTEXT *tdb, const char *keystr)
317 TDB_DATA key = string_term_tdb_data(keystr);
319 return tdb_fetch(tdb, key);
322 /****************************************************************************
323 Delete an entry using a null terminated string key.
324 ****************************************************************************/
326 int tdb_delete_bystring(TDB_CONTEXT *tdb, const char *keystr)
328 TDB_DATA key = string_term_tdb_data(keystr);
330 return tdb_delete(tdb, key);
333 /****************************************************************************
334 Atomic integer change. Returns old value. To create, set initial value in *oldval.
335 ****************************************************************************/
337 int32 tdb_change_int32_atomic(TDB_CONTEXT *tdb, const char *keystr, int32 *oldval, int32 change_val)
342 if (tdb_lock_bystring(tdb, keystr) == -1)
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 */
352 /* Start with 'old' value */
356 /* It worked, set return value (oldval) to tdb data */
360 /* Increment value for storage and return next time */
363 if (tdb_store_int32(tdb, keystr, val) == -1)
370 tdb_unlock_bystring(tdb, keystr);
374 /****************************************************************************
375 Atomic unsigned integer change. Returns old value. To create, set initial value in *oldval.
376 ****************************************************************************/
378 bool tdb_change_uint32_atomic(TDB_CONTEXT *tdb, const char *keystr, uint32 *oldval, uint32 change_val)
383 if (tdb_lock_bystring(tdb, keystr) == -1)
386 if (!tdb_fetch_uint32(tdb, keystr, &val)) {
388 if (tdb_error(tdb) != TDB_ERR_NOEXIST) {
389 /* and not because it didn't exist */
393 /* Start with 'old' value */
397 /* it worked, set return value (oldval) to tdb data */
402 /* get a new value to store */
405 if (!tdb_store_uint32(tdb, keystr, val))
412 tdb_unlock_bystring(tdb, keystr);
416 /****************************************************************************
417 Useful pair of routines for packing/unpacking data consisting of
418 integers and strings.
419 ****************************************************************************/
421 size_t tdb_pack_va(uint8 *buf, int bufsize, const char *fmt, va_list ap)
432 const char *fmt0 = fmt;
433 int bufsize0 = bufsize;
436 switch ((c = *fmt++)) {
437 case 'b': /* unsigned 8-bit integer */
439 bt = (uint8)va_arg(ap, int);
440 if (bufsize && bufsize >= len)
443 case 'w': /* unsigned 16-bit integer */
445 w = (uint16)va_arg(ap, int);
446 if (bufsize && bufsize >= len)
449 case 'd': /* signed 32-bit integer (standard int in most systems) */
451 d = va_arg(ap, uint32);
452 if (bufsize && bufsize >= len)
455 case 'p': /* pointer */
457 p = va_arg(ap, void *);
459 if (bufsize && bufsize >= len)
462 case 'P': /* null-terminated string */
463 s = va_arg(ap,char *);
466 if (bufsize && bufsize >= len)
469 case 'f': /* null-terminated string */
470 s = va_arg(ap,char *);
473 if (bufsize && bufsize >= len)
476 case 'B': /* fixed-length string */
478 s = va_arg(ap, char *);
480 if (bufsize && bufsize >= len) {
486 DEBUG(0,("Unknown tdb_pack format %c in %s\n",
499 DEBUG(18,("tdb_pack_va(%s, %d) -> %d\n",
500 fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
502 return PTR_DIFF(buf, buf0);
505 size_t tdb_pack(uint8 *buf, int bufsize, const char *fmt, ...)
511 result = tdb_pack_va(buf, bufsize, fmt, ap);
516 bool tdb_pack_append(TALLOC_CTX *mem_ctx, uint8 **buf, size_t *len,
517 const char *fmt, ...)
523 len1 = tdb_pack_va(NULL, 0, fmt, ap);
526 if (mem_ctx != NULL) {
527 *buf = TALLOC_REALLOC_ARRAY(mem_ctx, *buf, uint8,
530 *buf = SMB_REALLOC_ARRAY(*buf, uint8, (*len) + len1);
538 len2 = tdb_pack_va((*buf)+(*len), len1, fmt, ap);
550 /****************************************************************************
551 Useful pair of routines for packing/unpacking data consisting of
552 integers and strings.
553 ****************************************************************************/
555 int tdb_unpack(const uint8 *buf, int bufsize, const char *fmt, ...)
566 const uint8 *buf0 = buf;
567 const char *fmt0 = fmt;
568 int bufsize0 = bufsize;
573 switch ((c=*fmt++)) {
576 bt = va_arg(ap, uint8 *);
583 w = va_arg(ap, uint16 *);
590 d = va_arg(ap, uint32 *);
597 p = va_arg(ap, void **);
601 * This isn't a real pointer - only a token (1 or 0)
602 * to mark the fact a pointer is present.
605 *p = (void *)(IVAL(buf, 0) ? (void *)1 : NULL);
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);
614 s = va_arg(ap,char *);
615 len = strlen((const char *)buf) + 1;
616 if (bufsize < len || len > sizeof(fstring))
621 i = va_arg(ap, int *);
622 b = va_arg(ap, char **);
634 *b = (char *)SMB_MALLOC(*i);
637 memcpy(*b, buf+4, *i);
640 DEBUG(0,("Unknown tdb_unpack format %c in %s\n",
653 DEBUG(18,("tdb_unpack(%s, %d) -> %d\n",
654 fmt0, bufsize0, (int)PTR_DIFF(buf, buf0)));
656 return PTR_DIFF(buf, buf0);
663 /****************************************************************************
664 Log tdb messages via DEBUG().
665 ****************************************************************************/
667 static void tdb_log(TDB_CONTEXT *tdb, enum tdb_debug_level level, const char *format, ...)
672 va_start(ap, format);
673 vasprintf(&ptr, format, ap);
679 DEBUG((int)level, ("tdb(%s): %s", tdb_name(tdb) ? tdb_name(tdb) : "unnamed", ptr));
683 /****************************************************************************
684 Like tdb_open() but also setup a logging function that redirects to
685 the samba DEBUG() system.
686 ****************************************************************************/
688 TDB_CONTEXT *tdb_open_log(const char *name, int hash_size, int tdb_flags,
689 int open_flags, mode_t mode)
692 struct tdb_logging_context log_ctx;
695 tdb_flags |= TDB_NOMMAP;
697 log_ctx.log_fn = tdb_log;
698 log_ctx.log_private = NULL;
700 if ((hash_size == 0) && (name != NULL)) {
701 const char *base = strrchr_m(name, '/');
708 hash_size = lp_parm_int(-1, "tdb_hashsize", base, 0);
711 tdb = tdb_open_ex(name, hash_size, tdb_flags,
712 open_flags, mode, &log_ctx, NULL);
719 /****************************************************************************
720 Allow tdb_delete to be used as a tdb_traversal_fn.
721 ****************************************************************************/
723 int tdb_traverse_delete_fn(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf,
726 return tdb_delete(the_tdb, key);
732 * Search across the whole tdb for keys that match the given pattern
733 * return the result as a list of keys
735 * @param tdb pointer to opened tdb file context
736 * @param pattern searching pattern used by fnmatch(3) functions
738 * @return list of keys found by looking up with given pattern
740 TDB_LIST_NODE *tdb_search_keys(TDB_CONTEXT *tdb, const char* pattern)
743 TDB_LIST_NODE *list = NULL;
744 TDB_LIST_NODE *rec = NULL;
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);
750 DEBUG(0, ("tdb_search_keys: strndup() failed!\n"));
751 smb_panic("strndup failed!\n");
754 DEBUG(18, ("checking %s for match to pattern %s\n", key_str, pattern));
756 next = tdb_nextkey(tdb, key);
758 /* do the pattern checking */
759 if (fnmatch(pattern, key_str, 0) == 0) {
760 rec = SMB_MALLOC_P(TDB_LIST_NODE);
765 DLIST_ADD_END(list, rec, TDB_LIST_NODE *);
767 DEBUG(18, ("checking %s matched pattern %s\n", key_str, pattern));
772 /* free duplicated key string */
782 * Free the list returned by tdb_search_keys
784 * @param node list of results found by tdb_search_keys
786 void tdb_search_list_free(TDB_LIST_NODE* node)
788 TDB_LIST_NODE *next_node;
791 next_node = node->next;
792 SAFE_FREE(node->node_key.dptr);
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 ****************************************************************************/
803 int tdb_trans_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf,
808 if ((res = tdb_transaction_start(tdb)) != 0) {
809 DEBUG(5, ("tdb_transaction_start failed\n"));
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");
821 if ((res = tdb_transaction_commit(tdb)) != 0) {
822 DEBUG(5, ("tdb_transaction_commit failed\n"));
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 ****************************************************************************/
833 int tdb_trans_delete(struct tdb_context *tdb, TDB_DATA key)
837 if ((res = tdb_transaction_start(tdb)) != 0) {
838 DEBUG(5, ("tdb_transaction_start failed\n"));
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");
850 if ((res = tdb_transaction_commit(tdb)) != 0) {
851 DEBUG(5, ("tdb_transaction_commit failed\n"));
858 Log tdb messages via DEBUG().
860 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level,
861 const char *format, ...) PRINTF_ATTRIBUTE(3,4);
863 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level,
864 const char *format, ...)
870 va_start(ap, format);
871 vasprintf(&ptr, format, ap);
875 case TDB_DEBUG_FATAL:
878 case TDB_DEBUG_ERROR:
881 case TDB_DEBUG_WARNING:
884 case TDB_DEBUG_TRACE:
892 const char *name = tdb_name(tdb);
893 DEBUG(debuglevel, ("tdb(%s): %s", name ? name : "unnamed", ptr));
898 static struct tdb_wrap *tdb_list;
900 /* destroy the last connection to a tdb */
901 static int tdb_wrap_destructor(struct tdb_wrap *w)
904 DLIST_REMOVE(tdb_list, w);
909 wrapped connection to a tdb database
910 to close just talloc_free() the tdb_wrap pointer
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)
917 struct tdb_logging_context log_ctx;
918 log_ctx.log_fn = tdb_wrap_log;
921 tdb_flags |= TDB_NOMMAP;
923 for (w=tdb_list;w;w=w->next) {
924 if (strcmp(name, w->name) == 0) {
926 * Yes, talloc_reference is exactly what we want
927 * here. Otherwise we would have to implement our own
928 * reference counting.
930 return talloc_reference(mem_ctx, w);
934 w = talloc(mem_ctx, struct tdb_wrap);
939 if (!(w->name = talloc_strdup(w, name))) {
944 if ((hash_size == 0) && (name != NULL)) {
945 const char *base = strrchr_m(name, '/');
952 hash_size = lp_parm_int(-1, "tdb_hashsize", base, 0);
955 w->tdb = tdb_open_ex(name, hash_size, tdb_flags,
956 open_flags, mode, &log_ctx, NULL);
957 if (w->tdb == NULL) {
962 talloc_set_destructor(w, tdb_wrap_destructor);
964 DLIST_ADD(tdb_list, w);
969 NTSTATUS map_nt_error_from_tdb(enum TDB_ERROR err)
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 },
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
984 { TDB_ERR_LOCK, NT_STATUS_FILE_LOCK_CONFLICT },
986 * The next two ones in the enum are not actually used
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 }
997 for (i=0; i < sizeof(map) / sizeof(map[0]); i++) {
998 if (err == map[i].err) {
999 return map[i].status;
1003 return NT_STATUS_INTERNAL_ERROR;
1007 /*********************************************************************
1008 * the following is a generic validation mechanism for tdbs.
1009 *********************************************************************/
1012 * internal validation function, executed by the child.
1014 static int tdb_validate_child(struct tdb_context *tdb,
1015 tdb_validate_data_func validate_fn)
1018 int num_entries = 0;
1019 struct tdb_validation_status v_status;
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;
1028 v_status.tdb_error = True;
1029 v_status.success = False;
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;
1040 DEBUG(10,("tdb_validate_child: tdb %s freelist has %d entries\n",
1041 tdb_name(tdb), num_entries));
1043 /* Now traverse the tdb to validate it. */
1044 num_entries = tdb_traverse(tdb, validate_fn, (void *)&v_status);
1045 if (!v_status.success) {
1047 } else if (num_entries == -1) {
1048 v_status.tdb_error = True;
1049 v_status.success = False;
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. */
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"));
1069 * tdb validation function.
1070 * returns 0 if tdb is ok, != 0 if it isn't.
1071 * this function expects an opened tdb.
1073 int tdb_validate(struct tdb_context *tdb, tdb_validate_data_func validate_fn)
1075 pid_t child_pid = -1;
1076 int child_status = 0;
1081 DEBUG(1, ("Error: tdb_validate called with tdb == NULL\n"));
1085 DEBUG(5, ("tdb_validate called for tdb '%s'\n", tdb_name(tdb)));
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. */
1091 DEBUG(10, ("tdb_validate: forking to let child do validation.\n"));
1092 child_pid = sys_fork();
1093 if (child_pid == 0) {
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));
1100 else if (child_pid < 0) {
1101 DEBUG(1, ("tdb_validate: fork for validation failed.\n"));
1107 DEBUG(10, ("tdb_validate: fork succeeded, child PID = %d\n",child_pid));
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, "
1117 DEBUG(1, ("tdb_validate: waitpid failed with error '%s'.\n",
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));
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);
1133 if (WIFSIGNALED(child_status)) {
1134 DEBUG(10, ("tdb_validate: child terminated by signal %d\n",
1135 WTERMSIG(child_status)));
1137 if (WCOREDUMP(child_status)) {
1138 DEBUGADD(10, ("core dumped\n"));
1141 ret = WTERMSIG(child_status);
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);
1150 DEBUG(5, ("tdb_validate returning code '%d' for tdb '%s'\n", ret,
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
1162 int tdb_validate_open(const char *tdb_path, tdb_validate_data_func validate_fn)
1164 TDB_CONTEXT *tdb = NULL;
1167 DEBUG(5, ("tdb_validate_open called for tdb '%s'\n", tdb_path));
1169 tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDONLY, 0);
1171 DEBUG(1, ("Error opening tdb %s\n", tdb_path));
1175 ret = tdb_validate(tdb, validate_fn);
1181 * tdb backup function and helpers for tdb_validate wrapper with backup
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;
1192 static int traverse_copy_fn(struct tdb_context *tdb, TDB_DATA key,
1193 TDB_DATA dbuf, void *private_data)
1195 struct tdb_copy_data *data = (struct tdb_copy_data *)private_data;
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),
1200 data->success = False;
1206 static int tdb_copy(struct tdb_context *src, struct tdb_context *dst)
1208 struct tdb_copy_data data;
1212 data.success = True;
1214 count = tdb_traverse(src, traverse_copy_fn, (void *)(&data));
1215 if ((count < 0) || (data.success == False)) {
1221 static int tdb_verify_basic(struct tdb_context *tdb)
1223 return tdb_traverse(tdb, NULL, NULL);
1226 /* this backup function is essentially taken from lib/tdb/tools/tdbbackup.tdb
1228 static int tdb_backup(TALLOC_CTX *ctx, const char *src_path,
1229 const char *dst_path, int hash_size)
1231 struct tdb_context *src_tdb = NULL;
1232 struct tdb_context *dst_tdb = NULL;
1233 char *tmp_path = NULL;
1236 int saved_errno = 0;
1239 if (stat(src_path, &st) != 0) {
1240 DEBUG(3, ("Could not stat '%s': %s\n", src_path,
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));
1252 if (tdb_lockall(src_tdb) != 0) {
1253 DEBUG(3, ("Failed to lock tdb '%s'\n", src_path));
1257 tmp_path = talloc_asprintf(ctx, "%s%s", dst_path, ".tmp");
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,
1263 if (dst_tdb == NULL) {
1264 DEBUG(3, ("Error creating tdb '%s': %s\n", tmp_path,
1266 saved_errno = errno;
1271 count1 = tdb_copy(src_tdb, dst_tdb);
1273 DEBUG(3, ("Failed to copy tdb '%s': %s\n", src_path,
1279 /* reopen ro and do basic verification */
1281 dst_tdb = tdb_open_log(tmp_path, 0, TDB_DEFAULT, O_RDONLY, 0);
1283 DEBUG(3, ("Failed to reopen tdb '%s': %s\n", tmp_path,
1287 count2 = tdb_verify_basic(dst_tdb);
1288 if (count2 != count1) {
1289 DEBUG(3, ("Failed to verify result of copying tdb '%s'.\n",
1295 DEBUG(10, ("tdb_backup: successfully copied %d entries\n", count1));
1297 /* make sure the new tdb has reached stable storage
1298 * then rename it to its destination */
1299 fsync(tdb_fd(dst_tdb));
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)));
1312 if (src_tdb != NULL) {
1315 if (tmp_path != NULL) {
1317 TALLOC_FREE(tmp_path);
1319 if (saved_errno != 0) {
1320 errno = saved_errno;
1325 static int rename_file_with_suffix(TALLOC_CTX *ctx, const char *path,
1331 dst_path = talloc_asprintf(ctx, "%s%s", path, suffix);
1333 ret = (rename(path, dst_path) != 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));
1341 DEBUG(3, ("error renaming %s to %s: %s\n", path, dst_path,
1345 TALLOC_FREE(dst_path);
1350 * do a backup of a tdb, moving the destination out of the way first
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)
1360 rename_file_with_suffix(ctx, dst_path, rotate_suffix);
1362 ret = tdb_backup(ctx, src_path, dst_path, hash_size);
1365 DEBUG(10, ("backup of %s failed: %s\n", src_path, strerror(errno)));
1367 if ((ret != 0) && (errno == ENOSPC) && retry_norotate_if_nospc)
1369 char *rotate_path = talloc_asprintf(ctx, "%s%s", dst_path,
1371 DEBUG(10, ("backup of %s failed due to lack of space\n",
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,
1379 ret = tdb_backup(ctx, src_path, dst_path, hash_size);
1381 TALLOC_FREE(rotate_path);
1384 if ((ret != 0) && (errno == ENOSPC) && rename_as_last_resort_if_nospc)
1386 DEBUG(10, ("backup of %s failed due to lack of space\n",
1388 DEBUGADD(10, ("using 'rename' as a last resort\n"));
1389 ret = rename(src_path, dst_path);
1396 * validation function with backup handling:
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)
1409 int tdb_validate_and_backup(const char *tdb_path,
1410 tdb_validate_data_func validate_fn)
1413 const char *backup_suffix = ".bak";
1414 const char *corrupt_suffix = ".corrupt";
1415 const char *rotate_suffix = ".old";
1416 char *tdb_path_backup;
1418 TALLOC_CTX *ctx = NULL;
1420 ctx = talloc_new(NULL);
1422 DEBUG(0, ("tdb_validate_and_backup: out of memory\n"));
1426 tdb_path_backup = talloc_asprintf(ctx, "%s%s", tdb_path, backup_suffix);
1428 ret = tdb_validate_open(tdb_path, validate_fn);
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);
1435 DEBUG(1, ("Error creating backup of tdb '%s'\n",
1437 /* the actual validation was successful: */
1440 DEBUG(1, ("Created backup '%s' of tdb '%s'\n",
1441 tdb_path_backup, tdb_path));
1444 DEBUG(1, ("tdb '%s' is invalid\n", tdb_path));
1446 ret =stat(tdb_path_backup, &st);
1448 DEBUG(5, ("Could not stat '%s': %s\n", tdb_path_backup,
1450 DEBUG(1, ("No backup found.\n"));
1452 DEBUG(1, ("backup '%s' found.\n", tdb_path_backup));
1453 ret = tdb_validate_open(tdb_path_backup, validate_fn);
1455 DEBUG(1, ("Backup '%s' is invalid.\n",
1461 int renamed = rename_file_with_suffix(ctx, tdb_path,
1464 DEBUG(1, ("Error moving tdb to '%s%s'\n",
1465 tdb_path, corrupt_suffix));
1467 DEBUG(1, ("Corrupt tdb stored as '%s%s'\n",
1468 tdb_path, corrupt_suffix));
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);
1477 DEBUG(1, ("Error restoring backup from '%s'\n",
1480 DEBUG(1, ("Restored tdb backup from '%s'\n",