Coverage Report

Created: 2026-02-14 07:07

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