tdb: Make sure the hash size fits
[metze/samba/wip.git] / lib / tdb / common / 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 "tdb_private.h"
29
30 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
31 static struct tdb_context *tdbs = NULL;
32
33 /* We use two hashes to double-check they're using the right hash function. */
34 void tdb_header_hash(struct tdb_context *tdb,
35                      uint32_t *magic1_hash, uint32_t *magic2_hash)
36 {
37         TDB_DATA hash_key;
38         uint32_t tdb_magic = TDB_MAGIC;
39
40         hash_key.dptr = discard_const_p(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 *)CONVERT(tdb_magic);
45         hash_key.dsize = sizeof(tdb_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 tdb_new_database(struct tdb_context *tdb, struct tdb_header *header,
55                             int hash_size)
56 {
57         struct tdb_header *newdb;
58         size_t size;
59         int ret = -1;
60
61         /* We make it up in memory, then write it out if not internal */
62         size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off_t);
63         if (!(newdb = (struct tdb_header *)calloc(size, 1))) {
64                 tdb->ecode = TDB_ERR_OOM;
65                 return -1;
66         }
67
68         /* Fill in the header */
69         newdb->version = TDB_VERSION;
70         newdb->hash_size = hash_size;
71
72         tdb_header_hash(tdb, &newdb->magic1_hash, &newdb->magic2_hash);
73
74         /* Make sure older tdbs (which don't check the magic hash fields)
75          * will refuse to open this TDB. */
76         if (tdb->flags & TDB_INCOMPATIBLE_HASH)
77                 newdb->rwlocks = TDB_HASH_RWLOCK_MAGIC;
78
79         /*
80          * We create a tdb with TDB_FEATURE_FLAG_MUTEX support,
81          * the flag combination and runtime feature checks
82          * are done by the caller already.
83          */
84         if (tdb->flags & TDB_MUTEX_LOCKING) {
85                 newdb->feature_flags |= TDB_FEATURE_FLAG_MUTEX;
86         }
87
88         /*
89          * If we have any features we add the FEATURE_FLAG_MAGIC, overwriting the
90          * TDB_HASH_RWLOCK_MAGIC above.
91          */
92         if (newdb->feature_flags != 0) {
93                 newdb->rwlocks = TDB_FEATURE_FLAG_MAGIC;
94         }
95
96         /*
97          * It's required for some following code pathes
98          * to have the fields on 'tdb' up-to-date.
99          *
100          * E.g. tdb_mutex_size() requires it
101          */
102         tdb->feature_flags = newdb->feature_flags;
103         tdb->hash_size = newdb->hash_size;
104
105         if (tdb->flags & TDB_INTERNAL) {
106                 tdb->map_size = size;
107                 tdb->map_ptr = (char *)newdb;
108                 memcpy(header, newdb, sizeof(*header));
109                 /* Convert the `ondisk' version if asked. */
110                 CONVERT(*newdb);
111                 return 0;
112         }
113         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
114                 goto fail;
115
116         if (ftruncate(tdb->fd, 0) == -1)
117                 goto fail;
118
119         if (newdb->feature_flags & TDB_FEATURE_FLAG_MUTEX) {
120                 newdb->mutex_size = tdb_mutex_size(tdb);
121                 tdb->hdr_ofs = newdb->mutex_size;
122         }
123
124         /* This creates an endian-converted header, as if read from disk */
125         CONVERT(*newdb);
126         memcpy(header, newdb, sizeof(*header));
127         /* Don't endian-convert the magic food! */
128         memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
129
130         if (!tdb_write_all(tdb->fd, newdb, size))
131                 goto fail;
132
133         if (newdb->feature_flags & TDB_FEATURE_FLAG_MUTEX) {
134
135                 /*
136                  * Now we init the mutex area
137                  * followed by a second header.
138                  */
139
140                 ret = ftruncate(
141                         tdb->fd,
142                         newdb->mutex_size + sizeof(struct tdb_header));
143                 if (ret == -1) {
144                         goto fail;
145                 }
146                 ret = tdb_mutex_init(tdb);
147                 if (ret == -1) {
148                         goto fail;
149                 }
150
151                 /*
152                  * Write a second header behind the mutexes. That's the area
153                  * that will be mmapp'ed.
154                  */
155                 ret = lseek(tdb->fd, newdb->mutex_size, SEEK_SET);
156                 if (ret == -1) {
157                         goto fail;
158                 }
159                 if (!tdb_write_all(tdb->fd, newdb, size)) {
160                         goto fail;
161                 }
162         }
163
164         ret = 0;
165   fail:
166         SAFE_FREE(newdb);
167         return ret;
168 }
169
170
171
172 static int tdb_already_open(dev_t device,
173                             ino_t ino)
174 {
175         struct tdb_context *i;
176
177         for (i = tdbs; i; i = i->next) {
178                 if (i->device == device && i->inode == ino) {
179                         return 1;
180                 }
181         }
182
183         return 0;
184 }
185
186 /* open the database, creating it if necessary
187
188    The open_flags and mode are passed straight to the open call on the
189    database file. A flags value of O_WRONLY is invalid. The hash size
190    is advisory, use zero for a default value.
191
192    Return is NULL on error, in which case errno is also set.  Don't
193    try to call tdb_error or tdb_errname, just do strerror(errno).
194
195    @param name may be NULL for internal databases. */
196 _PUBLIC_ struct tdb_context *tdb_open(const char *name, int hash_size, int tdb_flags,
197                       int open_flags, mode_t mode)
198 {
199         return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL, NULL);
200 }
201
202 /* a default logging function */
203 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
204 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...)
205 {
206 }
207
208 static bool check_header_hash(struct tdb_context *tdb,
209                               struct tdb_header *header,
210                               bool default_hash, uint32_t *m1, uint32_t *m2)
211 {
212         tdb_header_hash(tdb, m1, m2);
213         if (header->magic1_hash == *m1 &&
214             header->magic2_hash == *m2) {
215                 return true;
216         }
217
218         /* If they explicitly set a hash, always respect it. */
219         if (!default_hash)
220                 return false;
221
222         /* Otherwise, try the other inbuilt hash. */
223         if (tdb->hash_fn == tdb_old_hash)
224                 tdb->hash_fn = tdb_jenkins_hash;
225         else
226                 tdb->hash_fn = tdb_old_hash;
227         return check_header_hash(tdb, header, false, m1, m2);
228 }
229
230 static bool tdb_mutex_open_ok(struct tdb_context *tdb,
231                               const struct tdb_header *header)
232 {
233         int locked;
234
235         if (tdb->flags & TDB_NOLOCK) {
236                 /*
237                  * We don't look at locks, so it does not matter to have a
238                  * compatible mutex implementation. Allow the open.
239                  */
240                 return true;
241         }
242
243         locked = tdb_nest_lock(tdb, ACTIVE_LOCK, F_WRLCK,
244                                TDB_LOCK_NOWAIT|TDB_LOCK_PROBE);
245
246         if ((locked == -1) && (tdb->ecode == TDB_ERR_LOCK)) {
247                 /*
248                  * CLEAR_IF_FIRST still active. The tdb was created on this
249                  * host, so we can assume the mutex implementation is
250                  * compatible. Important for tools like tdbdump on a still
251                  * open locking.tdb.
252                  */
253                 goto check_local_settings;
254         }
255
256         /*
257          * We got the CLEAR_IF_FIRST lock. That means the database was
258          * potentially copied from somewhere else. The mutex implementation
259          * might be incompatible.
260          */
261
262         if (tdb_nest_unlock(tdb, ACTIVE_LOCK, F_WRLCK, false) == -1) {
263                 /*
264                  * Should not happen
265                  */
266                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_mutex_open_ok: "
267                          "failed to release ACTIVE_LOCK on %s: %s\n",
268                          tdb->name, strerror(errno)));
269                 return false;
270         }
271
272 check_local_settings:
273
274         if (!(tdb->flags & TDB_MUTEX_LOCKING)) {
275                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_mutex_open_ok[%s]: "
276                          "Can use mutexes only with "
277                          "MUTEX_LOCKING or NOLOCK\n",
278                          tdb->name));
279                 return false;
280         }
281
282         if (tdb_mutex_size(tdb) != header->mutex_size) {
283                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_mutex_open_ok[%s]: "
284                          "Mutex size changed from %u to %u\n.",
285                          tdb->name,
286                          (unsigned int)header->mutex_size,
287                          (unsigned int)tdb_mutex_size(tdb)));
288                 return false;
289         }
290
291         return true;
292 }
293
294 _PUBLIC_ struct tdb_context *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
295                                 int open_flags, mode_t mode,
296                                 const struct tdb_logging_context *log_ctx,
297                                 tdb_hash_func hash_fn)
298 {
299         int orig_errno = errno;
300         struct tdb_header header;
301         struct tdb_context *tdb;
302         struct stat st;
303         int rev = 0;
304         bool locked = false;
305         unsigned char *vp;
306         uint32_t vertest;
307         unsigned v;
308         const char *hash_alg;
309         uint32_t magic1, magic2;
310         int ret;
311
312         ZERO_STRUCT(header);
313
314         if (!(tdb = (struct tdb_context *)calloc(1, sizeof *tdb))) {
315                 /* Can't log this */
316                 errno = ENOMEM;
317                 goto fail;
318         }
319         tdb_io_init(tdb);
320
321         if (tdb_flags & TDB_INTERNAL) {
322                 tdb_flags |= TDB_INCOMPATIBLE_HASH;
323         }
324         if (tdb_flags & TDB_MUTEX_LOCKING) {
325                 tdb_flags |= TDB_INCOMPATIBLE_HASH;
326         }
327
328         tdb->fd = -1;
329 #ifdef TDB_TRACE
330         tdb->tracefd = -1;
331 #endif
332         tdb->name = NULL;
333         tdb->map_ptr = NULL;
334         tdb->flags = tdb_flags;
335         tdb->open_flags = open_flags;
336         if (log_ctx) {
337                 tdb->log = *log_ctx;
338         } else {
339                 tdb->log.log_fn = null_log_fn;
340                 tdb->log.log_private = NULL;
341         }
342
343         if (name == NULL && (tdb_flags & TDB_INTERNAL)) {
344                 name = "__TDB_INTERNAL__";
345         }
346
347         if (name == NULL) {
348                 tdb->name = discard_const_p(char, "__NULL__");
349                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: called with name == NULL\n"));
350                 tdb->name = NULL;
351                 errno = EINVAL;
352                 goto fail;
353         }
354
355         /* now make a copy of the name, as the caller memory might go away */
356         if (!(tdb->name = (char *)strdup(name))) {
357                 /*
358                  * set the name as the given string, so that tdb_name() will
359                  * work in case of an error.
360                  */
361                 tdb->name = discard_const_p(char, name);
362                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: can't strdup(%s)\n",
363                          name));
364                 tdb->name = NULL;
365                 errno = ENOMEM;
366                 goto fail;
367         }
368
369         if (hash_fn) {
370                 tdb->hash_fn = hash_fn;
371                 hash_alg = "the user defined";
372         } else {
373                 /* This controls what we use when creating a tdb. */
374                 if (tdb->flags & TDB_INCOMPATIBLE_HASH) {
375                         tdb->hash_fn = tdb_jenkins_hash;
376                 } else {
377                         tdb->hash_fn = tdb_old_hash;
378                 }
379                 hash_alg = "either default";
380         }
381
382         /* cache the page size */
383         tdb->page_size = getpagesize();
384         if (tdb->page_size <= 0) {
385                 tdb->page_size = 0x2000;
386         }
387
388         tdb->max_dead_records = (tdb_flags & TDB_VOLATILE) ? 5 : 0;
389
390         if ((open_flags & O_ACCMODE) == O_WRONLY) {
391                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: can't open tdb %s write-only\n",
392                          name));
393                 errno = EINVAL;
394                 goto fail;
395         }
396
397         if (hash_size == 0)
398                 hash_size = DEFAULT_HASH_SIZE;
399         if ((open_flags & O_ACCMODE) == O_RDONLY) {
400                 tdb->read_only = 1;
401                 /* read only databases don't do locking or clear if first */
402                 tdb->flags |= TDB_NOLOCK;
403                 tdb->flags &= ~(TDB_CLEAR_IF_FIRST|TDB_MUTEX_LOCKING);
404         }
405
406         if ((tdb->flags & TDB_ALLOW_NESTING) &&
407             (tdb->flags & TDB_DISALLOW_NESTING)) {
408                 tdb->ecode = TDB_ERR_NESTING;
409                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
410                         "allow_nesting and disallow_nesting are not allowed together!"));
411                 errno = EINVAL;
412                 goto fail;
413         }
414
415         if (tdb->flags & TDB_MUTEX_LOCKING) {
416                 /*
417                  * Here we catch bugs in the callers,
418                  * the runtime check for existing tdb's comes later.
419                  */
420
421                 if (!(tdb->flags & TDB_CLEAR_IF_FIRST)) {
422                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
423                                 "invalid flags for %s - TDB_MUTEX_LOCKING "
424                                 "requires TDB_CLEAR_IF_FIRST\n", name));
425                         errno = EINVAL;
426                         goto fail;
427                 }
428
429                 if (tdb->flags & TDB_INTERNAL) {
430                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
431                                 "invalid flags for %s - TDB_MUTEX_LOCKING and "
432                                 "TDB_INTERNAL are not allowed together\n", name));
433                         errno = EINVAL;
434                         goto fail;
435                 }
436
437                 if (tdb->flags & TDB_NOMMAP) {
438                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
439                                 "invalid flags for %s - TDB_MUTEX_LOCKING and "
440                                 "TDB_NOMMAP are not allowed together\n", name));
441                         errno = EINVAL;
442                         goto fail;
443                 }
444
445                 if (tdb->read_only) {
446                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
447                                 "invalid flags for %s - TDB_MUTEX_LOCKING "
448                                 "not allowed read only\n", name));
449                         errno = EINVAL;
450                         goto fail;
451                 }
452
453                 /*
454                  * The callers should have called
455                  * tdb_runtime_check_for_robust_mutexes()
456                  * before using TDB_MUTEX_LOCKING!
457                  *
458                  * This makes sure the caller understands
459                  * that the locking may behave a bit differently
460                  * than with pure fcntl locking. E.g. multiple
461                  * read locks are not supported.
462                  */
463                 if (!tdb_runtime_check_for_robust_mutexes()) {
464                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
465                                 "invalid flags for %s - TDB_MUTEX_LOCKING "
466                                 "requires support for robust_mutexes\n",
467                                 name));
468                         errno = ENOSYS;
469                         goto fail;
470                 }
471         }
472
473         if (getenv("TDB_NO_FSYNC")) {
474                 tdb->flags |= TDB_NOSYNC;
475         }
476
477         /*
478          * TDB_ALLOW_NESTING is the default behavior.
479          * Note: this may change in future versions!
480          */
481         if (!(tdb->flags & TDB_DISALLOW_NESTING)) {
482                 tdb->flags |= TDB_ALLOW_NESTING;
483         }
484
485         /* internal databases don't mmap or lock, and start off cleared */
486         if (tdb->flags & TDB_INTERNAL) {
487                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
488                 tdb->flags &= ~TDB_CLEAR_IF_FIRST;
489                 if (tdb_new_database(tdb, &header, hash_size) != 0) {
490                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: tdb_new_database failed!"));
491                         goto fail;
492                 }
493                 tdb->hash_size = hash_size;
494                 goto internal;
495         }
496
497         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
498                 TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_open_ex: could not open file %s: %s\n",
499                          name, strerror(errno)));
500                 goto fail;      /* errno set by open(2) */
501         }
502
503         /* on exec, don't inherit the fd */
504         v = fcntl(tdb->fd, F_GETFD, 0);
505         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
506
507         /* ensure there is only one process initialising at once */
508         if (tdb_nest_lock(tdb, OPEN_LOCK, F_WRLCK, TDB_LOCK_WAIT) == -1) {
509                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to get open lock on %s: %s\n",
510                          name, strerror(errno)));
511                 goto fail;      /* errno set by tdb_brlock */
512         }
513
514         /* we need to zero database if we are the only one with it open */
515         if ((tdb_flags & TDB_CLEAR_IF_FIRST) &&
516             (!tdb->read_only)) {
517                 ret = tdb_nest_lock(tdb, ACTIVE_LOCK, F_WRLCK,
518                                     TDB_LOCK_NOWAIT|TDB_LOCK_PROBE);
519                 locked = (ret == 0);
520
521                 if (locked) {
522                         ret = tdb_brlock(tdb, F_WRLCK, FREELIST_TOP, 0,
523                                          TDB_LOCK_WAIT);
524                         if (ret == -1) {
525                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
526                                          "tdb_brlock failed for %s: %s\n",
527                                          name, strerror(errno)));
528                                 goto fail;
529                         }
530                         ret = tdb_new_database(tdb, &header, hash_size);
531                         if (ret == -1) {
532                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
533                                          "tdb_new_database failed for "
534                                          "%s: %s\n", name, strerror(errno)));
535                                 tdb_unlockall(tdb);
536                                 goto fail;
537                         }
538                         ret = tdb_brunlock(tdb, F_WRLCK, FREELIST_TOP, 0);
539                         if (ret == -1) {
540                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
541                                          "tdb_unlockall failed for %s: %s\n",
542                                          name, strerror(errno)));
543                                 goto fail;
544                         }
545                         ret = lseek(tdb->fd, 0, SEEK_SET);
546                         if (ret == -1) {
547                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
548                                          "lseek failed for %s: %s\n",
549                                          name, strerror(errno)));
550                                 goto fail;
551                         }
552                 }
553         }
554
555         errno = 0;
556         if (read(tdb->fd, &header, sizeof(header)) != sizeof(header)
557             || strcmp(header.magic_food, TDB_MAGIC_FOOD) != 0) {
558                 if (!(open_flags & O_CREAT) ||
559                     tdb_new_database(tdb, &header, hash_size) == -1) {
560                         if (errno == 0) {
561                                 errno = EIO; /* ie bad format or something */
562                         }
563                         goto fail;
564                 }
565                 rev = (tdb->flags & TDB_CONVERT);
566         } else if (header.version != TDB_VERSION
567                    && !(rev = (header.version==TDB_BYTEREV(TDB_VERSION)))) {
568                 /* wrong version */
569                 errno = EIO;
570                 goto fail;
571         }
572         vp = (unsigned char *)&header.version;
573         vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
574                   (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
575         tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
576         if (!rev)
577                 tdb->flags &= ~TDB_CONVERT;
578         else {
579                 tdb->flags |= TDB_CONVERT;
580                 tdb_convert(&header, sizeof(header));
581         }
582
583         /*
584          * We only use st.st_dev and st.st_ino from the raw fstat()
585          * call, everything else needs to use tdb_fstat() in order
586          * to skip tdb->hdr_ofs!
587          */
588         if (fstat(tdb->fd, &st) == -1) {
589                 goto fail;
590         }
591         tdb->device = st.st_dev;
592         tdb->inode = st.st_ino;
593         ZERO_STRUCT(st);
594
595         if (header.rwlocks != 0 &&
596             header.rwlocks != TDB_FEATURE_FLAG_MAGIC &&
597             header.rwlocks != TDB_HASH_RWLOCK_MAGIC) {
598                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: spinlocks no longer supported\n"));
599                 errno = ENOSYS;
600                 goto fail;
601         }
602
603         if (header.hash_size == 0) {
604                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: invalid database: 0 hash_size\n"));
605                 errno = ENOSYS;
606                 goto fail;
607         }
608
609         tdb->hash_size = header.hash_size;
610
611         if (header.rwlocks == TDB_FEATURE_FLAG_MAGIC) {
612                 tdb->feature_flags = header.feature_flags;
613         }
614
615         if (tdb->feature_flags & ~TDB_SUPPORTED_FEATURE_FLAGS) {
616                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: unsupported "
617                          "features in tdb %s: 0x%08x (supported: 0x%08x)\n",
618                          name, (unsigned)tdb->feature_flags,
619                          (unsigned)TDB_SUPPORTED_FEATURE_FLAGS));
620                 errno = ENOSYS;
621                 goto fail;
622         }
623
624         if (tdb->feature_flags & TDB_FEATURE_FLAG_MUTEX) {
625                 if (!tdb_mutex_open_ok(tdb, &header)) {
626                         errno = EINVAL;
627                         goto fail;
628                 }
629
630                 /*
631                  * We need to remember the hdr_ofs
632                  * also for the TDB_NOLOCK case
633                  * if the current library doesn't support
634                  * mutex locking.
635                  */
636                 tdb->hdr_ofs = header.mutex_size;
637         }
638
639         if ((header.magic1_hash == 0) && (header.magic2_hash == 0)) {
640                 /* older TDB without magic hash references */
641                 tdb->hash_fn = tdb_old_hash;
642         } else if (!check_header_hash(tdb, &header, !hash_fn,
643                                       &magic1, &magic2)) {
644                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
645                          "%s was not created with %s hash function we are using\n"
646                          "magic1_hash[0x%08X %s 0x%08X] "
647                          "magic2_hash[0x%08X %s 0x%08X]\n",
648                          name, hash_alg,
649                          header.magic1_hash,
650                          (header.magic1_hash == magic1) ? "==" : "!=",
651                          magic1,
652                          header.magic2_hash,
653                          (header.magic2_hash == magic2) ? "==" : "!=",
654                          magic2));
655                 errno = EINVAL;
656                 goto fail;
657         }
658
659         /* Is it already in the open list?  If so, fail. */
660         if (tdb_already_open(tdb->device, tdb->inode)) {
661                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
662                          "%s (%d,%d) is already open in this process\n",
663                          name, (int)tdb->device, (int)tdb->inode));
664                 errno = EBUSY;
665                 goto fail;
666         }
667
668         /*
669          * We had tdb_mmap(tdb) here before,
670          * but we need to use tdb_fstat(),
671          * which is triggered from tdb_oob() before calling tdb_mmap().
672          * As this skips tdb->hdr_ofs.
673          */
674         tdb->map_size = 0;
675         ret = tdb->methods->tdb_oob(tdb, 0, 1, 0);
676         if (ret == -1) {
677                 errno = EIO;
678                 goto fail;
679         }
680
681         if (tdb->feature_flags & TDB_FEATURE_FLAG_MUTEX) {
682                 if (!(tdb->flags & TDB_NOLOCK)) {
683                         ret = tdb_mutex_mmap(tdb);
684                         if (ret != 0) {
685                                 goto fail;
686                         }
687                 }
688         }
689
690         if (tdb->hash_size > UINT32_MAX/4) {
691                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
692                          "hash size %"PRIu32" too large\n", tdb->hash_size));
693                 errno = EINVAL;
694                 goto fail;
695         }
696
697         ret = tdb->methods->tdb_oob(tdb, FREELIST_TOP, 4*tdb->hash_size, 1);
698         if (ret == -1) {
699                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
700                          "hash size %"PRIu32" does not fit\n", tdb->hash_size));
701                 errno = EINVAL;
702                 goto fail;
703         }
704
705         if (locked) {
706                 if (tdb_nest_unlock(tdb, ACTIVE_LOCK, F_WRLCK, false) == -1) {
707                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
708                                  "failed to release ACTIVE_LOCK on %s: %s\n",
709                                  name, strerror(errno)));
710                         goto fail;
711                 }
712
713         }
714
715         /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
716            we didn't get the initial exclusive lock as we need to let all other
717            users know we're using it. */
718
719         if (tdb_flags & TDB_CLEAR_IF_FIRST) {
720                 /* leave this lock in place to indicate it's in use */
721                 if (tdb_nest_lock(tdb, ACTIVE_LOCK, F_RDLCK, TDB_LOCK_WAIT) == -1) {
722                         goto fail;
723                 }
724         }
725
726         /* if needed, run recovery */
727         if (tdb_transaction_recover(tdb) == -1) {
728                 goto fail;
729         }
730
731 #ifdef TDB_TRACE
732         {
733                 char tracefile[strlen(name) + 32];
734
735                 snprintf(tracefile, sizeof(tracefile),
736                          "%s.trace.%li", name, (long)getpid());
737                 tdb->tracefd = open(tracefile, O_WRONLY|O_CREAT|O_EXCL, 0600);
738                 if (tdb->tracefd >= 0) {
739                         tdb_enable_seqnum(tdb);
740                         tdb_trace_open(tdb, "tdb_open", hash_size, tdb_flags,
741                                        open_flags);
742                 } else
743                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to open trace file %s!\n", tracefile));
744         }
745 #endif
746
747  internal:
748         /* Internal (memory-only) databases skip all the code above to
749          * do with disk files, and resume here by releasing their
750          * open lock and hooking into the active list. */
751         if (tdb_nest_unlock(tdb, OPEN_LOCK, F_WRLCK, false) == -1) {
752                 goto fail;
753         }
754         tdb->next = tdbs;
755         tdbs = tdb;
756         errno = orig_errno;
757         return tdb;
758
759  fail:
760         { int save_errno = errno;
761
762         if (!tdb)
763                 return NULL;
764
765 #ifdef TDB_TRACE
766         close(tdb->tracefd);
767 #endif
768         if (tdb->map_ptr) {
769                 if (tdb->flags & TDB_INTERNAL)
770                         SAFE_FREE(tdb->map_ptr);
771                 else
772                         tdb_munmap(tdb);
773         }
774         if (tdb->fd != -1)
775                 if (close(tdb->fd) != 0)
776                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to close tdb->fd on error!\n"));
777         SAFE_FREE(tdb->lockrecs);
778         SAFE_FREE(tdb->name);
779         SAFE_FREE(tdb);
780         errno = save_errno;
781         return NULL;
782         }
783 }
784
785 /*
786  * Set the maximum number of dead records per hash chain
787  */
788
789 _PUBLIC_ void tdb_set_max_dead(struct tdb_context *tdb, int max_dead)
790 {
791         tdb->max_dead_records = max_dead;
792 }
793
794 /**
795  * Close a database.
796  *
797  * @returns -1 for error; 0 for success.
798  **/
799 _PUBLIC_ int tdb_close(struct tdb_context *tdb)
800 {
801         struct tdb_context **i;
802         int ret = 0;
803
804         if (tdb->transaction) {
805                 tdb_transaction_cancel(tdb);
806         }
807         tdb_trace(tdb, "tdb_close");
808
809         if (tdb->map_ptr) {
810                 if (tdb->flags & TDB_INTERNAL)
811                         SAFE_FREE(tdb->map_ptr);
812                 else
813                         tdb_munmap(tdb);
814         }
815
816         tdb_mutex_munmap(tdb);
817
818         SAFE_FREE(tdb->name);
819         if (tdb->fd != -1) {
820                 ret = close(tdb->fd);
821                 tdb->fd = -1;
822         }
823         SAFE_FREE(tdb->lockrecs);
824
825         /* Remove from contexts list */
826         for (i = &tdbs; *i; i = &(*i)->next) {
827                 if (*i == tdb) {
828                         *i = tdb->next;
829                         break;
830                 }
831         }
832
833 #ifdef TDB_TRACE
834         close(tdb->tracefd);
835 #endif
836         memset(tdb, 0, sizeof(*tdb));
837         SAFE_FREE(tdb);
838
839         return ret;
840 }
841
842 /* register a loging function */
843 _PUBLIC_ void tdb_set_logging_function(struct tdb_context *tdb,
844                                        const struct tdb_logging_context *log_ctx)
845 {
846         tdb->log = *log_ctx;
847 }
848
849 _PUBLIC_ void *tdb_get_logging_private(struct tdb_context *tdb)
850 {
851         return tdb->log.log_private;
852 }
853
854 static int tdb_reopen_internal(struct tdb_context *tdb, bool active_lock)
855 {
856 #if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
857         !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
858         struct stat st;
859 #endif
860
861         if (tdb->flags & TDB_INTERNAL) {
862                 return 0; /* Nothing to do. */
863         }
864
865         if (tdb_have_extra_locks(tdb)) {
866                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed with locks held\n"));
867                 goto fail;
868         }
869
870         if (tdb->transaction != 0) {
871                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed inside a transaction\n"));
872                 goto fail;
873         }
874
875 /* If we have real pread & pwrite, we can skip reopen. */
876 #if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
877         !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
878         if (tdb_munmap(tdb) != 0) {
879                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: munmap failed (%s)\n", strerror(errno)));
880                 goto fail;
881         }
882         if (close(tdb->fd) != 0)
883                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: WARNING closing tdb->fd failed!\n"));
884         tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
885         if (tdb->fd == -1) {
886                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: open failed (%s)\n", strerror(errno)));
887                 goto fail;
888         }
889         /*
890          * We only use st.st_dev and st.st_ino from the raw fstat()
891          * call, everything else needs to use tdb_fstat() in order
892          * to skip tdb->hdr_ofs!
893          */
894         if (fstat(tdb->fd, &st) != 0) {
895                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: fstat failed (%s)\n", strerror(errno)));
896                 goto fail;
897         }
898         if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
899                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: file dev/inode has changed!\n"));
900                 goto fail;
901         }
902         ZERO_STRUCT(st);
903
904         /*
905          * We had tdb_mmap(tdb) here before,
906          * but we need to use tdb_fstat(),
907          * which is triggered from tdb_oob() before calling tdb_mmap().
908          * As this skips tdb->hdr_ofs.
909          */
910         tdb->map_size = 0;
911         if (tdb->methods->tdb_oob(tdb, 0, 1, 0) != 0) {
912                 goto fail;
913         }
914 #endif /* fake pread or pwrite */
915
916         /* We may still think we hold the active lock. */
917         tdb->num_lockrecs = 0;
918         SAFE_FREE(tdb->lockrecs);
919         tdb->lockrecs_array_length = 0;
920
921         if (active_lock && tdb_nest_lock(tdb, ACTIVE_LOCK, F_RDLCK, TDB_LOCK_WAIT) == -1) {
922                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: failed to obtain active lock\n"));
923                 goto fail;
924         }
925
926         return 0;
927
928 fail:
929         tdb_close(tdb);
930         return -1;
931 }
932
933 /* reopen a tdb - this can be used after a fork to ensure that we have an independent
934    seek pointer from our parent and to re-establish locks */
935 _PUBLIC_ int tdb_reopen(struct tdb_context *tdb)
936 {
937         return tdb_reopen_internal(tdb, tdb->flags & TDB_CLEAR_IF_FIRST);
938 }
939
940 /* reopen all tdb's */
941 _PUBLIC_ int tdb_reopen_all(int parent_longlived)
942 {
943         struct tdb_context *tdb;
944
945         for (tdb=tdbs; tdb; tdb = tdb->next) {
946                 bool active_lock = (tdb->flags & TDB_CLEAR_IF_FIRST);
947
948                 /*
949                  * If the parent is longlived (ie. a
950                  * parent daemon architecture), we know
951                  * it will keep it's active lock on a
952                  * tdb opened with CLEAR_IF_FIRST. Thus
953                  * for child processes we don't have to
954                  * add an active lock. This is essential
955                  * to improve performance on systems that
956                  * keep POSIX locks as a non-scalable data
957                  * structure in the kernel.
958                  */
959                 if (parent_longlived) {
960                         /* Ensure no clear-if-first. */
961                         active_lock = false;
962                 }
963
964                 if (tdb_reopen_internal(tdb, active_lock) != 0)
965                         return -1;
966         }
967
968         return 0;
969 }