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 bool read_all(int fd, void *buf, size_t len)
29 ret = read(fd, buf, len);
37 buf = (char *)buf + ret;
43 static uint64_t random_number(struct tdb_context *tdb)
49 fd = open("/dev/urandom", O_RDONLY);
51 if (read_all(fd, &ret, sizeof(ret))) {
57 /* FIXME: Untested! Based on Wikipedia protocol description! */
58 fd = open("/dev/egd-pool", O_RDWR);
60 /* Command is 1, next byte is size we want to read. */
61 char cmd[2] = { 1, sizeof(uint64_t) };
62 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
63 char reply[1 + sizeof(uint64_t)];
64 int r = read(fd, reply, sizeof(reply));
66 /* Copy at least some bytes. */
67 memcpy(&ret, reply+1, r - 1);
68 if (reply[0] == sizeof(uint64_t)
69 && r == sizeof(reply)) {
78 /* Fallback: pid and time. */
79 gettimeofday(&now, NULL);
80 ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
81 tdb_logerr(tdb, TDB_SUCCESS, TDB_LOG_WARNING,
82 "tdb_open: random from getpid and time");
87 struct tdb_header hdr;
88 struct tdb_freetable ftable;
91 /* initialise a new database */
92 static int tdb_new_database(struct tdb_context *tdb,
93 struct tdb_attribute_seed *seed,
94 struct tdb_header *hdr)
96 /* We make it up in memory, then write it out if not internal */
97 struct new_database newdb;
98 unsigned int magic_len;
101 /* Fill in the header */
102 newdb.hdr.version = TDB_VERSION;
104 newdb.hdr.hash_seed = seed->seed;
106 newdb.hdr.hash_seed = random_number(tdb);
107 newdb.hdr.hash_test = TDB_HASH_MAGIC;
108 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
109 sizeof(newdb.hdr.hash_test),
112 newdb.hdr.recovery = 0;
113 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
114 /* Initial hashes are empty. */
115 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
118 newdb.hdr.free_table = offsetof(struct new_database, ftable);
119 memset(&newdb.ftable, 0, sizeof(newdb.ftable));
120 set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
121 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
122 sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr), 0);
125 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
126 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
128 /* This creates an endian-converted database, as if read from disk */
129 magic_len = sizeof(newdb.hdr.magic_food);
131 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
135 if (tdb->flags & TDB_INTERNAL) {
136 tdb->map_size = sizeof(newdb);
137 tdb->map_ptr = malloc(tdb->map_size);
139 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
140 "tdb_new_database: failed to allocate");
143 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
146 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
149 if (ftruncate(tdb->fd, 0) == -1)
152 rlen = write(tdb->fd, &newdb, sizeof(newdb));
153 if (rlen != sizeof(newdb)) {
156 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
157 "tdb_new_database: %zi writing header: %s",
158 rlen, strerror(errno));
164 struct tdb_context *tdb_open(const char *name, int tdb_flags,
165 int open_flags, mode_t mode,
166 union tdb_attribute *attr)
168 struct tdb_context *tdb;
174 struct tdb_header hdr;
175 struct tdb_attribute_seed *seed = NULL;
176 enum TDB_ERROR ecode;
178 tdb = malloc(sizeof(*tdb));
186 tdb->direct_access = 0;
188 tdb->map_size = sizeof(struct tdb_header);
189 tdb->ecode = TDB_SUCCESS;
190 tdb->flags = tdb_flags;
192 tdb->transaction = NULL;
200 switch (attr->base.attr) {
201 case TDB_ATTRIBUTE_LOG:
202 tdb->logfn = attr->log.log_fn;
203 tdb->log_private = attr->log.log_private;
205 case TDB_ATTRIBUTE_HASH:
206 tdb->khash = attr->hash.hash_fn;
207 tdb->hash_priv = attr->hash.hash_private;
209 case TDB_ATTRIBUTE_SEED:
212 case TDB_ATTRIBUTE_STATS:
213 tdb->stats = &attr->stats;
214 /* They have stats we don't know about? Tell them. */
215 if (tdb->stats->size > sizeof(attr->stats))
216 tdb->stats->size = sizeof(attr->stats);
219 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
220 "tdb_open: unknown attribute type %u",
224 attr = attr->base.next;
227 if ((open_flags & O_ACCMODE) == O_WRONLY) {
228 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
229 "tdb_open: can't open tdb %s write-only", name);
233 if ((open_flags & O_ACCMODE) == O_RDONLY) {
234 tdb->read_only = true;
235 /* read only databases don't do locking */
236 tdb->flags |= TDB_NOLOCK;
237 tdb->mmap_flags = PROT_READ;
239 tdb->read_only = false;
240 tdb->mmap_flags = PROT_READ | PROT_WRITE;
243 /* internal databases don't need any of the rest. */
244 if (tdb->flags & TDB_INTERNAL) {
245 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
246 if (tdb_new_database(tdb, seed, &hdr) != 0) {
249 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
250 tdb->hash_seed = hdr.hash_seed;
251 tdb_ftable_init(tdb);
255 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
256 /* errno set by open(2) */
258 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
259 "tdb_open: could not open file %s: %s",
260 name, strerror(errno));
264 /* on exec, don't inherit the fd */
265 v = fcntl(tdb->fd, F_GETFD, 0);
266 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
268 /* ensure there is only one process initialising at once */
269 tdb->ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
270 if (tdb->ecode != TDB_SUCCESS) {
274 /* If they used O_TRUNC, read will return 0. */
275 rlen = read(tdb->fd, &hdr, sizeof(hdr));
276 if (rlen == 0 && (open_flags & O_CREAT)) {
277 if (tdb_new_database(tdb, seed, &hdr) == -1) {
280 } else if (rlen < 0) {
281 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
282 "tdb_open: error %s reading %s",
283 strerror(errno), name);
285 } else if (rlen < sizeof(hdr)
286 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
287 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
288 "tdb_open: %s is not a tdb file", name);
292 if (hdr.version != TDB_VERSION) {
293 if (hdr.version == bswap_64(TDB_VERSION))
294 tdb->flags |= TDB_CONVERT;
297 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
298 "tdb_open: %s is unknown version 0x%llx",
299 name, (long long)hdr.version);
304 tdb_convert(tdb, &hdr, sizeof(hdr));
305 tdb->hash_seed = hdr.hash_seed;
306 hash_test = TDB_HASH_MAGIC;
307 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
308 if (hdr.hash_test != hash_test) {
309 /* wrong hash variant */
310 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
311 "tdb_open: %s uses a different hash function",
316 if (fstat(tdb->fd, &st) == -1) {
318 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
319 "tdb_open: could not stat open %s: %s",
320 name, strerror(errno));
324 /* Is it already in the open list? If so, fail. */
325 if (tdb_already_open(st.st_dev, st.st_ino)) {
327 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_USE_ERROR,
328 "tdb_open: %s (%d,%d) is already open in this"
330 name, (int)st.st_dev, (int)st.st_ino);
334 tdb->name = strdup(name);
336 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
337 "tdb_open: failed to allocate name");
341 tdb->device = st.st_dev;
342 tdb->inode = st.st_ino;
343 tdb_unlock_open(tdb);
345 /* This make sure we have current map_size and mmap. */
346 tdb->methods->oob(tdb, tdb->map_size + 1, true);
348 /* Now it's fully formed, recover if necessary. */
349 if (tdb_needs_recovery(tdb)) {
350 ecode = tdb_lock_and_recover(tdb);
351 if (ecode != TDB_SUCCESS) {
357 if (tdb_ftable_init(tdb) == -1)
365 /* Map ecode to some logical errno. */
367 switch (tdb->ecode) {
368 case TDB_ERR_CORRUPT:
373 saved_errno = EWOULDBLOCK;
376 saved_errno = ENOMEM;
379 saved_errno = EINVAL;
382 saved_errno = EINVAL;
391 if (tdb->flags & TDB_INTERNAL) {
397 free((char *)tdb->name);
399 if (close(tdb->fd) != 0)
400 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
401 "tdb_open: failed to close tdb->fd"
402 " on error: %s", strerror(errno));
408 static int update_rec_hdr(struct tdb_context *tdb,
412 struct tdb_used_record *rec,
415 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
416 enum TDB_ERROR ecode;
418 if (set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
419 keylen + dataroom, h))
422 ecode = tdb_write_convert(tdb, off, rec, sizeof(*rec));
423 if (ecode != TDB_SUCCESS) {
430 /* Returns -1 on error, 0 on OK */
431 static int replace_data(struct tdb_context *tdb,
433 struct tdb_data key, struct tdb_data dbuf,
434 tdb_off_t old_off, tdb_len_t old_room,
438 enum TDB_ERROR ecode;
440 /* Allocate a new record. */
441 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
443 if (unlikely(new_off == TDB_OFF_ERR))
446 /* We didn't like the existing one: remove it. */
448 add_stat(tdb, frees, 1);
449 add_free_record(tdb, old_off,
450 sizeof(struct tdb_used_record)
451 + key.dsize + old_room);
452 if (replace_in_hash(tdb, h, new_off) == -1)
455 if (add_to_hash(tdb, h, new_off) == -1)
459 new_off += sizeof(struct tdb_used_record);
460 ecode = tdb->methods->twrite(tdb, new_off, key.dptr, key.dsize);
461 if (ecode != TDB_SUCCESS) {
466 new_off += key.dsize;
467 ecode = tdb->methods->twrite(tdb, new_off, dbuf.dptr, dbuf.dsize);
468 if (ecode != TDB_SUCCESS) {
473 /* FIXME: tdb_increment_seqnum(tdb); */
477 int tdb_store(struct tdb_context *tdb,
478 struct tdb_data key, struct tdb_data dbuf, int flag)
482 tdb_len_t old_room = 0;
483 struct tdb_used_record rec;
485 enum TDB_ERROR ecode;
487 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
488 if (unlikely(off == TDB_OFF_ERR))
491 /* Now we have lock on this hash bucket. */
492 if (flag == TDB_INSERT) {
494 tdb->ecode = TDB_ERR_EXISTS;
499 old_room = rec_data_length(&rec)
500 + rec_extra_padding(&rec);
501 if (old_room >= dbuf.dsize) {
502 /* Can modify in-place. Easy! */
503 if (update_rec_hdr(tdb, off,
504 key.dsize, dbuf.dsize,
507 ecode = tdb->methods->twrite(tdb,
512 if (ecode != TDB_SUCCESS) {
516 tdb_unlock_hashes(tdb, h.hlock_start,
517 h.hlock_range, F_WRLCK);
521 if (flag == TDB_MODIFY) {
522 /* if the record doesn't exist and we
523 are in TDB_MODIFY mode then we should fail
525 tdb->ecode = TDB_ERR_NOEXIST;
531 /* If we didn't use the old record, this implies we're growing. */
532 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
533 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 int tdb_append(struct tdb_context *tdb,
542 struct tdb_data key, struct tdb_data dbuf)
546 struct tdb_used_record rec;
547 tdb_len_t old_room = 0, old_dlen;
548 unsigned char *newdata;
549 struct tdb_data new_dbuf;
550 enum TDB_ERROR ecode;
553 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
554 if (unlikely(off == TDB_OFF_ERR))
558 old_dlen = rec_data_length(&rec);
559 old_room = old_dlen + rec_extra_padding(&rec);
561 /* Fast path: can append in place. */
562 if (rec_extra_padding(&rec) >= dbuf.dsize) {
563 if (update_rec_hdr(tdb, off, key.dsize,
564 old_dlen + dbuf.dsize, &rec, h.h))
567 off += sizeof(rec) + key.dsize + old_dlen;
568 ecode = tdb->methods->twrite(tdb, off, dbuf.dptr,
570 if (ecode != TDB_SUCCESS) {
575 /* FIXME: tdb_increment_seqnum(tdb); */
576 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
582 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
584 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
585 "tdb_append: failed to allocate %zu bytes",
586 (size_t)(key.dsize+old_dlen+dbuf.dsize));
589 ecode = tdb->methods->tread(tdb, off + sizeof(rec) + key.dsize,
591 if (ecode != TDB_SUCCESS) {
596 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
597 new_dbuf.dptr = newdata;
598 new_dbuf.dsize = old_dlen + dbuf.dsize;
604 /* If they're using tdb_append(), it implies they're growing record. */
605 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
606 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
612 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
616 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
619 struct tdb_used_record rec;
623 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
624 if (unlikely(off == TDB_OFF_ERR))
628 tdb->ecode = TDB_ERR_NOEXIST;
631 ret.dsize = rec_data_length(&rec);
632 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
634 if (TDB_PTR_IS_ERR(ret.dptr)) {
635 tdb->ecode = TDB_PTR_ERR(ret.dptr);
640 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
644 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
647 struct tdb_used_record rec;
650 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
651 if (unlikely(off == TDB_OFF_ERR))
655 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
656 tdb->ecode = TDB_ERR_NOEXIST;
660 if (delete_from_hash(tdb, &h) == -1)
663 /* Free the deleted entry. */
664 add_stat(tdb, frees, 1);
665 if (add_free_record(tdb, off,
666 sizeof(struct tdb_used_record)
667 + rec_key_length(&rec)
668 + rec_data_length(&rec)
669 + rec_extra_padding(&rec)) != 0)
672 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
676 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
680 int tdb_close(struct tdb_context *tdb)
682 struct tdb_context **i;
685 tdb_trace(tdb, "tdb_close");
687 if (tdb->transaction) {
688 tdb_transaction_cancel(tdb);
692 if (tdb->flags & TDB_INTERNAL)
697 free((char *)tdb->name);
699 ret = close(tdb->fd);
704 /* Remove from contexts list */
705 for (i = &tdbs; *i; i = &(*i)->next) {
720 enum TDB_ERROR tdb_error(const struct tdb_context *tdb)
725 const char *tdb_errorstr(const struct tdb_context *tdb)
727 /* Gcc warns if you miss a case in the switch, so use that. */
728 switch (tdb->ecode) {
729 case TDB_SUCCESS: return "Success";
730 case TDB_ERR_CORRUPT: return "Corrupt database";
731 case TDB_ERR_IO: return "IO Error";
732 case TDB_ERR_LOCK: return "Locking error";
733 case TDB_ERR_OOM: return "Out of memory";
734 case TDB_ERR_EXISTS: return "Record exists";
735 case TDB_ERR_EINVAL: return "Invalid parameter";
736 case TDB_ERR_NOEXIST: return "Record does not exist";
737 case TDB_ERR_RDONLY: return "write not permitted";
739 return "Invalid error code";
742 enum TDB_ERROR COLD tdb_logerr(struct tdb_context *tdb,
743 enum TDB_ERROR ecode,
744 enum tdb_log_level level,
745 const char *fmt, ...)
750 /* tdb_open paths care about errno, so save it. */
751 int saved_errno = errno;
758 /* FIXME: Doesn't assume asprintf. */
760 len = vsnprintf(NULL, 0, fmt, ap);
763 message = malloc(len + 1);
765 tdb->logfn(tdb, TDB_LOG_ERROR, tdb->log_private,
766 "out of memory formatting message:");
767 tdb->logfn(tdb, level, tdb->log_private, fmt);
771 len = vsprintf(message, fmt, ap);
773 tdb->logfn(tdb, level, tdb->log_private, message);