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_freelist flist;
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_list = offsetof(struct new_database, flist);
105 memset(&newdb.flist, 0, sizeof(newdb.flist));
106 set_used_header(NULL, &newdb.flist.hdr, 0,
107 sizeof(newdb.flist) - sizeof(newdb.flist.hdr),
108 sizeof(newdb.flist) - sizeof(newdb.flist.hdr), 1);
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;
180 switch (attr->base.attr) {
181 case TDB_ATTRIBUTE_LOG:
182 tdb->logfn = attr->log.log_fn;
183 tdb->log_private = attr->log.log_private;
185 case TDB_ATTRIBUTE_HASH:
186 tdb->khash = attr->hash.hash_fn;
187 tdb->hash_priv = attr->hash.hash_private;
189 case TDB_ATTRIBUTE_SEED:
192 case TDB_ATTRIBUTE_STATS:
193 tdb->stats = &attr->stats;
194 /* They have stats we don't know about? Tell them. */
195 if (tdb->stats->size > sizeof(attr->stats))
196 tdb->stats->size = sizeof(attr->stats);
199 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_DEBUG_ERROR,
200 "tdb_open: unknown attribute type %u",
204 attr = attr->base.next;
207 if ((open_flags & O_ACCMODE) == O_WRONLY) {
208 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_DEBUG_ERROR,
209 "tdb_open: can't open tdb %s write-only", name);
213 if ((open_flags & O_ACCMODE) == O_RDONLY) {
214 tdb->read_only = true;
215 /* read only databases don't do locking */
216 tdb->flags |= TDB_NOLOCK;
217 tdb->mmap_flags = PROT_READ;
219 tdb->read_only = false;
220 tdb->mmap_flags = PROT_READ | PROT_WRITE;
223 /* internal databases don't need any of the rest. */
224 if (tdb->flags & TDB_INTERNAL) {
225 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
226 if (tdb_new_database(tdb, seed, &hdr) != 0) {
229 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
230 tdb->hash_seed = hdr.hash_seed;
235 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
236 /* errno set by open(2) */
238 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
239 "tdb_open: could not open file %s: %s",
240 name, strerror(errno));
244 /* on exec, don't inherit the fd */
245 v = fcntl(tdb->fd, F_GETFD, 0);
246 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
248 /* ensure there is only one process initialising at once */
249 if (tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK) == -1) {
250 /* errno set by tdb_brlock */
255 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
256 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
257 if (!(open_flags & O_CREAT)) {
258 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
259 "tdb_open: %s is not a tdb file", name);
262 if (tdb_new_database(tdb, seed, &hdr) == -1) {
265 } else if (hdr.version != TDB_VERSION) {
266 if (hdr.version == bswap_64(TDB_VERSION))
267 tdb->flags |= TDB_CONVERT;
270 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
271 "tdb_open: %s is unknown version 0x%llx",
272 name, (long long)hdr.version);
277 tdb_convert(tdb, &hdr, sizeof(hdr));
278 tdb->hash_seed = hdr.hash_seed;
279 hash_test = TDB_HASH_MAGIC;
280 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
281 if (hdr.hash_test != hash_test) {
282 /* wrong hash variant */
283 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
284 "tdb_open: %s uses a different hash function",
289 if (fstat(tdb->fd, &st) == -1) {
291 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
292 "tdb_open: could not stat open %s: %s",
293 name, strerror(errno));
297 /* Is it already in the open list? If so, fail. */
298 if (tdb_already_open(st.st_dev, st.st_ino)) {
300 tdb_logerr(tdb, TDB_ERR_NESTING, TDB_DEBUG_ERROR,
301 "tdb_open: %s (%d,%d) is already open in this"
303 name, (int)st.st_dev, (int)st.st_ino);
307 tdb->name = strdup(name);
309 tdb_logerr(tdb, TDB_ERR_OOM, TDB_DEBUG_ERROR,
310 "tdb_open: failed to allocate name");
314 tdb->device = st.st_dev;
315 tdb->inode = st.st_ino;
316 tdb_unlock_open(tdb);
318 /* This make sure we have current map_size and mmap. */
319 tdb->methods->oob(tdb, tdb->map_size + 1, true);
321 /* Now it's fully formed, recover if necessary. */
322 if (tdb_needs_recovery(tdb) && tdb_lock_and_recover(tdb) == -1) {
326 if (tdb_flist_init(tdb) == -1)
334 /* Map ecode to some logical errno. */
336 switch (tdb->ecode) {
337 case TDB_ERR_CORRUPT:
342 saved_errno = EWOULDBLOCK;
345 saved_errno = ENOMEM;
348 saved_errno = EINVAL;
350 case TDB_ERR_NESTING:
354 saved_errno = EINVAL;
363 if (tdb->flags & TDB_INTERNAL) {
368 free((char *)tdb->name);
370 if (close(tdb->fd) != 0)
371 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
372 "tdb_open: failed to close tdb->fd"
379 /* FIXME: modify, don't rewrite! */
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_used_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
392 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
395 /* Returns -1 on error, 0 on OK */
396 static int replace_data(struct tdb_context *tdb,
398 struct tdb_data key, struct tdb_data dbuf,
399 tdb_off_t old_off, tdb_len_t old_room,
404 /* Allocate a new record. */
405 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
406 if (unlikely(new_off == TDB_OFF_ERR))
409 /* We didn't like the existing one: remove it. */
411 add_stat(tdb, frees, 1);
412 add_free_record(tdb, old_off,
413 sizeof(struct tdb_used_record)
414 + key.dsize + old_room);
415 if (replace_in_hash(tdb, h, new_off) == -1)
418 if (add_to_hash(tdb, h, new_off) == -1)
422 new_off += sizeof(struct tdb_used_record);
423 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
426 new_off += key.dsize;
427 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
430 /* FIXME: tdb_increment_seqnum(tdb); */
434 int tdb_store(struct tdb_context *tdb,
435 struct tdb_data key, struct tdb_data dbuf, int flag)
439 tdb_len_t old_room = 0;
440 struct tdb_used_record rec;
443 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
444 if (unlikely(off == TDB_OFF_ERR))
447 /* Now we have lock on this hash bucket. */
448 if (flag == TDB_INSERT) {
450 tdb->ecode = TDB_ERR_EXISTS;
455 old_room = rec_data_length(&rec)
456 + rec_extra_padding(&rec);
457 if (old_room >= dbuf.dsize) {
458 /* Can modify in-place. Easy! */
459 if (update_rec_hdr(tdb, off,
460 key.dsize, dbuf.dsize,
463 if (tdb->methods->write(tdb, off + sizeof(rec)
465 dbuf.dptr, dbuf.dsize))
467 tdb_unlock_hashes(tdb, h.hlock_start,
468 h.hlock_range, F_WRLCK);
471 /* FIXME: See if right record is free? */
473 if (flag == TDB_MODIFY) {
474 /* if the record doesn't exist and we
475 are in TDB_MODIFY mode then we should fail
477 tdb->ecode = TDB_ERR_NOEXIST;
483 /* If we didn't use the old record, this implies we're growing. */
484 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
485 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
489 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
493 int tdb_append(struct tdb_context *tdb,
494 struct tdb_data key, struct tdb_data dbuf)
498 struct tdb_used_record rec;
499 tdb_len_t old_room = 0, old_dlen;
500 unsigned char *newdata;
501 struct tdb_data new_dbuf;
504 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
505 if (unlikely(off == TDB_OFF_ERR))
509 old_dlen = rec_data_length(&rec);
510 old_room = old_dlen + rec_extra_padding(&rec);
512 /* Fast path: can append in place. */
513 if (rec_extra_padding(&rec) >= dbuf.dsize) {
514 if (update_rec_hdr(tdb, off, key.dsize,
515 old_dlen + dbuf.dsize, &rec, h.h))
518 off += sizeof(rec) + key.dsize + old_dlen;
519 if (tdb->methods->write(tdb, off, dbuf.dptr,
523 /* FIXME: tdb_increment_seqnum(tdb); */
524 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
528 /* FIXME: Check right record free? */
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);