Skip to contentSkip to conversation

host->guest environment variables via fw_cfg

RFC PATCH In review Gabriel L. Somlo 5 participants 10 messages Feb 24, 2015 – Feb 26, 2015

lore
Share & tools
lore
#0 lore raw

cover host->guest environment variables via fw_cfg

Following up on a conversation I started a few weeks ago, regarding the ability to pass "environment variables" into a guest from the host, via the qemu command line, and without further requirements for guest- or host-initiated synchronization at a later time, after the act of firing up the guest.

I remember we had discussed SMBIOS as one of the options for "transport" of environment data; but then I thought that's still not "out-of-band" enough for my taste. Seeing how SMBIOS is passed in via fw_cfg, I thought the latter would be the perfect OOB transport mechanism for this type of data. Except instead of being consumed by the BIOS on the booting guest, the actual guest OS can read the data from fw_cfg directly.

So, I added a -guestenv qemu command line option on the host side (1/2) which results in the creation of a fw_cfg blob named "etc/guestenv", and added --getenv to qga on the guest side (2/2), to query fw_cfg and return the value of such an environment variable, if available.

Right now it's only used with i386, but there's no reason why it couldn't work with any guest type that uses fw_cfg.

Currently it's pretty bare bones (e.g. I'm not checking for duplicate keys on the host side, in fact I'm not even checking whether there's an '=' character present in each -guestenv argument). I just wanted to get something out there for folks to look at, and get feedback on whether this might be of interest.

The most important aspect of this feature is its asynchronous nature, i.e. we can pass data into the guest without having to bring up a subsequent connection (host->guest or guest-host) at a later time, with all the failure-mode handling and coordination that would entail.

A couple of extra random thoughts:

On the host side, it might be interesting/useful to allow a random file to be inserted into fw_cfg with a given fw_cfg name (something like "-fwcfgblob name=foo,file=./bar"), where ./bar could be anything, even a shell script or a text file with key=value pairs :)

On the guest side, I think it might be cool to write a device driver for fw_cfg, something that would allow reading fw_cfg blobs via /sys/firmware/fw_cfg/... I think just reading the fw_cfg data port as root is more portable (userspace code shipping with qga vs. kernel device driver), which is why I haven't started coding on this already :) Not to mention I don't know where I'd start with the equivalent driver for Windows :)

Anyhow, please let me know what you all think, and how it could be made more compelling to the qemu community at large.

Thanks,
--Gabriel

Gabriel L. Somlo (2):
fw_cfg: Add -guestenv qemu command line option
qga: add --getenv option to get env. vars from fw_cfg

 hw/i386/pc.c            |   4 ++
 include/sysemu/sysemu.h |   3 ++
 qemu-options.hx         |   9 ++++
 qga/Makefile.objs       |   1 +
 qga/getenv.c            | 140 ++++++++++++++++++++++++++++++++++++++++++++++++
 qga/guest-agent-core.h  |   2 +
 qga/main.c              |   7 ++-
 vl.c                    |  14 +++++
 8 files changed, 179 insertions(+), 1 deletion(-)
 create mode 100644 qga/getenv.c
Signature · 1 line
2.1.0
#1 lore raw

RFC PATCH 1/2 fw_cfg: Add -guestenv qemu command line option

Introduce "-guestenv" command line option, which allows passing of environment variables to the guest in a "fire-and-forget", asynchronous way. The guest may retrieve this data at its convenience, by accessing the provided fw_cfg device from the inside.

The new "etc/guestenv" blob will be a set of concatenated null-terminated ascii strings: "key1=val1\0key2=val2\0...\0keyN=valN\0", each string being added by its own separate "-guestenv <line>" command line argument to qemu.

I'm currently not checking for the presence of an '=' character in each entry, nor am I currently checking for duplicate keys.

Right now, I'm only inserting the new fw_cfg file from i386/pc.c, since this is a proof-of-concept/RFC, but this should work easily on any platform on which fw_cfg is supported.

---
 hw/i386/pc.c            |  4 ++++
 include/sysemu/sysemu.h |  3 +++
 qemu-options.hx         |  9 +++++++++
 vl.c                    | 14 ++++++++++++++
 4 files changed, 30 insertions(+)
