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