From a0d3bce827ca656fb5d8f462bb6786f9567dddfa Mon Sep 17 00:00:00 2001
From: Juergen Gross <jgross@suse.com>
Date: Tue, 13 Sep 2022 07:35:09 +0200
Subject: tools/xenstore: move the call of setup_structure() to dom0
 introduction

Setting up the basic structure when introducing dom0 has the advantage
to be able to add proper node memory accounting for the added nodes
later.

This makes it possible to do proper node accounting, too.

An additional requirement to make that work fine is to correct the
owner of the created nodes to be dom0_domid instead of domid 0.

This is part of XSA-326.

Reported-by: Julien Grall <jgrall@amazon.com>
Signed-off-by: Juergen Gross <jgross@suse.com>
Acked-by: Julien Grall <jgrall@amazon.com>

diff --git a/tools/xenstore/xenstored_core.c b/tools/xenstore/xenstored_core.c
index 57c9991292..1335051a53 100644
--- a/tools/xenstore/xenstored_core.c
+++ b/tools/xenstore/xenstored_core.c
@@ -1832,7 +1832,8 @@ static int tdb_flags;
 static void manual_node(const char *name, const char *child)
 {
 	struct node *node;
-	struct xs_permissions perms = { .id = 0, .perms = XS_PERM_NONE };
+	struct xs_permissions perms = { .id = dom0_domid,
+					.perms = XS_PERM_NONE };
 
 	node = talloc_zero(NULL, struct node);
 	if (!node)
@@ -1871,7 +1872,7 @@ static void tdb_logger(TDB_CONTEXT *tdb, int level, const char * fmt, ...)
 	}
 }
 
-static void setup_structure(void)
+void setup_structure(void)
 {
 	char *tdbname;
 	tdbname = talloc_strdup(talloc_autofree_context(), xs_daemon_tdb());
@@ -1889,6 +1890,7 @@ static void setup_structure(void)
 	manual_node("/", "tool");
 	manual_node("/tool", "xenstored");
 	manual_node("/tool/xenstored", NULL);
+	domain_entry_fix(dom0_domid, 3, true);
 
 	check_store();
 }
@@ -2402,9 +2404,6 @@ int main(int argc, char *argv[])
 
 	init_pipe(reopen_log_pipe);
 
-	/* Setup the database */
-	setup_structure();
-
 	/* Listen to hypervisor. */
 	if (!no_domain_init)
 		domain_init();
diff --git a/tools/xenstore/xenstored_core.h b/tools/xenstore/xenstored_core.h
index 7e371253d2..d95e4262a9 100644
--- a/tools/xenstore/xenstored_core.h
+++ b/tools/xenstore/xenstored_core.h
@@ -195,6 +195,7 @@ int write_node_raw(struct connection *conn, TDB_DATA *key, struct node *node,
 struct node *read_node(struct connection *conn, const void *ctx,
 		       const char *name);
 
+void setup_structure(void);
 struct connection *new_connection(connwritefn_t *write, connreadfn_t *read);
 void check_store(void);
 void corrupt(struct connection *conn, const char *fmt, ...);
diff --git a/tools/xenstore/xenstored_domain.c b/tools/xenstore/xenstored_domain.c
index f4134db3e7..8bf9db2d96 100644
--- a/tools/xenstore/xenstored_domain.c
+++ b/tools/xenstore/xenstored_domain.c
@@ -739,6 +739,8 @@ static int dom0_init(void)
 	if (dom0->interface == NULL)
 		return -1;
 
+	setup_structure();
+
 	talloc_steal(dom0->conn, dom0); 
 
 	xenevtchn_notify(xce_handle, dom0->port);
-- 
2.35.3