hw/i386/pc.c +4 -0
index c7af6aa..4133b21 100644
@@ -715,6 +715,10 @@ static FWCfgState *bochs_bios_init(void)
                      (1 + apic_id_limit + nb_numa_nodes) *
                      sizeof(*numa_fw_cfg));
 
+    if (guestenv) {
+        fw_cfg_add_file(fw_cfg, "etc/guestenv", guestenv, guestenv_len);
+    }
+
     return fw_cfg;
 }
 
include/sysemu/sysemu.h +3 -0
index 748d059..fd00266 100644
@@ -14,6 +14,9 @@
 
 /* vl.c */
 
+extern char *guestenv;
+extern int guestenv_len;
+
 extern const char *bios_name;
 
 extern const char *qemu_name;
qemu-options.hx +9 -0
index ee4b223..b9d5565 100644
@@ -2646,6 +2646,15 @@ STEXI
 @table @option
 ETEXI
 
+DEF("guestenv", HAS_ARG, QEMU_OPTION_guestenv, \
+    "-guestenv entry add 'entry' to environment passed to guest\n",
+    QEMU_ARCH_ALL)
+STEXI
+@item -guestenv @var{entry}
+@findex -guestenv
+Add @var{entry} to environment passed to guest
+ETEXI
+
 DEF("serial", HAS_ARG, QEMU_OPTION_serial, \
     "-serial dev     redirect the serial port to char device 'dev'\n",
     QEMU_ARCH_ALL)
vl.c +14 -0
index 8c8f142..a94dcb5 100644
@@ -187,6 +187,9 @@ int nb_numa_nodes;
 int max_numa_nodeid;
 NodeInfo numa_info[MAX_NODES];
 
+char *guestenv;
+int guestenv_len;
+
 /* The bytes in qemu_uuid[] are in the order specified by RFC4122, _not_ in the
  * little-endian "wire format" described in the SMBIOS 2.6 specification.
  */
