]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb1_open.c
tdb2: remove TDB1 TDB_NO_FSYNC environment variable hack.
[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         TDB1_DATA hash_key;
38         uint32_t tdb1_magic = TDB1_MAGIC;
39
40         hash_key.dptr = (unsigned char *)TDB1_MAGIC_FOOD;
41         hash_key.dsize = sizeof(TDB1_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->ecode = TDB1_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->flags & TDB1_INCOMPATIBLE_HASH)
76                 newdb->rwlocks = TDB1_HASH_RWLOCK_MAGIC;
77
78         if (tdb->flags & TDB1_INTERNAL) {
79                 tdb->map_size = size;
80                 tdb->map_ptr = (char *)newdb;
81                 memcpy(&tdb->header, newdb, sizeof(tdb->header));
82                 /* Convert the `ondisk' version if asked. */
83                 TDB1_CONV(*newdb);
84                 return 0;
85         }
86         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
87                 goto fail;
88
89         if (ftruncate(tdb->fd, 0) == -1)
90                 goto fail;
91
92         /* This creates an endian-converted header, as if read from disk */
93         TDB1_CONV(*newdb);
94         memcpy(&tdb->header, newdb, sizeof(tdb->header));
95         /* Don't endian-convert the magic food! */
96         memcpy(newdb->magic_food, TDB1_MAGIC_FOOD, strlen(TDB1_MAGIC_FOOD)+1);
97         /* we still have "ret == -1" here */
98         if (tdb1_write_all(tdb->fd, newdb, size))
99                 ret = 0;
100
101   fail:
102         SAFE_FREE(newdb);
103         return ret;
104 }
105
106
107
108 static int tdb1_already_open(dev_t device,
109                             ino_t ino)
110 {
111         struct tdb1_context *i;
112
113         for (i = tdb1s; i; i = i->next) {
114                 if (i->device == device && i->inode == ino) {
115                         return 1;
116                 }
117         }
118
119         return 0;
120 }
121
122 /* open the database, creating it if necessary
123
124    The open_flags and mode are passed straight to the open call on the
125    database file. A flags value of O_WRONLY is invalid. The hash size
126    is advisory, use zero for a default value.
127
128    Return is NULL on error, in which case errno is also set.  Don't
129    try to call tdb1_error or tdb1_errname, just do strerror(errno).
130
131    @param name may be NULL for internal databases. */
132 struct tdb1_context *tdb1_open(const char *name, int hash_size, int tdb1_flags,
133                       int open_flags, mode_t mode)
134 {
135         return tdb1_open_ex(name, hash_size, tdb1_flags, open_flags, mode, NULL, NULL);
136 }
137
138 /* a default logging function */
139 static void null_log_fn(struct tdb1_context *tdb, enum tdb1_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
140 static void null_log_fn(struct tdb1_context *tdb, enum tdb1_debug_level level, const char *fmt, ...)
141 {
142 }
143
144 static bool check_header_hash(struct tdb1_context *tdb,
145                               bool default_hash, uint32_t *m1, uint32_t *m2)
146 {
147         tdb1_header_hash(tdb, m1, m2);
148         if (tdb->header.magic1_hash == *m1 &&
149             tdb->header.magic2_hash == *m2) {
150                 return true;
151         }
152
153         /* If they explicitly set a hash, always respect it. */
154         if (!default_hash)
155                 return false;
156
157         /* Otherwise, try the other inbuilt hash. */
158         if (tdb->hash_fn == tdb1_old_hash)
159                 tdb->hash_fn = tdb1_jenkins_hash;
160         else
161                 tdb->hash_fn = tdb1_old_hash;
162         return check_header_hash(tdb, false, m1, m2);
163 }
164
165 struct tdb1_context *tdb1_open_ex(const char *name, int hash_size, int tdb1_flags,
166                                 int open_flags, mode_t mode,
167                                 const struct tdb1_logging_context *log_ctx,
168                                 tdb1_hash_func hash_fn)
169 {
170         struct tdb1_context *tdb;
171         struct stat st;
172         int rev = 0, locked = 0;
173         unsigned char *vp;
174         uint32_t vertest;
175         unsigned v;
176         const char *hash_alg;
177         uint32_t magic1, magic2;
178
179         if (!(tdb = (struct tdb1_context *)calloc(1, sizeof *tdb))) {
180                 /* Can't log this */
181                 errno = ENOMEM;
182                 goto fail;
183         }
184         tdb1_io_init(tdb);
185         tdb->fd = -1;
186         tdb->name = NULL;
187         tdb->map_ptr = NULL;
188         tdb->flags = tdb1_flags;
189         tdb->open_flags = open_flags;
190         if (log_ctx) {
191                 tdb->log = *log_ctx;
192         } else {
193                 tdb->log.log_fn = null_log_fn;
194                 tdb->log.log_private = NULL;
195         }
196
197         if (name == NULL && (tdb1_flags & TDB1_INTERNAL)) {
198                 name = "__TDB1_INTERNAL__";
199         }
200
201         if (name == NULL) {
202                 tdb->name = (char *)"__NULL__";
203                 TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: called with name == NULL\n"));
204                 tdb->name = NULL;
205                 errno = EINVAL;
206                 goto fail;
207         }
208
209         /* now make a copy of the name, as the caller memory might went away */
210         if (!(tdb->name = (char *)strdup(name))) {
211                 /*
212                  * set the name as the given string, so that tdb1_name() will
213                  * work in case of an error.
214                  */
215                 tdb->name = (char *)name;
216                 TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: can't strdup(%s)\n",
217                          name));
218                 tdb->name = NULL;
219                 errno = ENOMEM;
220                 goto fail;
221         }
222
223         if (hash_fn) {
224                 tdb->hash_fn = hash_fn;
225                 hash_alg = "the user defined";
226         } else {
227                 /* This controls what we use when creating a tdb. */
228                 if (tdb->flags & TDB1_INCOMPATIBLE_HASH) {
229                         tdb->hash_fn = tdb1_jenkins_hash;
230                 } else {
231                         tdb->hash_fn = tdb1_old_hash;
232                 }
233                 hash_alg = "either default";
234         }
235
236         /* cache the page size */
237         tdb->page_size = getpagesize();
238         if (tdb->page_size <= 0) {
239                 tdb->page_size = 0x2000;
240         }
241
242         tdb->max_dead_records = (tdb1_flags & TDB1_VOLATILE) ? 5 : 0;
243
244         if ((open_flags & O_ACCMODE) == O_WRONLY) {
245                 TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: can't open tdb %s write-only\n",
246                          name));
247                 errno = EINVAL;
248                 goto fail;
249         }
250
251         if (hash_size == 0)
252                 hash_size = TDB1_DEFAULT_HASH_SIZE;
253         if ((open_flags & O_ACCMODE) == O_RDONLY) {
254                 tdb->read_only = 1;
255                 /* read only databases don't do locking or clear if first */
256                 tdb->flags |= TDB1_NOLOCK;
257                 tdb->flags &= ~TDB1_CLEAR_IF_FIRST;
258         }
259
260         if ((tdb->flags & TDB1_ALLOW_NESTING) &&
261             (tdb->flags & TDB1_DISALLOW_NESTING)) {
262                 tdb->ecode = TDB1_ERR_NESTING;
263                 TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
264                         "allow_nesting and disallow_nesting are not allowed together!"));
265                 errno = EINVAL;
266                 goto fail;
267         }
268
269         /*
270          * TDB1_ALLOW_NESTING is the default behavior.
271          * Note: this may change in future versions!
272          */
273         if (!(tdb->flags & TDB1_DISALLOW_NESTING)) {
274                 tdb->flags |= TDB1_ALLOW_NESTING;
275         }
276
277         /* internal databases don't mmap or lock, and start off cleared */
278         if (tdb->flags & TDB1_INTERNAL) {
279                 tdb->flags |= (TDB1_NOLOCK | TDB1_NOMMAP);
280                 tdb->flags &= ~TDB1_CLEAR_IF_FIRST;
281                 if (tdb1_new_database(tdb, hash_size) != 0) {
282                         TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: tdb1_new_database failed!"));
283                         goto fail;
284                 }
285                 goto internal;
286         }
287
288         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
289                 TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_open_ex: could not open file %s: %s\n",
290                          name, strerror(errno)));
291                 goto fail;      /* errno set by open(2) */
292         }
293
294         /* on exec, don't inherit the fd */
295         v = fcntl(tdb->fd, F_GETFD, 0);
296         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
297
298         /* ensure there is only one process initialising at once */
299         if (tdb1_nest_lock(tdb, TDB1_OPEN_LOCK, F_WRLCK, TDB1_LOCK_WAIT) == -1) {
300                 TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: failed to get open lock on %s: %s\n",
301                          name, strerror(errno)));
302                 goto fail;      /* errno set by tdb1_brlock */
303         }
304
305         /* we need to zero database if we are the only one with it open */
306         if ((tdb1_flags & TDB1_CLEAR_IF_FIRST) &&
307             (!tdb->read_only) &&
308             (locked = (tdb1_nest_lock(tdb, TDB1_ACTIVE_LOCK, F_WRLCK, TDB1_LOCK_NOWAIT|TDB1_LOCK_PROBE) == 0))) {
309                 open_flags |= O_CREAT;
310                 if (ftruncate(tdb->fd, 0) == -1) {
311                         TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
312                                  "failed to truncate %s: %s\n",
313                                  name, strerror(errno)));
314                         goto fail; /* errno set by ftruncate */
315                 }
316         }
317
318         errno = 0;
319         if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
320             || strcmp(tdb->header.magic_food, TDB1_MAGIC_FOOD) != 0) {
321                 if (!(open_flags & O_CREAT) || tdb1_new_database(tdb, hash_size) == -1) {
322                         if (errno == 0) {
323                                 errno = EIO; /* ie bad format or something */
324                         }
325                         goto fail;
326                 }
327                 rev = (tdb->flags & TDB1_CONVERT);
328         } else if (tdb->header.version != TDB1_VERSION
329                    && !(rev = (tdb->header.version==TDB1_BYTEREV(TDB1_VERSION)))) {
330                 /* wrong version */
331                 errno = EIO;
332                 goto fail;
333         }
334         vp = (unsigned char *)&tdb->header.version;
335         vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
336                   (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
337         tdb->flags |= (vertest==TDB1_VERSION) ? TDB1_BIGENDIAN : 0;
338         if (!rev)
339                 tdb->flags &= ~TDB1_CONVERT;
340         else {
341                 tdb->flags |= TDB1_CONVERT;
342                 tdb1_convert(&tdb->header, sizeof(tdb->header));
343         }
344         if (fstat(tdb->fd, &st) == -1)
345                 goto fail;
346
347         if (tdb->header.rwlocks != 0 &&
348             tdb->header.rwlocks != TDB1_HASH_RWLOCK_MAGIC) {
349                 TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: spinlocks no longer supported\n"));
350                 goto fail;
351         }
352
353         if ((tdb->header.magic1_hash == 0) && (tdb->header.magic2_hash == 0)) {
354                 /* older TDB without magic hash references */
355                 tdb->hash_fn = tdb1_old_hash;
356         } else if (!check_header_hash(tdb, !hash_fn, &magic1, &magic2)) {
357                 TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
358                          "%s was not created with %s hash function we are using\n"
359                          "magic1_hash[0x%08X %s 0x%08X] "
360                          "magic2_hash[0x%08X %s 0x%08X]\n",
361                          name, hash_alg,
362                          tdb->header.magic1_hash,
363                          (tdb->header.magic1_hash == magic1) ? "==" : "!=",
364                          magic1,
365                          tdb->header.magic2_hash,
366                          (tdb->header.magic2_hash == magic2) ? "==" : "!=",
367                          magic2));
368                 errno = EINVAL;
369                 goto fail;
370         }
371
372         /* Is it already in the open list?  If so, fail. */
373         if (tdb1_already_open(st.st_dev, st.st_ino)) {
374                 TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: "
375                          "%s (%d,%d) is already open in this process\n",
376                          name, (int)st.st_dev, (int)st.st_ino));
377                 errno = EBUSY;
378                 goto fail;
379         }
380
381         tdb->map_size = st.st_size;
382         tdb->device = st.st_dev;
383         tdb->inode = st.st_ino;
384         tdb1_mmap(tdb);
385         if (locked) {
386                 if (tdb1_nest_unlock(tdb, TDB1_ACTIVE_LOCK, F_WRLCK) == -1) {
387                         TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: "
388                                  "failed to release ACTIVE_LOCK on %s: %s\n",
389                                  name, strerror(errno)));
390                         goto fail;
391                 }
392
393         }
394
395         /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
396            we didn't get the initial exclusive lock as we need to let all other
397            users know we're using it. */
398
399         if (tdb1_flags & TDB1_CLEAR_IF_FIRST) {
400                 /* leave this lock in place to indicate it's in use */
401                 if (tdb1_nest_lock(tdb, TDB1_ACTIVE_LOCK, F_RDLCK, TDB1_LOCK_WAIT) == -1) {
402                         goto fail;
403                 }
404         }
405
406         /* if needed, run recovery */
407         if (tdb1_transaction_recover(tdb) == -1) {
408                 goto fail;
409         }
410
411  internal:
412         /* Internal (memory-only) databases skip all the code above to
413          * do with disk files, and resume here by releasing their
414          * open lock and hooking into the active list. */
415         if (tdb1_nest_unlock(tdb, TDB1_OPEN_LOCK, F_WRLCK) == -1) {
416                 goto fail;
417         }
418         tdb->next = tdb1s;
419         tdb1s = tdb;
420         return tdb;
421
422  fail:
423         { int save_errno = errno;
424
425         if (!tdb)
426                 return NULL;
427
428         if (tdb->map_ptr) {
429                 if (tdb->flags & TDB1_INTERNAL)
430                         SAFE_FREE(tdb->map_ptr);
431                 else
432                         tdb1_munmap(tdb);
433         }
434         if (tdb->fd != -1)
435                 if (close(tdb->fd) != 0)
436                         TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: failed to close tdb->fd on error!\n"));
437         SAFE_FREE(tdb->lockrecs);
438         SAFE_FREE(tdb->name);
439         SAFE_FREE(tdb);
440         errno = save_errno;
441         return NULL;
442         }
443 }
444
445 /*
446  * Set the maximum number of dead records per hash chain
447  */
448
449 void tdb1_set_max_dead(struct tdb1_context *tdb, int max_dead)
450 {
451         tdb->max_dead_records = max_dead;
452 }
453
454 /**
455  * Close a database.
456  *
457  * @returns -1 for error; 0 for success.
458  **/
459 int tdb1_close(struct tdb1_context *tdb)
460 {
461         struct tdb1_context **i;
462         int ret = 0;
463
464         if (tdb->transaction) {
465                 tdb1_transaction_cancel(tdb);
466         }
467
468         if (tdb->map_ptr) {
469                 if (tdb->flags & TDB1_INTERNAL)
470                         SAFE_FREE(tdb->map_ptr);
471                 else
472                         tdb1_munmap(tdb);
473         }
474         SAFE_FREE(tdb->name);
475         if (tdb->fd != -1) {
476                 ret = close(tdb->fd);
477                 tdb->fd = -1;
478         }
479         SAFE_FREE(tdb->lockrecs);
480
481         /* Remove from contexts list */
482         for (i = &tdb1s; *i; i = &(*i)->next) {
483                 if (*i == tdb) {
484                         *i = tdb->next;
485                         break;
486                 }
487         }
488
489         memset(tdb, 0, sizeof(*tdb));
490         SAFE_FREE(tdb);
491
492         return ret;
493 }