- /* on exec, don't inherit the fd */
- v = fcntl(tdb->fd, F_GETFD, 0);
- fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
-
- /* ensure there is only one process initialising at once */
- if (tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK) == -1) {
- /* errno set by tdb_brlock */
- saved_errno = errno;
- goto fail;
- }
-
- if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
- || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
- if (!(open_flags & O_CREAT)) {
- tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
- "tdb_open: %s is not a tdb file", name);
- goto fail;
- }
- if (tdb_new_database(tdb, seed, &hdr) == -1) {
- goto fail;
- }
- } else if (hdr.version != TDB_VERSION) {
- if (hdr.version == bswap_64(TDB_VERSION))
- tdb->flags |= TDB_CONVERT;
- else {
- /* wrong version */
- tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
- "tdb_open: %s is unknown version 0x%llx",
- name, (long long)hdr.version);
- goto fail;
- }
- }
-
- tdb_convert(tdb, &hdr, sizeof(hdr));
- tdb->hash_seed = hdr.hash_seed;
- hash_test = TDB_HASH_MAGIC;
- hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
- if (hdr.hash_test != hash_test) {
- /* wrong hash variant */
- tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
- "tdb_open: %s uses a different hash function",
- name);
- goto fail;
- }
-
- if (fstat(tdb->fd, &st) == -1) {
- saved_errno = errno;
- tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
- "tdb_open: could not stat open %s: %s",
- name, strerror(errno));
- goto fail;
- }
-
- /* Is it already in the open list? If so, fail. */
- if (tdb_already_open(st.st_dev, st.st_ino)) {
- /* FIXME */
- tdb_logerr(tdb, TDB_ERR_NESTING, TDB_DEBUG_ERROR,
- "tdb_open: %s (%d,%d) is already open in this"
- " process",
- name, (int)st.st_dev, (int)st.st_ino);
- goto fail;
- }
-
- tdb->name = strdup(name);
- if (!tdb->name) {
- tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_ERROR,
- "tdb_open: failed to allocate name");
- goto fail;
- }
-
- tdb->device = st.st_dev;
- tdb->inode = st.st_ino;
- tdb_unlock_open(tdb);
-
- /* This make sure we have current map_size and mmap. */
- tdb->methods->oob(tdb, tdb->map_size + 1, true);
-
- /* Now it's fully formed, recover if necessary. */
- if (tdb_needs_recovery(tdb) && tdb_lock_and_recover(tdb) == -1) {
- goto fail;
- }
-
- if (tdb_flist_init(tdb) == -1)
- goto fail;
-
- tdb->next = tdbs;
- tdbs = tdb;
- return tdb;
-
- fail:
- /* Map ecode to some logical errno. */
- if (!saved_errno) {
- switch (tdb->ecode) {
- case TDB_ERR_CORRUPT:
- case TDB_ERR_IO:
- saved_errno = EIO;
- break;
- case TDB_ERR_LOCK:
- saved_errno = EWOULDBLOCK;
- break;
- case TDB_ERR_OOM:
- saved_errno = ENOMEM;
- break;
- case TDB_ERR_EINVAL:
- saved_errno = EINVAL;
- break;
- case TDB_ERR_NESTING:
- saved_errno = EBUSY;
- break;
- default:
- saved_errno = EINVAL;
- break;
- }