@@ -2249,6 +2252,14 @@ struct device_config {
 static QTAILQ_HEAD(, device_config) device_configs =
     QTAILQ_HEAD_INITIALIZER(device_configs);
 
+static void add_guestenv_entry(const char *entry)
+{
+    int entry_len = strlen(entry) + 1;
+    guestenv = g_realloc(guestenv, guestenv_len + entry_len);
+    strcpy(guestenv + guestenv_len, entry);
+    guestenv_len += entry_len;
+}
+
 static void add_device_config(int type, const char *cmdline)
 {
     struct device_config *conf;
@@ -3320,6 +3331,9 @@ int main(int argc, char **argv, char **envp)
                 qemu_opt_set(device, "mount_tag", "v_synth");
                 break;
             }
+            case QEMU_OPTION_guestenv:
+                add_guestenv_entry(optarg);
+                break;
             case QEMU_OPTION_serial:
                 add_device_config(DEV_SERIAL, optarg);
                 default_serial = 0;
Signature · 1 line
2.1.0
#2 lore raw

RFC PATCH 2/2 qga: add --getenv option to get env. vars from fw_cfg

In reply to Gabriel L. Somlo

The new "-g" (or "--getenv") command line option causes qemu-ga to extract and parse the "etc/guestenv" blob from fw_cfg, and return the value of the requested key (if available) on stdout.

Warnings and error messages are printed to stderr, and only the actual value portion of a "key=value" string matching the "--getenv key" argument will be printed to stdout. Strings are searched in reverse order to implement a sort of "last dupe wins" policy -- but I expect to refine things quite a bit after receiving some feedback.

I've added a flag to qemu-ga instead of creating a completely separate binary, but I don't feel strongly about keeping it that way. I just need something that would end up tightly integrated with the "qemu guest tools" package...

I also haven't built this on cygwin yet, so it's only tested on Linux and gcc 4.9.2 (which stubbornly optimizes away one of my "true" if branches with -O2, if I let it, but that's something else I'm planning to have figured out by the time the dust settles on this :)

---
 qga/Makefile.objs      |   1 +
 qga/getenv.c           | 140 +++++++++++++++++++++++++++++++++++++++++++++++++
 qga/guest-agent-core.h |   2 +
 qga/main.c             |   7 ++-
 4 files changed, 149 insertions(+), 1 deletion(-)
 create mode 100644 qga/getenv.c
qga/Makefile.objs +1 -0
index 1c5986c..6392b93 100644
@@ -4,5 +4,6 @@ qga-obj-$(CONFIG_WIN32) += commands-win32.o channel-win32.o service-win32.o
 qga-obj-$(CONFIG_WIN32) += vss-win32.o
 qga-obj-y += qapi-generated/qga-qapi-types.o qapi-generated/qga-qapi-visit.o
 qga-obj-y += qapi-generated/qga-qmp-marshal.o
+qga-obj-y += getenv.o
 
 qga-vss-dll-obj-$(CONFIG_QGA_VSS) += vss-win32/
qga/getenv.c new file +140 -0

140 lines not on this page · raw message

qga/guest-agent-core.h +2 -0
index e92c6ab..ef54b45 100644
@@ -41,3 +41,5 @@ int64_t ga_get_fd_handle(GAState *s, Error **errp);
 #ifndef _WIN32
 void reopen_fd_to_null(int fd);
 #endif
+
+int ga_getenv(const char *key);
qga/main.c +6 -1
index 9939a2b..9159244 100644
@@ -215,6 +215,8 @@ static void usage(const char *cmd)
 #endif
 "  -b, --blacklist   comma-separated list of RPCs to disable (no spaces, \"?\"\n"
 "                    to list available RPCs)\n"
+"  -g, --getenv      display the value of a given guest environment variable\n"
+"                    (passed into the guest via the -guestenv \"name=value\" option\n"
 "  -h, --help        display this help and exit\n"
 "\n"
 "Report bugs to <[email protected]>\n"
@@ -923,7 +925,7 @@ static void ga_print_cmd(QmpCommand *cmd, void *opaque)
 
 int main(int argc, char **argv)
 {
-    const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
+    const char *sopt = "hVvdm:p:l:f:F::b:s:t:g:";
     const char *method = NULL, *path = NULL;
     const char *log_filepath = NULL;
     const char *pid_filepath;
@@ -951,6 +953,7 @@ int main(int argc, char **argv)
         { "service", 1, NULL, 's' },
 #endif
         { "statedir", 1, NULL, 't' },
+        { "getenv", 1, NULL, 'g' },
         { NULL, 0, NULL, 0 }
     };
     int opt_ind = 0, ch, daemonize = 0, i, j, len;
@@ -1042,6 +1045,8 @@ int main(int argc, char **argv)
             }
             break;
 #endif
+        case 'g':
+            return ga_getenv(optarg);
         case 'h':
             usage(argv[0]);
             return 0;
Signature · 1 line
2.1.0
#3 lore raw

Re: [Qemu-devel] [RFC PATCH 2/2] qga: add --getenv option to get env. vars from fw_cfg

Quoted 10 lines · Gabriel L. Somlo

The new "-g" (or "--getenv") command line option causes qemu-ga to extract and parse the "etc/guestenv" blob from fw_cfg, and return the value of the requested key (if available) on stdout.

Warnings and error messages are printed to stderr, and only the actual value portion of a "key=value" string matching the "--getenv key" argument will be printed to stdout. Strings are searched in reverse order to implement a sort of "last dupe wins" policy -- but I expect to refine things quite a bit after receiving some feedback.

Quoted 4 lines

I've added a flag to qemu-ga instead of creating a completely separate binary, but I don't feel strongly about keeping it that way. I just need something that would end up tightly integrated with the "qemu guest tools" package...

It should really be a separate binary. Overloading multiple functions in one binary makes it very hard to write a security policy to confine what the binary can do, as you can't get the kernel to apply different policies based on what CLI flag was passed.

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#4 lore raw
In reply to Gabriel L. Somlo
Quoted 58 lines · Gabriel L. Somlo

