idmap-autorid: Slightly simplify idmap_autorid_get_domainrange
[Samba.git] / source4 / lib / tdb_wrap.c
blob97294e13d30b53f0541b3e9e7dd3932a28adf4da
1 /*
2 Unix SMB/CIFS implementation.
3 TDB wrap functions
5 Copyright (C) Andrew Tridgell 2004
6 Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include <tdb.h>
24 #include "../lib/util/dlinklist.h"
25 #include "tdb_wrap.h"
26 #include <tdb.h>
28 static struct tdb_wrap *tdb_list;
30 /* destroy the last connection to a tdb */
31 static int tdb_wrap_destructor(struct tdb_wrap *w)
33 tdb_close(w->tdb);
34 DLIST_REMOVE(tdb_list, w);
35 return 0;
39 Log tdb messages via DEBUG().
41 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level,
42 const char *format, ...) PRINTF_ATTRIBUTE(3,4);
44 static void tdb_wrap_log(TDB_CONTEXT *tdb, enum tdb_debug_level level,
45 const char *format, ...)
47 va_list ap;
48 char *ptr = NULL;
49 int dl;
51 va_start(ap, format);
52 vasprintf(&ptr, format, ap);
53 va_end(ap);
55 switch (level) {
56 case TDB_DEBUG_FATAL:
57 dl = 0;
58 break;
59 case TDB_DEBUG_ERROR:
60 dl = 1;
61 break;
62 case TDB_DEBUG_WARNING:
63 dl = 2;
64 break;
65 case TDB_DEBUG_TRACE:
66 dl = 5;
67 break;
68 default:
69 dl = 0;
72 if (ptr != NULL) {
73 const char *name = tdb_name(tdb);
74 DEBUG(dl, ("tdb(%s): %s", name ? name : "unnamed", ptr));
75 free(ptr);
81 wrapped connection to a tdb database
82 to close just talloc_free() the tdb_wrap pointer
84 struct tdb_wrap *tdb_wrap_open(TALLOC_CTX *mem_ctx,
85 const char *name, int hash_size, int tdb_flags,
86 int open_flags, mode_t mode)
88 struct tdb_wrap *w;
89 struct tdb_logging_context log_ctx;
90 log_ctx.log_fn = tdb_wrap_log;
92 for (w=tdb_list;w;w=w->next) {
93 if (strcmp(name, w->name) == 0) {
94 return talloc_reference(mem_ctx, w);
98 w = talloc(mem_ctx, struct tdb_wrap);
99 if (w == NULL) {
100 return NULL;
103 w->name = talloc_strdup(w, name);
105 w->tdb = tdb_open_ex(name, hash_size, tdb_flags,
106 open_flags, mode, &log_ctx, NULL);
107 if (w->tdb == NULL) {
108 talloc_free(w);
109 return NULL;
112 talloc_set_destructor(w, tdb_wrap_destructor);
114 DLIST_ADD(tdb_list, w);
116 return w;