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 tdb->ecode = 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),
124 if (tdb->ecode != TDB_SUCCESS) {
129 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
130 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
132 /* This creates an endian-converted database, as if read from disk */
133 magic_len = sizeof(newdb.hdr.magic_food);
135 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
139 if (tdb->flags & TDB_INTERNAL) {
140 tdb->map_size = sizeof(newdb);
141 tdb->map_ptr = malloc(tdb->map_size);
143 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
144 "tdb_new_database: failed to allocate");
147 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
150 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
153 if (ftruncate(tdb->fd, 0) == -1)
156 rlen = write(tdb->fd, &newdb, sizeof(newdb));
157 if (rlen != sizeof(newdb)) {
160 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
161 "tdb_new_database: %zi writing header: %s",
162 rlen, strerror(errno));
168 struct tdb_context *tdb_open(const char *name, int tdb_flags,
169 int open_flags, mode_t mode,
170 union tdb_attribute *attr)
172 struct tdb_context *tdb;
178 struct tdb_header hdr;
179 struct tdb_attribute_seed *seed = NULL;
181 enum TDB_ERROR ecode;
183 tdb = malloc(sizeof(*tdb));
191 tdb->direct_access = 0;
193 tdb->map_size = sizeof(struct tdb_header);
194 tdb->ecode = TDB_SUCCESS;
195 tdb->flags = tdb_flags;
197 tdb->transaction = NULL;
205 switch (attr->base.attr) {
206 case TDB_ATTRIBUTE_LOG:
207 tdb->logfn = attr->log.log_fn;
208 tdb->log_private = attr->log.log_private;
210 case TDB_ATTRIBUTE_HASH:
211 tdb->khash = attr->hash.hash_fn;
212 tdb->hash_priv = attr->hash.hash_private;
214 case TDB_ATTRIBUTE_SEED:
217 case TDB_ATTRIBUTE_STATS:
218 tdb->stats = &attr->stats;
219 /* They have stats we don't know about? Tell them. */
220 if (tdb->stats->size > sizeof(attr->stats))
221 tdb->stats->size = sizeof(attr->stats);
224 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
225 "tdb_open: unknown attribute type %u",
229 attr = attr->base.next;
232 if ((open_flags & O_ACCMODE) == O_WRONLY) {
233 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
234 "tdb_open: can't open tdb %s write-only", name);
238 if ((open_flags & O_ACCMODE) == O_RDONLY) {
239 tdb->read_only = true;
240 /* read only databases don't do locking */
241 tdb->flags |= TDB_NOLOCK;
242 tdb->mmap_flags = PROT_READ;
244 tdb->read_only = false;
245 tdb->mmap_flags = PROT_READ | PROT_WRITE;
248 /* internal databases don't need any of the rest. */
249 if (tdb->flags & TDB_INTERNAL) {
250 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
251 if (tdb_new_database(tdb, seed, &hdr) != 0) {
254 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
255 tdb->hash_seed = hdr.hash_seed;
256 tdb_ftable_init(tdb);
260 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
261 /* errno set by open(2) */
263 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
264 "tdb_open: could not open file %s: %s",
265 name, strerror(errno));
269 /* on exec, don't inherit the fd */
270 v = fcntl(tdb->fd, F_GETFD, 0);
271 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
273 /* ensure there is only one process initialising at once */
274 tdb->ecode = tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
275 if (tdb->ecode != TDB_SUCCESS) {
279 /* If they used O_TRUNC, read will return 0. */
280 rlen = read(tdb->fd, &hdr, sizeof(hdr));
281 if (rlen == 0 && (open_flags & O_CREAT)) {
282 if (tdb_new_database(tdb, seed, &hdr) == -1) {
285 } else if (rlen < 0) {
286 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
287 "tdb_open: error %s reading %s",
288 strerror(errno), name);
290 } else if (rlen < sizeof(hdr)
291 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
292 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
293 "tdb_open: %s is not a tdb file", name);
297 if (hdr.version != TDB_VERSION) {
298 if (hdr.version == bswap_64(TDB_VERSION))
299 tdb->flags |= TDB_CONVERT;
302 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
303 "tdb_open: %s is unknown version 0x%llx",
304 name, (long long)hdr.version);
309 tdb_convert(tdb, &hdr, sizeof(hdr));
310 tdb->hash_seed = hdr.hash_seed;
311 hash_test = TDB_HASH_MAGIC;
312 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
313 if (hdr.hash_test != hash_test) {
314 /* wrong hash variant */
315 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
316 "tdb_open: %s uses a different hash function",
321 if (fstat(tdb->fd, &st) == -1) {
323 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
324 "tdb_open: could not stat open %s: %s",
325 name, strerror(errno));
329 /* Is it already in the open list? If so, fail. */
330 if (tdb_already_open(st.st_dev, st.st_ino)) {
332 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_USE_ERROR,
333 "tdb_open: %s (%d,%d) is already open in this"
335 name, (int)st.st_dev, (int)st.st_ino);
339 tdb->name = strdup(name);
341 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
342 "tdb_open: failed to allocate name");
346 tdb->device = st.st_dev;
347 tdb->inode = st.st_ino;
348 tdb_unlock_open(tdb);
350 /* This make sure we have current map_size and mmap. */
351 tdb->methods->oob(tdb, tdb->map_size + 1, true);
353 /* Now it's fully formed, recover if necessary. */
354 berr = tdb_needs_recovery(tdb);
355 if (unlikely(berr != false)) {
360 ecode = tdb_lock_and_recover(tdb);
361 if (ecode != TDB_SUCCESS) {
367 tdb->ecode = tdb_ftable_init(tdb);
368 if (tdb->ecode != TDB_SUCCESS) {
377 /* Map ecode to some logical errno. */
379 switch (tdb->ecode) {
380 case TDB_ERR_CORRUPT:
385 saved_errno = EWOULDBLOCK;
388 saved_errno = ENOMEM;
391 saved_errno = EINVAL;
394 saved_errno = EINVAL;
403 if (tdb->flags & TDB_INTERNAL) {
409 free((char *)tdb->name);
411 if (close(tdb->fd) != 0)
412 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
413 "tdb_open: failed to close tdb->fd"
414 " on error: %s", strerror(errno));
420 static int update_rec_hdr(struct tdb_context *tdb,
424 struct tdb_used_record *rec,
427 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
428 enum TDB_ERROR ecode;
430 ecode = set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
431 keylen + dataroom, h);
432 if (ecode != TDB_SUCCESS) {
437 ecode = tdb_write_convert(tdb, off, rec, sizeof(*rec));
438 if (ecode != TDB_SUCCESS) {
445 /* Returns -1 on error, 0 on OK */
446 static int replace_data(struct tdb_context *tdb,
448 struct tdb_data key, struct tdb_data dbuf,
449 tdb_off_t old_off, tdb_len_t old_room,
453 enum TDB_ERROR ecode;
455 /* Allocate a new record. */
456 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
458 if (TDB_OFF_IS_ERR(new_off)) {
459 tdb->ecode = new_off;
463 /* We didn't like the existing one: remove it. */
465 add_stat(tdb, frees, 1);
466 ecode = add_free_record(tdb, old_off,
467 sizeof(struct tdb_used_record)
468 + key.dsize + old_room);
469 if (ecode == TDB_SUCCESS)
470 ecode = replace_in_hash(tdb, h, new_off);
472 ecode = add_to_hash(tdb, h, new_off);
474 if (ecode != TDB_SUCCESS) {
479 new_off += sizeof(struct tdb_used_record);
480 ecode = tdb->methods->twrite(tdb, new_off, key.dptr, key.dsize);
481 if (ecode != TDB_SUCCESS) {
486 new_off += key.dsize;
487 ecode = tdb->methods->twrite(tdb, new_off, dbuf.dptr, dbuf.dsize);
488 if (ecode != TDB_SUCCESS) {
493 /* FIXME: tdb_increment_seqnum(tdb); */
497 int tdb_store(struct tdb_context *tdb,
498 struct tdb_data key, struct tdb_data dbuf, int flag)
502 tdb_len_t old_room = 0;
503 struct tdb_used_record rec;
505 enum TDB_ERROR ecode;
507 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
508 if (TDB_OFF_IS_ERR(off)) {
513 /* Now we have lock on this hash bucket. */
514 if (flag == TDB_INSERT) {
516 tdb->ecode = TDB_ERR_EXISTS;
521 old_room = rec_data_length(&rec)
522 + rec_extra_padding(&rec);
523 if (old_room >= dbuf.dsize) {
524 /* Can modify in-place. Easy! */
525 if (update_rec_hdr(tdb, off,
526 key.dsize, dbuf.dsize,
529 ecode = tdb->methods->twrite(tdb,
534 if (ecode != TDB_SUCCESS) {
538 tdb_unlock_hashes(tdb, h.hlock_start,
539 h.hlock_range, F_WRLCK);
543 if (flag == TDB_MODIFY) {
544 /* if the record doesn't exist and we
545 are in TDB_MODIFY mode then we should fail
547 tdb->ecode = TDB_ERR_NOEXIST;
553 /* If we didn't use the old record, this implies we're growing. */
554 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
555 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 int tdb_append(struct tdb_context *tdb,
564 struct tdb_data key, struct tdb_data dbuf)
568 struct tdb_used_record rec;
569 tdb_len_t old_room = 0, old_dlen;
570 unsigned char *newdata;
571 struct tdb_data new_dbuf;
572 enum TDB_ERROR ecode;
575 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
576 if (TDB_OFF_IS_ERR(off)) {
582 old_dlen = rec_data_length(&rec);
583 old_room = old_dlen + rec_extra_padding(&rec);
585 /* Fast path: can append in place. */
586 if (rec_extra_padding(&rec) >= dbuf.dsize) {
587 if (update_rec_hdr(tdb, off, key.dsize,
588 old_dlen + dbuf.dsize, &rec, h.h))
591 off += sizeof(rec) + key.dsize + old_dlen;
592 ecode = tdb->methods->twrite(tdb, off, dbuf.dptr,
594 if (ecode != TDB_SUCCESS) {
599 /* FIXME: tdb_increment_seqnum(tdb); */
600 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
606 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
608 tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
609 "tdb_append: failed to allocate %zu bytes",
610 (size_t)(key.dsize+old_dlen+dbuf.dsize));
613 ecode = tdb->methods->tread(tdb, off + sizeof(rec) + key.dsize,
615 if (ecode != TDB_SUCCESS) {
620 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
621 new_dbuf.dptr = newdata;
622 new_dbuf.dsize = old_dlen + dbuf.dsize;
628 /* If they're using tdb_append(), it implies they're growing record. */
629 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
630 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
636 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
640 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
643 struct tdb_used_record rec;
647 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
648 if (TDB_OFF_IS_ERR(off)) {
654 tdb->ecode = TDB_ERR_NOEXIST;
657 ret.dsize = rec_data_length(&rec);
658 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
660 if (TDB_PTR_IS_ERR(ret.dptr)) {
661 tdb->ecode = TDB_PTR_ERR(ret.dptr);
666 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
670 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
673 struct tdb_used_record rec;
675 enum TDB_ERROR ecode;
677 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
678 if (TDB_OFF_IS_ERR(off)) {
684 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
685 tdb->ecode = TDB_ERR_NOEXIST;
689 ecode = delete_from_hash(tdb, &h);
690 if (ecode != TDB_SUCCESS) {
695 /* Free the deleted entry. */
696 add_stat(tdb, frees, 1);
697 ecode = add_free_record(tdb, off,
698 sizeof(struct tdb_used_record)
699 + rec_key_length(&rec)
700 + rec_data_length(&rec)
701 + rec_extra_padding(&rec));
702 if (ecode != TDB_SUCCESS) {
707 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
711 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
715 int tdb_close(struct tdb_context *tdb)
717 struct tdb_context **i;
720 tdb_trace(tdb, "tdb_close");
722 if (tdb->transaction) {
723 tdb_transaction_cancel(tdb);
727 if (tdb->flags & TDB_INTERNAL)
732 free((char *)tdb->name);
734 ret = close(tdb->fd);
739 /* Remove from contexts list */
740 for (i = &tdbs; *i; i = &(*i)->next) {
755 enum TDB_ERROR tdb_error(const struct tdb_context *tdb)
760 const char *tdb_errorstr(const struct tdb_context *tdb)
762 /* Gcc warns if you miss a case in the switch, so use that. */
763 switch (tdb->ecode) {
764 case TDB_SUCCESS: return "Success";
765 case TDB_ERR_CORRUPT: return "Corrupt database";
766 case TDB_ERR_IO: return "IO Error";
767 case TDB_ERR_LOCK: return "Locking error";
768 case TDB_ERR_OOM: return "Out of memory";
769 case TDB_ERR_EXISTS: return "Record exists";
770 case TDB_ERR_EINVAL: return "Invalid parameter";
771 case TDB_ERR_NOEXIST: return "Record does not exist";
772 case TDB_ERR_RDONLY: return "write not permitted";
774 return "Invalid error code";
777 enum TDB_ERROR COLD tdb_logerr(struct tdb_context *tdb,
778 enum TDB_ERROR ecode,
779 enum tdb_log_level level,
780 const char *fmt, ...)
785 /* tdb_open paths care about errno, so save it. */
786 int saved_errno = errno;
793 /* FIXME: Doesn't assume asprintf. */
795 len = vsnprintf(NULL, 0, fmt, ap);
798 message = malloc(len + 1);
800 tdb->logfn(tdb, TDB_LOG_ERROR, tdb->log_private,
801 "out of memory formatting message:");
802 tdb->logfn(tdb, level, tdb->log_private, fmt);
806 len = vsprintf(message, fmt, ap);
808 tdb->logfn(tdb, level, tdb->log_private, message);