Following up on a conversation I started a few weeks ago, regarding the ability to pass "environment variables" into a guest from the host, via the qemu command line, and without further requirements for guest- or host-initiated synchronization at a later time, after the act of firing up the guest.

I remember we had discussed SMBIOS as one of the options for "transport" of environment data; but then I thought that's still not "out-of-band" enough for my taste. Seeing how SMBIOS is passed in via fw_cfg, I thought the latter would be the perfect OOB transport mechanism for this type of data. Except instead of being consumed by the BIOS on the booting guest, the actual guest OS can read the data from fw_cfg directly.

So, I added a -guestenv qemu command line option on the host side (1/2) which results in the creation of a fw_cfg blob named "etc/guestenv", and added --getenv to qga on the guest side (2/2), to query fw_cfg and return the value of such an environment variable, if available.

Right now it's only used with i386, but there's no reason why it couldn't work with any guest type that uses fw_cfg.

Currently it's pretty bare bones (e.g. I'm not checking for duplicate keys on the host side, in fact I'm not even checking whether there's an '=' character present in each -guestenv argument). I just wanted to get something out there for folks to look at, and get feedback on whether this might be of interest.

The most important aspect of this feature is its asynchronous nature, i.e. we can pass data into the guest without having to bring up a subsequent connection (host->guest or guest-host) at a later time, with all the failure-mode handling and coordination that would entail.

A couple of extra random thoughts:

On the host side, it might be interesting/useful to allow a random file to be inserted into fw_cfg with a given fw_cfg name (something like "-fwcfgblob name=foo,file=./bar"), where ./bar could be anything, even a shell script or a text file with key=value pairs :)

On the guest side, I think it might be cool to write a device driver for fw_cfg, something that would allow reading fw_cfg blobs via /sys/firmware/fw_cfg/... I think just reading the fw_cfg data port as root is more portable (userspace code shipping with qga vs. kernel device driver), which is why I haven't started coding on this already :) Not to mention I don't know where I'd start with the equivalent driver for Windows :)

Anyhow, please let me know what you all think, and how it could be made more compelling to the qemu community at large.

Thanks,
--Gabriel

Gabriel L. Somlo (2):
fw_cfg: Add -guestenv qemu command line option
qga: add --getenv option to get env. vars from fw_cfg

Quoted 11 lines
 hw/i386/pc.c            |   4 ++
 include/sysemu/sysemu.h |   3 ++
 qemu-options.hx         |   9 ++++
 qga/Makefile.objs       |   1 +
 qga/getenv.c            | 140 ++++++++++++++++++++++++++++++++++++++++++++++++
 qga/guest-agent-core.h  |   2 +
 qga/main.c              |   7 ++-
 vl.c                    |  14 +++++
 8 files changed, 179 insertions(+), 1 deletion(-)
 create mode 100644 qga/getenv.c

Matt Fleming was thinking about something like this, I'm CC'ing him.

Thanks
Laszlo

#5 lore raw
Quoted 2 lines · Laszlo Ersek

Matt Fleming was thinking about something like this, I'm CC'ing him.

Right, I was thinking about this in the context of configuring the BIOS (OVMF in my case) with runtime tunable knobs instead of having to recompile the BIOS image from scratch.

I'll carve out some time to review your patches Gabriel.

#6 lore raw
Quoted 6 lines · Matt Fleming

Right, I was thinking about this in the context of configuring the BIOS (OVMF in my case) with runtime tunable knobs instead of having to recompile the BIOS image from scratch.

I'll carve out some time to review your patches Gabriel.

