2 #include <ccan/tdb2/tdb2.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
8 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
10 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
11 static struct tdb_context *tdbs = NULL;
13 PRINTF_FMT(4, 5) static void
14 null_log_fn(struct tdb_context *tdb,
15 enum tdb_debug_level level, void *priv,
20 static bool tdb_already_open(dev_t device, ino_t ino)
22 struct tdb_context *i;
24 for (i = tdbs; i; i = i->next) {
25 if (i->device == device && i->inode == ino) {
33 static uint64_t random_number(struct tdb_context *tdb)
39 fd = open("/dev/urandom", O_RDONLY);
41 if (tdb_read_all(fd, &ret, sizeof(ret))) {
42 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
43 "tdb_open: random from /dev/urandom\n");
49 /* FIXME: Untested! Based on Wikipedia protocol description! */
50 fd = open("/dev/egd-pool", O_RDWR);
52 /* Command is 1, next byte is size we want to read. */
53 char cmd[2] = { 1, sizeof(uint64_t) };
54 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
55 char reply[1 + sizeof(uint64_t)];
56 int r = read(fd, reply, sizeof(reply));
58 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
59 "tdb_open: %u random bytes from"
60 " /dev/egd-pool\n", r-1);
61 /* Copy at least some bytes. */
62 memcpy(&ret, reply+1, r - 1);
63 if (reply[0] == sizeof(uint64_t)
64 && r == sizeof(reply)) {
73 /* Fallback: pid and time. */
74 gettimeofday(&now, NULL);
75 ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
76 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
77 "tdb_open: random from getpid and time\n");
82 struct tdb_header hdr;
83 struct tdb_freelist flist;
86 /* initialise a new database */
87 static int tdb_new_database(struct tdb_context *tdb,
88 struct tdb_attribute_seed *seed,
89 struct tdb_header *hdr)
91 /* We make it up in memory, then write it out if not internal */
92 struct new_database newdb;
93 unsigned int magic_len;
95 /* Fill in the header */
96 newdb.hdr.version = TDB_VERSION;
98 newdb.hdr.hash_seed = seed->seed;
100 newdb.hdr.hash_seed = random_number(tdb);
101 newdb.hdr.hash_test = TDB_HASH_MAGIC;
102 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
103 sizeof(newdb.hdr.hash_test),
106 newdb.hdr.recovery = 0;
107 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
108 /* Initial hashes are empty. */
109 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
112 newdb.hdr.free_list = offsetof(struct new_database, flist);
113 memset(&newdb.flist, 0, sizeof(newdb.flist));
114 set_header(NULL, &newdb.flist.hdr, 0,
115 sizeof(newdb.flist) - sizeof(newdb.flist.hdr),
116 sizeof(newdb.flist) - sizeof(newdb.flist.hdr), 1);
119 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
120 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
122 /* This creates an endian-converted database, as if read from disk */
123 magic_len = sizeof(newdb.hdr.magic_food);
125 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
129 if (tdb->flags & TDB_INTERNAL) {
130 tdb->map_size = sizeof(newdb);
131 tdb->map_ptr = malloc(tdb->map_size);
133 tdb->ecode = TDB_ERR_OOM;
136 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
139 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
142 if (ftruncate(tdb->fd, 0) == -1)
145 if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
146 tdb->ecode = TDB_ERR_IO;
152 struct tdb_context *tdb_open(const char *name, int tdb_flags,
153 int open_flags, mode_t mode,
154 union tdb_attribute *attr)
156 struct tdb_context *tdb;
161 struct tdb_header hdr;
162 struct tdb_attribute_seed *seed = NULL;
164 tdb = malloc(sizeof(*tdb));
172 tdb->direct_access = 0;
174 tdb->map_size = sizeof(struct tdb_header);
175 tdb->ecode = TDB_SUCCESS;
176 tdb->flags = tdb_flags;
177 tdb->log = null_log_fn;
178 tdb->log_priv = NULL;
179 tdb->transaction = NULL;
185 switch (attr->base.attr) {
186 case TDB_ATTRIBUTE_LOG:
187 tdb->log = attr->log.log_fn;
188 tdb->log_priv = attr->log.log_private;
190 case TDB_ATTRIBUTE_HASH:
191 tdb->khash = attr->hash.hash_fn;
192 tdb->hash_priv = attr->hash.hash_private;
194 case TDB_ATTRIBUTE_SEED:
198 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
199 "tdb_open: unknown attribute type %u\n",
204 attr = attr->base.next;
207 if ((open_flags & O_ACCMODE) == O_WRONLY) {
208 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
209 "tdb_open: can't open tdb %s write-only\n", name);
214 if ((open_flags & O_ACCMODE) == O_RDONLY) {
215 tdb->read_only = true;
216 /* read only databases don't do locking */
217 tdb->flags |= TDB_NOLOCK;
218 tdb->mmap_flags = PROT_READ;
220 tdb->read_only = false;
221 tdb->mmap_flags = PROT_READ | PROT_WRITE;
224 /* internal databases don't need any of the rest. */
225 if (tdb->flags & TDB_INTERNAL) {
226 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
227 if (tdb_new_database(tdb, seed, &hdr) != 0) {
228 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
229 "tdb_open: tdb_new_database failed!");
232 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
233 tdb->hash_seed = hdr.hash_seed;
238 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
239 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
240 "tdb_open: could not open file %s: %s\n",
241 name, strerror(errno));
242 goto fail; /* errno set by open(2) */
245 /* on exec, don't inherit the fd */
246 v = fcntl(tdb->fd, F_GETFD, 0);
247 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
249 /* ensure there is only one process initialising at once */
250 if (tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK) == -1) {
251 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
252 "tdb_open: failed to get open lock on %s: %s\n",
253 name, strerror(errno));
254 goto fail; /* errno set by tdb_brlock */
257 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
258 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
259 if (!(open_flags & O_CREAT)
260 || tdb_new_database(tdb, seed, &hdr) == -1) {
262 errno = EIO; /* ie bad format or something */
266 } else if (hdr.version != TDB_VERSION) {
267 if (hdr.version == bswap_64(TDB_VERSION))
268 tdb->flags |= TDB_CONVERT;
271 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
272 "tdb_open: %s is unknown version 0x%llx\n",
273 name, (long long)hdr.version);
279 tdb_convert(tdb, &hdr, sizeof(hdr));
280 tdb->hash_seed = hdr.hash_seed;
281 hash_test = TDB_HASH_MAGIC;
282 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
283 if (hdr.hash_test != hash_test) {
284 /* wrong hash variant */
285 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
286 "tdb_open: %s uses a different hash function\n",
292 if (fstat(tdb->fd, &st) == -1)
295 /* Is it already in the open list? If so, fail. */
296 if (tdb_already_open(st.st_dev, st.st_ino)) {
298 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
299 "tdb_open: %s (%d,%d) is already open in this process\n",
300 name, (int)st.st_dev, (int)st.st_ino);
305 tdb->name = strdup(name);
311 tdb->device = st.st_dev;
312 tdb->inode = st.st_ino;
313 tdb_unlock_open(tdb);
315 /* This make sure we have current map_size and mmap. */
316 tdb->methods->oob(tdb, tdb->map_size + 1, true);
318 /* Now it's fully formed, recover if necessary. */
319 if (tdb_needs_recovery(tdb) && tdb_lock_and_recover(tdb) == -1) {
324 if (tdb_flist_init(tdb) == -1)
341 if (tdb->flags & TDB_INTERNAL) {
346 free((char *)tdb->name);
348 if (close(tdb->fd) != 0)
349 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
350 "tdb_open: failed to close tdb->fd"
357 /* FIXME: modify, don't rewrite! */
358 static int update_rec_hdr(struct tdb_context *tdb,
362 struct tdb_used_record *rec,
365 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
367 if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
370 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
373 /* Returns -1 on error, 0 on OK */
374 static int replace_data(struct tdb_context *tdb,
376 struct tdb_data key, struct tdb_data dbuf,
377 tdb_off_t old_off, tdb_len_t old_room,
382 /* Allocate a new record. */
383 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
384 if (unlikely(new_off == TDB_OFF_ERR))
387 /* We didn't like the existing one: remove it. */
389 add_free_record(tdb, old_off,
390 sizeof(struct tdb_used_record)
391 + key.dsize + old_room);
392 if (replace_in_hash(tdb, h, new_off) == -1)
395 if (add_to_hash(tdb, h, new_off) == -1)
399 new_off += sizeof(struct tdb_used_record);
400 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
403 new_off += key.dsize;
404 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
407 /* FIXME: tdb_increment_seqnum(tdb); */
411 int tdb_store(struct tdb_context *tdb,
412 struct tdb_data key, struct tdb_data dbuf, int flag)
416 tdb_len_t old_room = 0;
417 struct tdb_used_record rec;
420 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
421 if (unlikely(off == TDB_OFF_ERR))
424 /* Now we have lock on this hash bucket. */
425 if (flag == TDB_INSERT) {
427 tdb->ecode = TDB_ERR_EXISTS;
432 old_room = rec_data_length(&rec)
433 + rec_extra_padding(&rec);
434 if (old_room >= dbuf.dsize) {
435 /* Can modify in-place. Easy! */
436 if (update_rec_hdr(tdb, off,
437 key.dsize, dbuf.dsize,
440 if (tdb->methods->write(tdb, off + sizeof(rec)
442 dbuf.dptr, dbuf.dsize))
444 tdb_unlock_hashes(tdb, h.hlock_start,
445 h.hlock_range, F_WRLCK);
448 /* FIXME: See if right record is free? */
450 if (flag == TDB_MODIFY) {
451 /* if the record doesn't exist and we
452 are in TDB_MODIFY mode then we should fail
454 tdb->ecode = TDB_ERR_NOEXIST;
460 /* If we didn't use the old record, this implies we're growing. */
461 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
462 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
466 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
470 int tdb_append(struct tdb_context *tdb,
471 struct tdb_data key, struct tdb_data dbuf)
475 struct tdb_used_record rec;
476 tdb_len_t old_room = 0, old_dlen;
477 unsigned char *newdata;
478 struct tdb_data new_dbuf;
481 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
482 if (unlikely(off == TDB_OFF_ERR))
486 old_dlen = rec_data_length(&rec);
487 old_room = old_dlen + rec_extra_padding(&rec);
489 /* Fast path: can append in place. */
490 if (rec_extra_padding(&rec) >= dbuf.dsize) {
491 if (update_rec_hdr(tdb, off, key.dsize,
492 old_dlen + dbuf.dsize, &rec, h.h))
495 off += sizeof(rec) + key.dsize + old_dlen;
496 if (tdb->methods->write(tdb, off, dbuf.dptr,
500 /* FIXME: tdb_increment_seqnum(tdb); */
501 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
505 /* FIXME: Check right record free? */
508 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
510 tdb->ecode = TDB_ERR_OOM;
511 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
512 "tdb_append: cannot allocate %llu bytes!\n",
513 (long long)key.dsize + old_dlen + dbuf.dsize);
516 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
517 newdata, old_dlen) != 0) {
521 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
522 new_dbuf.dptr = newdata;
523 new_dbuf.dsize = old_dlen + dbuf.dsize;
529 /* If they're using tdb_append(), it implies they're growing record. */
530 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
531 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
537 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
541 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
544 struct tdb_used_record rec;
548 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
549 if (unlikely(off == TDB_OFF_ERR))
553 tdb->ecode = TDB_ERR_NOEXIST;
556 ret.dsize = rec_data_length(&rec);
557 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
561 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
565 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
568 struct tdb_used_record rec;
571 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
572 if (unlikely(off == TDB_OFF_ERR))
576 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
577 tdb->ecode = TDB_ERR_NOEXIST;
581 if (delete_from_hash(tdb, &h) == -1)
584 /* Free the deleted entry. */
585 if (add_free_record(tdb, off,
586 sizeof(struct tdb_used_record)
587 + rec_key_length(&rec)
588 + rec_data_length(&rec)
589 + rec_extra_padding(&rec)) != 0)
592 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
596 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
600 int tdb_close(struct tdb_context *tdb)
602 struct tdb_context **i;
605 tdb_trace(tdb, "tdb_close");
607 if (tdb->transaction) {
608 tdb_transaction_cancel(tdb);
612 if (tdb->flags & TDB_INTERNAL)
617 free((char *)tdb->name);
619 ret = close(tdb->fd);
624 /* Remove from contexts list */
625 for (i = &tdbs; *i; i = &(*i)->next) {
640 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
645 const char *tdb_errorstr(struct tdb_context *tdb)
647 /* Gcc warns if you miss a case in the switch, so use that. */
648 switch (tdb->ecode) {
649 case TDB_SUCCESS: return "Success";
650 case TDB_ERR_CORRUPT: return "Corrupt database";
651 case TDB_ERR_IO: return "IO Error";
652 case TDB_ERR_LOCK: return "Locking error";
653 case TDB_ERR_OOM: return "Out of memory";
654 case TDB_ERR_EXISTS: return "Record exists";
655 case TDB_ERR_NESTING: return "Transaction already started";
656 case TDB_ERR_EINVAL: return "Invalid parameter";
657 case TDB_ERR_NOEXIST: return "Record does not exist";
658 case TDB_ERR_RDONLY: return "write not permitted";
660 return "Invalid error code";