# HG changeset patch
# User Rusty Russell <rusty@xxxxxxxxxxxxxxx>
# Node ID 76af1a1df67cd8958fc40b1c574a8bd26d5026c2
# Parent 6aef7d1062bb6035a2a84603d9f054b24e14c9b2
Make xenstored use tdb, transactions can soft-fail (EAGAIN)
Transactions no longer take root dir, no longer lock & block: commit can fail
spuriously with EAGAIN, not ETIMEDOUT.
Speeds up transactions by over 1000 times, should be NFS safe.
New program: xs_tdb_dump to dump raw TDB contents.
Don't do failure testing: we are no longer robust against all ENOMEM 8(
Introduce "struct node" which contains perms, children and data.
Make struct xs_permissions unpadded, so we can write to tdb w/o valgrind
complaints.
Gently modify TDB to use talloc, not do alloc on tdb_delete.
Signed-off-by: Rusty Russell <rusty@xxxxxxxxxxxxxxx>
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/Makefile
--- a/tools/xenstore/Makefile Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/Makefile Fri Sep 23 13:25:01 2005
@@ -28,11 +28,11 @@
CLIENTS += xenstore-write
CLIENTS_OBJS := $(patsubst xenstore-%,xenstore_%.o,$(CLIENTS))
-all: libxenstore.so xenstored $(CLIENTS)
+all: libxenstore.so xenstored $(CLIENTS) xs_tdb_dump
testcode: xs_test xenstored_test xs_random xs_dom0_test
-xenstored: xenstored_core.o xenstored_watch.o xenstored_domain.o
xenstored_transaction.o xs_lib.o talloc.o utils.o
+xenstored: xenstored_core.o xenstored_watch.o xenstored_domain.o
xenstored_transaction.o xs_lib.o talloc.o utils.o tdb.o
$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -lxenctrl -o $@
$(CLIENTS): libxenstore.so
@@ -42,7 +42,10 @@
$(CLIENTS_OBJS): xenstore_%.o: xenstore_client.c
$(COMPILE.c) -DCLIENT_$(*F) -o $@ $<
-xenstored_test: xenstored_core_test.o xenstored_watch_test.o
xenstored_domain_test.o xenstored_transaction_test.o xs_lib.o talloc_test.o
fake_libxc.o utils.o
+xenstored_test: xenstored_core_test.o xenstored_watch_test.o
xenstored_domain_test.o xenstored_transaction_test.o xs_lib.o talloc_test.o
fake_libxc.o utils.o tdb.o
+ $(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
+
+xs_tdb_dump: xs_tdb_dump.o utils.o tdb.o talloc.o
$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
xs_test: xs_test.o xs_lib.o utils.o
@@ -103,7 +106,7 @@
randomcheck: xs_random xenstored_test $(TESTDIR)
$(TESTENV) ./xs_random --simple --fast /tmp/xs_random 200000
$(RANDSEED) && echo
$(TESTENV) ./xs_random --fast /tmp/xs_random 100000 $(RANDSEED) && echo
- $(TESTENV) ./xs_random --fail /tmp/xs_random 10000 $(RANDSEED)
+# $(TESTENV) ./xs_random --fail /tmp/xs_random 10000 $(RANDSEED)
crashme: xs_crashme xenstored_test $(TESTDIR)
rm -rf $(TESTDIR)/store $(TESTDIR)/transactions /tmp/xs_crashme.vglog*
/tmp/trace
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/testsuite/04rm.test
--- a/tools/xenstore/testsuite/04rm.test Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/04rm.test Fri Sep 23 13:25:01 2005
@@ -6,6 +6,8 @@
# Create file and remove it
write /test contents
rm /test
+expect tool
+dir /
# Create directory and remove it.
mkdir /dir
@@ -15,3 +17,4 @@
mkdir /dir
write /dir/test contents
rm /dir
+
diff -r 6aef7d1062bb -r 76af1a1df67c
tools/xenstore/testsuite/08transaction.slowtest
--- a/tools/xenstore/testsuite/08transaction.slowtest Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/08transaction.slowtest Fri Sep 23 13:25:01 2005
@@ -1,21 +1,43 @@
-# Test transaction timeouts. Take a second each.
+# Test transaction clashes.
mkdir /test
write /test/entry1 contents
-# Transactions can take as long as the want...
-start /test
-sleep 1100
-rm /test/entry1
+# Start transaction, do read-only op, transaction succeeds
+1 start
+1 write /test/entry1 contents2
+expect contents
+read /test/entry1
+1 commit
+expect contents2
+read /test/entry1
+
+# Start transaction, abort other transaction, transaction succeeds.
+1 start
+1 write /test/entry1 contents3
+start
+write /test/entry1 contents
+abort
+1 commit
+expect contents3
+read /test/entry1
+
+# Start transaction, do write op, transaction fails
+1 start
+1 write /test/entry1 contents4
+write /test/entry1 contents
+expect 1: commit failed: Resource temporarily unavailable
+1 commit
+expect contents
+read /test/entry1
+
+# Start transaction, do other transaction, transaction fails
+1 start
+1 write /test/entry1 contents4
+start
+write /test/entry1 contents5
commit
-dir /test
-
-# ... as long as noone is waiting.
-1 start /test
-notimeout
-2 mkdir /test/dir
-1 mkdir /test/dir
-expect 1:dir
-1 dir /test
-expect 1: commit failed: Connection timed out
+expect 1: commit failed: Resource temporarily unavailable
1 commit
+expect contents5
+read /test/entry1
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/testsuite/08transaction.test
--- a/tools/xenstore/testsuite/08transaction.test Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/08transaction.test Fri Sep 23 13:25:01 2005
@@ -3,7 +3,7 @@
mkdir /test
# Simple transaction: create a file inside transaction.
-1 start /test
+1 start
1 write /test/entry1 contents
2 dir /test
expect 1:entry1
@@ -15,7 +15,7 @@
rm /test/entry1
# Create a file and abort transaction.
-1 start /test
+1 start
1 write /test/entry1 contents
2 dir /test
expect 1:entry1
@@ -25,7 +25,7 @@
write /test/entry1 contents
# Delete in transaction, commit
-1 start /test
+1 start
1 rm /test/entry1
expect 2:entry1
2 dir /test
@@ -35,7 +35,7 @@
# Delete in transaction, abort.
write /test/entry1 contents
-1 start /test
+1 start
1 rm /test/entry1
expect 2:entry1
2 dir /test
@@ -47,7 +47,7 @@
# Events inside transactions don't trigger watches until (successful) commit.
mkdir /test/dir
1 watch /test token
-2 start /test
+2 start
2 mkdir /test/dir/sub
expect 1: waitwatch failed: Connection timed out
1 waitwatch
@@ -55,7 +55,7 @@
1 close
1 watch /test token
-2 start /test
+2 start
2 mkdir /test/dir/sub
2 abort
expect 1: waitwatch failed: Connection timed out
@@ -63,7 +63,7 @@
1 close
1 watch /test token
-2 start /test
+2 start
2 mkdir /test/dir/sub
2 commit
expect 1:/test/dir/sub:token
@@ -73,7 +73,7 @@
# Rm inside transaction works like rm outside: children get notified.
1 watch /test/dir/sub token
-2 start /test
+2 start
2 rm /test/dir
2 commit
expect 1:/test/dir/sub:token
@@ -83,7 +83,7 @@
# Multiple events from single transaction don't trigger assert
1 watch /test token
-2 start /test
+2 start
2 write /test/1 contents
2 write /test/2 contents
2 commit
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/testsuite/12readonly.test
--- a/tools/xenstore/testsuite/12readonly.test Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/12readonly.test Fri Sep 23 13:25:01 2005
@@ -13,23 +13,23 @@
getperm /test
watch /test token
unwatch /test token
-start /
+start
commit
-start /
+start
abort
# These don't work
-expect write failed: Read-only file system
+expect write failed: Permission denied
write /test2 contents
-expect write failed: Read-only file system
+expect write failed: Permission denied
write /test contents
-expect setperm failed: Read-only file system
+expect setperm failed: Permission denied
setperm /test 100 NONE
-expect setperm failed: Read-only file system
+expect setperm failed: Permission denied
setperm /test 100 NONE
-expect shutdown failed: Read-only file system
+expect shutdown failed: Permission denied
shutdown
-expect introduce failed: Read-only file system
+expect introduce failed: Permission denied
introduce 1 100 7 /home
# Check that watches work like normal.
diff -r 6aef7d1062bb -r 76af1a1df67c
tools/xenstore/testsuite/14complexperms.test
--- a/tools/xenstore/testsuite/14complexperms.test Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/14complexperms.test Fri Sep 23 13:25:01 2005
@@ -33,14 +33,6 @@
expect *No such file or directory
unwatch /dir/file token
expect *Permission denied
-start /dir/file
-expect *No such file or directory
-abort
-expect *Permission denied
-start /dir/file
-expect *No such file or directory
-commit
-expect *Permission denied
introduce 2 100 7 /dir/file
# Now it exists
@@ -73,12 +65,4 @@
expect *No such file or directory
unwatch /dir/file token
expect *Permission denied
-start /dir/file
-expect *No such file or directory
-abort
-expect *Permission denied
-start /dir/file
-expect *No such file or directory
-commit
-expect *Permission denied
introduce 2 100 7 /dir/file
diff -r 6aef7d1062bb -r 76af1a1df67c
tools/xenstore/testsuite/16block-watch-crash.test
--- a/tools/xenstore/testsuite/16block-watch-crash.test Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/testsuite/16block-watch-crash.test Fri Sep 23 13:25:01 2005
@@ -1,13 +1,14 @@
# Test case where blocked connection gets sent watch.
-mkdir /test
-watch /test token
-1 start /test
-# This will block on above
-noackwrite /test/entry contents
-1 write /test/entry2 contents
-1 commit
-readack
-expect /test/entry2:token
-waitwatch
-ackwatch token
+# FIXME: We no longer block connections
+# mkdir /test
+# watch /test token
+# 1 start
+# # This will block on above
+# noackwrite /test/entry contents
+# 1 write /test/entry2 contents
+# 1 commit
+# readack
+# expect /test/entry2:token
+# waitwatch
+# ackwatch token
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored.h
--- a/tools/xenstore/xenstored.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored.h Fri Sep 23 13:25:01 2005
@@ -75,7 +75,7 @@
XSD_ERROR(ENOSYS),
XSD_ERROR(EROFS),
XSD_ERROR(EBUSY),
- XSD_ERROR(ETIMEDOUT),
+ XSD_ERROR(EAGAIN),
XSD_ERROR(EISCONN),
};
struct xsd_sockmsg
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_core.c
--- a/tools/xenstore/xenstored_core.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_core.c Fri Sep 23 13:25:01 2005
@@ -50,10 +50,12 @@
#include "xenstored_transaction.h"
#include "xenstored_domain.h"
#include "xenctrl.h"
+#include "tdb.h"
static bool verbose;
LIST_HEAD(connections);
static int tracefd = -1;
+static TDB_CONTEXT *tdb_ctx;
#ifdef TESTING
static bool failtest = false;
@@ -124,6 +126,23 @@
"xenstored corruption: connection id %i: err %s: %s",
conn ? (int)conn->id : -1, strerror(saved_errno), str);
_exit(2);
+}
+
+TDB_CONTEXT *tdb_context(struct connection *conn)
+{
+ /* conn = NULL used in manual_node at setup. */
+ if (!conn || !conn->transaction)
+ return tdb_ctx;
+ return tdb_transaction_context(conn->transaction);
+}
+
+bool replace_tdb(const char *newname, TDB_CONTEXT *newtdb)
+{
+ if (rename(newname, xs_daemon_tdb()) != 0)
+ return false;
+ tdb_close(tdb_ctx);
+ tdb_ctx = talloc_steal(talloc_autofree_context(), newtdb);
+ return true;
}
static char *sockmsg_string(enum xsd_sockmsg_type type)
@@ -202,37 +221,6 @@
write(tracefd, string, strlen(string));
}
-void trace_watch_timeout(const struct connection *conn, const char *node,
const char *token)
-{
- char string[64];
- if (tracefd < 0)
- return;
- write(tracefd, "WATCH_TIMEOUT ", strlen("WATCH_TIMEOUT "));
- sprintf(string, " %p ", conn);
- write(tracefd, string, strlen(string));
- write(tracefd, " (", 2);
- write(tracefd, node, strlen(node));
- write(tracefd, " ", 1);
- write(tracefd, token, strlen(token));
- write(tracefd, ")\n", 2);
-}
-
-static void trace_blocked(const struct connection *conn,
- const struct buffered_data *data)
-{
- char string[64];
-
- if (tracefd < 0)
- return;
-
- write(tracefd, "BLOCKED", strlen("BLOCKED"));
- sprintf(string, " %p (", conn);
- write(tracefd, string, strlen(string));
- write(tracefd, sockmsg_string(data->hdr.msg.type),
- strlen(sockmsg_string(data->hdr.msg.type)));
- write(tracefd, ")\n", 2);
-}
-
void trace(const char *fmt, ...)
{
va_list arglist;
@@ -253,7 +241,6 @@
int ret;
struct buffered_data *out = conn->out;
- assert(conn->state != BLOCKED);
if (out->inhdr) {
if (verbose)
xprintf("Writing msg %s (%s) out to %p\n",
@@ -351,24 +338,6 @@
return max;
}
-/* Read everything from a talloc_open'ed fd. */
-void *read_all(int *fd, unsigned int *size)
-{
- unsigned int max = 4;
- int ret;
- void *buffer = talloc_size(fd, max);
-
- *size = 0;
- while ((ret = read(*fd, buffer + *size, max - *size)) > 0) {
- *size += ret;
- if (*size == max)
- buffer = talloc_realloc_size(fd, buffer, max *= 2);
- }
- if (ret < 0)
- return NULL;
- return buffer;
-}
-
static int destroy_fd(void *_fd)
{
int *fd = _fd;
@@ -409,42 +378,167 @@
return child[len] == '/' || child[len] == '\0';
}
-/* Answer never ends in /. */
-char *node_dir_outside_transaction(const char *node)
-{
- if (streq(node, "/"))
- return talloc_strdup(node, xs_daemon_store());
- return talloc_asprintf(node, "%s%s", xs_daemon_store(), node);
-}
-
-static char *node_dir(struct transaction *trans, const char *node)
-{
- if (!trans || !within_transaction(trans, node))
- return node_dir_outside_transaction(node);
- return node_dir_inside_transaction(trans, node);
-}
-
-static char *datafile(const char *dir)
-{
- return talloc_asprintf(dir, "%s/.data", dir);
-}
-
-static char *node_datafile(struct transaction *trans, const char *node)
-{
- return datafile(node_dir(trans, node));
-}
-
-static char *permfile(const char *dir)
-{
- return talloc_asprintf(dir, "%s/.perms", dir);
-}
-
-static char *node_permfile(struct transaction *trans, const char *node)
-{
- return permfile(node_dir(trans, node));
-}
-
-struct buffered_data *new_buffer(void *ctx)
+/* If it fails, returns NULL and sets errno. */
+static struct node *read_node(struct connection *conn, const char *name)
+{
+ TDB_DATA key, data;
+ u32 *p;
+ struct node *node;
+
+ key.dptr = (void *)name;
+ key.dsize = strlen(name);
+ data = tdb_fetch(tdb_context(conn), key);
+
+ if (data.dptr == NULL) {
+ if (tdb_error(tdb_context(conn)) == TDB_ERR_NOEXIST)
+ errno = ENOENT;
+ else
+ errno = EIO;
+ return NULL;
+ }
+
+ node = talloc(name, struct node);
+ node->name = talloc_strdup(node, name);
+ node->parent = NULL;
+ node->tdb = tdb_context(conn);
+ talloc_steal(node, data.dptr);
+
+ /* Datalen, childlen, number of permissions */
+ p = (u32 *)data.dptr;
+ node->num_perms = p[0];
+ node->datalen = p[1];
+ node->childlen = p[2];
+
+ /* Permissions are struct xs_permissions. */
+ node->perms = (void *)&p[3];
+ /* Data is binary blob (usually ascii, no nul). */
+ node->data = node->perms + node->num_perms;
+ /* Children is strings, nul separated. */
+ node->children = node->data + node->datalen;
+
+ return node;
+}
+
+static bool write_node(struct connection *conn, const struct node *node)
+{
+ TDB_DATA key, data;
+ void *p;
+
+ key.dptr = (void *)node->name;
+ key.dsize = strlen(node->name);
+
+ data.dsize = 3*sizeof(u32)
+ + node->num_perms*sizeof(node->perms[0])
+ + node->datalen + node->childlen;
+ data.dptr = talloc_size(node, data.dsize);
+ ((u32 *)data.dptr)[0] = node->num_perms;
+ ((u32 *)data.dptr)[1] = node->datalen;
+ ((u32 *)data.dptr)[2] = node->childlen;
+ p = data.dptr + 3 * sizeof(u32);
+
+ memcpy(p, node->perms, node->num_perms*sizeof(node->perms[0]));
+ p += node->num_perms*sizeof(node->perms[0]);
+ memcpy(p, node->data, node->datalen);
+ p += node->datalen;
+ memcpy(p, node->children, node->childlen);
+
+ /* TDB should set errno, but doesn't even set ecode AFAICT. */
+ if (tdb_store(tdb_context(conn), key, data, TDB_REPLACE) != 0) {
+ errno = ENOSPC;
+ return false;
+ }
+ return true;
+}
+
+static enum xs_perm_type perm_for_conn(struct connection *conn,
+ struct xs_permissions *perms,
+ unsigned int num)
+{
+ unsigned int i;
+ enum xs_perm_type mask = XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER;
+
+ if (!conn->can_write)
+ mask &= ~XS_PERM_WRITE;
+
+ /* Owners and tools get it all... */
+ if (!conn->id || perms[0].id == conn->id)
+ return (XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER) & mask;
+
+ for (i = 1; i < num; i++)
+ if (perms[i].id == conn->id)
+ return perms[i].perms & mask;
+
+ return perms[0].perms & mask;
+}
+
+static char *get_parent(const char *node)
+{
+ char *slash = strrchr(node + 1, '/');
+ if (!slash)
+ return talloc_strdup(node, "/");
+ return talloc_asprintf(node, "%.*s", (int)(slash - node), node);
+}
+
+/* What do parents say? */
+static enum xs_perm_type ask_parents(struct connection *conn, const char *name)
+{
+ struct node *node;
+
+ do {
+ name = get_parent(name);
+ node = read_node(conn, name);
+ if (node)
+ break;
+ } while (!streq(name, "/"));
+
+ /* No permission at root? We're in trouble. */
+ if (!node)
+ corrupt(conn, "No permissions file at root");
+
+ return perm_for_conn(conn, node->perms, node->num_perms);
+}
+
+/* We have a weird permissions system. You can allow someone into a
+ * specific node without allowing it in the parents. If it's going to
+ * fail, however, we don't want the errno to indicate any information
+ * about the node. */
+static int errno_from_parents(struct connection *conn, const char *node,
+ int errnum, enum xs_perm_type perm)
+{
+ /* We always tell them about memory failures. */
+ if (errnum == ENOMEM)
+ return errnum;
+
+ if (ask_parents(conn, node) & perm)
+ return errnum;
+ return EACCES;
+}
+
+/* If it fails, returns NULL and sets errno. */
+struct node *get_node(struct connection *conn,
+ const char *name,
+ enum xs_perm_type perm)
+{
+ struct node *node;
+
+ if (!name || !is_valid_nodename(name)) {
+ errno = EINVAL;
+ return NULL;
+ }
+ node = read_node(conn, name);
+ /* If we don't have permission, we don't have node. */
+ if (node) {
+ if ((perm_for_conn(conn, node->perms, node->num_perms) & perm)
+ != perm)
+ node = NULL;
+ }
+ /* Clean up errno if they weren't supposed to know. */
+ if (!node)
+ errno = errno_from_parents(conn, name, errno, perm);
+ return node;
+}
+
+static struct buffered_data *new_buffer(void *ctx)
{
struct buffered_data *data;
@@ -457,7 +551,8 @@
}
/* Return length of string (including nul) at this offset. */
-unsigned int get_string(const struct buffered_data *data, unsigned int offset)
+static unsigned int get_string(const struct buffered_data *data,
+ unsigned int offset)
{
const char *nul;
@@ -508,7 +603,6 @@
conn->waiting_reply = bdata;
} else
conn->out = bdata;
- assert(conn->state != BLOCKED);
conn->state = BUSY;
}
@@ -567,29 +661,6 @@
return in->buffer;
}
-/* If it fails, returns NULL and sets errno. */
-static struct xs_permissions *get_perms(const char *dir, unsigned int *num)
-{
- unsigned int size;
- char *strings;
- struct xs_permissions *ret;
- int *fd;
-
- fd = talloc_open(permfile(dir), O_RDONLY, 0);
- if (!fd)
- return NULL;
- strings = read_all(fd, &size);
- if (!strings)
- return NULL;
-
- *num = xs_count_strings(strings, size);
- ret = talloc_array(dir, struct xs_permissions, *num);
- if (!xs_strings_to_perms(ret, *num, strings))
- corrupt(NULL, "Permissions corrupt for %s", dir);
-
- return ret;
-}
-
static char *perms_to_strings(const void *ctx,
struct xs_permissions *perms, unsigned int num,
unsigned int *len)
@@ -608,173 +679,6 @@
*len += strlen(buffer) + 1;
}
return strings;
-}
-
-/* Destroy this, and its children, and its children's children. */
-int destroy_path(void *path)
-{
- DIR *dir;
- struct dirent *dirent;
-
- dir = opendir(path);
- if (!dir) {
- if (unlink(path) == 0 || errno == ENOENT)
- return 0;
- corrupt(NULL, "Destroying path %s", path);
- }
-
- while ((dirent = readdir(dir)) != NULL) {
- char fullpath[strlen(path) + 1 + strlen(dirent->d_name) + 1];
- sprintf(fullpath, "%s/%s", (char *)path, dirent->d_name);
- if (!streq(dirent->d_name,".") && !streq(dirent->d_name,".."))
- destroy_path(fullpath);
- }
- closedir(dir);
- if (rmdir(path) != 0)
- corrupt(NULL, "Destroying directory %s", path);
- return 0;
-}
-
-/* Create a self-destructing temporary path */
-static char *temppath(const char *path)
-{
- char *tmppath = talloc_asprintf(path, "%s.tmp", path);
- talloc_set_destructor(tmppath, destroy_path);
- return tmppath;
-}
-
-/* Create a self-destructing temporary file */
-static char *tempfile(const char *path, void *contents, unsigned int len)
-{
- int *fd;
- char *tmppath = temppath(path);
-
- fd = talloc_open(tmppath, O_WRONLY|O_CREAT|O_EXCL, 0640);
- if (!fd)
- return NULL;
- if (!xs_write_all(*fd, contents, len))
- return NULL;
-
- return tmppath;
-}
-
-static int destroy_opendir(void *_dir)
-{
- DIR **dir = _dir;
- closedir(*dir);
- return 0;
-}
-
-/* Return a pointer to a DIR*, self-closing and attached to this pathname. */
-DIR **talloc_opendir(const char *pathname)
-{
- DIR **dir;
-
- dir = talloc(pathname, DIR *);
- *dir = opendir(pathname);
- if (!*dir) {
- int saved_errno = errno;
- talloc_free(dir);
- errno = saved_errno;
- return NULL;
- }
- talloc_set_destructor(dir, destroy_opendir);
- return dir;
-}
-
-/* We assume rename() doesn't fail on moves in same dir. */
-static void commit_tempfile(const char *path)
-{
- char realname[strlen(path) + 1];
- unsigned int len = strrchr(path, '.') - path;
-
- memcpy(realname, path, len);
- realname[len] = '\0';
- if (rename(path, realname) != 0)
- corrupt(NULL, "Committing %s", realname);
- talloc_set_destructor(path, NULL);
-}
-
-static bool set_perms(struct transaction *transaction,
- const char *node,
- struct xs_permissions *perms, unsigned int num)
-{
- unsigned int len;
- char *permpath, *strings;
-
- strings = perms_to_strings(node, perms, num, &len);
- if (!strings)
- return false;
-
- /* Create then move. */
- permpath = tempfile(node_permfile(transaction, node), strings, len);
- if (!permpath)
- return false;
-
- commit_tempfile(permpath);
- return true;
-}
-
-static char *get_parent(const char *node)
-{
- char *slash = strrchr(node + 1, '/');
- if (!slash)
- return talloc_strdup(node, "/");
- return talloc_asprintf(node, "%.*s", (int)(slash - node), node);
-}
-
-static enum xs_perm_type perm_for_id(domid_t id,
- struct xs_permissions *perms,
- unsigned int num)
-{
- unsigned int i;
-
- /* Owners and tools get it all... */
- if (!id || perms[0].id == id)
- return XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER;
-
- for (i = 1; i < num; i++)
- if (perms[i].id == id)
- return perms[i].perms;
-
- return perms[0].perms;
-}
-
-/* What do parents say? */
-static enum xs_perm_type ask_parents(struct connection *conn,
- const char *node)
-{
- struct xs_permissions *perms;
- unsigned int num;
-
- do {
- node = get_parent(node);
- perms = get_perms(node_dir(conn->transaction, node), &num);
- if (perms)
- break;
- } while (!streq(node, "/"));
-
- /* No permission at root? We're in trouble. */
- if (!perms)
- corrupt(conn, "No permissions file at root");
-
- return perm_for_id(conn->id, perms, num);
-}
-
-/* We have a weird permissions system. You can allow someone into a
- * specific node without allowing it in the parents. If it's going to
- * fail, however, we don't want the errno to indicate any information
- * about the node. */
-static int errno_from_parents(struct connection *conn, const char *node,
- int errnum)
-{
- /* We always tell them about memory failures. */
- if (errnum == ENOMEM)
- return errnum;
-
- if (ask_parents(conn, node) & XS_PERM_READ)
- return errnum;
- return EACCES;
}
char *canonicalize(struct connection *conn, const char *node)
@@ -789,46 +693,6 @@
return (char *)node;
}
-bool check_node_perms(struct connection *conn, const char *node,
- enum xs_perm_type perm)
-{
- struct xs_permissions *perms;
- unsigned int num;
-
- if (!node || !is_valid_nodename(node)) {
- errno = EINVAL;
- return false;
- }
-
- if (!conn->can_write && (perm & XS_PERM_WRITE)) {
- errno = EROFS;
- return false;
- }
-
- perms = get_perms(node_dir(conn->transaction, node), &num);
-
- if (perms) {
- if (perm_for_id(conn->id, perms, num) & perm)
- return true;
- errno = EACCES;
- return false;
- }
-
- /* If it's OK not to exist, we consult parents. */
- if (errno == ENOENT && (perm & XS_PERM_ENOENT_OK)) {
- if (ask_parents(conn, node) & perm)
- return true;
- /* Parents say they should not know. */
- errno = EACCES;
- return false;
- }
-
- /* They might not have permission to even *see* this node, in
- * which case we return EACCES even if it's ENOENT or EIO. */
- errno = errno_from_parents(conn, node, errno);
- return false;
-}
-
bool check_event_node(const char *node)
{
if (!node || !strstarts(node, "@")) {
@@ -838,142 +702,144 @@
return true;
}
-static void send_directory(struct connection *conn, const char *node)
-{
- char *path, *reply;
- unsigned int reply_len = 0;
- DIR **dir;
- struct dirent *dirent;
-
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_READ)) {
+static void send_directory(struct connection *conn, const char *name)
+{
+ struct node *node;
+
+ name = canonicalize(conn, name);
+ node = get_node(conn, name, XS_PERM_READ);
+ if (!node) {
send_error(conn, errno);
return;
}
- path = node_dir(conn->transaction, node);
- dir = talloc_opendir(path);
- if (!dir) {
+ send_reply(conn, XS_DIRECTORY, node->children, node->childlen);
+}
+
+static void do_read(struct connection *conn, const char *name)
+{
+ struct node *node;
+
+ name = canonicalize(conn, name);
+ node = get_node(conn, name, XS_PERM_READ);
+ if (!node) {
send_error(conn, errno);
return;
}
- reply = talloc_strdup(node, "");
- while ((dirent = readdir(*dir)) != NULL) {
- int len = strlen(dirent->d_name) + 1;
-
- if (!valid_chars(dirent->d_name))
- continue;
-
- reply = talloc_realloc(path, reply, char, reply_len + len);
- strcpy(reply + reply_len, dirent->d_name);
- reply_len += len;
- }
-
- send_reply(conn, XS_DIRECTORY, reply, reply_len);
-}
-
-static void do_read(struct connection *conn, const char *node)
-{
- char *value;
- unsigned int size;
- int *fd;
-
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_READ)) {
- send_error(conn, errno);
- return;
- }
-
- fd = talloc_open(node_datafile(conn->transaction, node), O_RDONLY, 0);
- if (!fd) {
- /* Data file doesn't exist? We call that a directory */
- if (errno == ENOENT)
- errno = EISDIR;
- send_error(conn, errno);
- return;
- }
-
- value = read_all(fd, &size);
- if (!value)
- send_error(conn, errno);
- else
- send_reply(conn, XS_READ, value, size);
-}
-
-/* Commit this directory, eg. comitting a/b.tmp/c causes a/b.tmp -> a.b */
-static bool commit_dir(char *dir)
-{
- char *dot, *slash, *dest;
-
- dot = strrchr(dir, '.');
- slash = strchr(dot, '/');
- if (slash)
- *slash = '\0';
-
- dest = talloc_asprintf(dir, "%.*s", (int)(dot - dir), dir);
- return rename(dir, dest) == 0;
-}
-
-/* Create a temporary directory. Put data in it (if data != NULL) */
-static char *tempdir(struct connection *conn,
- const char *node, void *data, unsigned int datalen)
-{
- struct xs_permissions *perms;
- char *permstr;
- unsigned int num, len;
- int *fd;
- char *dir;
-
- dir = temppath(node_dir(conn->transaction, node));
- if (mkdir(dir, 0750) != 0) {
- if (errno != ENOENT)
+ send_reply(conn, XS_READ, node->data, node->datalen);
+}
+
+static void delete_node_single(struct connection *conn, struct node *node)
+{
+ TDB_DATA key;
+
+ key.dptr = (void *)node->name;
+ key.dsize = strlen(node->name);
+
+ if (tdb_delete(tdb_context(conn), key) != 0)
+ corrupt(conn, "Could not delete '%s'", node->name);
+}
+
+/* Must not be / */
+static char *basename(const char *name)
+{
+ return strrchr(name, '/') + 1;
+}
+
+static struct node *construct_node(struct connection *conn, const char *name)
+{
+ const char *base;
+ unsigned int baselen;
+ struct node *parent, *node;
+ char *children, *parentname = get_parent(name);
+
+ /* If parent doesn't exist, create it. */
+ parent = read_node(conn, parentname);
+ if (!parent)
+ parent = construct_node(conn, parentname);
+ if (!parent)
+ return NULL;
+
+ /* Add child to parent. */
+ base = basename(name);
+ baselen = strlen(base) + 1;
+ children = talloc_array(name, char, parent->childlen + baselen);
+ memcpy(children, parent->children, parent->childlen);
+ memcpy(children + parent->childlen, base, baselen);
+ parent->children = children;
+ parent->childlen += baselen;
+
+ /* Allocate node */
+ node = talloc(name, struct node);
+ node->tdb = tdb_context(conn);
+ node->name = talloc_strdup(node, name);
+
+ /* Inherit permissions, except domains own what they create */
+ node->num_perms = parent->num_perms;
+ node->perms = talloc_memdup(node, parent->perms,
+ node->num_perms * sizeof(node->perms[0]));
+ if (conn->id)
+ node->perms[0].id = conn->id;
+
+ /* No children, no data */
+ node->children = node->data = NULL;
+ node->childlen = node->datalen = 0;
+ node->parent = parent;
+ return node;
+}
+
+static int destroy_node(void *_node)
+{
+ struct node *node = _node;
+ TDB_DATA key;
+
+ if (streq(node->name, "/"))
+ corrupt(NULL, "Destroying root node!");
+
+ key.dptr = (void *)node->name;
+ key.dsize = strlen(node->name);
+
+ tdb_delete(node->tdb, key);
+ return 0;
+}
+
+/* Be careful: create heirarchy, put entry in existing parent *last*.
+ * This helps fsck if we die during this. */
+static struct node *create_node(struct connection *conn,
+ const char *name,
+ void *data, unsigned int datalen)
+{
+ struct node *node, *i;
+
+ node = construct_node(conn, name);
+ if (!node)
+ return NULL;
+
+ node->data = data;
+ node->datalen = datalen;
+
+ /* We write out the nodes down, setting destructor in case
+ * something goes wrong. */
+ for (i = node; i; i = i->parent) {
+ if (!write_node(conn, i))
return NULL;
-
- dir = tempdir(conn, get_parent(node), NULL, 0);
- if (!dir)
- return NULL;
-
- dir = talloc_asprintf(dir, "%s%s", dir, strrchr(node, '/'));
- if (mkdir(dir, 0750) != 0)
- return NULL;
- talloc_set_destructor(dir, destroy_path);
- }
-
- perms = get_perms(get_parent(dir), &num);
- assert(perms);
- /* Domains own what they create. */
- if (conn->id)
- perms->id = conn->id;
-
- permstr = perms_to_strings(dir, perms, num, &len);
- fd = talloc_open(permfile(dir), O_WRONLY|O_CREAT|O_EXCL, 0640);
- if (!fd || !xs_write_all(*fd, permstr, len))
- return NULL;
-
- if (data) {
- char *datapath = datafile(dir);
-
- fd = talloc_open(datapath, O_WRONLY|O_CREAT|O_EXCL, 0640);
- if (!fd || !xs_write_all(*fd, data, datalen))
- return NULL;
- }
- return dir;
-}
-
-static bool node_exists(struct connection *conn, const char *node)
-{
- struct stat st;
-
- return lstat(node_dir(conn->transaction, node), &st) == 0;
+ talloc_set_destructor(i, destroy_node);
+ }
+
+ /* OK, now remove destructors so they stay around */
+ for (i = node; i; i = i->parent)
+ talloc_set_destructor(i, NULL);
+ return node;
}
/* path, data... */
static void do_write(struct connection *conn, struct buffered_data *in)
{
unsigned int offset, datalen;
+ struct node *node;
char *vec[1] = { NULL }; /* gcc4 + -W + -Werror fucks code. */
- char *node, *tmppath;
+ char *name;
/* Extra "strings" can be created by binary data. */
if (get_strings(in, vec, ARRAY_SIZE(vec)) < ARRAY_SIZE(vec)) {
@@ -981,99 +847,115 @@
return;
}
- node = canonicalize(conn, vec[0]);
- if (!within_transaction(conn->transaction, node)) {
- send_error(conn, EROFS);
- return;
- }
-
- if (transaction_block(conn, node))
- return;
-
offset = strlen(vec[0]) + 1;
datalen = in->used - offset;
- if (!check_node_perms(conn, node, XS_PERM_WRITE|XS_PERM_ENOENT_OK)) {
- send_error(conn, errno);
- return;
- }
-
- if (!node_exists(conn, node)) {
- char *dir;
-
- /* Does not exist... */
+ name = canonicalize(conn, vec[0]);
+ node = get_node(conn, name, XS_PERM_WRITE);
+ if (!node) {
+ /* No permissions, invalid input? */
if (errno != ENOENT) {
send_error(conn, errno);
return;
}
-
- dir = tempdir(conn, node, in->buffer + offset, datalen);
- if (!dir || !commit_dir(dir)) {
+ node = create_node(conn, name, in->buffer + offset, datalen);
+ if (!node) {
send_error(conn, errno);
return;
}
-
} else {
- /* Exists... */
- tmppath = tempfile(node_datafile(conn->transaction, node),
- in->buffer + offset, datalen);
- if (!tmppath) {
+ node->data = in->buffer + offset;
+ node->datalen = datalen;
+ if (!write_node(conn, node)){
send_error(conn, errno);
return;
}
-
- commit_tempfile(tmppath);
- }
-
- add_change_node(conn->transaction, node, false);
- fire_watches(conn, node, false);
+ }
+
+ add_change_node(conn->transaction, name, false);
+ fire_watches(conn, name, false);
send_ack(conn, XS_WRITE);
}
-static void do_mkdir(struct connection *conn, const char *node)
-{
- char *dir;
-
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_WRITE|XS_PERM_ENOENT_OK)) {
- send_error(conn, errno);
- return;
- }
-
- if (!within_transaction(conn->transaction, node)) {
- send_error(conn, EROFS);
- return;
- }
-
- if (transaction_block(conn, node))
- return;
+static void do_mkdir(struct connection *conn, const char *name)
+{
+ struct node *node;
+
+ name = canonicalize(conn, name);
+ node = get_node(conn, name, XS_PERM_WRITE);
/* If it already exists, fine. */
- if (node_exists(conn, node)) {
- send_ack(conn, XS_MKDIR);
- return;
- }
-
- dir = tempdir(conn, node, NULL, 0);
- if (!dir || !commit_dir(dir)) {
- send_error(conn, errno);
- return;
- }
-
- add_change_node(conn->transaction, node, false);
- fire_watches(conn, node, false);
+ if (!node) {
+ /* No permissions? */
+ if (errno != ENOENT) {
+ send_error(conn, errno);
+ return;
+ }
+ node = create_node(conn, name, NULL, 0);
+ if (!node) {
+ send_error(conn, errno);
+ return;
+ }
+ add_change_node(conn->transaction, name, false);
+ fire_watches(conn, name, false);
+ }
send_ack(conn, XS_MKDIR);
}
-static void do_rm(struct connection *conn, const char *node)
-{
- char *tmppath, *path;
-
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_WRITE)) {
+static void delete_node(struct connection *conn, struct node *node)
+{
+ unsigned int i;
+
+ /* Delete self, then delete children. If something goes wrong,
+ * consistency check will clean up this way. */
+ delete_node_single(conn, node);
+
+ /* Delete children, too. */
+ for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) {
+ struct node *child;
+
+ child = read_node(conn,
+ talloc_asprintf(node, "%s/%s", node->name,
+ node->children + i));
+ if (!child)
+ corrupt(conn, "No child '%s' found", child);
+ delete_node(conn, child);
+ }
+}
+
+/* Delete memory using memmove. */
+static void memdel(void *mem, unsigned off, unsigned len, unsigned total)
+{
+ memmove(mem + off, mem + off + len, total - off - len);
+}
+
+static bool delete_child(struct connection *conn,
+ struct node *node, const char *childname)
+{
+ unsigned int i;
+
+ for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) {
+ if (streq(node->children+i, childname)) {
+ memdel(node->children, i, strlen(childname) + 1,
+ node->childlen);
+ node->childlen -= strlen(childname) + 1;
+ return write_node(conn, node);
+ }
+ }
+ corrupt(conn, "Can't find child '%s' in %s", childname, node->name);
+}
+
+static void do_rm(struct connection *conn, const char *name)
+{
+ struct node *node, *parent;
+
+ name = canonicalize(conn, name);
+ node = get_node(conn, name, XS_PERM_WRITE);
+ if (!node) {
/* Didn't exist already? Fine, if parent exists. */
if (errno == ENOENT) {
- if (node_exists(conn, get_parent(node))) {
+ node = read_node(conn, get_parent(name));
+ if (node) {
send_ack(conn, XS_RM);
return;
}
@@ -1084,53 +966,43 @@
return;
}
- if (!within_transaction(conn->transaction, node)) {
- send_error(conn, EROFS);
- return;
- }
-
- if (transaction_block(conn, node))
- return;
-
- if (streq(node, "/")) {
+ if (streq(name, "/")) {
send_error(conn, EINVAL);
return;
}
- /* We move the directory to temporary name, destructor cleans up. */
- path = node_dir(conn->transaction, node);
- tmppath = talloc_asprintf(node, "%s.tmp", path);
- talloc_set_destructor(tmppath, destroy_path);
-
- if (rename(path, tmppath) != 0) {
+ /* Delete from parent first, then if something explodes fsck cleans. */
+ parent = read_node(conn, get_parent(name));
+ if (!parent) {
+ send_error(conn, EINVAL);
+ return;
+ }
+
+ if (!delete_child(conn, parent, basename(name))) {
+ send_error(conn, EINVAL);
+ return;
+ }
+
+ delete_node(conn, node);
+ add_change_node(conn->transaction, name, true);
+ fire_watches(conn, name, true);
+ send_ack(conn, XS_RM);
+}
+
+static void do_get_perms(struct connection *conn, const char *name)
+{
+ struct node *node;
+ char *strings;
+ unsigned int len;
+
+ name = canonicalize(conn, name);
+ node = get_node(conn, name, XS_PERM_READ);
+ if (!node) {
send_error(conn, errno);
return;
}
- add_change_node(conn->transaction, node, true);
- fire_watches(conn, node, true);
- send_ack(conn, XS_RM);
-}
-
-static void do_get_perms(struct connection *conn, const char *node)
-{
- struct xs_permissions *perms;
- char *strings;
- unsigned int len, num;
-
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_READ)) {
- send_error(conn, errno);
- return;
- }
-
- perms = get_perms(node_dir(conn->transaction, node), &num);
- if (!perms) {
- send_error(conn, errno);
- return;
- }
-
- strings = perms_to_strings(node, perms, num, &len);
+ strings = perms_to_strings(node, node->perms, node->num_perms, &len);
if (!strings)
send_error(conn, errno);
else
@@ -1140,8 +1012,8 @@
static void do_set_perms(struct connection *conn, struct buffered_data *in)
{
unsigned int num;
- char *node, *permstr;
- struct xs_permissions *perms;
+ char *name, *permstr;
+ struct node *node;
num = xs_count_strings(in->buffer, in->used);
if (num < 2) {
@@ -1150,37 +1022,30 @@
}
/* First arg is node name. */
- node = canonicalize(conn, in->buffer);
+ name = canonicalize(conn, in->buffer);
permstr = in->buffer + strlen(in->buffer) + 1;
num--;
- if (!within_transaction(conn->transaction, node)) {
- send_error(conn, EROFS);
- return;
- }
-
- if (transaction_block(conn, node))
- return;
-
/* We must own node to do this (tools can do this too). */
- if (!check_node_perms(conn, node, XS_PERM_WRITE|XS_PERM_OWNER)) {
+ node = get_node(conn, name, XS_PERM_WRITE|XS_PERM_OWNER);
+ if (!node) {
send_error(conn, errno);
return;
}
- perms = talloc_array(node, struct xs_permissions, num);
- if (!xs_strings_to_perms(perms, num, permstr)) {
+ node->perms = talloc_array(node, struct xs_permissions, num);
+ node->num_perms = num;
+ if (!xs_strings_to_perms(node->perms, num, permstr)) {
send_error(conn, errno);
return;
}
-
- if (!set_perms(conn->transaction, node, perms, num)) {
+ if (!write_node(conn, node)) {
send_error(conn, errno);
return;
}
- add_change_node(conn->transaction, node, false);
- fire_watches(conn, node, false);
+ add_change_node(conn->transaction, name, false);
+ fire_watches(conn, name, false);
send_ack(conn, XS_SET_PERMS);
}
@@ -1221,12 +1086,8 @@
case XS_SHUTDOWN:
/* FIXME: Implement gentle shutdown too. */
/* Only tools can do this. */
- if (conn->id != 0) {
+ if (conn->id != 0 || !conn->can_write) {
send_error(conn, EACCES);
- break;
- }
- if (!conn->can_write) {
- send_error(conn, EROFS);
break;
}
send_ack(conn, XS_SHUTDOWN);
@@ -1263,7 +1124,7 @@
break;
case XS_TRANSACTION_START:
- do_transaction_start(conn, onearg(in));
+ do_transaction_start(conn, in);
break;
case XS_TRANSACTION_END:
@@ -1309,6 +1170,8 @@
/* For simplicity, we kill the connection on OOM. */
talloc_set_fail_handler(out_of_mem, &talloc_fail);
if (setjmp(talloc_fail)) {
+ /* Free in before conn, in case it needs something. */
+ talloc_free(in);
talloc_free(conn);
goto end;
}
@@ -1330,16 +1193,8 @@
conn->in = new_buffer(conn);
process_message(conn, in);
- if (conn->state == BLOCKED) {
- /* Blocked by transaction: queue for re-xmit. */
- talloc_free(conn->in);
- conn->in = in;
- in = NULL;
- trace_blocked(conn, conn->in);
- }
-
+ talloc_free(in);
end:
- talloc_free(in);
talloc_set_fail_handler(NULL, NULL);
if (talloc_total_blocks(NULL)
!= talloc_total_blocks(talloc_autofree_context()) + 1) {
@@ -1350,7 +1205,7 @@
/* Errors in reading or allocating here mean we get out of sync, so we
* drop the whole client connection. */
-void handle_input(struct connection *conn)
+static void handle_input(struct connection *conn)
{
int bytes;
struct buffered_data *in;
@@ -1402,39 +1257,10 @@
talloc_free(conn);
}
-void handle_output(struct connection *conn)
+static void handle_output(struct connection *conn)
{
if (!write_message(conn))
talloc_free(conn);
-}
-
-/* If a transaction has ended, see if we can unblock any connections. */
-static void unblock_connections(void)
-{
- struct connection *i, *tmp;
-
- list_for_each_entry_safe(i, tmp, &connections, list) {
- switch (i->state) {
- case BLOCKED:
- if (!transaction_covering_node(i->blocked_by)) {
- talloc_free(i->blocked_by);
- i->blocked_by = NULL;
- i->state = OK;
- consider_message(i);
- }
- break;
- case BUSY:
- case OK:
- break;
- }
- }
-
- /* To balance bias, move first entry to end. */
- if (!list_empty(&connections)) {
- i = list_top(&connections, struct connection, list);
- list_del(&i->list);
- list_add_tail(&i->list, &connections);
- }
}
struct connection *new_connection(connwritefn_t *write, connreadfn_t *read)
@@ -1451,7 +1277,6 @@
return NULL;
new->state = OK;
- new->blocked_by = NULL;
new->out = new->waiting_reply = NULL;
new->waiting_for_ack = NULL;
new->fd = -1;
@@ -1504,25 +1329,9 @@
close(fd);
}
-/* Calc timespan from now to absolute time. */
-static void time_relative_to_now(struct timeval *tv)
-{
- struct timeval now;
-
- gettimeofday(&now, NULL);
- if (timercmp(&now, tv, >))
- timerclear(tv);
- else {
- tv->tv_sec -= now.tv_sec;
- if (now.tv_usec > tv->tv_usec) {
- tv->tv_sec--;
- tv->tv_usec += 1000000;
- }
- tv->tv_usec -= now.tv_usec;
- }
-}
-
#ifdef TESTING
+/* Valgrind can check our writes better if we don't use mmap */
+#define TDB_FLAGS TDB_NOMMAP
/* Useful for running under debugger. */
void dump_connection(void)
{
@@ -1532,13 +1341,10 @@
printf("Connection %p:\n", i);
printf(" state = %s\n",
i->state == OK ? "OK"
- : i->state == BLOCKED ? "BLOCKED"
: i->state == BUSY ? "BUSY"
: "INVALID");
if (i->id)
printf(" id = %i\n", i->id);
- if (i->blocked_by)
- printf(" blocked on = %s\n", i->blocked_by);
if (!i->in->inhdr || i->in->used)
printf(" got %i bytes of %s\n",
i->in->used, i->in->inhdr ? "header" : "data");
@@ -1559,44 +1365,53 @@
dump_watches(i);
}
}
+#else
+#define TDB_FLAGS 0
#endif
+/* We create initial nodes manually. */
+static void manual_node(const char *name, const char *child)
+{
+ struct node *node;
+ struct xs_permissions perms = { .id = 0, .perms = XS_PERM_READ };
+
+ node = talloc(NULL, struct node);
+ node->name = name;
+ node->perms = &perms;
+ node->num_perms = 1;
+ node->data = NULL;
+ node->datalen = 0;
+ node->children = (char *)child;
+ if (child)
+ node->childlen = strlen(child) + 1;
+ else
+ node->childlen = 0;
+
+ if (!write_node(NULL, node))
+ barf_perror("Could not create initial node %s", name);
+ talloc_free(node);
+}
+
+#
+
static void setup_structure(void)
{
- struct xs_permissions perms = { .id = 0, .perms = XS_PERM_READ };
- char *root, *dir, *permfile;
-
- /* Create root directory, with permissions. */
- if (mkdir(xs_daemon_store(), 0750) != 0) {
- if (errno != EEXIST)
- barf_perror("Could not create root %s",
- xs_daemon_store());
- return;
- }
- root = talloc_strdup(talloc_autofree_context(), "/");
- if (!set_perms(NULL, root, &perms, 1))
- barf_perror("Could not create permissions in root");
-
- /* Create tool directory, with xenstored subdir. */
- dir = talloc_asprintf(root, "%s/%s", xs_daemon_store(), "tool");
- if (mkdir(dir, 0750) != 0)
- barf_perror("Making dir %s", dir);
-
- permfile = talloc_strdup(root, "/tool");
- if (!set_perms(NULL, permfile, &perms, 1))
- barf_perror("Could not create permissions on %s", permfile);
-
- dir = talloc_asprintf(root, "%s/%s", dir, "xenstored");
- if (mkdir(dir, 0750) != 0)
- barf_perror("Making dir %s", dir);
-
- permfile = talloc_strdup(root, "/tool/xenstored");
- if (!set_perms(NULL, permfile, &perms, 1))
- barf_perror("Could not create permissions on %s", permfile);
- talloc_free(root);
- if (mkdir(xs_daemon_transactions(), 0750) != 0)
- barf_perror("Could not create transaction dir %s",
- xs_daemon_transactions());
+ char *tdbname;
+ tdbname = talloc_strdup(talloc_autofree_context(), xs_daemon_tdb());
+ tdb_ctx = tdb_open(tdbname, 0, TDB_FLAGS, O_RDWR, 0);
+
+ if (!tdb_ctx) {
+ tdb_ctx = tdb_open(tdbname, 7919, TDB_FLAGS, O_RDWR|O_CREAT,
+ 0640);
+ if (!tdb_ctx)
+ barf_perror("Could not create tdb file %s", tdbname);
+
+ manual_node("/", "tool");
+ manual_node("/tool", "xenstored");
+ manual_node("/tool/xenstored", NULL);
+ }
+
+ /* FIXME: Fsck */
}
static void write_pidfile(const char *pidfile)
@@ -1759,17 +1574,8 @@
/* FIXME: Rewrite so noone can starve. */
for (;;) {
struct connection *i;
- struct timeval *tvp = NULL, tv;
-
- timerclear(&tv);
- shortest_transaction_timeout(&tv);
- shortest_watch_ack_timeout(&tv);
- if (timerisset(&tv)) {
- time_relative_to_now(&tv);
- tvp = &tv;
- }
-
- if (select(max+1, &inset, &outset, NULL, tvp) < 0) {
+
+ if (select(max+1, &inset, &outset, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
barf_perror("Select failed");
@@ -1818,14 +1624,6 @@
}
}
- if (tvp) {
- check_transaction_timeout();
- check_watch_ack_timeout();
- }
-
- /* If transactions ended, we might be able to do more work. */
- unblock_connections();
-
max = initialize_set(&inset, &outset, *sock, *ro_sock,
event_fd);
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_core.h
--- a/tools/xenstore/xenstored_core.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_core.h Fri Sep 23 13:25:01 2005
@@ -28,6 +28,7 @@
#include "xs_lib.h"
#include "xenstored.h"
#include "list.h"
+#include "tdb.h"
struct buffered_data
{
@@ -49,8 +50,6 @@
enum state
{
- /* Blocked by transaction. */
- BLOCKED,
/* Doing action, not listening */
BUSY,
/* Completed */
@@ -69,9 +68,6 @@
/* Blocked on transaction? Busy? */
enum state state;
-
- /* Node we are waiting for (if state == BLOCKED) */
- char *blocked_by;
/* Is this a read-only connection? */
bool can_write;
@@ -103,9 +99,27 @@
};
extern struct list_head connections;
-/* Return length of string (including nul) at this offset. */
-unsigned int get_string(const struct buffered_data *data,
- unsigned int offset);
+struct node {
+ const char *name;
+
+ /* Database I came from */
+ TDB_CONTEXT *tdb;
+
+ /* Parent (optional) */
+ struct node *parent;
+
+ /* Permissions. */
+ unsigned int num_perms;
+ struct xs_permissions *perms;
+
+ /* Contents. */
+ unsigned int datalen;
+ void *data;
+
+ /* Children, each nul-terminated. */
+ unsigned int childlen;
+ char *children;
+};
/* Break input into vectors, return the number, fill in up to num of them. */
unsigned int get_strings(struct buffered_data *data,
@@ -113,9 +127,6 @@
/* Is child node a child or equal to parent node? */
bool is_child(const char *child, const char *parent);
-
-/* Create a new buffer with lifetime of context. */
-struct buffered_data *new_buffer(void *ctx);
void send_reply(struct connection *conn, enum xsd_sockmsg_type type,
const void *data, unsigned int len);
@@ -129,15 +140,22 @@
/* Canonicalize this path if possible. */
char *canonicalize(struct connection *conn, const char *node);
-/* Check permissions on this node. */
-bool check_node_perms(struct connection *conn, const char *node,
- enum xs_perm_type perm);
-
/* Check if node is an event node. */
bool check_event_node(const char *node);
-/* Path to this node outside transaction. */
-char *node_dir_outside_transaction(const char *node);
+/* Get this node, checking we have permissions. */
+struct node *get_node(struct connection *conn,
+ const char *name,
+ enum xs_perm_type perm);
+
+/* Get TDB context for this connection */
+TDB_CONTEXT *tdb_context(struct connection *conn);
+
+/* Destructor for tdbs: required for transaction code */
+int destroy_tdb(void *_tdb);
+
+/* Replace the tdb: required for transaction code */
+bool replace_tdb(const char *newname, TDB_CONTEXT *newtdb);
/* Fail due to excessive corruption, capitalist pigdogs! */
void __attribute__((noreturn)) corrupt(struct connection *conn,
@@ -145,23 +163,9 @@
struct connection *new_connection(connwritefn_t *write, connreadfn_t *read);
-void handle_input(struct connection *conn);
-void handle_output(struct connection *conn);
-
/* Is this a valid node name? */
bool is_valid_nodename(const char *node);
-/* Return a pointer to an open dir, self-closig and attached to pathname. */
-DIR **talloc_opendir(const char *pathname);
-
-/* Return a pointer to an fd, self-closing and attached to this pathname. */
-int *talloc_open(const char *pathname, int flags, int mode);
-
-/* Convenient talloc-style destructor for paths. */
-int destroy_path(void *path);
-
-/* Read entire contents of a talloced fd. */
-void *read_all(int *fd, unsigned int *size);
/* Tracing infrastructure. */
void trace_create(const void *data, const char *type);
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_domain.c
--- a/tools/xenstore/xenstored_domain.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_domain.c Fri Sep 23 13:25:01 2005
@@ -309,13 +309,8 @@
return;
}
- if (conn->id != 0) {
+ if (conn->id != 0 || !conn->can_write) {
send_error(conn, EACCES);
- return;
- }
-
- if (!conn->can_write) {
- send_error(conn, EROFS);
return;
}
@@ -386,7 +381,7 @@
talloc_free(domain->conn);
- fire_watches(NULL, "@releaseDomain", false);
+ fire_watches(conn, "@releaseDomain", false);
send_ack(conn, XS_RELEASE);
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_transaction.c
--- a/tools/xenstore/xenstored_transaction.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_transaction.c Fri Sep 23 13:25:01 2005
@@ -26,6 +26,7 @@
#include <stdarg.h>
#include <stdlib.h>
#include <fcntl.h>
+#include <unistd.h>
#include "talloc.h"
#include "list.h"
#include "xenstored_transaction.h"
@@ -51,74 +52,26 @@
/* Global list of transactions. */
struct list_head list;
+ /* Generation when transaction started. */
+ unsigned int generation;
+
/* My owner (conn->transaction == me). */
struct connection *conn;
- /* Subtree this transaction covers */
- char *node;
-
- /* Base for this transaction. */
- char *divert;
+ /* TDB to work on, and filename */
+ TDB_CONTEXT *tdb;
+ char *tdb_name;
/* List of changed nodes. */
struct list_head changes;
-
- /* Someone's waiting: time limit. */
- struct timeval timeout;
-
- /* We've timed out. */
- bool destined_to_fail;
};
static LIST_HEAD(transactions);
+static unsigned int generation;
-bool within_transaction(struct transaction *trans, const char *node)
+/* Return tdb context to use for this connection. */
+TDB_CONTEXT *tdb_transaction_context(struct transaction *trans)
{
- if (!trans)
- return true;
- return is_child(node, trans->node);
-}
-
-/* You are on notice: this transaction is blocking someone. */
-static void start_transaction_timeout(struct transaction *trans)
-{
- if (timerisset(&trans->timeout))
- return;
-
- /* One second timeout. */
- gettimeofday(&trans->timeout, NULL);
- trans->timeout.tv_sec += 1;
-}
-
-struct transaction *transaction_covering_node(const char *node)
-{
- struct transaction *i;
-
- list_for_each_entry(i, &transactions, list) {
- if (i->destined_to_fail)
- continue;
- if (is_child(i->node, node) || is_child(node, i->node))
- return i;
- }
- return NULL;
-}
-
-bool transaction_block(struct connection *conn, const char *node)
-{
- struct transaction *trans;
-
- /* Transactions don't overlap, so we can't be blocked by
- * others if we're in one. */
- if (conn->transaction)
- return false;
-
- trans = transaction_covering_node(node);
- if (trans) {
- start_transaction_timeout(trans);
- conn->state = BLOCKED;
- conn->blocked_by = talloc_strdup(conn, node);
- return true;
- }
- return false;
+ return trans->tdb;
}
/* Callers get a change node (which can fail) and only commit after they've
@@ -127,8 +80,11 @@
{
struct changed_node *i;
- if (!trans)
+ if (!trans) {
+ /* They're changing the global database. */
+ generation++;
return;
+ }
list_for_each_entry(i, &trans->changes, list)
if (streq(i->node, node))
@@ -140,167 +96,47 @@
list_add_tail(&i->list, &trans->changes);
}
-char *node_dir_inside_transaction(struct transaction *trans, const char *node)
-{
- return talloc_asprintf(node, "%s/%s", trans->divert,
- node + strlen(trans->node));
-}
-
-void shortest_transaction_timeout(struct timeval *tv)
-{
- struct transaction *i;
-
- list_for_each_entry(i, &transactions, list) {
- if (!timerisset(&i->timeout))
- continue;
-
- if (!timerisset(tv) || timercmp(&i->timeout, tv, <))
- *tv = i->timeout;
- }
-}
-
-void check_transaction_timeout(void)
-{
- struct transaction *i;
- struct timeval now;
-
- gettimeofday(&now, NULL);
-
- list_for_each_entry(i, &transactions, list) {
- if (!timerisset(&i->timeout))
- continue;
-
- if (timercmp(&i->timeout, &now, <))
- i->destined_to_fail = true;
- }
-}
-
static int destroy_transaction(void *_transaction)
{
struct transaction *trans = _transaction;
list_del(&trans->list);
trace_destroy(trans, "transaction");
- return destroy_path(trans->divert);
+ if (trans->tdb)
+ tdb_close(trans->tdb);
+ unlink(trans->tdb_name);
+ return 0;
}
-static bool copy_file(const char *src, const char *dst)
+void do_transaction_start(struct connection *conn, struct buffered_data *in)
{
- int *infd, *outfd;
- void *data;
- unsigned int size;
-
- infd = talloc_open(src, O_RDONLY, 0);
- if (!infd)
- return false;
- outfd = talloc_open(dst, O_WRONLY|O_CREAT|O_EXCL, 0640);
- if (!outfd)
- return false;
- data = read_all(infd, &size);
- if (!data)
- return false;
- return xs_write_all(*outfd, data, size);
-}
-
-static bool copy_dir(const char *src, const char *dst)
-{
- DIR **dir;
- struct dirent *dirent;
-
- if (mkdir(dst, 0750) != 0)
- return false;
-
- dir = talloc_opendir(src);
- if (!dir)
- return false;
-
- while ((dirent = readdir(*dir)) != NULL) {
- struct stat st;
- char *newsrc, *newdst;
-
- if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
- continue;
-
- newsrc = talloc_asprintf(src, "%s/%s", src, dirent->d_name);
- newdst = talloc_asprintf(src, "%s/%s", dst, dirent->d_name);
- if (stat(newsrc, &st) != 0)
- return false;
-
- if (S_ISDIR(st.st_mode)) {
- if (!copy_dir(newsrc, newdst))
- return false;
- } else {
- if (!copy_file(newsrc, newdst))
- return false;
- }
- /* Free now so we don't run out of file descriptors */
- talloc_free(newsrc);
- talloc_free(newdst);
- }
- return true;
-}
-
-void do_transaction_start(struct connection *conn, const char *node)
-{
- struct transaction *transaction;
- char *dir;
+ struct transaction *trans;
if (conn->transaction) {
send_error(conn, EBUSY);
return;
}
- node = canonicalize(conn, node);
- if (!check_node_perms(conn, node, XS_PERM_READ)) {
+ /* Attach transaction to input for autofree until it's complete */
+ trans = talloc(in, struct transaction);
+ INIT_LIST_HEAD(&trans->changes);
+ trans->conn = conn;
+ trans->generation = generation;
+ trans->tdb_name = talloc_asprintf(trans, "%s.%p",
+ xs_daemon_tdb(), trans);
+ trans->tdb = tdb_copy(tdb_context(conn), trans->tdb_name);
+ if (!trans->tdb) {
send_error(conn, errno);
return;
}
+ /* Make it close if we go away. */
+ talloc_steal(trans, trans->tdb);
- if (transaction_block(conn, node))
- return;
-
- dir = node_dir_outside_transaction(node);
-
- /* Attach transaction to node for autofree until it's complete */
- transaction = talloc(node, struct transaction);
- transaction->node = talloc_strdup(transaction, node);
- transaction->divert = talloc_asprintf(transaction, "%s/%p",
- xs_daemon_transactions(),
- transaction);
- INIT_LIST_HEAD(&transaction->changes);
- transaction->conn = conn;
- timerclear(&transaction->timeout);
- transaction->destined_to_fail = false;
- list_add_tail(&transaction->list, &transactions);
- talloc_set_destructor(transaction, destroy_transaction);
- trace_create(transaction, "transaction");
-
- if (!copy_dir(dir, transaction->divert)) {
- send_error(conn, errno);
- return;
- }
-
- talloc_steal(conn, transaction);
- conn->transaction = transaction;
- send_ack(transaction->conn, XS_TRANSACTION_START);
-}
-
-static bool commit_transaction(struct transaction *trans)
-{
- char *tmp, *dir;
-
- /* Move: orig -> .old, repl -> orig. Cleanup deletes .old. */
- dir = node_dir_outside_transaction(trans->node);
- tmp = talloc_asprintf(trans, "%s.old", dir);
-
- if (rename(dir, tmp) != 0)
- return false;
- if (rename(trans->divert, dir) != 0)
- corrupt(trans->conn, "Failed rename %s to %s",
- trans->divert, dir);
-
- trans->divert = tmp;
- return true;
+ /* Now we own it. */
+ conn->transaction = talloc_steal(conn, trans);
+ list_add_tail(&trans->list, &transactions);
+ talloc_set_destructor(trans, destroy_transaction);
+ send_ack(conn, XS_TRANSACTION_START);
}
void do_transaction_end(struct connection *conn, const char *arg)
@@ -318,25 +154,29 @@
return;
}
- /* Set to NULL so fire_watches sends events. */
+ /* Set to NULL so fire_watches sends events, tdb_context works. */
trans = conn->transaction;
conn->transaction = NULL;
/* Attach transaction to arg for auto-cleanup */
talloc_steal(arg, trans);
if (streq(arg, "T")) {
- if (trans->destined_to_fail) {
- send_error(conn, ETIMEDOUT);
+ /* FIXME: Merge, rather failing on any change. */
+ if (trans->generation != generation) {
+ send_error(conn, EAGAIN);
return;
}
- if (!commit_transaction(trans)) {
+ if (!replace_tdb(trans->tdb_name, trans->tdb)) {
send_error(conn, errno);
return;
}
+ /* Don't close this: we won! */
+ trans->tdb = NULL;
/* Fire off the watches for everything that changed. */
list_for_each_entry(i, &trans->changes, list)
fire_watches(conn, i->node, i->recurse);
+ generation++;
}
send_ack(conn, XS_TRANSACTION_END);
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_transaction.h
--- a/tools/xenstore/xenstored_transaction.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_transaction.h Fri Sep 23 13:25:01 2005
@@ -22,29 +22,14 @@
struct transaction;
-void do_transaction_start(struct connection *conn, const char *node);
+void do_transaction_start(struct connection *conn, struct buffered_data *node);
void do_transaction_end(struct connection *conn, const char *arg);
-/* Is node covered by this transaction? */
-bool within_transaction(struct transaction *trans, const char *node);
-
-/* If a write op on this node blocked by another connections' transaction,
- * mark conn, setup transaction timeout and return true.
- */
-bool transaction_block(struct connection *conn, const char *node);
-
-/* Return transaction which covers this node. */
-struct transaction *transaction_covering_node(const char *node);
-
-/* Return directory of node within transaction t. */
-char *node_dir_inside_transaction(struct transaction *t, const char *node);
+bool transaction_block(struct connection *conn);
/* This node was changed: can fail and longjmp. */
void add_change_node(struct transaction *trans, const char *node, bool
recurse);
-/* Get shortest timeout: leave tv unset if none. */
-void shortest_transaction_timeout(struct timeval *tv);
-
-/* Have any transactions timed out yet? */
-void check_transaction_timeout(void);
+/* Return tdb context to use for this connection. */
+TDB_CONTEXT *tdb_transaction_context(struct transaction *trans);
#endif /* _XENSTORED_TRANSACTION_H */
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_watch.c
--- a/tools/xenstore/xenstored_watch.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_watch.c Fri Sep 23 13:25:01 2005
@@ -96,36 +96,38 @@
}
static void add_event(struct connection *conn,
- struct watch *watch, const char *node)
-{
- struct watch_event *event;
-
- /* Check read permission: no permission, no watch event.
- * If it doesn't exist, we need permission to read parent.
- */
- if (!check_node_perms(conn, node, XS_PERM_READ|XS_PERM_ENOENT_OK) &&
- !check_event_node(node)) {
- return;
+ struct watch *watch,
+ const char *name)
+{
+ struct watch_event *event;
+
+ if (!check_event_node(name)) {
+ /* Can this conn load node, or see that it doesn't exist? */
+ struct node *node;
+
+ node = get_node(conn, name, XS_PERM_READ);
+ if (!node && errno != ENOENT)
+ return;
}
if (watch->relative_path) {
- node += strlen(watch->relative_path);
- if (*node == '/') /* Could be "" */
- node++;
+ name += strlen(watch->relative_path);
+ if (*name == '/') /* Could be "" */
+ name++;
}
event = talloc(watch, struct watch_event);
- event->len = strlen(node) + 1 + strlen(watch->token) + 1;
+ event->len = strlen(name) + 1 + strlen(watch->token) + 1;
event->data = talloc_array(event, char, event->len);
- strcpy(event->data, node);
- strcpy(event->data + strlen(node) + 1, watch->token);
+ strcpy(event->data, name);
+ strcpy(event->data + strlen(name) + 1, watch->token);
talloc_set_destructor(event, destroy_watch_event);
list_add_tail(&event->list, &watch->events);
trace_create(event, "watch_event");
}
/* FIXME: we fail to fire on out of memory. Should drop connections. */
-void fire_watches(struct connection *conn, const char *node, bool recurse)
+void fire_watches(struct connection *conn, const char *name, bool recurse)
{
struct connection *i;
struct watch *watch;
@@ -137,9 +139,9 @@
/* Create an event for each watch. */
list_for_each_entry(i, &connections, list) {
list_for_each_entry(watch, &i->watches, list) {
- if (is_child(node, watch->node))
- add_event(i, watch, node);
- else if (recurse && is_child(watch->node, node))
+ if (is_child(name, watch->node))
+ add_event(i, watch, name);
+ else if (recurse && is_child(watch->node, name))
add_event(i, watch, watch->node);
else
continue;
@@ -154,49 +156,6 @@
{
trace_destroy(_watch, "watch");
return 0;
-}
-
-void shortest_watch_ack_timeout(struct timeval *tv)
-{
- (void)tv;
-#if 0 /* FIXME */
- struct watch *watch;
-
- list_for_each_entry(watch, &watches, list) {
- struct watch_event *i;
- list_for_each_entry(i, &watch->events, list) {
- if (!timerisset(&i->timeout))
- continue;
- if (!timerisset(tv) || timercmp(&i->timeout, tv, <))
- *tv = i->timeout;
- }
- }
-#endif
-}
-
-void check_watch_ack_timeout(void)
-{
-#if 0
- struct watch *watch;
- struct timeval now;
-
- gettimeofday(&now, NULL);
- list_for_each_entry(watch, &watches, list) {
- struct watch_event *i, *tmp;
- list_for_each_entry_safe(i, tmp, &watch->events, list) {
- if (!timerisset(&i->timeout))
- continue;
- if (timercmp(&i->timeout, &now, <)) {
- xprintf("Warning: timeout on watch event %s"
- " token %s\n",
- i->node, watch->token);
- trace_watch_timeout(watch->conn, i->node,
- watch->token);
- timerclear(&i->timeout);
- }
- }
- }
-#endif
}
void do_watch(struct connection *conn, struct buffered_data *in)
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xenstored_watch.h
--- a/tools/xenstore/xenstored_watch.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xenstored_watch.h Fri Sep 23 13:25:01 2005
@@ -32,15 +32,9 @@
/* Look through our watches: if any of them have an event, queue it. */
void queue_next_event(struct connection *conn);
-/* Fire all watches: recurse means all the children are effected (ie. rm).
+/* Fire all watches: recurse means all the children are affected (ie. rm).
*/
-void fire_watches(struct connection *conn, const char *node, bool recurse);
-
-/* Find shortest timeout: if any, reduce tv (may already be set). */
-void shortest_watch_ack_timeout(struct timeval *tv);
-
-/* Check for watches which may have timed out. */
-void check_watch_ack_timeout(void);
+void fire_watches(struct connection *conn, const char *name, bool recurse);
void dump_watches(struct connection *conn);
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs.c
--- a/tools/xenstore/xs.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs.c Fri Sep 23 13:25:01 2005
@@ -497,13 +497,12 @@
/* Start a transaction: changes by others will not be seen during this
* transaction, and changes will not be visible to others until end.
- * Transaction only applies to the given subtree.
* You can only have one transaction at any time.
* Returns false on failure.
*/
-bool xs_transaction_start(struct xs_handle *h, const char *subtree)
-{
- return xs_bool(xs_single(h, XS_TRANSACTION_START, subtree, NULL));
+bool xs_transaction_start(struct xs_handle *h)
+{
+ return xs_bool(xs_single(h, XS_TRANSACTION_START, "", NULL));
}
/* End a transaction.
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs.h
--- a/tools/xenstore/xs.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs.h Fri Sep 23 13:25:01 2005
@@ -109,11 +109,10 @@
/* Start a transaction: changes by others will not be seen during this
* transaction, and changes will not be visible to others until end.
- * Transaction only applies to the given subtree.
* You can only have one transaction at any time.
* Returns false on failure.
*/
-bool xs_transaction_start(struct xs_handle *h, const char *subtree);
+bool xs_transaction_start(struct xs_handle *h);
/* End a transaction.
* If abandon is true, transaction is discarded instead of committed.
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_lib.c
--- a/tools/xenstore/xs_lib.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_lib.c Fri Sep 23 13:25:01 2005
@@ -50,6 +50,13 @@
return buf;
}
+const char *xs_daemon_tdb(void)
+{
+ static char buf[PATH_MAX];
+ sprintf(buf, "%s/tdb", xs_daemon_rootdir());
+ return buf;
+}
+
const char *xs_daemon_socket(void)
{
return xs_daemon_path();
@@ -62,24 +69,6 @@
if (s == NULL)
return NULL;
if (snprintf(buf, PATH_MAX, "%s_ro", s) >= PATH_MAX)
- return NULL;
- return buf;
-}
-
-const char *xs_daemon_store(void)
-{
- static char buf[PATH_MAX];
- if (snprintf(buf, PATH_MAX, "%s/store",
- xs_daemon_rootdir()) >= PATH_MAX)
- return NULL;
- return buf;
-}
-
-const char *xs_daemon_transactions(void)
-{
- static char buf[PATH_MAX];
- if (snprintf(buf, PATH_MAX, "%s/transactions",
- xs_daemon_rootdir()) >= PATH_MAX)
return NULL;
return buf;
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_lib.h
--- a/tools/xenstore/xs_lib.h Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_lib.h Fri Sep 23 13:25:01 2005
@@ -36,7 +36,7 @@
struct xs_permissions
{
- domid_t id;
+ unsigned int id;
enum xs_perm_type perms;
};
@@ -46,9 +46,8 @@
/* Path for various daemon things: env vars can override. */
const char *xs_daemon_socket(void);
const char *xs_daemon_socket_ro(void);
-const char *xs_daemon_store(void);
-const char *xs_daemon_transactions(void);
const char *xs_domain_dev(void);
+const char *xs_daemon_tdb(void);
/* Simple write function: loops for you. */
bool xs_write_all(int fd, const void *data, unsigned int len);
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_random.c
--- a/tools/xenstore/xs_random.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_random.c Fri Sep 23 13:25:01 2005
@@ -41,7 +41,7 @@
struct xs_permissions *perms,
unsigned int num);
- bool (*transaction_start)(void *h, const char *subtree);
+ bool (*transaction_start)(void *h);
bool (*transaction_end)(void *h, bool abort);
/* Create and destroy a new handle. */
@@ -53,7 +53,6 @@
{
const char *base;
char *transact_base;
- char *transact;
};
static void convert_to_dir(const char *dirname)
@@ -95,31 +94,6 @@
maybe_convert_to_directory(filename);
return filename;
}
-
-/* Is child a subnode of parent, or equal? */
-static bool is_child(const char *child, const char *parent)
-{
- unsigned int len = strlen(parent);
-
- /* / should really be "" for this algorithm to work, but that's a
- * usability nightmare. */
- if (streq(parent, "/"))
- return true;
-
- if (strncmp(child, parent, len) != 0)
- return false;
-
- return child[len] == '/' || child[len] == '\0';
-}
-
-static bool write_ok(struct file_ops_info *info, const char *path)
-{
- if (info->transact && !is_child(path, info->transact)) {
- errno = EROFS;
- return false;
- }
- return true;
-}
static char **file_directory(struct file_ops_info *info,
const char *path, unsigned int *num)
@@ -184,8 +158,10 @@
ret = grab_file(filename, &size);
/* Directory exists, .DATA doesn't. */
- if (!ret && errno == ENOENT && strends(filename, ".DATA"))
- errno = EISDIR;
+ if (!ret && errno == ENOENT && strends(filename, ".DATA")) {
+ ret = strdup("");
+ size = 0;
+ }
*len = size;
return ret;
}
@@ -270,9 +246,6 @@
return false;
}
- if (!write_ok(info, path))
- return false;
-
/* Check non-perm file exists/ */
if (lstat(filename, &st) != 0)
return false;
@@ -338,9 +311,6 @@
char *filename = filename_to_data(path_to_name(info, path));
int fd;
- if (!write_ok(info, path))
- return false;
-
make_dirs(parent_filename(filename));
fd = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0600);
if (fd < 0)
@@ -358,9 +328,6 @@
{
char *dirname = path_to_name(info, path);
- if (!write_ok(info, path))
- return false;
-
make_dirs(parent_filename(dirname));
if (mkdir(dirname, 0700) != 0)
return (errno == EEXIST);
@@ -373,11 +340,6 @@
{
char *filename = path_to_name(info, path);
struct stat st;
-
- if (info->transact && streq(info->transact, path)) {
- errno = EINVAL;
- return false;
- }
if (lstat(filename, &st) != 0) {
if (lstat(parent_filename(filename), &st) != 0)
@@ -385,9 +347,6 @@
return true;
}
- if (!write_ok(info, path))
- return false;
-
if (streq(path, "/")) {
errno = EINVAL;
return false;
@@ -398,28 +357,20 @@
return true;
}
-static bool file_transaction_start(struct file_ops_info *info,
- const char *subtree)
+static bool file_transaction_start(struct file_ops_info *info)
{
char *cmd;
- char *filename = path_to_name(info, subtree);
- struct stat st;
-
- if (info->transact) {
+
+ if (info->transact_base) {
errno = EBUSY;
return false;
}
- if (lstat(filename, &st) != 0)
- return false;
-
- cmd = talloc_asprintf(NULL, "cp -r %s %s.transact",
- info->base, info->base);
+ info->transact_base = talloc_asprintf(NULL, "%s.transact", info->base);
+ cmd = talloc_asprintf(NULL, "cp -r %s %s",
+ info->base, info->transact_base);
do_command(cmd);
talloc_free(cmd);
-
- info->transact_base = talloc_asprintf(NULL, "%s.transact", info->base);
- info->transact = talloc_strdup(NULL, subtree);
return true;
}
@@ -427,7 +378,7 @@
{
char *old, *cmd;
- if (!info->transact) {
+ if (!info->transact_base) {
errno = ENOENT;
return false;
}
@@ -448,9 +399,7 @@
success:
talloc_free(cmd);
- talloc_free(info->transact);
talloc_free(info->transact_base);
- info->transact = NULL;
info->transact_base = NULL;
return true;
}
@@ -461,7 +410,6 @@
info->base = dir;
info->transact_base = NULL;
- info->transact = NULL;
return info;
}
@@ -898,11 +846,10 @@
case 7: {
if (verbose)
printf("START %s\n", name);
- ret = bool_to_errstring(ops->transaction_start(h, name));
+ ret = bool_to_errstring(ops->transaction_start(h));
if (streq(ret, "OK")) {
talloc_free(ret);
- ret = talloc_asprintf(NULL, "OK:START-TRANSACT:%s",
- name);
+ ret = talloc_asprintf(NULL, "OK:START-TRANSACT");
}
break;
@@ -978,6 +925,8 @@
barf_perror("Creating directory %s/tool", dir);
if (!file_set_perms(h, talloc_strdup(h, "/"), &perm, 1))
barf_perror("Setting root perms in %s", dir);
+ if (!file_set_perms(h, talloc_strdup(h, "/tool"), &perm, 1))
+ barf_perror("Setting root perms in %s/tool", dir);
file_close(h);
}
@@ -1071,7 +1020,7 @@
goto out;
if (!data->fast) {
- if (strstarts(ret, "OK:START-TRANSACT:")) {
+ if (streq(ret, "OK:START-TRANSACT")) {
void *pre = data->ops->handle(data->dir);
snapshot = dump(data->ops, pre);
@@ -1303,7 +1252,7 @@
void *_data)
{
void *fileh, *xsh;
- char *transact = NULL;
+ bool transact = false;
struct ops *fail;
struct diff_data *data = _data;
unsigned int i, print;
@@ -1348,13 +1297,9 @@
goto out;
if (strstarts(file, "OK:START-TRANSACT:"))
- transact = talloc_strdup(NULL,
- file +
- strlen("OK:START-TRANSACT:"));
- else if (streq(file, "OK:STOP-TRANSACT")) {
- talloc_free(transact);
- transact = NULL;
- }
+ transact = true;
+ else if (streq(file, "OK:STOP-TRANSACT"))
+ transact = false;
talloc_free(file);
talloc_free(xs);
@@ -1379,7 +1324,7 @@
fail = NULL;
if (!ops_equal(&xs_ops, xsh_pre, &file_ops, fileh_pre,
- transact, &fail)) {
+ "/", &fail)) {
if (fail)
barf("%s failed during transact\n",
fail->name);
@@ -1455,9 +1400,6 @@
fileh = file_handle(data->dir);
xsh = xs_handle(data->dir);
-
- sprintf(seed, "%i", data->seed);
- free(xs_debug_command(xsh, "failtest", seed, strlen(seed)+1));
print = number / 76;
if (!print)
@@ -1491,8 +1433,12 @@
if (trymap && !trymap[i])
continue;
- if (verbose)
- printf("(%i) ", i);
+ /* Turn on failure. */
+ sprintf(seed, "%i", data->seed + i);
+ free(xs_debug_command(xsh, "failtest",seed,strlen(seed)+1));
+
+ if (verbose)
+ printf("(%i) seed %s ", i, seed);
ret = do_next_op(&xs_ops, xsh, i + data->seed, verbose);
if (streq(ret, "FAILED:Connection reset by peer")
|| streq(ret, "FAILED:Bad file descriptor")
@@ -1549,8 +1495,6 @@
fail = NULL;
if (!ops_equal(&xs_ops, tmpxsh, &file_ops, tmpfileh, "/",
&fail)) {
- xs_close(tmpxsh);
- file_close(tmpfileh);
if (fail) {
if (verbose)
printf("%s failed\n", fail->name);
@@ -1561,10 +1505,16 @@
failed = 0;
if (verbose)
printf("(Looks like it succeeded)\n");
+ xs_close(tmpxsh);
+ file_close(tmpfileh);
goto try_applying;
}
if (verbose)
- printf("Two backends not equal\n");
+ printf("Trees differ:\nXS:%s\nFILE:%s\n",
+ dump(&xs_ops, tmpxsh),
+ dump(&file_ops, tmpfileh));
+ xs_close(tmpxsh);
+ file_close(tmpfileh);
goto out;
}
@@ -1572,8 +1522,6 @@
if (!xsh)
file_transaction_end(fileh, true);
- /* Turn failures back on. */
- free(xs_debug_command(tmpxsh, "failtest", NULL, 0));
xs_close(tmpxsh);
file_close(tmpfileh);
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_stress.c
--- a/tools/xenstore/xs_stress.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_stress.c Fri Sep 23 13:25:01 2005
@@ -8,6 +8,7 @@
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
+#include <errno.h>
#define NUM_HANDLES 2
#define DIR_FANOUT 3
@@ -36,24 +37,18 @@
srandom(childnum);
for (i = 0; i < cycles; i++) {
- unsigned int lockdepth, j, len;
- char file[100] = "", lockdir[100];
+ unsigned int j, len;
+ char file[100] = "";
char *contents, tmp[100];
struct xs_handle *h = handles[random() % NUM_HANDLES];
- lockdepth = random() % DIR_DEPTH;
- for (j = 0; j < DIR_DEPTH; j++) {
- if (j == lockdepth)
- strcpy(lockdir, file);
+ for (j = 0; j < DIR_DEPTH; j++)
sprintf(file + strlen(file), "/%li",
random()%DIR_FANOUT);
- }
- if (streq(lockdir, ""))
- strcpy(lockdir, "/");
-
- if (!xs_transaction_start(h, lockdir))
- barf_perror("%i: starting transaction %i on %s",
- childnum, i, lockdir);
+
+ if (!xs_transaction_start(h))
+ barf_perror("%i: starting transaction %i",
+ childnum, i);
sprintf(file + strlen(file), "/count");
contents = xs_read(h, file, &len);
@@ -68,18 +63,23 @@
/* Abandon 1 in 10 */
if (random() % 10 == 0) {
if (!xs_transaction_end(h, true))
- barf_perror("%i: can't abort transact %s",
- childnum, lockdir);
+ barf_perror("%i: can't abort transact",
+ childnum);
i--;
} else {
- if (!xs_transaction_end(h, false))
- barf_perror("%i: can't commit transact %s",
- childnum, lockdir);
-
- /* Offset when we print . so kids don't all
- * print at once. */
- if ((i + print/(childnum+1)) % print == 0)
- write(STDOUT_FILENO, &id, 1);
+ if (!xs_transaction_end(h, false)) {
+ if (errno == EAGAIN) {
+ write(STDOUT_FILENO, "!", 1);
+ i--;
+ } else
+ barf_perror("%i: can't commit trans",
+ childnum);
+ } else {
+ /* Offset when we print . so kids don't all
+ * print at once. */
+ if ((i + print/(childnum+1)) % print == 0)
+ write(STDOUT_FILENO, &id, 1);
+ }
}
}
}
@@ -201,7 +201,7 @@
printf("\nCounting results...\n");
i = tally_counts();
if (i != (unsigned)atoi(argv[1]))
- barf("Total counts %i not %s", i, atoi(argv[1]));
+ barf("Total counts %i not %s", i, argv[1]);
printf("Success!\n");
exit(0);
}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_test.c
--- a/tools/xenstore/xs_test.c Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_test.c Fri Sep 23 13:25:01 2005
@@ -562,9 +562,9 @@
failed(handle);
}
-static void do_start(unsigned int handle, const char *node)
-{
- if (!xs_transaction_start(handles[handle], node))
+static void do_start(unsigned int handle)
+{
+ if (!xs_transaction_start(handles[handle]))
failed(handle);
}
@@ -791,7 +791,7 @@
xs_daemon_close(handles[handle]);
handles[handle] = NULL;
} else if (streq(command, "start"))
- do_start(handle, arg(line, 1));
+ do_start(handle);
else if (streq(command, "commit"))
do_end(handle, false);
else if (streq(command, "abort"))
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/tdb.c
--- /dev/null Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/tdb.c Fri Sep 23 13:25:01 2005
@@ -0,0 +1,2151 @@
+ /*
+ Unix SMB/CIFS implementation.
+
+ trivial database library
+
+ Copyright (C) Andrew Tridgell 1999-2004
+ Copyright (C) Paul `Rusty' Russell 2000
+ Copyright (C) Jeremy Allison 2000-2003
+
+ ** NOTE! The following LGPL license applies to the tdb
+ ** library. This does NOT imply that all of Samba is released
+ ** under the LGPL
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+
+
+#ifndef _SAMBA_BUILD_
+#if HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <string.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include "tdb.h"
+#include <stdarg.h>
+#include "talloc.h"
+#define HAVE_MMAP
+#else
+#include "includes.h"
+#include "lib/tdb/include/tdb.h"
+#include "system/time.h"
+#include "system/shmem.h"
+#include "system/filesys.h"
+#endif
+
+#define TDB_MAGIC_FOOD "TDB file\n"
+#define TDB_VERSION (0x26011967 + 6)
+#define TDB_MAGIC (0x26011999U)
+#define TDB_FREE_MAGIC (~TDB_MAGIC)
+#define TDB_DEAD_MAGIC (0xFEE1DEAD)
+#define TDB_ALIGNMENT 4
+#define MIN_REC_SIZE (2*sizeof(struct list_struct) + TDB_ALIGNMENT)
+#define DEFAULT_HASH_SIZE 131
+#define TDB_PAGE_SIZE 0x2000
+#define FREELIST_TOP (sizeof(struct tdb_header))
+#define TDB_ALIGN(x,a) (((x) + (a)-1) & ~((a)-1))
+#define TDB_BYTEREV(x)
(((((x)&0xff)<<24)|((x)&0xFF00)<<8)|(((x)>>8)&0xFF00)|((x)>>24))
+#define TDB_DEAD(r) ((r)->magic == TDB_DEAD_MAGIC)
+#define TDB_BAD_MAGIC(r) ((r)->magic != TDB_MAGIC && !TDB_DEAD(r))
+#define TDB_HASH_TOP(hash) (FREELIST_TOP + (BUCKET(hash)+1)*sizeof(tdb_off))
+#define TDB_DATA_START(hash_size) (TDB_HASH_TOP(hash_size-1))
+
+
+/* NB assumes there is a local variable called "tdb" that is the
+ * current context, also takes doubly-parenthesized print-style
+ * argument. */
+#define TDB_LOG(x) tdb->log_fn x
+
+/* lock offsets */
+#define GLOBAL_LOCK 0
+#define ACTIVE_LOCK 4
+
+#ifndef MAP_FILE
+#define MAP_FILE 0
+#endif
+
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void *)-1)
+#endif
+
+#ifndef discard_const_p
+# if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
+# define discard_const(ptr) ((void *)((intptr_t)(ptr)))
+# else
+# define discard_const(ptr) ((void *)(ptr))
+# endif
+# define discard_const_p(type, ptr) ((type *)discard_const(ptr))
+#endif
+
+/* free memory if the pointer is valid and zero the pointer */
+#ifndef SAFE_FREE
+#define SAFE_FREE(x) do { if ((x) != NULL) {talloc_free(discard_const_p(void
*, (x))); (x)=NULL;} } while(0)
+#endif
+
+#define BUCKET(hash) ((hash) % tdb->header.hash_size)
+TDB_DATA tdb_null;
+
+/* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
+static TDB_CONTEXT *tdbs = NULL;
+
+static int tdb_munmap(TDB_CONTEXT *tdb)
+{
+ if (tdb->flags & TDB_INTERNAL)
+ return 0;
+
+#ifdef HAVE_MMAP
+ if (tdb->map_ptr) {
+ int ret = munmap(tdb->map_ptr, tdb->map_size);
+ if (ret != 0)
+ return ret;
+ }
+#endif
+ tdb->map_ptr = NULL;
+ return 0;
+}
+
+static void tdb_mmap(TDB_CONTEXT *tdb)
+{
+ if (tdb->flags & TDB_INTERNAL)
+ return;
+
+#ifdef HAVE_MMAP
+ if (!(tdb->flags & TDB_NOMMAP)) {
+ tdb->map_ptr = mmap(NULL, tdb->map_size,
+ PROT_READ|(tdb->read_only? 0:PROT_WRITE),
+ MAP_SHARED|MAP_FILE, tdb->fd, 0);
+
+ /*
+ * NB. When mmap fails it returns MAP_FAILED *NOT* NULL !!!!
+ */
+
+ if (tdb->map_ptr == MAP_FAILED) {
+ tdb->map_ptr = NULL;
+ TDB_LOG((tdb, 2, "tdb_mmap failed for size %d (%s)\n",
+ tdb->map_size, strerror(errno)));
+ }
+ } else {
+ tdb->map_ptr = NULL;
+ }
+#else
+ tdb->map_ptr = NULL;
+#endif
+}
+
+/* Endian conversion: we only ever deal with 4 byte quantities */
+static void *convert(void *buf, u32 size)
+{
+ u32 i, *p = buf;
+ for (i = 0; i < size / 4; i++)
+ p[i] = TDB_BYTEREV(p[i]);
+ return buf;
+}
+#define DOCONV() (tdb->flags & TDB_CONVERT)
+#define CONVERT(x) (DOCONV() ? convert(&x, sizeof(x)) : &x)
+
+/* the body of the database is made of one list_struct for the free space
+ plus a separate data list for each hash value */
+struct list_struct {
+ tdb_off next; /* offset of the next record in the list */
+ tdb_len rec_len; /* total byte length of record */
+ tdb_len key_len; /* byte length of key */
+ tdb_len data_len; /* byte length of data */
+ u32 full_hash; /* the full 32 bit hash of the key */
+ u32 magic; /* try to catch errors */
+ /* the following union is implied:
+ union {
+ char record[rec_len];
+ struct {
+ char key[key_len];
+ char data[data_len];
+ }
+ u32 totalsize; (tailer)
+ }
+ */
+};
+
+/* a byte range locking function - return 0 on success
+ this functions locks/unlocks 1 byte at the specified offset.
+
+ On error, errno is also set so that errors are passed back properly
+ through tdb_open(). */
+static int tdb_brlock(TDB_CONTEXT *tdb, tdb_off offset,
+ int rw_type, int lck_type, int probe)
+{
+ struct flock fl;
+ int ret;
+
+ if (tdb->flags & TDB_NOLOCK)
+ return 0;
+ if ((rw_type == F_WRLCK) && (tdb->read_only)) {
+ errno = EACCES;
+ return -1;
+ }
+
+ fl.l_type = rw_type;
+ fl.l_whence = SEEK_SET;
+ fl.l_start = offset;
+ fl.l_len = 1;
+ fl.l_pid = 0;
+
+ do {
+ ret = fcntl(tdb->fd,lck_type,&fl);
+ } while (ret == -1 && errno == EINTR);
+
+ if (ret == -1) {
+ if (!probe && lck_type != F_SETLK) {
+ /* Ensure error code is set for log fun to examine. */
+ tdb->ecode = TDB_ERR_LOCK;
+ TDB_LOG((tdb, 5,"tdb_brlock failed (fd=%d) at offset %d
rw_type=%d lck_type=%d\n",
+ tdb->fd, offset, rw_type, lck_type));
+ }
+ /* Generic lock error. errno set by fcntl.
+ * EAGAIN is an expected return from non-blocking
+ * locks. */
+ if (errno != EAGAIN) {
+ TDB_LOG((tdb, 5, "tdb_brlock failed (fd=%d) at offset %d
rw_type=%d lck_type=%d: %s\n",
+ tdb->fd, offset, rw_type, lck_type,
+ strerror(errno)));
+ }
+ return TDB_ERRCODE(TDB_ERR_LOCK, -1);
+ }
+ return 0;
+}
+
+/* lock a list in the database. list -1 is the alloc list */
+static int tdb_lock(TDB_CONTEXT *tdb, int list, int ltype)
+{
+ if (list < -1 || list >= (int)tdb->header.hash_size) {
+ TDB_LOG((tdb, 0,"tdb_lock: invalid list %d for ltype=%d\n",
+ list, ltype));
+ return -1;
+ }
+ if (tdb->flags & TDB_NOLOCK)
+ return 0;
+
+ /* Since fcntl locks don't nest, we do a lock for the first one,
+ and simply bump the count for future ones */
+ if (tdb->locked[list+1].count == 0) {
+ if (tdb_brlock(tdb,FREELIST_TOP+4*list,ltype,F_SETLKW, 0)) {
+ TDB_LOG((tdb, 0,"tdb_lock failed on list %d ltype=%d
(%s)\n",
+ list, ltype, strerror(errno)));
+ return -1;
+ }
+ tdb->locked[list+1].ltype = ltype;
+ }
+ tdb->locked[list+1].count++;
+ return 0;
+}
+
+/* unlock the database: returns void because it's too late for errors. */
+ /* changed to return int it may be interesting to know there
+ has been an error --simo */
+static int tdb_unlock(TDB_CONTEXT *tdb, int list,
+ int ltype __attribute__((unused)))
+{
+ int ret = -1;
+
+ if (tdb->flags & TDB_NOLOCK)
+ return 0;
+
+ /* Sanity checks */
+ if (list < -1 || list >= (int)tdb->header.hash_size) {
+ TDB_LOG((tdb, 0, "tdb_unlock: list %d invalid (%d)\n", list,
tdb->header.hash_size));
+ return ret;
+ }
+
+ if (tdb->locked[list+1].count==0) {
+ TDB_LOG((tdb, 0, "tdb_unlock: count is 0\n"));
+ return ret;
+ }
+
+ if (tdb->locked[list+1].count == 1) {
+ /* Down to last nested lock: unlock underneath */
+ ret = tdb_brlock(tdb, FREELIST_TOP+4*list, F_UNLCK, F_SETLKW,
0);
+ } else {
+ ret = 0;
+ }
+ tdb->locked[list+1].count--;
+
+ if (ret)
+ TDB_LOG((tdb, 0,"tdb_unlock: An error occurred unlocking!\n"));
+ return ret;
+}
+
+/* This is based on the hash algorithm from gdbm */
+static u32 default_tdb_hash(TDB_DATA *key)
+{
+ u32 value; /* Used to compute the hash value. */
+ u32 i; /* Used to cycle through random values. */
+
+ /* Set the initial value from the key size. */
+ for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
+ value = (value + (key->dptr[i] << (i*5 % 24)));
+
+ return (1103515243 * value + 12345);
+}
+
+/* check for an out of bounds access - if it is out of bounds then
+ see if the database has been expanded by someone else and expand
+ if necessary
+ note that "len" is the minimum length needed for the db
+*/
+static int tdb_oob(TDB_CONTEXT *tdb, tdb_off len, int probe)
+{
+ struct stat st;
+ if (len <= tdb->map_size)
+ return 0;
+ if (tdb->flags & TDB_INTERNAL) {
+ if (!probe) {
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_IO;
+ TDB_LOG((tdb, 0,"tdb_oob len %d beyond internal malloc
size %d\n",
+ (int)len, (int)tdb->map_size));
+ }
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+ }
+
+ if (fstat(tdb->fd, &st) == -1)
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+
+ if (st.st_size < (off_t)len) {
+ if (!probe) {
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_IO;
+ TDB_LOG((tdb, 0,"tdb_oob len %d beyond eof at %d\n",
+ (int)len, (int)st.st_size));
+ }
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+ }
+
+ /* Unmap, update size, remap */
+ if (tdb_munmap(tdb) == -1)
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+ tdb->map_size = st.st_size;
+ tdb_mmap(tdb);
+ return 0;
+}
+
+/* write a lump of data at a specified offset */
+static int tdb_write(TDB_CONTEXT *tdb, tdb_off off, void *buf, tdb_len len)
+{
+ if (tdb_oob(tdb, off + len, 0) != 0)
+ return -1;
+
+ if (tdb->map_ptr)
+ memcpy(off + (char *)tdb->map_ptr, buf, len);
+#ifdef HAVE_PWRITE
+ else if (pwrite(tdb->fd, buf, len, off) != (ssize_t)len) {
+#else
+ else if (lseek(tdb->fd, off, SEEK_SET) != (off_t)off
+ || write(tdb->fd, buf, len) != (off_t)len) {
+#endif
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_IO;
+ TDB_LOG((tdb, 0,"tdb_write failed at %d len=%d (%s)\n",
+ off, len, strerror(errno)));
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+ }
+ return 0;
+}
+
+/* read a lump of data at a specified offset, maybe convert */
+static int tdb_read(TDB_CONTEXT *tdb,tdb_off off,void *buf,tdb_len len,int cv)
+{
+ if (tdb_oob(tdb, off + len, 0) != 0)
+ return -1;
+
+ if (tdb->map_ptr)
+ memcpy(buf, off + (char *)tdb->map_ptr, len);
+#ifdef HAVE_PREAD
+ else if (pread(tdb->fd, buf, len, off) != (off_t)len) {
+#else
+ else if (lseek(tdb->fd, off, SEEK_SET) != (off_t)off
+ || read(tdb->fd, buf, len) != (off_t)len) {
+#endif
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_IO;
+ TDB_LOG((tdb, 0,"tdb_read failed at %d len=%d (%s)\n",
+ off, len, strerror(errno)));
+ return TDB_ERRCODE(TDB_ERR_IO, -1);
+ }
+ if (cv)
+ convert(buf, len);
+ return 0;
+}
+
+/* don't allocate memory: used in tdb_delete path. */
+static int tdb_key_eq(TDB_CONTEXT *tdb, tdb_off off, TDB_DATA key)
+{
+ char buf[64];
+ u32 len;
+
+ if (tdb_oob(tdb, off + key.dsize, 0) != 0)
+ return -1;
+
+ if (tdb->map_ptr)
+ return !memcmp(off + (char*)tdb->map_ptr, key.dptr, key.dsize);
+
+ while (key.dsize) {
+ len = key.dsize;
+ if (len > sizeof(buf))
+ len = sizeof(buf);
+ if (tdb_read(tdb, off, buf, len, 0) != 0)
+ return -1;
+ if (memcmp(buf, key.dptr, len) != 0)
+ return 0;
+ key.dptr += len;
+ key.dsize -= len;
+ off += len;
+ }
+ return 1;
+}
+
+/* read a lump of data, allocating the space for it */
+static char *tdb_alloc_read(TDB_CONTEXT *tdb, tdb_off offset, tdb_len len)
+{
+ char *buf;
+
+ if (!(buf = talloc_size(tdb, len))) {
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_OOM;
+ TDB_LOG((tdb, 0,"tdb_alloc_read malloc failed len=%d (%s)\n",
+ len, strerror(errno)));
+ return TDB_ERRCODE(TDB_ERR_OOM, buf);
+ }
+ if (tdb_read(tdb, offset, buf, len, 0) == -1) {
+ SAFE_FREE(buf);
+ return NULL;
+ }
+ return buf;
+}
+
+/* read/write a tdb_off */
+static int ofs_read(TDB_CONTEXT *tdb, tdb_off offset, tdb_off *d)
+{
+ return tdb_read(tdb, offset, (char*)d, sizeof(*d), DOCONV());
+}
+static int ofs_write(TDB_CONTEXT *tdb, tdb_off offset, tdb_off *d)
+{
+ tdb_off off = *d;
+ return tdb_write(tdb, offset, CONVERT(off), sizeof(*d));
+}
+
+/* read/write a record */
+static int rec_read(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
+{
+ if (tdb_read(tdb, offset, rec, sizeof(*rec),DOCONV()) == -1)
+ return -1;
+ if (TDB_BAD_MAGIC(rec)) {
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_CORRUPT;
+ TDB_LOG((tdb, 0,"rec_read bad magic 0x%x at offset=%d\n",
rec->magic, offset));
+ return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
+ }
+ return tdb_oob(tdb, rec->next+sizeof(*rec), 0);
+}
+static int rec_write(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
+{
+ struct list_struct r = *rec;
+ return tdb_write(tdb, offset, CONVERT(r), sizeof(r));
+}
+
+/* read a freelist record and check for simple errors */
+static int rec_free_read(TDB_CONTEXT *tdb, tdb_off off, struct list_struct
*rec)
+{
+ if (tdb_read(tdb, off, rec, sizeof(*rec),DOCONV()) == -1)
+ return -1;
+
+ if (rec->magic == TDB_MAGIC) {
+ /* this happens when a app is showdown while deleting a record
- we should
+ not completely fail when this happens */
+ TDB_LOG((tdb, 0,"rec_free_read non-free magic 0x%x at offset=%d
- fixing\n",
+ rec->magic, off));
+ rec->magic = TDB_FREE_MAGIC;
+ if (tdb_write(tdb, off, rec, sizeof(*rec)) == -1)
+ return -1;
+ }
+
+ if (rec->magic != TDB_FREE_MAGIC) {
+ /* Ensure ecode is set for log fn. */
+ tdb->ecode = TDB_ERR_CORRUPT;
+ TDB_LOG((tdb, 0,"rec_free_read bad magic 0x%x at offset=%d\n",
+ rec->magic, off));
+ return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
+ }
+ if (tdb_oob(tdb, rec->next+sizeof(*rec), 0) != 0)
+ return -1;
+ return 0;
+}
+
+/* update a record tailer (must hold allocation lock) */
+static int update_tailer(TDB_CONTEXT *tdb, tdb_off offset,
+ const struct list_struct *rec)
+{
+ tdb_off totalsize;
+
+ /* Offset of tailer from record header */
+ totalsize = sizeof(*rec) + rec->rec_len;
+ return ofs_write(tdb, offset + totalsize - sizeof(tdb_off),
+ &totalsize);
+}
+
+static tdb_off tdb_dump_record(TDB_CONTEXT *tdb, tdb_off offset)
+{
+ struct list_struct rec;
+ tdb_off tailer_ofs, tailer;
+
+ if (tdb_read(tdb, offset, (char *)&rec, sizeof(rec), DOCONV()) == -1) {
+ printf("ERROR: failed to read record at %u\n", offset);
+ return 0;
+ }
+
+ printf(" rec: offset=0x%08x next=0x%08x rec_len=%d key_len=%d
data_len=%d full_hash=0x%x magic=0x%x\n",
+ offset, rec.next, rec.rec_len, rec.key_len, rec.data_len,
rec.full_hash, rec.magic);
+
+ tailer_ofs = offset + sizeof(rec) + rec.rec_len - sizeof(tdb_off);
+ if (ofs_read(tdb, tailer_ofs, &tailer) == -1) {
+ printf("ERROR: failed to read tailer at %u\n", tailer_ofs);
+ return rec.next;
+ }
+
+ if (tailer != rec.rec_len + sizeof(rec)) {
+ printf("ERROR: tailer does not match record! tailer=%u
totalsize=%u\n",
+ (unsigned int)tailer, (unsigned
int)(rec.rec_len + sizeof(rec)));
+ }
+ return rec.next;
+}
+
+static int tdb_dump_chain(TDB_CONTEXT *tdb, int i)
+{
+ tdb_off rec_ptr, top;
+
+ top = TDB_HASH_TOP(i);
+
+ if (tdb_lock(tdb, i, F_WRLCK) != 0)
+ return -1;
+
+ if (ofs_read(tdb, top, &rec_ptr) == -1)
+ return tdb_unlock(tdb, i, F_WRLCK);
+
+ if (rec_ptr)
+ printf("hash=%d\n", i);
+
+ while (rec_ptr) {
+ rec_ptr = tdb_dump_record(tdb, rec_ptr);
+ }
+
+ return tdb_unlock(tdb, i, F_WRLCK);
+}
+
+void tdb_dump_all(TDB_CONTEXT *tdb)
+{
+ unsigned int i;
+ for (i=0;i<tdb->header.hash_size;i++) {
+ tdb_dump_chain(tdb, i);
+ }
+ printf("freelist:\n");
+ tdb_dump_chain(tdb, -1);
+}
+
+int tdb_printfreelist(TDB_CONTEXT *tdb)
+{
+ int ret;
+ long total_free = 0;
+ tdb_off offset, rec_ptr;
+ struct list_struct rec;
+
+ if ((ret = tdb_lock(tdb, -1, F_WRLCK)) != 0)
+ return ret;
+
+ offset = FREELIST_TOP;
+
+ /* read in the freelist top */
+ if (ofs_read(tdb, offset, &rec_ptr) == -1) {
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return 0;
+ }
+
+ printf("freelist top=[0x%08x]\n", rec_ptr );
+ while (rec_ptr) {
+ if (tdb_read(tdb, rec_ptr, (char *)&rec, sizeof(rec), DOCONV())
== -1) {
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return -1;
+ }
+
+ if (rec.magic != TDB_FREE_MAGIC) {
+ printf("bad magic 0x%08x in free list\n", rec.magic);
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return -1;
+ }
+
+ printf("entry offset=[0x%08x], rec.rec_len = [0x%08x (%d)] (end
= 0x%08x)\n",
+ rec_ptr, rec.rec_len, rec.rec_len, rec_ptr +
rec.rec_len);
+ total_free += rec.rec_len;
+
+ /* move to the next record */
+ rec_ptr = rec.next;
+ }
+ printf("total rec_len = [0x%08x (%d)]\n", (int)total_free,
+ (int)total_free);
+
+ return tdb_unlock(tdb, -1, F_WRLCK);
+}
+
+/* Remove an element from the freelist. Must have alloc lock. */
+static int remove_from_freelist(TDB_CONTEXT *tdb, tdb_off off, tdb_off next)
+{
+ tdb_off last_ptr, i;
+
+ /* read in the freelist top */
+ last_ptr = FREELIST_TOP;
+ while (ofs_read(tdb, last_ptr, &i) != -1 && i != 0) {
+ if (i == off) {
+ /* We've found it! */
+ return ofs_write(tdb, last_ptr, &next);
+ }
+ /* Follow chain (next offset is at start of record) */
+ last_ptr = i;
+ }
+ TDB_LOG((tdb, 0,"remove_from_freelist: not on list at off=%d\n", off));
+ return TDB_ERRCODE(TDB_ERR_CORRUPT, -1);
+}
+
+/* Add an element into the freelist. Merge adjacent records if
+ neccessary. */
+static int tdb_free(TDB_CONTEXT *tdb, tdb_off offset, struct list_struct *rec)
+{
+ tdb_off right, left;
+
+ /* Allocation and tailer lock */
+ if (tdb_lock(tdb, -1, F_WRLCK) != 0)
+ return -1;
+
+ /* set an initial tailer, so if we fail we don't leave a bogus record */
+ if (update_tailer(tdb, offset, rec) != 0) {
+ TDB_LOG((tdb, 0, "tdb_free: upfate_tailer failed!\n"));
+ goto fail;
+ }
+
+ /* Look right first (I'm an Australian, dammit) */
+ right = offset + sizeof(*rec) + rec->rec_len;
+ if (right + sizeof(*rec) <= tdb->map_size) {
+ struct list_struct r;
+
+ if (tdb_read(tdb, right, &r, sizeof(r), DOCONV()) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: right read failed at %u\n",
right));
+ goto left;
+ }
+
+ /* If it's free, expand to include it. */
+ if (r.magic == TDB_FREE_MAGIC) {
+ if (remove_from_freelist(tdb, right, r.next) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: right free failed
at %u\n", right));
+ goto left;
+ }
+ rec->rec_len += sizeof(r) + r.rec_len;
+ }
+ }
+
+left:
+ /* Look left */
+ left = offset - sizeof(tdb_off);
+ if (left > TDB_DATA_START(tdb->header.hash_size)) {
+ struct list_struct l;
+ tdb_off leftsize;
+
+ /* Read in tailer and jump back to header */
+ if (ofs_read(tdb, left, &leftsize) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: left offset read failed at
%u\n", left));
+ goto update;
+ }
+ left = offset - leftsize;
+
+ /* Now read in record */
+ if (tdb_read(tdb, left, &l, sizeof(l), DOCONV()) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: left read failed at %u
(%u)\n", left, leftsize));
+ goto update;
+ }
+
+ /* If it's free, expand to include it. */
+ if (l.magic == TDB_FREE_MAGIC) {
+ if (remove_from_freelist(tdb, left, l.next) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: left free failed at
%u\n", left));
+ goto update;
+ } else {
+ offset = left;
+ rec->rec_len += leftsize;
+ }
+ }
+ }
+
+update:
+ if (update_tailer(tdb, offset, rec) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free: update_tailer failed at %u\n",
offset));
+ goto fail;
+ }
+
+ /* Now, prepend to free list */
+ rec->magic = TDB_FREE_MAGIC;
+
+ if (ofs_read(tdb, FREELIST_TOP, &rec->next) == -1 ||
+ rec_write(tdb, offset, rec) == -1 ||
+ ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
+ TDB_LOG((tdb, 0, "tdb_free record write failed at offset=%d\n",
offset));
+ goto fail;
+ }
+
+ /* And we're done. */
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return 0;
+
+ fail:
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return -1;
+}
+
+
+/* expand a file. we prefer to use ftruncate, as that is what posix
+ says to use for mmap expansion */
+static int expand_file(TDB_CONTEXT *tdb, tdb_off size, tdb_off addition)
+{
+ char buf[1024];
+#if HAVE_FTRUNCATE_EXTEND
+ if (ftruncate(tdb->fd, size+addition) != 0) {
+ TDB_LOG((tdb, 0, "expand_file ftruncate to %d failed (%s)\n",
+ size+addition, strerror(errno)));
+ return -1;
+ }
+#else
+ char b = 0;
+
+#ifdef HAVE_PWRITE
+ if (pwrite(tdb->fd, &b, 1, (size+addition) - 1) != 1) {
+#else
+ if (lseek(tdb->fd, (size+addition) - 1, SEEK_SET) !=
(off_t)(size+addition) - 1 ||
+ write(tdb->fd, &b, 1) != 1) {
+#endif
+ TDB_LOG((tdb, 0, "expand_file to %d failed (%s)\n",
+ size+addition, strerror(errno)));
+ return -1;
+ }
+#endif
+
+ /* now fill the file with something. This ensures that the file isn't
sparse, which would be
+ very bad if we ran out of disk. This must be done with write, not
via mmap */
+ memset(buf, 0x42, sizeof(buf));
+ while (addition) {
+ int n = addition>sizeof(buf)?sizeof(buf):addition;
+#ifdef HAVE_PWRITE
+ int ret = pwrite(tdb->fd, buf, n, size);
+#else
+ int ret;
+ if (lseek(tdb->fd, size, SEEK_SET) != (off_t)size)
+ return -1;
+ ret = write(tdb->fd, buf, n);
+#endif
+ if (ret != n) {
+ TDB_LOG((tdb, 0, "expand_file write of %d failed
(%s)\n",
+ n, strerror(errno)));
+ return -1;
+ }
+ addition -= n;
+ size += n;
+ }
+ return 0;
+}
+
+
+/* expand the database at least size bytes by expanding the underlying
+ file and doing the mmap again if necessary */
+static int tdb_expand(TDB_CONTEXT *tdb, tdb_off size)
+{
+ struct list_struct rec;
+ tdb_off offset;
+
+ if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
+ TDB_LOG((tdb, 0, "lock failed in tdb_expand\n"));
+ return -1;
+ }
+
+ /* must know about any previous expansions by another process */
+ tdb_oob(tdb, tdb->map_size + 1, 1);
+
+ /* always make room for at least 10 more records, and round
+ the database up to a multiple of TDB_PAGE_SIZE */
+ size = TDB_ALIGN(tdb->map_size + size*10, TDB_PAGE_SIZE) -
tdb->map_size;
+
+ if (!(tdb->flags & TDB_INTERNAL))
+ tdb_munmap(tdb);
+
+ /*
+ * We must ensure the file is unmapped before doing this
+ * to ensure consistency with systems like OpenBSD where
+ * writes and mmaps are not consistent.
+ */
+
+ /* expand the file itself */
+ if (!(tdb->flags & TDB_INTERNAL)) {
+ if (expand_file(tdb, tdb->map_size, size) != 0)
+ goto fail;
+ }
+
+ tdb->map_size += size;
+
+ if (tdb->flags & TDB_INTERNAL) {
+ char *new_map_ptr = talloc_realloc_size(tdb, tdb->map_ptr,
+ tdb->map_size);
+ if (!new_map_ptr) {
+ tdb->map_size -= size;
+ goto fail;
+ }
+ tdb->map_ptr = new_map_ptr;
+ } else {
+ /*
+ * We must ensure the file is remapped before adding the space
+ * to ensure consistency with systems like OpenBSD where
+ * writes and mmaps are not consistent.
+ */
+
+ /* We're ok if the mmap fails as we'll fallback to read/write */
+ tdb_mmap(tdb);
+ }
+
+ /* form a new freelist record */
+ memset(&rec,'\0',sizeof(rec));
+ rec.rec_len = size - sizeof(rec);
+
+ /* link it into the free list */
+ offset = tdb->map_size - size;
+ if (tdb_free(tdb, offset, &rec) == -1)
+ goto fail;
+
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return 0;
+ fail:
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return -1;
+}
+
+
+/*
+ the core of tdb_allocate - called when we have decided which
+ free list entry to use
+ */
+static tdb_off tdb_allocate_ofs(TDB_CONTEXT *tdb, tdb_len length, tdb_off
rec_ptr,
+ struct list_struct *rec, tdb_off last_ptr)
+{
+ struct list_struct newrec;
+ tdb_off newrec_ptr;
+
+ memset(&newrec, '\0', sizeof(newrec));
+
+ /* found it - now possibly split it up */
+ if (rec->rec_len > length + MIN_REC_SIZE) {
+ /* Length of left piece */
+ length = TDB_ALIGN(length, TDB_ALIGNMENT);
+
+ /* Right piece to go on free list */
+ newrec.rec_len = rec->rec_len - (sizeof(*rec) + length);
+ newrec_ptr = rec_ptr + sizeof(*rec) + length;
+
+ /* And left record is shortened */
+ rec->rec_len = length;
+ } else {
+ newrec_ptr = 0;
+ }
+
+ /* Remove allocated record from the free list */
+ if (ofs_write(tdb, last_ptr, &rec->next) == -1) {
+ return 0;
+ }
+
+ /* Update header: do this before we drop alloc
+ lock, otherwise tdb_free() might try to
+ merge with us, thinking we're free.
+ (Thanks Jeremy Allison). */
+ rec->magic = TDB_MAGIC;
+ if (rec_write(tdb, rec_ptr, rec) == -1) {
+ return 0;
+ }
+
+ /* Did we create new block? */
+ if (newrec_ptr) {
+ /* Update allocated record tailer (we
+ shortened it). */
+ if (update_tailer(tdb, rec_ptr, rec) == -1) {
+ return 0;
+ }
+
+ /* Free new record */
+ if (tdb_free(tdb, newrec_ptr, &newrec) == -1) {
+ return 0;
+ }
+ }
+
+ /* all done - return the new record offset */
+ return rec_ptr;
+}
+
+/* allocate some space from the free list. The offset returned points
+ to a unconnected list_struct within the database with room for at
+ least length bytes of total data
+
+ 0 is returned if the space could not be allocated
+ */
+static tdb_off tdb_allocate(TDB_CONTEXT *tdb, tdb_len length,
+ struct list_struct *rec)
+{
+ tdb_off rec_ptr, last_ptr, newrec_ptr;
+ struct {
+ tdb_off rec_ptr, last_ptr;
+ tdb_len rec_len;
+ } bestfit = { 0, 0, 0 };
+
+ if (tdb_lock(tdb, -1, F_WRLCK) == -1)
+ return 0;
+
+ /* Extra bytes required for tailer */
+ length += sizeof(tdb_off);
+
+ again:
+ last_ptr = FREELIST_TOP;
+
+ /* read in the freelist top */
+ if (ofs_read(tdb, FREELIST_TOP, &rec_ptr) == -1)
+ goto fail;
+
+ bestfit.rec_ptr = 0;
+
+ /*
+ this is a best fit allocation strategy. Originally we used
+ a first fit strategy, but it suffered from massive fragmentation
+ issues when faced with a slowly increasing record size.
+ */
+ while (rec_ptr) {
+ if (rec_free_read(tdb, rec_ptr, rec) == -1) {
+ goto fail;
+ }
+
+ if (rec->rec_len >= length) {
+ if (bestfit.rec_ptr == 0 ||
+ rec->rec_len < bestfit.rec_len) {
+ bestfit.rec_len = rec->rec_len;
+ bestfit.rec_ptr = rec_ptr;
+ bestfit.last_ptr = last_ptr;
+ /* consider a fit to be good enough if we
aren't wasting more than half the space */
+ if (bestfit.rec_len < 2*length) {
+ break;
+ }
+ }
+ }
+
+ /* move to the next record */
+ last_ptr = rec_ptr;
+ rec_ptr = rec->next;
+ }
+
+ if (bestfit.rec_ptr != 0) {
+ if (rec_free_read(tdb, bestfit.rec_ptr, rec) == -1) {
+ goto fail;
+ }
+
+ newrec_ptr = tdb_allocate_ofs(tdb, length, bestfit.rec_ptr,
rec, bestfit.last_ptr);
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return newrec_ptr;
+ }
+
+ /* we didn't find enough space. See if we can expand the
+ database and if we can then try again */
+ if (tdb_expand(tdb, length + sizeof(*rec)) == 0)
+ goto again;
+ fail:
+ tdb_unlock(tdb, -1, F_WRLCK);
+ return 0;
+}
+
+/* initialise a new database with a specified hash size */
+static int tdb_new_database(TDB_CONTEXT *tdb, int hash_size)
+{
+ struct tdb_header *newdb;
+ int size, ret = -1;
+
+ /* We make it up in memory, then write it out if not internal */
+ size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off);
+ if (!(newdb = talloc_zero_size(tdb, size)))
+ return TDB_ERRCODE(TDB_ERR_OOM, -1);
+
+ /* Fill in the header */
+ newdb->version = TDB_VERSION;
+ newdb->hash_size = hash_size;
+ if (tdb->flags & TDB_INTERNAL) {
+ tdb->map_size = size;
+ tdb->map_ptr = (char *)newdb;
+ memcpy(&tdb->header, newdb, sizeof(tdb->header));
+ /* Convert the `ondisk' version if asked. */
+ CONVERT(*newdb);
+ return 0;
+ }
+ if (lseek(tdb->fd, 0, SEEK_SET) == -1)
+ goto fail;
+
+ if (ftruncate(tdb->fd, 0) == -1)
+ goto fail;
+
+ /* This creates an endian-converted header, as if read from disk */
+ CONVERT(*newdb);
+ memcpy(&tdb->header, newdb, sizeof(tdb->header));
+ /* Don't endian-convert the magic food! */
+ memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
+ if (write(tdb->fd, newdb, size) != size)
+ ret = -1;
+ else
+ ret = 0;
+
+ fail:
+ SAFE_FREE(newdb);
+ return ret;
+}
+
+/* Returns 0 on fail. On success, return offset of record, and fills
+ in rec */
+static tdb_off tdb_find(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash,
+ struct list_struct *r)
+{
+ tdb_off rec_ptr;
+
+ /* read in the hash top */
+ if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
+ return 0;
+
+ /* keep looking until we find the right record */
+ while (rec_ptr) {
+ if (rec_read(tdb, rec_ptr, r) == -1)
+ return 0;
+
+ if (!TDB_DEAD(r) && hash==r->full_hash &&
key.dsize==r->key_len) {
+ /* a very likely hit - read the key */
+ int cmp = tdb_key_eq(tdb, rec_ptr + sizeof(*r), key);
+ if (cmp < 0)
+ return 0;
+ else if (cmp > 0)
+ return rec_ptr;
+ }
+ rec_ptr = r->next;
+ }
+ return TDB_ERRCODE(TDB_ERR_NOEXIST, 0);
+}
+
+/* As tdb_find, but if you succeed, keep the lock */
+static tdb_off tdb_find_lock_hash(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash,
int locktype,
+ struct list_struct *rec)
+{
+ u32 rec_ptr;
+
+ if (tdb_lock(tdb, BUCKET(hash), locktype) == -1)
+ return 0;
+ if (!(rec_ptr = tdb_find(tdb, key, hash, rec)))
+ tdb_unlock(tdb, BUCKET(hash), locktype);
+ return rec_ptr;
+}
+
+enum TDB_ERROR tdb_error(TDB_CONTEXT *tdb)
+{
+ return tdb->ecode;
+}
+
+static struct tdb_errname {
+ enum TDB_ERROR ecode; const char *estring;
+} emap[] = { {TDB_SUCCESS, "Success"},
+ {TDB_ERR_CORRUPT, "Corrupt database"},
+ {TDB_ERR_IO, "IO Error"},
+ {TDB_ERR_LOCK, "Locking error"},
+ {TDB_ERR_OOM, "Out of memory"},
+ {TDB_ERR_EXISTS, "Record exists"},
+ {TDB_ERR_NOLOCK, "Lock exists on other keys"},
+ {TDB_ERR_NOEXIST, "Record does not exist"} };
+
+/* Error string for the last tdb error */
+const char *tdb_errorstr(TDB_CONTEXT *tdb)
+{
+ u32 i;
+ for (i = 0; i < sizeof(emap) / sizeof(struct tdb_errname); i++)
+ if (tdb->ecode == emap[i].ecode)
+ return emap[i].estring;
+ return "Invalid error code";
+}
+
+/* update an entry in place - this only works if the new data size
+ is <= the old data size and the key exists.
+ on failure return -1.
+*/
+
+static int tdb_update_hash(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash, TDB_DATA
dbuf)
+{
+ struct list_struct rec;
+ tdb_off rec_ptr;
+
+ /* find entry */
+ if (!(rec_ptr = tdb_find(tdb, key, hash, &rec)))
+ return -1;
+
+ /* must be long enough key, data and tailer */
+ if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb_off)) {
+ tdb->ecode = TDB_SUCCESS; /* Not really an error */
+ return -1;
+ }
+
+ if (tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+ dbuf.dptr, dbuf.dsize) == -1)
+ return -1;
+
+ if (dbuf.dsize != rec.data_len) {
+ /* update size */
+ rec.data_len = dbuf.dsize;
+ return rec_write(tdb, rec_ptr, &rec);
+ }
+
+ return 0;
+}
+
+/* find an entry in the database given a key */
+/* If an entry doesn't exist tdb_err will be set to
+ * TDB_ERR_NOEXIST. If a key has no data attached
+ * then the TDB_DATA will have zero length but
+ * a non-zero pointer
+ */
+
+TDB_DATA tdb_fetch(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ tdb_off rec_ptr;
+ struct list_struct rec;
+ TDB_DATA ret;
+ u32 hash;
+
+ /* find which hash bucket it is in */
+ hash = tdb->hash_fn(&key);
+ if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec)))
+ return tdb_null;
+
+ ret.dptr = tdb_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+ rec.data_len);
+ ret.dsize = rec.data_len;
+ tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
+ return ret;
+}
+
+/* check if an entry in the database exists
+
+ note that 1 is returned if the key is found and 0 is returned if not found
+ this doesn't match the conventions in the rest of this module, but is
+ compatible with gdbm
+*/
+static int tdb_exists_hash(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash)
+{
+ struct list_struct rec;
+
+ if (tdb_find_lock_hash(tdb, key, hash, F_RDLCK, &rec) == 0)
+ return 0;
+ tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
+ return 1;
+}
+
+int tdb_exists(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ u32 hash = tdb->hash_fn(&key);
+ return tdb_exists_hash(tdb, key, hash);
+}
+
+/* record lock stops delete underneath */
+static int lock_record(TDB_CONTEXT *tdb, tdb_off off)
+{
+ return off ? tdb_brlock(tdb, off, F_RDLCK, F_SETLKW, 0) : 0;
+}
+/*
+ Write locks override our own fcntl readlocks, so check it here.
+ Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
+ an error to fail to get the lock here.
+*/
+
+static int write_lock_record(TDB_CONTEXT *tdb, tdb_off off)
+{
+ struct tdb_traverse_lock *i;
+ for (i = &tdb->travlocks; i; i = i->next)
+ if (i->off == off)
+ return -1;
+ return tdb_brlock(tdb, off, F_WRLCK, F_SETLK, 1);
+}
+
+/*
+ Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
+ an error to fail to get the lock here.
+*/
+
+static int write_unlock_record(TDB_CONTEXT *tdb, tdb_off off)
+{
+ return tdb_brlock(tdb, off, F_UNLCK, F_SETLK, 0);
+}
+/* fcntl locks don't stack: avoid unlocking someone else's */
+static int unlock_record(TDB_CONTEXT *tdb, tdb_off off)
+{
+ struct tdb_traverse_lock *i;
+ u32 count = 0;
+
+ if (off == 0)
+ return 0;
+ for (i = &tdb->travlocks; i; i = i->next)
+ if (i->off == off)
+ count++;
+ return (count == 1 ? tdb_brlock(tdb, off, F_UNLCK, F_SETLKW, 0) : 0);
+}
+
+/* actually delete an entry in the database given the offset */
+static int do_delete(TDB_CONTEXT *tdb, tdb_off rec_ptr, struct list_struct*rec)
+{
+ tdb_off last_ptr, i;
+ struct list_struct lastrec;
+
+ if (tdb->read_only) return -1;
+
+ if (write_lock_record(tdb, rec_ptr) == -1) {
+ /* Someone traversing here: mark it as dead */
+ rec->magic = TDB_DEAD_MAGIC;
+ return rec_write(tdb, rec_ptr, rec);
+ }
+ if (write_unlock_record(tdb, rec_ptr) != 0)
+ return -1;
+
+ /* find previous record in hash chain */
+ if (ofs_read(tdb, TDB_HASH_TOP(rec->full_hash), &i) == -1)
+ return -1;
+ for (last_ptr = 0; i != rec_ptr; last_ptr = i, i = lastrec.next)
+ if (rec_read(tdb, i, &lastrec) == -1)
+ return -1;
+
+ /* unlink it: next ptr is at start of record. */
+ if (last_ptr == 0)
+ last_ptr = TDB_HASH_TOP(rec->full_hash);
+ if (ofs_write(tdb, last_ptr, &rec->next) == -1)
+ return -1;
+
+ /* recover the space */
+ if (tdb_free(tdb, rec_ptr, rec) == -1)
+ return -1;
+ return 0;
+}
+
+/* Uses traverse lock: 0 = finish, -1 = error, other = record offset */
+static int tdb_next_lock(TDB_CONTEXT *tdb, struct tdb_traverse_lock *tlock,
+ struct list_struct *rec)
+{
+ int want_next = (tlock->off != 0);
+
+ /* Lock each chain from the start one. */
+ for (; tlock->hash < tdb->header.hash_size; tlock->hash++) {
+
+ /* this is an optimisation for the common case where
+ the hash chain is empty, which is particularly
+ common for the use of tdb with ldb, where large
+ hashes are used. In that case we spend most of our
+ time in tdb_brlock(), locking empty hash chains.
+
+ To avoid this, we do an unlocked pre-check to see
+ if the hash chain is empty before starting to look
+ inside it. If it is empty then we can avoid that
+ hash chain. If it isn't empty then we can't believe
+ the value we get back, as we read it without a
+ lock, so instead we get the lock and re-fetch the
+ value below.
+
+ Notice that not doing this optimisation on the
+ first hash chain is critical. We must guarantee
+ that we have done at least one fcntl lock at the
+ start of a search to guarantee that memory is
+ coherent on SMP systems. If records are added by
+ others during the search then thats OK, and we
+ could possibly miss those with this trick, but we
+ could miss them anyway without this trick, so the
+ semantics don't change.
+
+ With a non-indexed ldb search this trick gains us a
+ factor of around 80 in speed on a linux 2.6.x
+ system (testing using ldbtest).
+ */
+ if (!tlock->off && tlock->hash != 0) {
+ u32 off;
+ if (tdb->map_ptr) {
+ for (;tlock->hash <
tdb->header.hash_size;tlock->hash++) {
+ if (0 != *(u32
*)(TDB_HASH_TOP(tlock->hash) + (unsigned char *)tdb->map_ptr)) {
+ break;
+ }
+ }
+ if (tlock->hash == tdb->header.hash_size) {
+ continue;
+ }
+ } else {
+ if (ofs_read(tdb, TDB_HASH_TOP(tlock->hash),
&off) == 0 &&
+ off == 0) {
+ continue;
+ }
+ }
+ }
+
+ if (tdb_lock(tdb, tlock->hash, F_WRLCK) == -1)
+ return -1;
+
+ /* No previous record? Start at top of chain. */
+ if (!tlock->off) {
+ if (ofs_read(tdb, TDB_HASH_TOP(tlock->hash),
+ &tlock->off) == -1)
+ goto fail;
+ } else {
+ /* Otherwise unlock the previous record. */
+ if (unlock_record(tdb, tlock->off) != 0)
+ goto fail;
+ }
+
+ if (want_next) {
+ /* We have offset of old record: grab next */
+ if (rec_read(tdb, tlock->off, rec) == -1)
+ goto fail;
+ tlock->off = rec->next;
+ }
+
+ /* Iterate through chain */
+ while( tlock->off) {
+ tdb_off current;
+ if (rec_read(tdb, tlock->off, rec) == -1)
+ goto fail;
+
+ /* Detect infinite loops. From "Shlomi Yaakobovich"
<Shlomi@xxxxxxxxxx>. */
+ if (tlock->off == rec->next) {
+ TDB_LOG((tdb, 0, "tdb_next_lock: loop
detected.\n"));
+ goto fail;
+ }
+
+ if (!TDB_DEAD(rec)) {
+ /* Woohoo: we found one! */
+ if (lock_record(tdb, tlock->off) != 0)
+ goto fail;
+ return tlock->off;
+ }
+
+ /* Try to clean dead ones from old traverses */
+ current = tlock->off;
+ tlock->off = rec->next;
+ if (!tdb->read_only &&
+ do_delete(tdb, current, rec) != 0)
+ goto fail;
+ }
+ tdb_unlock(tdb, tlock->hash, F_WRLCK);
+ want_next = 0;
+ }
+ /* We finished iteration without finding anything */
+ return TDB_ERRCODE(TDB_SUCCESS, 0);
+
+ fail:
+ tlock->off = 0;
+ if (tdb_unlock(tdb, tlock->hash, F_WRLCK) != 0)
+ TDB_LOG((tdb, 0, "tdb_next_lock: On error unlock failed!\n"));
+ return -1;
+}
+
+/* traverse the entire database - calling fn(tdb, key, data) on each element.
+ return -1 on error or the record count traversed
+ if fn is NULL then it is not called
+ a non-zero return value from fn() indicates that the traversal should stop
+ */
+int tdb_traverse(TDB_CONTEXT *tdb, tdb_traverse_func fn, void *private)
+{
+ TDB_DATA key, dbuf;
+ struct list_struct rec;
+ struct tdb_traverse_lock tl = { NULL, 0, 0 };
+ int ret, count = 0;
+
+ /* This was in the initializaton, above, but the IRIX compiler
+ * did not like it. crh
+ */
+ tl.next = tdb->travlocks.next;
+
+ /* fcntl locks don't stack: beware traverse inside traverse */
+ tdb->travlocks.next = &tl;
+
+ /* tdb_next_lock places locks on the record returned, and its chain */
+ while ((ret = tdb_next_lock(tdb, &tl, &rec)) > 0) {
+ count++;
+ /* now read the full record */
+ key.dptr = tdb_alloc_read(tdb, tl.off + sizeof(rec),
+ rec.key_len + rec.data_len);
+ if (!key.dptr) {
+ ret = -1;
+ if (tdb_unlock(tdb, tl.hash, F_WRLCK) != 0)
+ goto out;
+ if (unlock_record(tdb, tl.off) != 0)
+ TDB_LOG((tdb, 0, "tdb_traverse: key.dptr ==
NULL and unlock_record failed!\n"));
+ goto out;
+ }
+ key.dsize = rec.key_len;
+ dbuf.dptr = key.dptr + rec.key_len;
+ dbuf.dsize = rec.data_len;
+
+ /* Drop chain lock, call out */
+ if (tdb_unlock(tdb, tl.hash, F_WRLCK) != 0) {
+ ret = -1;
+ goto out;
+ }
+ if (fn && fn(tdb, key, dbuf, private)) {
+ /* They want us to terminate traversal */
+ ret = count;
+ if (unlock_record(tdb, tl.off) != 0) {
+ TDB_LOG((tdb, 0, "tdb_traverse: unlock_record
failed!\n"));;
+ ret = -1;
+ }
+ tdb->travlocks.next = tl.next;
+ SAFE_FREE(key.dptr);
+ return count;
+ }
+ SAFE_FREE(key.dptr);
+ }
+out:
+ tdb->travlocks.next = tl.next;
+ if (ret < 0)
+ return -1;
+ else
+ return count;
+}
+
+/* find the first entry in the database and return its key */
+TDB_DATA tdb_firstkey(TDB_CONTEXT *tdb)
+{
+ TDB_DATA key;
+ struct list_struct rec;
+
+ /* release any old lock */
+ if (unlock_record(tdb, tdb->travlocks.off) != 0)
+ return tdb_null;
+ tdb->travlocks.off = tdb->travlocks.hash = 0;
+
+ if (tdb_next_lock(tdb, &tdb->travlocks, &rec) <= 0)
+ return tdb_null;
+ /* now read the key */
+ key.dsize = rec.key_len;
+ key.dptr =tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),key.dsize);
+ if (tdb_unlock(tdb, BUCKET(tdb->travlocks.hash), F_WRLCK) != 0)
+ TDB_LOG((tdb, 0, "tdb_firstkey: error occurred while
tdb_unlocking!\n"));
+ return key;
+}
+
+/* find the next entry in the database, returning its key */
+TDB_DATA tdb_nextkey(TDB_CONTEXT *tdb, TDB_DATA oldkey)
+{
+ u32 oldhash;
+ TDB_DATA key = tdb_null;
+ struct list_struct rec;
+ char *k = NULL;
+
+ /* Is locked key the old key? If so, traverse will be reliable. */
+ if (tdb->travlocks.off) {
+ if (tdb_lock(tdb,tdb->travlocks.hash,F_WRLCK))
+ return tdb_null;
+ if (rec_read(tdb, tdb->travlocks.off, &rec) == -1
+ || !(k = tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),
+ rec.key_len))
+ || memcmp(k, oldkey.dptr, oldkey.dsize) != 0) {
+ /* No, it wasn't: unlock it and start from scratch */
+ if (unlock_record(tdb, tdb->travlocks.off) != 0)
+ return tdb_null;
+ if (tdb_unlock(tdb, tdb->travlocks.hash, F_WRLCK) != 0)
+ return tdb_null;
+ tdb->travlocks.off = 0;
+ }
+
+ SAFE_FREE(k);
+ }
+
+ if (!tdb->travlocks.off) {
+ /* No previous element: do normal find, and lock record */
+ tdb->travlocks.off = tdb_find_lock_hash(tdb, oldkey,
tdb->hash_fn(&oldkey), F_WRLCK, &rec);
+ if (!tdb->travlocks.off)
+ return tdb_null;
+ tdb->travlocks.hash = BUCKET(rec.full_hash);
+ if (lock_record(tdb, tdb->travlocks.off) != 0) {
+ TDB_LOG((tdb, 0, "tdb_nextkey: lock_record failed
(%s)!\n", strerror(errno)));
+ return tdb_null;
+ }
+ }
+ oldhash = tdb->travlocks.hash;
+
+ /* Grab next record: locks chain and returned record,
+ unlocks old record */
+ if (tdb_next_lock(tdb, &tdb->travlocks, &rec) > 0) {
+ key.dsize = rec.key_len;
+ key.dptr = tdb_alloc_read(tdb, tdb->travlocks.off+sizeof(rec),
+ key.dsize);
+ /* Unlock the chain of this new record */
+ if (tdb_unlock(tdb, tdb->travlocks.hash, F_WRLCK) != 0)
+ TDB_LOG((tdb, 0, "tdb_nextkey: WARNING tdb_unlock
failed!\n"));
+ }
+ /* Unlock the chain of old record */
+ if (tdb_unlock(tdb, BUCKET(oldhash), F_WRLCK) != 0)
+ TDB_LOG((tdb, 0, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
+ return key;
+}
+
+/* delete an entry in the database given a key */
+static int tdb_delete_hash(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash)
+{
+ tdb_off rec_ptr;
+ struct list_struct rec;
+ int ret;
+
+ if (!(rec_ptr = tdb_find_lock_hash(tdb, key, hash, F_WRLCK, &rec)))
+ return -1;
+ ret = do_delete(tdb, rec_ptr, &rec);
+ if (tdb_unlock(tdb, BUCKET(rec.full_hash), F_WRLCK) != 0)
+ TDB_LOG((tdb, 0, "tdb_delete: WARNING tdb_unlock failed!\n"));
+ return ret;
+}
+
+int tdb_delete(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ u32 hash = tdb->hash_fn(&key);
+ return tdb_delete_hash(tdb, key, hash);
+}
+
+/* store an element in the database, replacing any existing element
+ with the same key
+
+ return 0 on success, -1 on failure
+*/
+int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
+{
+ struct list_struct rec;
+ u32 hash;
+ tdb_off rec_ptr;
+ char *p = NULL;
+ int ret = 0;
+
+ /* find which hash bucket it is in */
+ hash = tdb->hash_fn(&key);
+ if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
+ return -1;
+
+ /* check for it existing, on insert. */
+ if (flag == TDB_INSERT) {
+ if (tdb_exists_hash(tdb, key, hash)) {
+ tdb->ecode = TDB_ERR_EXISTS;
+ goto fail;
+ }
+ } else {
+ /* first try in-place update, on modify or replace. */
+ if (tdb_update_hash(tdb, key, hash, dbuf) == 0)
+ goto out;
+ if (tdb->ecode == TDB_ERR_NOEXIST &&
+ flag == TDB_MODIFY) {
+ /* if the record doesn't exist and we are in TDB_MODIFY
mode then
+ we should fail the store */
+ goto fail;
+ }
+ }
+ /* reset the error code potentially set by the tdb_update() */
+ tdb->ecode = TDB_SUCCESS;
+
+ /* delete any existing record - if it doesn't exist we don't
+ care. Doing this first reduces fragmentation, and avoids
+ coalescing with `allocated' block before it's updated. */
+ if (flag != TDB_INSERT)
+ tdb_delete_hash(tdb, key, hash);
+
+ /* Copy key+value *before* allocating free space in case malloc
+ fails and we are left with a dead spot in the tdb. */
+
+ if (!(p = (char *)talloc_size(tdb, key.dsize + dbuf.dsize))) {
+ tdb->ecode = TDB_ERR_OOM;
+ goto fail;
+ }
+
+ memcpy(p, key.dptr, key.dsize);
+ if (dbuf.dsize)
+ memcpy(p+key.dsize, dbuf.dptr, dbuf.dsize);
+
+ /* we have to allocate some space */
+ if (!(rec_ptr = tdb_allocate(tdb, key.dsize + dbuf.dsize, &rec)))
+ goto fail;
+
+ /* Read hash top into next ptr */
+ if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
+ goto fail;
+
+ rec.key_len = key.dsize;
+ rec.data_len = dbuf.dsize;
+ rec.full_hash = hash;
+ rec.magic = TDB_MAGIC;
+
+ /* write out and point the top of the hash chain at it */
+ if (rec_write(tdb, rec_ptr, &rec) == -1
+ || tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
+ || ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
+ /* Need to tdb_unallocate() here */
+ goto fail;
+ }
+ out:
+ SAFE_FREE(p);
+ tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
+ return ret;
+fail:
+ ret = -1;
+ goto out;
+}
+
+/* Attempt to append data to an entry in place - this only works if the new
data size
+ is <= the old data size and the key exists.
+ on failure return -1. Record must be locked before calling.
+*/
+static int tdb_append_inplace(TDB_CONTEXT *tdb, TDB_DATA key, u32 hash,
TDB_DATA new_dbuf)
+{
+ struct list_struct rec;
+ tdb_off rec_ptr;
+
+ /* find entry */
+ if (!(rec_ptr = tdb_find(tdb, key, hash, &rec)))
+ return -1;
+
+ /* Append of 0 is always ok. */
+ if (new_dbuf.dsize == 0)
+ return 0;
+
+ /* must be long enough for key, old data + new data and tailer */
+ if (rec.rec_len < key.dsize + rec.data_len + new_dbuf.dsize +
sizeof(tdb_off)) {
+ /* No room. */
+ tdb->ecode = TDB_SUCCESS; /* Not really an error */
+ return -1;
+ }
+
+ if (tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len + rec.data_len,
+ new_dbuf.dptr, new_dbuf.dsize) == -1)
+ return -1;
+
+ /* update size */
+ rec.data_len += new_dbuf.dsize;
+ return rec_write(tdb, rec_ptr, &rec);
+}
+
+/* Append to an entry. Create if not exist. */
+
+int tdb_append(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA new_dbuf)
+{
+ struct list_struct rec;
+ u32 hash;
+ tdb_off rec_ptr;
+ char *p = NULL;
+ int ret = 0;
+ size_t new_data_size = 0;
+
+ /* find which hash bucket it is in */
+ hash = tdb->hash_fn(&key);
+ if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
+ return -1;
+
+ /* first try in-place. */
+ if (tdb_append_inplace(tdb, key, hash, new_dbuf) == 0)
+ goto out;
+
+ /* reset the error code potentially set by the tdb_append_inplace() */
+ tdb->ecode = TDB_SUCCESS;
+
+ /* find entry */
+ if (!(rec_ptr = tdb_find(tdb, key, hash, &rec))) {
+ if (tdb->ecode != TDB_ERR_NOEXIST)
+ goto fail;
+
+ /* Not found - create. */
+
+ ret = tdb_store(tdb, key, new_dbuf, TDB_INSERT);
+ goto out;
+ }
+
+ new_data_size = rec.data_len + new_dbuf.dsize;
+
+ /* Copy key+old_value+value *before* allocating free space in case
malloc
+ fails and we are left with a dead spot in the tdb. */
+
+ if (!(p = (char *)talloc_size(tdb, key.dsize + new_data_size))) {
+ tdb->ecode = TDB_ERR_OOM;
+ goto fail;
+ }
+
+ /* Copy the key in place. */
+ memcpy(p, key.dptr, key.dsize);
+
+ /* Now read the old data into place. */
+ if (rec.data_len &&
+ tdb_read(tdb, rec_ptr + sizeof(rec) + rec.key_len, p +
key.dsize, rec.data_len, 0) == -1)
+ goto fail;
+
+ /* Finally append the new data. */
+ if (new_dbuf.dsize)
+ memcpy(p+key.dsize+rec.data_len, new_dbuf.dptr, new_dbuf.dsize);
+
+ /* delete any existing record - if it doesn't exist we don't
+ care. Doing this first reduces fragmentation, and avoids
+ coalescing with `allocated' block before it's updated. */
+
+ tdb_delete_hash(tdb, key, hash);
+
+ if (!(rec_ptr = tdb_allocate(tdb, key.dsize + new_data_size, &rec)))
+ goto fail;
+
+ /* Read hash top into next ptr */
+ if (ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
+ goto fail;
+
+ rec.key_len = key.dsize;
+ rec.data_len = new_data_size;
+ rec.full_hash = hash;
+ rec.magic = TDB_MAGIC;
+
+ /* write out and point the top of the hash chain at it */
+ if (rec_write(tdb, rec_ptr, &rec) == -1
+ || tdb_write(tdb, rec_ptr+sizeof(rec), p,
key.dsize+new_data_size)==-1
+ || ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
+ /* Need to tdb_unallocate() here */
+ goto fail;
+ }
+
+ out:
+ SAFE_FREE(p);
+ tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
+ return ret;
+
+fail:
+ ret = -1;
+ goto out;
+}
+
+static int tdb_already_open(dev_t device,
+ ino_t ino)
+{
+ TDB_CONTEXT *i;
+
+ for (i = tdbs; i; i = i->next) {
+ if (i->device == device && i->inode == ino) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+/* open the database, creating it if necessary
+
+ The open_flags and mode are passed straight to the open call on the
+ database file. A flags value of O_WRONLY is invalid. The hash size
+ is advisory, use zero for a default value.
+
+ Return is NULL on error, in which case errno is also set. Don't
+ try to call tdb_error or tdb_errname, just do strerror(errno).
+
+ @param name may be NULL for internal databases. */
+TDB_CONTEXT *tdb_open(const char *name, int hash_size, int tdb_flags,
+ int open_flags, mode_t mode)
+{
+ return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL,
NULL);
+}
+
+/* a default logging function */
+static void null_log_fn(TDB_CONTEXT *tdb __attribute__((unused)),
+ int level __attribute__((unused)),
+ const char *fmt __attribute__((unused)), ...)
+{
+}
+
+
+TDB_CONTEXT *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
+ int open_flags, mode_t mode,
+ tdb_log_func log_fn,
+ tdb_hash_func hash_fn)
+{
+ TDB_CONTEXT *tdb;
+ struct stat st;
+ int rev = 0, locked = 0;
+ uint8_t *vp;
+ u32 vertest;
+
+ if (!(tdb = talloc_zero(name, TDB_CONTEXT))) {
+ /* Can't log this */
+ errno = ENOMEM;
+ goto fail;
+ }
+ tdb->fd = -1;
+ tdb->name = NULL;
+ tdb->map_ptr = NULL;
+ tdb->flags = tdb_flags;
+ tdb->open_flags = open_flags;
+ tdb->log_fn = log_fn?log_fn:null_log_fn;
+ tdb->hash_fn = hash_fn ? hash_fn : default_tdb_hash;
+
+ if ((open_flags & O_ACCMODE) == O_WRONLY) {
+ TDB_LOG((tdb, 0, "tdb_open_ex: can't open tdb %s write-only\n",
+ name));
+ errno = EINVAL;
+ goto fail;
+ }
+
+ if (hash_size == 0)
+ hash_size = DEFAULT_HASH_SIZE;
+ if ((open_flags & O_ACCMODE) == O_RDONLY) {
+ tdb->read_only = 1;
+ /* read only databases don't do locking or clear if first */
+ tdb->flags |= TDB_NOLOCK;
+ tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+ }
+
+ /* internal databases don't mmap or lock, and start off cleared */
+ if (tdb->flags & TDB_INTERNAL) {
+ tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
+ tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+ if (tdb_new_database(tdb, hash_size) != 0) {
+ TDB_LOG((tdb, 0, "tdb_open_ex: tdb_new_database
failed!"));
+ goto fail;
+ }
+ goto internal;
+ }
+
+ if ((tdb->fd = open(name, open_flags, mode)) == -1) {
+ TDB_LOG((tdb, 5, "tdb_open_ex: could not open file %s: %s\n",
+ name, strerror(errno)));
+ goto fail; /* errno set by open(2) */
+ }
+
+ /* ensure there is only one process initialising at once */
+ if (tdb_brlock(tdb, GLOBAL_LOCK, F_WRLCK, F_SETLKW, 0) == -1) {
+ TDB_LOG((tdb, 0, "tdb_open_ex: failed to get global lock on %s:
%s\n",
+ name, strerror(errno)));
+ goto fail; /* errno set by tdb_brlock */
+ }
+
+ /* we need to zero database if we are the only one with it open */
+ if ((tdb_flags & TDB_CLEAR_IF_FIRST) &&
+ (locked = (tdb_brlock(tdb, ACTIVE_LOCK, F_WRLCK, F_SETLK, 0) ==
0))) {
+ open_flags |= O_CREAT;
+ if (ftruncate(tdb->fd, 0) == -1) {
+ TDB_LOG((tdb, 0, "tdb_open_ex: "
+ "failed to truncate %s: %s\n",
+ name, strerror(errno)));
+ goto fail; /* errno set by ftruncate */
+ }
+ }
+
+ if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) !=
sizeof(tdb->header)
+ || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0
+ || (tdb->header.version != TDB_VERSION
+ && !(rev = (tdb->header.version==TDB_BYTEREV(TDB_VERSION))))) {
+ /* its not a valid database - possibly initialise it */
+ if (!(open_flags & O_CREAT) || tdb_new_database(tdb, hash_size)
== -1) {
+ errno = EIO; /* ie bad format or something */
+ goto fail;
+ }
+ rev = (tdb->flags & TDB_CONVERT);
+ }
+ vp = (uint8_t *)&tdb->header.version;
+ vertest = (((u32)vp[0]) << 24) | (((u32)vp[1]) << 16) |
+ (((u32)vp[2]) << 8) | (u32)vp[3];
+ tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
+ if (!rev)
+ tdb->flags &= ~TDB_CONVERT;
+ else {
+ tdb->flags |= TDB_CONVERT;
+ convert(&tdb->header, sizeof(tdb->header));
+ }
+ if (fstat(tdb->fd, &st) == -1)
+ goto fail;
+
+ /* Is it already in the open list? If so, fail. */
+ if (tdb_already_open(st.st_dev, st.st_ino)) {
+ TDB_LOG((tdb, 2, "tdb_open_ex: "
+ "%s (%d,%d) is already open in this process\n",
+ name, (int)st.st_dev, (int)st.st_ino));
+ errno = EBUSY;
+ goto fail;
+ }
+
+ if (!(tdb->name = (char *)talloc_strdup(tdb, name))) {
+ errno = ENOMEM;
+ goto fail;
+ }
+
+ tdb->map_size = st.st_size;
+ tdb->device = st.st_dev;
+ tdb->inode = st.st_ino;
+ tdb->locked = talloc_zero_array(tdb, struct tdb_lock_type,
+ tdb->header.hash_size+1);
+ if (!tdb->locked) {
+ TDB_LOG((tdb, 2, "tdb_open_ex: "
+ "failed to allocate lock structure for %s\n",
+ name));
+ errno = ENOMEM;
+ goto fail;
+ }
+ tdb_mmap(tdb);
+ if (locked) {
+ if (tdb_brlock(tdb, ACTIVE_LOCK, F_UNLCK, F_SETLK, 0) == -1) {
+ TDB_LOG((tdb, 0, "tdb_open_ex: "
+ "failed to take ACTIVE_LOCK on %s: %s\n",
+ name, strerror(errno)));
+ goto fail;
+ }
+
+ }
+
+ /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
+ we didn't get the initial exclusive lock as we need to let all other
+ users know we're using it. */
+
+ if (tdb_flags & TDB_CLEAR_IF_FIRST) {
+ /* leave this lock in place to indicate it's in use */
+ if (tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0) == -1)
+ goto fail;
+ }
+
+
+ internal:
+ /* Internal (memory-only) databases skip all the code above to
+ * do with disk files, and resume here by releasing their
+ * global lock and hooking into the active list. */
+ if (tdb_brlock(tdb, GLOBAL_LOCK, F_UNLCK, F_SETLKW, 0) == -1)
+ goto fail;
+ tdb->next = tdbs;
+ tdbs = tdb;
+ return tdb;
+
+ fail:
+ { int save_errno = errno;
+
+ if (!tdb)
+ return NULL;
+
+ if (tdb->map_ptr) {
+ if (tdb->flags & TDB_INTERNAL)
+ SAFE_FREE(tdb->map_ptr);
+ else
+ tdb_munmap(tdb);
+ }
+ SAFE_FREE(tdb->name);
+ if (tdb->fd != -1)
+ if (close(tdb->fd) != 0)
+ TDB_LOG((tdb, 5, "tdb_open_ex: failed to close tdb->fd
on error!\n"));
+ SAFE_FREE(tdb->locked);
+ SAFE_FREE(tdb);
+ errno = save_errno;
+ return NULL;
+ }
+}
+
+/**
+ * Close a database.
+ *
+ * @returns -1 for error; 0 for success.
+ **/
+int tdb_close(TDB_CONTEXT *tdb)
+{
+ TDB_CONTEXT **i;
+ int ret = 0;
+
+ if (tdb->map_ptr) {
+ if (tdb->flags & TDB_INTERNAL)
+ SAFE_FREE(tdb->map_ptr);
+ else
+ tdb_munmap(tdb);
+ }
+ SAFE_FREE(tdb->name);
+ if (tdb->fd != -1)
+ ret = close(tdb->fd);
+ SAFE_FREE(tdb->locked);
+
+ /* Remove from contexts list */
+ for (i = &tdbs; *i; i = &(*i)->next) {
+ if (*i == tdb) {
+ *i = tdb->next;
+ break;
+ }
+ }
+
+ memset(tdb, 0, sizeof(*tdb));
+ SAFE_FREE(tdb);
+
+ return ret;
+}
+
+/* lock/unlock entire database */
+int tdb_lockall(TDB_CONTEXT *tdb)
+{
+ u32 i;
+
+ /* There are no locks on read-only dbs */
+ if (tdb->read_only)
+ return TDB_ERRCODE(TDB_ERR_LOCK, -1);
+ for (i = 0; i < tdb->header.hash_size; i++)
+ if (tdb_lock(tdb, i, F_WRLCK))
+ break;
+
+ /* If error, release locks we have... */
+ if (i < tdb->header.hash_size) {
+ u32 j;
+
+ for ( j = 0; j < i; j++)
+ tdb_unlock(tdb, j, F_WRLCK);
+ return TDB_ERRCODE(TDB_ERR_NOLOCK, -1);
+ }
+
+ return 0;
+}
+void tdb_unlockall(TDB_CONTEXT *tdb)
+{
+ u32 i;
+ for (i=0; i < tdb->header.hash_size; i++)
+ tdb_unlock(tdb, i, F_WRLCK);
+}
+
+/* lock/unlock one hash chain. This is meant to be used to reduce
+ contention - it cannot guarantee how many records will be locked */
+int tdb_chainlock(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ return tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+}
+
+int tdb_chainunlock(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+}
+
+int tdb_chainlock_read(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ return tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+}
+
+int tdb_chainunlock_read(TDB_CONTEXT *tdb, TDB_DATA key)
+{
+ return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+}
+
+
+/* register a loging function */
+void tdb_logging_function(TDB_CONTEXT *tdb, void (*fn)(TDB_CONTEXT *, int ,
const char *, ...))
+{
+ tdb->log_fn = fn?fn:null_log_fn;
+}
+
+
+/* reopen a tdb - this can be used after a fork to ensure that we have an
independent
+ seek pointer from our parent and to re-establish locks */
+int tdb_reopen(TDB_CONTEXT *tdb)
+{
+ struct stat st;
+
+ if (tdb->flags & TDB_INTERNAL)
+ return 0; /* Nothing to do. */
+ if (tdb_munmap(tdb) != 0) {
+ TDB_LOG((tdb, 0, "tdb_reopen: munmap failed (%s)\n",
strerror(errno)));
+ goto fail;
+ }
+ if (close(tdb->fd) != 0)
+ TDB_LOG((tdb, 0, "tdb_reopen: WARNING closing tdb->fd
failed!\n"));
+ tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
+ if (tdb->fd == -1) {
+ TDB_LOG((tdb, 0, "tdb_reopen: open failed (%s)\n",
strerror(errno)));
+ goto fail;
+ }
+ if (fstat(tdb->fd, &st) != 0) {
+ TDB_LOG((tdb, 0, "tdb_reopen: fstat failed (%s)\n",
strerror(errno)));
+ goto fail;
+ }
+ if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
+ TDB_LOG((tdb, 0, "tdb_reopen: file dev/inode has changed!\n"));
+ goto fail;
+ }
+ tdb_mmap(tdb);
+ if ((tdb->flags & TDB_CLEAR_IF_FIRST) && (tdb_brlock(tdb, ACTIVE_LOCK,
F_RDLCK, F_SETLKW, 0) == -1)) {
+ TDB_LOG((tdb, 0, "tdb_reopen: failed to obtain active lock\n"));
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ tdb_close(tdb);
+ return -1;
+}
+
+/* Not general: only works if single writer. */
+TDB_CONTEXT *tdb_copy(TDB_CONTEXT *tdb, const char *outfile)
+{
+ int fd, saved_errno;
+ TDB_CONTEXT *copy;
+
+ fd = open(outfile, O_TRUNC|O_CREAT|O_WRONLY, 0640);
+ if (fd < 0)
+ return NULL;
+ if (tdb->map_ptr) {
+ if (write(fd,tdb->map_ptr,tdb->map_size) != (int)tdb->map_size)
+ goto fail;
+ } else {
+ char buf[65536];
+ int r;
+
+ lseek(tdb->fd, 0, SEEK_SET);
+ while ((r = read(tdb->fd, buf, sizeof(buf))) > 0) {
+ if (write(fd, buf, r) != r)
+ goto fail;
+ }
+ if (r < 0)
+ goto fail;
+ }
+ copy = tdb_open(outfile, 0, 0, O_RDWR, 0);
+ if (!copy)
+ goto fail;
+ close(fd);
+ return copy;
+
+fail:
+ saved_errno = errno;
+ close(fd);
+ unlink(outfile);
+ errno = saved_errno;
+ return NULL;
+}
+
+/* reopen all tdb's */
+int tdb_reopen_all(void)
+{
+ TDB_CONTEXT *tdb;
+
+ for (tdb=tdbs; tdb; tdb = tdb->next) {
+ /* Ensure no clear-if-first. */
+ tdb->flags &= ~TDB_CLEAR_IF_FIRST;
+ if (tdb_reopen(tdb) != 0)
+ return -1;
+ }
+
+ return 0;
+}
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/tdb.h
--- /dev/null Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/tdb.h Fri Sep 23 13:25:01 2005
@@ -0,0 +1,157 @@
+#ifndef __TDB_H__
+#define __TDB_H__
+
+/*
+ Unix SMB/CIFS implementation.
+
+ trivial database library
+
+ Copyright (C) Andrew Tridgell 1999-2004
+
+ ** NOTE! The following LGPL license applies to the tdb
+ ** library. This does NOT imply that all of Samba is released
+ ** under the LGPL
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* flags to tdb_store() */
+#define TDB_REPLACE 1
+#define TDB_INSERT 2
+#define TDB_MODIFY 3
+
+/* flags for tdb_open() */
+#define TDB_DEFAULT 0 /* just a readability place holder */
+#define TDB_CLEAR_IF_FIRST 1
+#define TDB_INTERNAL 2 /* don't store on disk */
+#define TDB_NOLOCK 4 /* don't do any locking */
+#define TDB_NOMMAP 8 /* don't use mmap */
+#define TDB_CONVERT 16 /* convert endian (internal use) */
+#define TDB_BIGENDIAN 32 /* header is big-endian (internal use) */
+
+#define TDB_ERRCODE(code, ret) ((tdb->ecode = (code)), ret)
+
+/* error codes */
+enum TDB_ERROR {TDB_SUCCESS=0, TDB_ERR_CORRUPT, TDB_ERR_IO, TDB_ERR_LOCK,
+ TDB_ERR_OOM, TDB_ERR_EXISTS, TDB_ERR_NOLOCK,
TDB_ERR_LOCK_TIMEOUT,
+ TDB_ERR_NOEXIST};
+
+#ifndef u32
+#define u32 unsigned
+#endif
+
+typedef struct TDB_DATA {
+ char *dptr;
+ size_t dsize;
+} TDB_DATA;
+
+typedef u32 tdb_len;
+typedef u32 tdb_off;
+
+/* this is stored at the front of every database */
+struct tdb_header {
+ char magic_food[32]; /* for /etc/magic */
+ u32 version; /* version of the code */
+ u32 hash_size; /* number of hash entries */
+ tdb_off rwlocks;
+ tdb_off reserved[31];
+};
+
+struct tdb_lock_type {
+ u32 count;
+ u32 ltype;
+};
+
+struct tdb_traverse_lock {
+ struct tdb_traverse_lock *next;
+ u32 off;
+ u32 hash;
+};
+
+#ifndef PRINTF_ATTRIBUTE
+#define PRINTF_ATTRIBUTE(a,b)
+#endif
+
+/* this is the context structure that is returned from a db open */
+typedef struct tdb_context {
+ char *name; /* the name of the database */
+ void *map_ptr; /* where it is currently mapped */
+ int fd; /* open file descriptor for the database */
+ tdb_len map_size; /* how much space has been mapped */
+ int read_only; /* opened read-only */
+ struct tdb_lock_type *locked; /* array of chain locks */
+ enum TDB_ERROR ecode; /* error code for last tdb error */
+ struct tdb_header header; /* a cached copy of the header */
+ u32 flags; /* the flags passed to tdb_open */
+ struct tdb_traverse_lock travlocks; /* current traversal locks */
+ struct tdb_context *next; /* all tdbs to avoid multiple opens */
+ dev_t device; /* uniquely identifies this tdb */
+ ino_t inode; /* uniquely identifies this tdb */
+ void (*log_fn)(struct tdb_context *tdb, int level, const char *, ...)
PRINTF_ATTRIBUTE(3,4); /* logging function */
+ u32 (*hash_fn)(TDB_DATA *key);
+ int open_flags; /* flags used in the open - needed by reopen */
+} TDB_CONTEXT;
+
+typedef int (*tdb_traverse_func)(TDB_CONTEXT *, TDB_DATA, TDB_DATA, void *);
+typedef void (*tdb_log_func)(TDB_CONTEXT *, int , const char *, ...);
+typedef u32 (*tdb_hash_func)(TDB_DATA *key);
+
+TDB_CONTEXT *tdb_open(const char *name, int hash_size, int tdb_flags,
+ int open_flags, mode_t mode);
+TDB_CONTEXT *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
+ int open_flags, mode_t mode,
+ tdb_log_func log_fn,
+ tdb_hash_func hash_fn);
+
+int tdb_reopen(TDB_CONTEXT *tdb);
+int tdb_reopen_all(void);
+void tdb_logging_function(TDB_CONTEXT *tdb, tdb_log_func);
+enum TDB_ERROR tdb_error(TDB_CONTEXT *tdb);
+const char *tdb_errorstr(TDB_CONTEXT *tdb);
+TDB_DATA tdb_fetch(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_delete(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_store(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, int flag);
+int tdb_append(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA new_dbuf);
+int tdb_close(TDB_CONTEXT *tdb);
+TDB_DATA tdb_firstkey(TDB_CONTEXT *tdb);
+TDB_DATA tdb_nextkey(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_traverse(TDB_CONTEXT *tdb, tdb_traverse_func fn, void *);
+int tdb_exists(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_lockall(TDB_CONTEXT *tdb);
+void tdb_unlockall(TDB_CONTEXT *tdb);
+
+/* Low level locking functions: use with care */
+int tdb_chainlock(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_chainunlock(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_chainlock_read(TDB_CONTEXT *tdb, TDB_DATA key);
+int tdb_chainunlock_read(TDB_CONTEXT *tdb, TDB_DATA key);
+TDB_CONTEXT *tdb_copy(TDB_CONTEXT *tdb, const char *outfile);
+
+/* Debug functions. Not used in production. */
+void tdb_dump_all(TDB_CONTEXT *tdb);
+int tdb_printfreelist(TDB_CONTEXT *tdb);
+
+extern TDB_DATA tdb_null;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* tdb.h */
diff -r 6aef7d1062bb -r 76af1a1df67c tools/xenstore/xs_tdb_dump.c
--- /dev/null Fri Sep 23 13:24:58 2005
+++ b/tools/xenstore/xs_tdb_dump.c Fri Sep 23 13:25:01 2005
@@ -0,0 +1,81 @@
+/* Simple program to dump out all records of TDB */
+#include <stdint.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <stdio.h>
+
+#include "xs_lib.h"
+#include "tdb.h"
+#include "talloc.h"
+#include "utils.h"
+
+struct record_hdr {
+ u32 num_perms;
+ u32 datalen;
+ u32 childlen;
+ struct xs_permissions perms[0];
+};
+
+static u32 total_size(struct record_hdr *hdr)
+{
+ return sizeof(*hdr) + hdr->num_perms * sizeof(struct xs_permissions)
+ + hdr->datalen + hdr->childlen;
+}
+
+static char perm_to_char(enum xs_perm_type perm)
+{
+ return perm == XS_PERM_READ ? 'r' :
+ perm == XS_PERM_WRITE ? 'w' :
+ perm == XS_PERM_NONE ? '-' :
+ perm == (XS_PERM_READ|XS_PERM_WRITE) ? 'b' :
+ '?';
+}
+
+int main(int argc, char *argv[])
+{
+ TDB_DATA key;
+ TDB_CONTEXT *tdb;
+
+ if (argc != 2)
+ barf("Usage: xs_tdb_dump <tdbfile>");
+
+ tdb = tdb_open(talloc_strdup(NULL, argv[1]), 0, 0, O_RDONLY, 0);
+ if (!tdb)
+ barf_perror("Could not open %s", argv[1]);
+
+ key = tdb_firstkey(tdb);
+ while (key.dptr) {
+ TDB_DATA data;
+ struct record_hdr *hdr;
+
+ data = tdb_fetch(tdb, key);
+ hdr = (void *)data.dptr;
+ if (data.dsize < sizeof(*hdr))
+ fprintf(stderr, "%.*s: BAD truncated\n",
+ key.dsize, key.dptr);
+ else if (data.dsize != total_size(hdr))
+ fprintf(stderr, "%.*s: BAD length %i for %i/%i/%i
(%i)\n",
+ key.dsize, key.dptr, data.dsize,
+ hdr->num_perms, hdr->datalen,
+ hdr->childlen, total_size(hdr));
+ else {
+ unsigned int i;
+ char *p;
+
+ printf("%.*s: ", key.dsize, key.dptr);
+ for (i = 0; i < hdr->num_perms; i++)
+ printf("%s%c%i",
+ i == 0 ? "" : ",",
+ perm_to_char(hdr->perms[i].perms),
+ hdr->perms[i].id);
+ p = (void *)&hdr->perms[hdr->num_perms];
+ printf(" %.*s\n", hdr->datalen, p);
+ p += hdr->datalen;
+ for (i = 0; i < hdr->childlen; i += strlen(p+i)+1)
+ printf("\t-> %s\n", p+i);
+ }
+ key = tdb_nextkey(tdb, key);
+ }
+ return 0;
+}
+
_______________________________________________
Xen-changelog mailing list
Xen-changelog@xxxxxxxxxxxxxxxxxxx
http://lists.xensource.com/xen-changelog
|