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 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
107 /* Initial hashes are empty. */
108 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
111 newdb.hdr.free_list = offsetof(struct new_database, flist);
112 memset(&newdb.flist, 0, sizeof(newdb.flist));
113 set_header(NULL, &newdb.flist.hdr, 0,
114 sizeof(newdb.flist) - sizeof(newdb.flist.hdr),
115 sizeof(newdb.flist) - sizeof(newdb.flist.hdr), 1);
118 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
119 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
121 /* This creates an endian-converted database, as if read from disk */
122 magic_len = sizeof(newdb.hdr.magic_food);
124 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
128 if (tdb->flags & TDB_INTERNAL) {
129 tdb->map_size = sizeof(newdb);
130 tdb->map_ptr = malloc(tdb->map_size);
132 tdb->ecode = TDB_ERR_OOM;
135 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
138 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
141 if (ftruncate(tdb->fd, 0) == -1)
144 if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
145 tdb->ecode = TDB_ERR_IO;
151 struct tdb_context *tdb_open(const char *name, int tdb_flags,
152 int open_flags, mode_t mode,
153 union tdb_attribute *attr)
155 struct tdb_context *tdb;
160 struct tdb_header hdr;
161 struct tdb_attribute_seed *seed = NULL;
163 tdb = malloc(sizeof(*tdb));
171 tdb->direct_access = 0;
173 tdb->map_size = sizeof(struct tdb_header);
174 tdb->ecode = TDB_SUCCESS;
175 tdb->flags = tdb_flags;
176 tdb->log = null_log_fn;
177 tdb->log_priv = NULL;
178 tdb->transaction = NULL;
184 switch (attr->base.attr) {
185 case TDB_ATTRIBUTE_LOG:
186 tdb->log = attr->log.log_fn;
187 tdb->log_priv = attr->log.log_private;
189 case TDB_ATTRIBUTE_HASH:
190 tdb->khash = attr->hash.hash_fn;
191 tdb->hash_priv = attr->hash.hash_private;
193 case TDB_ATTRIBUTE_SEED:
197 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
198 "tdb_open: unknown attribute type %u\n",
203 attr = attr->base.next;
206 if ((open_flags & O_ACCMODE) == O_WRONLY) {
207 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
208 "tdb_open: can't open tdb %s write-only\n", 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) {
227 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
228 "tdb_open: tdb_new_database failed!");
231 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
232 tdb->hash_seed = hdr.hash_seed;
237 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
238 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
239 "tdb_open: could not open file %s: %s\n",
240 name, strerror(errno));
241 goto fail; /* errno set by open(2) */
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) == -1) {
250 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
251 "tdb_open: failed to get open lock on %s: %s\n",
252 name, strerror(errno));
253 goto fail; /* 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_new_database(tdb, seed, &hdr) == -1) {
261 errno = EIO; /* ie bad format or something */
265 } else if (hdr.version != TDB_VERSION) {
266 if (hdr.version == bswap_64(TDB_VERSION))
267 tdb->flags |= TDB_CONVERT;
270 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
271 "tdb_open: %s is unknown version 0x%llx\n",
272 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->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
285 "tdb_open: %s uses a different hash function\n",
291 if (fstat(tdb->fd, &st) == -1)
294 /* Is it already in the open list? If so, fail. */
295 if (tdb_already_open(st.st_dev, st.st_ino)) {
297 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
298 "tdb_open: %s (%d,%d) is already open in this process\n",
299 name, (int)st.st_dev, (int)st.st_ino);
304 tdb->name = strdup(name);
310 tdb->device = st.st_dev;
311 tdb->inode = st.st_ino;
312 tdb_unlock_open(tdb);
314 /* This make sure we have current map_size and mmap. */
315 tdb->methods->oob(tdb, tdb->map_size + 1, true);
317 if (tdb_flist_init(tdb) == -1)
334 if (tdb->flags & TDB_INTERNAL) {
339 free((char *)tdb->name);
341 if (close(tdb->fd) != 0)
342 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
343 "tdb_open: failed to close tdb->fd"
350 /* FIXME: modify, don't rewrite! */
351 static int update_rec_hdr(struct tdb_context *tdb,
355 struct tdb_used_record *rec,
358 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
360 if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
363 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
366 /* Returns -1 on error, 0 on OK */
367 static int replace_data(struct tdb_context *tdb,
369 struct tdb_data key, struct tdb_data dbuf,
370 tdb_off_t old_off, tdb_len_t old_room,
375 /* Allocate a new record. */
376 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
377 if (unlikely(new_off == TDB_OFF_ERR))
380 /* We didn't like the existing one: remove it. */
382 add_free_record(tdb, old_off,
383 sizeof(struct tdb_used_record)
384 + key.dsize + old_room);
385 if (replace_in_hash(tdb, h, new_off) == -1)
388 if (add_to_hash(tdb, h, new_off) == -1)
392 new_off += sizeof(struct tdb_used_record);
393 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
396 new_off += key.dsize;
397 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
400 /* FIXME: tdb_increment_seqnum(tdb); */
404 int tdb_store(struct tdb_context *tdb,
405 struct tdb_data key, struct tdb_data dbuf, int flag)
409 tdb_len_t old_room = 0;
410 struct tdb_used_record rec;
413 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
414 if (unlikely(off == TDB_OFF_ERR))
417 /* Now we have lock on this hash bucket. */
418 if (flag == TDB_INSERT) {
420 tdb->ecode = TDB_ERR_EXISTS;
425 old_room = rec_data_length(&rec)
426 + rec_extra_padding(&rec);
427 if (old_room >= dbuf.dsize) {
428 /* Can modify in-place. Easy! */
429 if (update_rec_hdr(tdb, off,
430 key.dsize, dbuf.dsize,
433 if (tdb->methods->write(tdb, off + sizeof(rec)
435 dbuf.dptr, dbuf.dsize))
437 tdb_unlock_hashes(tdb, h.hlock_start,
438 h.hlock_range, F_WRLCK);
441 /* FIXME: See if right record is free? */
443 if (flag == TDB_MODIFY) {
444 /* if the record doesn't exist and we
445 are in TDB_MODIFY mode then we should fail
447 tdb->ecode = TDB_ERR_NOEXIST;
453 /* If we didn't use the old record, this implies we're growing. */
454 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
455 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
459 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
463 int tdb_append(struct tdb_context *tdb,
464 struct tdb_data key, struct tdb_data dbuf)
468 struct tdb_used_record rec;
469 tdb_len_t old_room = 0, old_dlen;
470 unsigned char *newdata;
471 struct tdb_data new_dbuf;
474 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
475 if (unlikely(off == TDB_OFF_ERR))
479 old_dlen = rec_data_length(&rec);
480 old_room = old_dlen + rec_extra_padding(&rec);
482 /* Fast path: can append in place. */
483 if (rec_extra_padding(&rec) >= dbuf.dsize) {
484 if (update_rec_hdr(tdb, off, key.dsize,
485 old_dlen + dbuf.dsize, &rec, h.h))
488 off += sizeof(rec) + key.dsize + old_dlen;
489 if (tdb->methods->write(tdb, off, dbuf.dptr,
493 /* FIXME: tdb_increment_seqnum(tdb); */
494 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
498 /* FIXME: Check right record free? */
501 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
503 tdb->ecode = TDB_ERR_OOM;
504 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
505 "tdb_append: cannot allocate %llu bytes!\n",
506 (long long)key.dsize + old_dlen + dbuf.dsize);
509 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
510 newdata, old_dlen) != 0) {
514 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
515 new_dbuf.dptr = newdata;
516 new_dbuf.dsize = old_dlen + dbuf.dsize;
522 /* If they're using tdb_append(), it implies they're growing record. */
523 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
524 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
530 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
534 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
537 struct tdb_used_record rec;
541 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
542 if (unlikely(off == TDB_OFF_ERR))
546 tdb->ecode = TDB_ERR_NOEXIST;
549 ret.dsize = rec_data_length(&rec);
550 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
554 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
558 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
561 struct tdb_used_record rec;
564 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
565 if (unlikely(off == TDB_OFF_ERR))
569 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
570 tdb->ecode = TDB_ERR_NOEXIST;
574 if (delete_from_hash(tdb, &h) == -1)
577 /* Free the deleted entry. */
578 if (add_free_record(tdb, off,
579 sizeof(struct tdb_used_record)
580 + rec_key_length(&rec)
581 + rec_data_length(&rec)
582 + rec_extra_padding(&rec)) != 0)
585 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
589 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
593 int tdb_close(struct tdb_context *tdb)
595 struct tdb_context **i;
599 if (tdb->transaction) {
600 tdb_transaction_cancel(tdb);
603 tdb_trace(tdb, "tdb_close");
606 if (tdb->flags & TDB_INTERNAL)
611 free((char *)tdb->name);
613 ret = close(tdb->fd);
618 /* Remove from contexts list */
619 for (i = &tdbs; *i; i = &(*i)->next) {
634 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
639 const char *tdb_errorstr(struct tdb_context *tdb)
641 /* Gcc warns if you miss a case in the switch, so use that. */
642 switch (tdb->ecode) {
643 case TDB_SUCCESS: return "Success";
644 case TDB_ERR_CORRUPT: return "Corrupt database";
645 case TDB_ERR_IO: return "IO Error";
646 case TDB_ERR_LOCK: return "Locking error";
647 case TDB_ERR_OOM: return "Out of memory";
648 case TDB_ERR_EXISTS: return "Record exists";
649 case TDB_ERR_NESTING: return "Transaction already started";
650 case TDB_ERR_EINVAL: return "Invalid parameter";
651 case TDB_ERR_NOEXIST: return "Record does not exist";
652 case TDB_ERR_RDONLY: return "write not permitted";
654 return "Invalid error code";