2 #include <ccan/tdb2/tdb2.h>
7 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
9 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
10 static struct tdb_context *tdbs = NULL;
12 static bool tdb_already_open(dev_t device, ino_t ino)
14 struct tdb_context *i;
16 for (i = tdbs; i; i = i->next) {
17 if (i->device == device && i->inode == ino) {
25 static uint64_t random_number(struct tdb_context *tdb)
31 fd = open("/dev/urandom", O_RDONLY);
33 if (tdb_read_all(fd, &ret, sizeof(ret))) {
34 tdb_logerr(tdb, TDB_SUCCESS, TDB_DEBUG_TRACE,
35 "tdb_open: random from /dev/urandom");
41 /* FIXME: Untested! Based on Wikipedia protocol description! */
42 fd = open("/dev/egd-pool", O_RDWR);
44 /* Command is 1, next byte is size we want to read. */
45 char cmd[2] = { 1, sizeof(uint64_t) };
46 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
47 char reply[1 + sizeof(uint64_t)];
48 int r = read(fd, reply, sizeof(reply));
50 tdb_logerr(tdb, TDB_SUCCESS, TDB_DEBUG_TRACE,
51 "tdb_open: %u random bytes from"
52 " /dev/egd-pool", r-1);
53 /* Copy at least some bytes. */
54 memcpy(&ret, reply+1, r - 1);
55 if (reply[0] == sizeof(uint64_t)
56 && r == sizeof(reply)) {
65 /* Fallback: pid and time. */
66 gettimeofday(&now, NULL);
67 ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
68 tdb_logerr(tdb, TDB_SUCCESS, TDB_DEBUG_TRACE,
69 "tdb_open: random from getpid and time");
74 struct tdb_header hdr;
75 struct tdb_freetable ftable;
78 /* initialise a new database */
79 static int tdb_new_database(struct tdb_context *tdb,
80 struct tdb_attribute_seed *seed,
81 struct tdb_header *hdr)
83 /* We make it up in memory, then write it out if not internal */
84 struct new_database newdb;
85 unsigned int magic_len;
87 /* Fill in the header */
88 newdb.hdr.version = TDB_VERSION;
90 newdb.hdr.hash_seed = seed->seed;
92 newdb.hdr.hash_seed = random_number(tdb);
93 newdb.hdr.hash_test = TDB_HASH_MAGIC;
94 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
95 sizeof(newdb.hdr.hash_test),
98 newdb.hdr.recovery = 0;
99 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
100 /* Initial hashes are empty. */
101 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
104 newdb.hdr.free_table = offsetof(struct new_database, ftable);
105 memset(&newdb.ftable, 0, sizeof(newdb.ftable));
106 set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
107 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
108 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr), 0);
111 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
112 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
114 /* This creates an endian-converted database, as if read from disk */
115 magic_len = sizeof(newdb.hdr.magic_food);
117 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
121 if (tdb->flags & TDB_INTERNAL) {
122 tdb->map_size = sizeof(newdb);
123 tdb->map_ptr = malloc(tdb->map_size);
125 tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_FATAL,
126 "tdb_new_database: failed to allocate");
129 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
132 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
135 if (ftruncate(tdb->fd, 0) == -1)
138 if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
139 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_FATAL,
140 "tdb_new_database: failed to write: %s",
147 struct tdb_context *tdb_open(const char *name, int tdb_flags,
148 int open_flags, mode_t mode,
149 union tdb_attribute *attr)
151 struct tdb_context *tdb;
156 struct tdb_header hdr;
157 struct tdb_attribute_seed *seed = NULL;
159 tdb = malloc(sizeof(*tdb));
167 tdb->direct_access = 0;
169 tdb->map_size = sizeof(struct tdb_header);
170 tdb->ecode = TDB_SUCCESS;
171 tdb->flags = tdb_flags;
173 tdb->transaction = NULL;
181 switch (attr->base.attr) {
182 case TDB_ATTRIBUTE_LOG:
183 tdb->logfn = attr->log.log_fn;
184 tdb->log_private = attr->log.log_private;
186 case TDB_ATTRIBUTE_HASH:
187 tdb->khash = attr->hash.hash_fn;
188 tdb->hash_priv = attr->hash.hash_private;
190 case TDB_ATTRIBUTE_SEED:
193 case TDB_ATTRIBUTE_STATS:
194 tdb->stats = &attr->stats;
195 /* They have stats we don't know about? Tell them. */
196 if (tdb->stats->size > sizeof(attr->stats))
197 tdb->stats->size = sizeof(attr->stats);
200 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_DEBUG_ERROR,
201 "tdb_open: unknown attribute type %u",
205 attr = attr->base.next;
208 if ((open_flags & O_ACCMODE) == O_WRONLY) {
209 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_DEBUG_ERROR,
210 "tdb_open: can't open tdb %s write-only", 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) {
230 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
231 tdb->hash_seed = hdr.hash_seed;
232 tdb_ftable_init(tdb);
236 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
237 /* errno set by open(2) */
239 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
240 "tdb_open: could not open file %s: %s",
241 name, strerror(errno));
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 /* errno set by tdb_brlock */
256 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
257 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
258 if (!(open_flags & O_CREAT)) {
259 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
260 "tdb_open: %s is not a tdb file", name);
263 if (tdb_new_database(tdb, seed, &hdr) == -1) {
266 } else if (hdr.version != TDB_VERSION) {
267 if (hdr.version == bswap_64(TDB_VERSION))
268 tdb->flags |= TDB_CONVERT;
271 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
272 "tdb_open: %s is unknown version 0x%llx",
273 name, (long long)hdr.version);
278 tdb_convert(tdb, &hdr, sizeof(hdr));
279 tdb->hash_seed = hdr.hash_seed;
280 hash_test = TDB_HASH_MAGIC;
281 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
282 if (hdr.hash_test != hash_test) {
283 /* wrong hash variant */
284 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
285 "tdb_open: %s uses a different hash function",
290 if (fstat(tdb->fd, &st) == -1) {
292 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
293 "tdb_open: could not stat open %s: %s",
294 name, strerror(errno));
298 /* Is it already in the open list? If so, fail. */
299 if (tdb_already_open(st.st_dev, st.st_ino)) {
301 tdb_logerr(tdb, TDB_ERR_NESTING, TDB_DEBUG_ERROR,
302 "tdb_open: %s (%d,%d) is already open in this"
304 name, (int)st.st_dev, (int)st.st_ino);
308 tdb->name = strdup(name);
310 tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_ERROR,
311 "tdb_open: failed to allocate name");
315 tdb->device = st.st_dev;
316 tdb->inode = st.st_ino;
317 tdb_unlock_open(tdb);
319 /* This make sure we have current map_size and mmap. */
320 tdb->methods->oob(tdb, tdb->map_size + 1, true);
322 /* Now it's fully formed, recover if necessary. */
323 if (tdb_needs_recovery(tdb) && tdb_lock_and_recover(tdb) == -1) {
327 if (tdb_ftable_init(tdb) == -1)
335 /* Map ecode to some logical errno. */
337 switch (tdb->ecode) {
338 case TDB_ERR_CORRUPT:
343 saved_errno = EWOULDBLOCK;
346 saved_errno = ENOMEM;
349 saved_errno = EINVAL;
351 case TDB_ERR_NESTING:
355 saved_errno = EINVAL;
364 if (tdb->flags & TDB_INTERNAL) {
369 free((char *)tdb->name);
371 if (close(tdb->fd) != 0)
372 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
373 "tdb_open: failed to close tdb->fd"
380 static int update_rec_hdr(struct tdb_context *tdb,
384 struct tdb_used_record *rec,
387 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
389 if (set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
390 keylen + dataroom, h))
393 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
396 /* Returns -1 on error, 0 on OK */
397 static int replace_data(struct tdb_context *tdb,
399 struct tdb_data key, struct tdb_data dbuf,
400 tdb_off_t old_off, tdb_len_t old_room,
405 /* Allocate a new record. */
406 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
408 if (unlikely(new_off == TDB_OFF_ERR))
411 /* We didn't like the existing one: remove it. */
413 add_stat(tdb, frees, 1);
414 add_free_record(tdb, old_off,
415 sizeof(struct tdb_used_record)
416 + key.dsize + old_room);
417 if (replace_in_hash(tdb, h, new_off) == -1)
420 if (add_to_hash(tdb, h, new_off) == -1)
424 new_off += sizeof(struct tdb_used_record);
425 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
428 new_off += key.dsize;
429 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
432 /* FIXME: tdb_increment_seqnum(tdb); */
436 int tdb_store(struct tdb_context *tdb,
437 struct tdb_data key, struct tdb_data dbuf, int flag)
441 tdb_len_t old_room = 0;
442 struct tdb_used_record rec;
445 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
446 if (unlikely(off == TDB_OFF_ERR))
449 /* Now we have lock on this hash bucket. */
450 if (flag == TDB_INSERT) {
452 tdb->ecode = TDB_ERR_EXISTS;
457 old_room = rec_data_length(&rec)
458 + rec_extra_padding(&rec);
459 if (old_room >= dbuf.dsize) {
460 /* Can modify in-place. Easy! */
461 if (update_rec_hdr(tdb, off,
462 key.dsize, dbuf.dsize,
465 if (tdb->methods->write(tdb, off + sizeof(rec)
467 dbuf.dptr, dbuf.dsize))
469 tdb_unlock_hashes(tdb, h.hlock_start,
470 h.hlock_range, F_WRLCK);
474 if (flag == TDB_MODIFY) {
475 /* if the record doesn't exist and we
476 are in TDB_MODIFY mode then we should fail
478 tdb->ecode = TDB_ERR_NOEXIST;
484 /* If we didn't use the old record, this implies we're growing. */
485 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
486 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
490 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
494 int tdb_append(struct tdb_context *tdb,
495 struct tdb_data key, struct tdb_data dbuf)
499 struct tdb_used_record rec;
500 tdb_len_t old_room = 0, old_dlen;
501 unsigned char *newdata;
502 struct tdb_data new_dbuf;
505 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
506 if (unlikely(off == TDB_OFF_ERR))
510 old_dlen = rec_data_length(&rec);
511 old_room = old_dlen + rec_extra_padding(&rec);
513 /* Fast path: can append in place. */
514 if (rec_extra_padding(&rec) >= dbuf.dsize) {
515 if (update_rec_hdr(tdb, off, key.dsize,
516 old_dlen + dbuf.dsize, &rec, h.h))
519 off += sizeof(rec) + key.dsize + old_dlen;
520 if (tdb->methods->write(tdb, off, dbuf.dptr,
524 /* FIXME: tdb_increment_seqnum(tdb); */
525 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
531 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
533 tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_FATAL,
534 "tdb_append: failed to allocate %zu bytes",
535 (size_t)(key.dsize+old_dlen+dbuf.dsize));
538 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
539 newdata, old_dlen) != 0) {
543 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
544 new_dbuf.dptr = newdata;
545 new_dbuf.dsize = old_dlen + dbuf.dsize;
551 /* If they're using tdb_append(), it implies they're growing record. */
552 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
553 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
559 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
563 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
566 struct tdb_used_record rec;
570 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
571 if (unlikely(off == TDB_OFF_ERR))
575 tdb->ecode = TDB_ERR_NOEXIST;
578 ret.dsize = rec_data_length(&rec);
579 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
583 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
587 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
590 struct tdb_used_record rec;
593 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
594 if (unlikely(off == TDB_OFF_ERR))
598 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
599 tdb->ecode = TDB_ERR_NOEXIST;
603 if (delete_from_hash(tdb, &h) == -1)
606 /* Free the deleted entry. */
607 add_stat(tdb, frees, 1);
608 if (add_free_record(tdb, off,
609 sizeof(struct tdb_used_record)
610 + rec_key_length(&rec)
611 + rec_data_length(&rec)
612 + rec_extra_padding(&rec)) != 0)
615 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
619 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
623 int tdb_close(struct tdb_context *tdb)
625 struct tdb_context **i;
628 tdb_trace(tdb, "tdb_close");
630 if (tdb->transaction) {
631 tdb_transaction_cancel(tdb);
635 if (tdb->flags & TDB_INTERNAL)
640 free((char *)tdb->name);
642 ret = close(tdb->fd);
647 /* Remove from contexts list */
648 for (i = &tdbs; *i; i = &(*i)->next) {
663 enum TDB_ERROR tdb_error(const struct tdb_context *tdb)
668 const char *tdb_errorstr(const struct tdb_context *tdb)
670 /* Gcc warns if you miss a case in the switch, so use that. */
671 switch (tdb->ecode) {
672 case TDB_SUCCESS: return "Success";
673 case TDB_ERR_CORRUPT: return "Corrupt database";
674 case TDB_ERR_IO: return "IO Error";
675 case TDB_ERR_LOCK: return "Locking error";
676 case TDB_ERR_OOM: return "Out of memory";
677 case TDB_ERR_EXISTS: return "Record exists";
678 case TDB_ERR_NESTING: return "Transaction already started";
679 case TDB_ERR_EINVAL: return "Invalid parameter";
680 case TDB_ERR_NOEXIST: return "Record does not exist";
681 case TDB_ERR_RDONLY: return "write not permitted";
683 return "Invalid error code";
686 void COLD tdb_logerr(struct tdb_context *tdb,
687 enum TDB_ERROR ecode,
688 enum tdb_debug_level level,
689 const char *fmt, ...)
694 /* tdb_open paths care about errno, so save it. */
695 int saved_errno = errno;
702 /* FIXME: Doesn't assume asprintf. */
704 len = vsnprintf(NULL, 0, fmt, ap);
707 message = malloc(len + 1);
709 tdb->logfn(tdb, level, tdb->log_private,
710 "out of memory formatting message");
714 len = vsprintf(message, fmt, ap);
716 tdb->logfn(tdb, level, tdb->log_private, message);