Thanks ! Although the more I think about it, the more I like the idea of simply adding a generic named blob to fw_cfg from the host side (rather than adding a dedicated "-guestenv 'foo=bar'" option.

If I make sure the generic "-fwcfg name='blob-name',file=./blob_file" is processed *after* everything else is already inserted into fw_cfg, and that we throw an error if 'blob-name' collides with anything already added during qemu setup, there's no reason I can't pass a blob named 'etc/guest-info'.

So I'll send out a v2 attempting to do that, which should take care of both of our needs on the host side.

On the guest side, you should be taken care of -- read whatever you need to read from fw_cfg using the BIOS's existing mechanisms.

For myself, I'm tempted to write a kernel driver to allow me to simply "cat /sys/firmware/fw_cfg/etc/guestinfo | grep '^key_name='" when I need to retrieve a guest environment variable.

However, I'd first need to figure out how to do the equivalent thing on Windows, and whether the requirement to add a kernel module is worth it when my main purpose is making it easy to recycle VMWare VMs which use "vmware-tools --cmd info-get guestinfo.key_name" :)

Maybe it's better to stick with accessing the fw_cfg io ports from guest-side userspace, so patch 2/2 should stand as is (modulo Daniel's suggestion to make it a separate binary from "qemu-ga", of course).

Thanks,
--Gabriel

#7 lore raw
Quoted 11 lines · Gabriel L. Somlo
Quoted 6 lines · Matt Fleming

Right, I was thinking about this in the context of configuring the BIOS (OVMF in my case) with runtime tunable knobs instead of having to recompile the BIOS image from scratch.

I'll carve out some time to review your patches Gabriel.

Thanks ! Although the more I think about it, the more I like the idea of simply adding a generic named blob to fw_cfg from the host side (rather than adding a dedicated "-guestenv 'foo=bar'" option.

Such named blobs were exactly the idea we had with Matt when discussing this briefly on IRC.

Quoted 5 lines

If I make sure the generic "-fwcfg name='blob-name',file=./blob_file" is processed *after* everything else is already inserted into fw_cfg, and that we throw an error if 'blob-name' collides with anything already added during qemu setup,

Precisely; please do that.

Quoted 5 lines

there's no reason I can't pass a
blob named 'etc/guest-info'.

So I'll send out a v2 attempting to do that, which should take care of both of our needs on the host side.

I too can try to review that, but I definitely expect my review not to be the "last word". :)

Quoted 2 lines

On the guest side, you should be taken care of -- read whatever you need to read from fw_cfg using the BIOS's existing mechanisms.

Yup.

Quoted 5 lines

For myself, I'm tempted to write a kernel driver to allow me to simply "cat /sys/firmware/fw_cfg/etc/guestinfo | grep '^key_name='" when I need to retrieve a guest environment variable.

You might not need a kernel driver for this. If you have ioport access (on x86), you can speak the fwcfg "protocol" directly.

Quoted 7 lines

However, I'd first need to figure out how to do the equivalent thing on Windows, and whether the requirement to add a kernel module is worth it when my main purpose is making it easy to recycle VMWare VMs which use "vmware-tools --cmd info-get guestinfo.key_name" :)

Maybe it's better to stick with accessing the fw_cfg io ports from guest-side userspace,

Right; as long as you stay with x86 guests only.

Quoted 2 lines

so patch 2/2 should stand as is (modulo Daniel's suggestion to make it a separate binary from "qemu-ga", of course).

Qga already implements a number of commands with fork() + execle(), so maybe you could separate out a small, "dumb" helper binary for the ioport access.

Thanks
Laszlo

#8 lore raw
Quoted 7 lines · Laszlo Ersek
Quoted 3 lines · Gabriel L. Somlo

For myself, I'm tempted to write a kernel driver to allow me to simply "cat /sys/firmware/fw_cfg/etc/guestinfo | grep '^key_name='" when I need to retrieve a guest environment variable.

You might not need a kernel driver for this. If you have ioport access (on x86), you can speak the fwcfg "protocol" directly.

Personally, I'd be much happier to see this information exposed via /sys/firmware/fw_cfg, not least because that allows you to use the same tools on x86, arm64, etc.

#9 lore raw
In reply to Laszlo Ersek
Quoted 2 lines · Laszlo Ersek

You might not need a kernel driver for this. If you have ioport access (on x86), you can speak the fwcfg "protocol" directly.

Ta da ..

http://people.redhat.com/~rjones/ioport/

Rich.

Signature · 5 lines
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
virt-top is 'top' for virtual machines.  Tiny program with many
powerful monitoring features, net stats, disk stats, logging, etc.
http://people.redhat.com/~rjones/virt-top