]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb1_open.c
c1729b577f78a857e117d84d0bcab8de69df2247
[ccan] / ccan / tdb2 / tdb1_open.c
1  /*
2    Unix SMB/CIFS implementation.
3
4    trivial database library
5
6    Copyright (C) Andrew Tridgell              1999-2005
7    Copyright (C) Paul `Rusty' Russell              2000
8    Copyright (C) Jeremy Allison                    2000-2003
9
10      ** NOTE! The following LGPL license applies to the tdb
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 3 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 */
27 #include <assert.h>
28 #include "tdb1_private.h"
29
30 /* We use two hashes to double-check they're using the right hash function. */
31 void tdb1_header_hash(struct tdb_context *tdb,
32                      uint32_t *magic1_hash, uint32_t *magic2_hash)
33 {
34         uint32_t tdb1_magic = TDB1_MAGIC;
35
36         *magic1_hash = tdb_hash(tdb, TDB_MAGIC_FOOD, sizeof(TDB_MAGIC_FOOD));
37         *magic2_hash = tdb_hash(tdb, TDB1_CONV(tdb1_magic), sizeof(tdb1_magic));
38
39         /* Make sure at least one hash is non-zero! */
40         if (*magic1_hash == 0 && *magic2_hash == 0)
41                 *magic1_hash = 1;
42 }
43
44 /* initialise a new database with a specified hash size */
45 static int tdb1_new_database(struct tdb_context *tdb, int hash_size)
46 {
47         struct tdb1_header *newdb;
48         size_t size;
49         int ret = -1;
50
51         /* We make it up in memory, then write it out if not internal */
52         size = sizeof(struct tdb1_header) + (hash_size+1)*sizeof(tdb1_off_t);
53         if (!(newdb = (struct tdb1_header *)calloc(size, 1))) {
54                 tdb->last_error = TDB_ERR_OOM;
55                 return -1;
56         }
57
58         /* Fill in the header */
59         newdb->version = TDB1_VERSION;
60         newdb->hash_size = hash_size;
61
62         tdb1_header_hash(tdb, &newdb->magic1_hash, &newdb->magic2_hash);
63
64         /* Make sure older tdbs (which don't check the magic hash fields)
65          * will refuse to open this TDB. */
66         if (tdb->hash_fn == tdb1_incompatible_hash)
67                 newdb->rwlocks = TDB1_HASH_RWLOCK_MAGIC;
68
69         if (tdb->flags & TDB_INTERNAL) {
70                 tdb->file->fd = -1;
71                 tdb->file->map_size = size;
72                 tdb->file->map_ptr = (char *)newdb;
73                 memcpy(&tdb->tdb1.header, newdb, sizeof(tdb->tdb1.header));
74                 /* Convert the `ondisk' version if asked. */
75                 TDB1_CONV(*newdb);
76                 return 0;
77         }
78         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1)
79                 goto fail;
80
81         if (ftruncate(tdb->file->fd, 0) == -1)
82                 goto fail;
83
84         /* This creates an endian-converted header, as if read from disk */
85         TDB1_CONV(*newdb);
86         memcpy(&tdb->tdb1.header, newdb, sizeof(tdb->tdb1.header));
87         /* Don't endian-convert the magic food! */
88         memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
89         /* we still have "ret == -1" here */
90         if (tdb1_write_all(tdb->file->fd, newdb, size))
91                 ret = 0;
92
93   fail:
94         SAFE_FREE(newdb);
95         return ret;
96 }
97
98 typedef void (*tdb1_log_func)(struct tdb_context *, enum tdb_log_level, enum TDB_ERROR,
99                               const char *, void *);
100 typedef uint64_t (*tdb1_hash_func)(const void *key, size_t len, uint64_t seed,
101                                    void *data);
102
103 struct tdb1_logging_context {
104         tdb1_log_func log_fn;
105         void *log_private;
106 };
107
108 static bool hash_correct(struct tdb_context *tdb,
109                          uint32_t *m1, uint32_t *m2)
110 {
111         tdb1_header_hash(tdb, m1, m2);
112         return (tdb->tdb1.header.magic1_hash == *m1 &&
113                 tdb->tdb1.header.magic2_hash == *m2);
114 }
115
116 static bool check_header_hash(struct tdb_context *tdb,
117                               uint32_t *m1, uint32_t *m2)
118 {
119         if (hash_correct(tdb, m1, m2))
120                 return true;
121
122         /* If they use one inbuilt, try the other inbuilt hash. */
123         if (tdb->hash_fn == tdb1_old_hash)
124                 tdb->hash_fn = tdb1_incompatible_hash;
125         else if (tdb->hash_fn == tdb1_incompatible_hash)
126                 tdb->hash_fn = tdb1_old_hash;
127         else
128                 return false;
129         return hash_correct(tdb, m1, m2);
130 }
131
132 static struct tdb_context *tdb1_open_ex(const char *name, int hash_size, int tdb1_flags,
133                                 int open_flags, mode_t mode,
134                                 const struct tdb1_logging_context *log_ctx,
135                                 tdb1_hash_func hash_fn)
136 {
137         struct tdb_context *tdb;
138         struct stat st;
139         int rev = 0;
140         unsigned v;
141         const char *hash_alg;
142         uint32_t magic1, magic2;
143
144         if (!(tdb = (struct tdb_context *)calloc(1, sizeof *tdb))) {
145                 /* Can't log this */
146                 errno = ENOMEM;
147                 goto fail;
148         }
149         tdb->file = calloc(1, sizeof *tdb->file);
150         if (!tdb->file) {
151                 free(tdb);
152                 errno = ENOMEM;
153                 goto fail;
154         }
155         tdb1_io_init(tdb);
156         tdb->file->fd = -1;
157         tdb->name = NULL;
158         tdb->file->map_ptr = NULL;
159         tdb->flags = tdb1_flags|TDB_VERSION1;
160         tdb->open_flags = open_flags;
161         tdb->lock_fn = tdb_fcntl_lock;
162         tdb->unlock_fn = tdb_fcntl_unlock;
163         if (log_ctx) {
164                 tdb->log_fn = log_ctx->log_fn;
165                 tdb->log_data = log_ctx->log_private;
166         } else
167                 tdb->log_fn = NULL;
168
169         if (name == NULL && (tdb1_flags & TDB_INTERNAL)) {
170                 name = "__TDB1_INTERNAL__";
171         }
172
173         if (name == NULL) {
174                 tdb->name = (char *)"__NULL__";
175                 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
176                            "tdb1_open_ex: called with name == NULL");
177                 tdb->name = NULL;
178                 errno = EINVAL;
179                 goto fail;
180         }
181
182         /* now make a copy of the name, as the caller memory might went away */
183         if (!(tdb->name = (char *)strdup(name))) {
184                 /*
185                  * set the name as the given string, so that tdb1_name() will
186                  * work in case of an error.
187                  */
188                 tdb->name = (char *)name;
189                 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
190                            "tdb1_open_ex: can't strdup(%s)", name);
191                 tdb->name = NULL;
192                 errno = ENOMEM;
193                 goto fail;
194         }
195         tdb->hash_seed = 0;
196
197         if (hash_fn) {
198                 tdb->hash_fn = hash_fn;
199                 if (hash_fn == tdb1_incompatible_hash)
200                         hash_alg = "tdb1_incompatible_hash";
201                 else
202                         hash_alg = "the user defined";
203         } else {
204                 tdb->hash_fn = tdb1_old_hash;
205                 hash_alg = "default";
206         }
207
208         /* cache the page size */
209         tdb->tdb1.page_size = getpagesize();
210         if (tdb->tdb1.page_size <= 0) {
211                 tdb->tdb1.page_size = 0x2000;
212         }
213
214         /* FIXME: Used to be 5 for TDB_VOLATILE. */
215         tdb->tdb1.max_dead_records = 0;
216
217         if ((open_flags & O_ACCMODE) == O_WRONLY) {
218                 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
219                            "tdb1_open_ex: can't open tdb %s write-only",
220                            name);
221                 errno = EINVAL;
222                 goto fail;
223         }
224
225         if ((open_flags & O_ACCMODE) == O_RDONLY) {
226                 tdb->flags |= TDB_RDONLY;
227                 /* read only databases don't do locking */
228                 tdb->flags |= TDB_NOLOCK;
229         }
230
231         /* internal databases don't mmap or lock, and start off cleared */
232         if (tdb->flags & TDB_INTERNAL) {
233                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
234                 if (tdb1_new_database(tdb, hash_size) != 0) {
235                         tdb_logerr(tdb, tdb->last_error, TDB_LOG_ERROR,
236                                    "tdb1_open_ex: tdb1_new_database failed!");
237                         goto fail;
238                 }
239                 goto internal;
240         }
241
242         if ((tdb->file->fd = open(name, open_flags, mode)) == -1) {
243                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
244                            "tdb1_open_ex: could not open file %s: %s",
245                            name, strerror(errno));
246                 goto fail;      /* errno set by open(2) */
247         }
248
249         /* on exec, don't inherit the fd */
250         v = fcntl(tdb->file->fd, F_GETFD, 0);
251         fcntl(tdb->file->fd, F_SETFD, v | FD_CLOEXEC);
252
253         /* ensure there is only one process initialising at once */
254         if (tdb1_nest_lock(tdb, TDB1_OPEN_LOCK, F_WRLCK, TDB_LOCK_WAIT) == -1) {
255                 tdb_logerr(tdb, tdb->last_error, TDB_LOG_ERROR,
256                            "tdb1_open_ex: failed to get open lock on %s: %s",
257                            name, strerror(errno));
258                 goto fail;      /* errno set by tdb1_brlock */
259         }
260
261         errno = 0;
262         if (read(tdb->file->fd, &tdb->tdb1.header, sizeof(tdb->tdb1.header)) != sizeof(tdb->tdb1.header)
263             || strcmp(tdb->tdb1.header.magic_food, TDB_MAGIC_FOOD) != 0) {
264                 if (!(open_flags & O_CREAT) || tdb1_new_database(tdb, hash_size) == -1) {
265                         if (errno == 0) {
266                                 errno = EIO; /* ie bad format or something */
267                         }
268                         goto fail;
269                 }
270                 rev = (tdb->flags & TDB_CONVERT);
271         } else if (tdb->tdb1.header.version != TDB1_VERSION
272                    && !(rev = (tdb->tdb1.header.version==TDB1_BYTEREV(TDB1_VERSION)))) {
273                 /* wrong version */
274                 errno = EIO;
275                 goto fail;
276         }
277         if (!rev)
278                 tdb->flags &= ~TDB_CONVERT;
279         else {
280                 tdb->flags |= TDB_CONVERT;
281                 tdb1_convert(&tdb->tdb1.header, sizeof(tdb->tdb1.header));
282         }
283         if (fstat(tdb->file->fd, &st) == -1)
284                 goto fail;
285
286         if (tdb->tdb1.header.rwlocks != 0 &&
287             tdb->tdb1.header.rwlocks != TDB1_HASH_RWLOCK_MAGIC) {
288                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
289                            "tdb1_open_ex: spinlocks no longer supported");
290                 goto fail;
291         }
292
293         if ((tdb->tdb1.header.magic1_hash == 0) && (tdb->tdb1.header.magic2_hash == 0)) {
294                 /* older TDB without magic hash references */
295                 tdb->hash_fn = tdb1_old_hash;
296         } else if (!check_header_hash(tdb, &magic1, &magic2)) {
297                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_USE_ERROR,
298                            "tdb1_open_ex: "
299                            "%s was not created with %s hash function we are using\n"
300                            "magic1_hash[0x%08X %s 0x%08X] "
301                            "magic2_hash[0x%08X %s 0x%08X]",
302                            name, hash_alg,
303                            tdb->tdb1.header.magic1_hash,
304                            (tdb->tdb1.header.magic1_hash == magic1) ? "==" : "!=",
305                            magic1,
306                            tdb->tdb1.header.magic2_hash,
307                            (tdb->tdb1.header.magic2_hash == magic2) ? "==" : "!=",
308                            magic2);
309                 errno = EINVAL;
310                 goto fail;
311         }
312
313         tdb->file->map_size = st.st_size;
314         tdb->file->device = st.st_dev;
315         tdb->file->inode = st.st_ino;
316         tdb1_mmap(tdb);
317
318         /* if needed, run recovery */
319         if (tdb1_transaction_recover(tdb) == -1) {
320                 goto fail;
321         }
322
323  internal:
324         /* Internal (memory-only) databases skip all the code above to
325          * do with disk files, and resume here by releasing their
326          * open lock and hooking into the active list. */
327         if (tdb1_nest_unlock(tdb, TDB1_OPEN_LOCK, F_WRLCK) == -1) {
328                 goto fail;
329         }
330         return tdb;
331
332  fail:
333         { int save_errno = errno;
334
335         if (!tdb)
336                 return NULL;
337
338         if (tdb->file->map_ptr) {
339                 if (tdb->flags & TDB_INTERNAL)
340                         SAFE_FREE(tdb->file->map_ptr);
341                 else
342                         tdb1_munmap(tdb);
343         }
344         if (tdb->file->fd != -1)
345                 if (close(tdb->file->fd) != 0)
346                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
347                                    "tdb1_open_ex: failed to close tdb->fd on error!");
348         if (tdb->file) {
349                 SAFE_FREE(tdb->file->lockrecs);
350                 SAFE_FREE(tdb->file);
351         }
352         SAFE_FREE(tdb->name);
353         SAFE_FREE(tdb);
354         errno = save_errno;
355         return NULL;
356         }
357 }
358
359 /* Temporart wrapper for transition. */
360 struct tdb_context *tdb1_open(const char *name, int tdb1_flags,
361                               int open_flags, mode_t mode,
362                               union tdb_attribute *attr)
363 {
364         struct tdb1_logging_context *log_ctx = NULL, log;
365         tdb1_hash_func hash_fn = NULL;
366         struct tdb_attribute_tdb1_hashsize *hsize = NULL;
367
368         while (attr) {
369                 switch (attr->base.attr) {
370                 case TDB_ATTRIBUTE_HASH:
371                         hash_fn = attr->hash.fn;
372                         break;
373                 case TDB_ATTRIBUTE_LOG:
374                         log.log_fn = attr->log.fn;
375                         log.log_private = attr->log.data;
376                         log_ctx = &log;
377                         break;
378                 case TDB_ATTRIBUTE_TDB1_HASHSIZE:
379                         hsize = &attr->tdb1_hashsize;
380                         break;
381                         break;
382                 default:
383                         abort();
384                 }
385                 attr = attr->base.next;
386         }
387
388         if (hsize && !(open_flags & O_CREAT)) {
389                 if (log_ctx) {
390                         log_ctx->log_fn(NULL,
391                                         TDB_ERR_EINVAL,
392                                         TDB_LOG_USE_ERROR,
393                                         "tdb_open: can only use"
394                                         " TDB_ATTRIBUTE_TDB1_HASHSIZE when"
395                                         " creating a tdb",
396                                         log_ctx->log_private);
397                 }
398                 errno = EINVAL;
399                 return NULL;
400         }
401         return tdb1_open_ex(name, hsize ? hsize->hsize : TDB1_DEFAULT_HASH_SIZE,
402                             tdb1_flags, open_flags, mode,
403                             log_ctx, hash_fn);
404 }
405
406 /*
407  * Set the maximum number of dead records per hash chain
408  */
409
410 void tdb1_set_max_dead(struct tdb_context *tdb, int max_dead)
411 {
412         tdb->tdb1.max_dead_records = max_dead;
413 }
414
415 /**
416  * Close a database.
417  *
418  * @returns -1 for error; 0 for success.
419  **/
420 int tdb1_close(struct tdb_context *tdb)
421 {
422         int ret = 0;
423
424         if (tdb->tdb1.transaction) {
425                 tdb1_transaction_cancel(tdb);
426         }
427
428         if (tdb->file->map_ptr) {
429                 if (tdb->flags & TDB_INTERNAL)
430                         SAFE_FREE(tdb->file->map_ptr);
431                 else
432                         tdb1_munmap(tdb);
433         }
434         SAFE_FREE(tdb->name);
435         if (tdb->file->fd != -1) {
436                 ret = close(tdb->file->fd);
437                 tdb->file->fd = -1;
438         }
439         SAFE_FREE(tdb->file->lockrecs);
440         SAFE_FREE(tdb->file);
441
442         memset(tdb, 0, sizeof(*tdb));
443         SAFE_FREE(tdb);
444
445         return ret;
446 }