2 * Copyright (C) 2009-2010 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
34 #include <sys/select.h>
38 #include <rpc/types.h>
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
49 #ifdef HAVE_SYS_WAIT_H
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
65 #include "glthread/lock.h"
66 #include "ignore-value.h"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
73 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
74 static int qemu_supports (guestfs_h *g, const char *option);
76 /* Add a string to the current command line. */
78 incr_cmdline_size (guestfs_h *g)
80 if (g->cmdline == NULL) {
81 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
83 g->cmdline = safe_malloc (g, sizeof (char *));
88 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
92 add_cmdline (guestfs_h *g, const char *str)
94 if (g->state != CONFIG) {
96 _("command line cannot be altered after qemu subprocess launched"));
100 incr_cmdline_size (g);
101 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
106 guestfs__config (guestfs_h *g,
107 const char *qemu_param, const char *qemu_value)
109 if (qemu_param[0] != '-') {
110 error (g, _("guestfs_config: parameter must begin with '-' character"));
114 /* A bit fascist, but the user will probably break the extra
115 * parameters that we add if they try to set any of these.
117 if (STREQ (qemu_param, "-kernel") ||
118 STREQ (qemu_param, "-initrd") ||
119 STREQ (qemu_param, "-nographic") ||
120 STREQ (qemu_param, "-serial") ||
121 STREQ (qemu_param, "-full-screen") ||
122 STREQ (qemu_param, "-std-vga") ||
123 STREQ (qemu_param, "-vnc")) {
124 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
128 if (add_cmdline (g, qemu_param) != 0) return -1;
130 if (qemu_value != NULL) {
131 if (add_cmdline (g, qemu_value) != 0) return -1;
138 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
139 const char *drive_if)
141 size_t len = strlen (filename) + 64;
144 if (strchr (filename, ',') != NULL) {
145 error (g, _("filename cannot contain ',' (comma) character"));
149 /* cache=off improves reliability in the event of a host crash.
151 * However this option causes qemu to try to open the file with
152 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
153 * So we check if we can open the file with or without O_DIRECT,
154 * and use cache=off (or not) accordingly.
156 * This test also checks for the presence of the file, which
157 * is a documented semantic of this interface.
159 int fd = open (filename, O_RDONLY|O_DIRECT);
162 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
164 fd = open (filename, O_RDONLY);
167 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
169 perrorf (g, "%s", filename);
174 return guestfs__config (g, "-drive", buf);
178 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
179 const char *drive_if)
181 if (strchr (filename, ',') != NULL) {
182 error (g, _("filename cannot contain ',' (comma) character"));
186 if (access (filename, F_OK) == -1) {
187 perrorf (g, "%s", filename);
191 size_t len = strlen (filename) + 64;
194 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
196 return guestfs__config (g, "-drive", buf);
200 guestfs__add_drive (guestfs_h *g, const char *filename)
202 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
206 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
208 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
212 guestfs__add_cdrom (guestfs_h *g, const char *filename)
214 if (strchr (filename, ',') != NULL) {
215 error (g, _("filename cannot contain ',' (comma) character"));
219 if (access (filename, F_OK) == -1) {
220 perrorf (g, "%s", filename);
224 return guestfs__config (g, "-cdrom", filename);
227 /* Returns true iff file is contained in dir. */
229 dir_contains_file (const char *dir, const char *file)
231 int dirlen = strlen (dir);
232 int filelen = strlen (file);
233 int len = dirlen+filelen+2;
236 snprintf (path, len, "%s/%s", dir, file);
237 return access (path, F_OK) == 0;
240 /* Returns true iff every listed file is contained in 'dir'. */
242 dir_contains_files (const char *dir, ...)
247 va_start (args, dir);
248 while ((file = va_arg (args, const char *)) != NULL) {
249 if (!dir_contains_file (dir, file)) {
258 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
259 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
260 static int is_openable (guestfs_h *g, const char *path, int flags);
261 static void print_cmdline (guestfs_h *g);
263 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
264 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
267 guestfs__launch (guestfs_h *g)
270 char dir_template[PATH_MAX];
275 char *path, *pelem, *pend;
276 char *kernel = NULL, *initrd = NULL;
277 int null_vmchannel_sock;
279 struct sockaddr_un addr;
283 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
287 if (g->state != CONFIG) {
288 error (g, _("the libguestfs handle has already been launched"));
292 /* Start the clock ... */
293 gettimeofday (&g->launch_t, NULL);
295 /* Make the temporary directory. */
302 tmpdir = getenv ("TMPDIR") ? : tmpdir;
303 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
306 g->tmpdir = safe_strdup (g, dir_template);
307 if (mkdtemp (g->tmpdir) == NULL) {
308 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
313 /* Allow anyone to read the temporary directory. There are no
314 * secrets in the kernel or initrd files. The socket in this
315 * directory won't be readable but anyone can see it exists if they
316 * want. (RHBZ#610880).
318 if (chmod (g->tmpdir, 0755) == -1)
319 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
321 /* First search g->path for the supermin appliance, and try to
322 * synthesize a kernel and initrd from that. If it fails, we
323 * try the path search again looking for a backup ordinary
326 pelem = path = safe_strdup (g, g->path);
328 pend = strchrnul (pelem, ':');
329 pmore = *pend == ':';
333 /* Empty element of "." means cwd. */
334 if (len == 0 || (len == 1 && *pelem == '.')) {
337 "looking for supermin appliance in current directory\n");
338 if (dir_contains_files (".",
339 "supermin.d", "kmod.whitelist", NULL)) {
340 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
345 /* Look at <path>/supermin* etc. */
348 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
350 if (dir_contains_files (pelem,
351 "supermin.d", "kmod.whitelist", NULL)) {
352 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
363 if (kernel == NULL || initrd == NULL) {
364 /* Search g->path for the kernel and initrd. */
365 pelem = path = safe_strdup (g, g->path);
367 pend = strchrnul (pelem, ':');
368 pmore = *pend == ':';
372 /* Empty element or "." means cwd. */
373 if (len == 0 || (len == 1 && *pelem == '.')) {
376 "looking for appliance in current directory\n");
377 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
378 kernel = safe_strdup (g, kernel_name);
379 initrd = safe_strdup (g, initrd_name);
383 /* Look at <path>/kernel etc. */
386 fprintf (stderr, "looking for appliance in %s\n", pelem);
388 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
389 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
390 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
391 sprintf (kernel, "%s/%s", pelem, kernel_name);
392 sprintf (initrd, "%s/%s", pelem, initrd_name);
403 if (kernel == NULL || initrd == NULL) {
404 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
405 kernel_name, initrd_name, g->path);
410 print_timestamped_message (g, "begin testing qemu features");
412 /* Get qemu help text and version. */
413 if (qemu_supports (g, NULL) == -1)
416 /* Choose which vmchannel implementation to use. */
417 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
418 /* The "null vmchannel" implementation. Requires SLIRP (user mode
419 * networking in qemu) but no other vmchannel support. The daemon
420 * will connect back to a random port number on localhost.
422 struct sockaddr_in addr;
423 socklen_t addrlen = sizeof addr;
425 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
427 perrorf (g, "socket");
430 addr.sin_family = AF_INET;
431 addr.sin_port = htons (0);
432 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
433 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
438 if (listen (g->sock, 256) == -1) {
439 perrorf (g, "listen");
443 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
444 perrorf (g, "getsockname");
448 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
449 perrorf (g, "fcntl");
453 null_vmchannel_sock = ntohs (addr.sin_port);
455 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
457 /* Using some vmchannel impl. We need to create a local Unix
458 * domain socket for qemu to use.
460 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
462 null_vmchannel_sock = 0;
466 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
473 print_timestamped_message (g, "finished testing qemu features");
487 if (r == 0) { /* Child (qemu). */
489 const char *vmchannel = NULL;
491 /* Set up the full command line. Do this in the subprocess so we
492 * don't need to worry about cleaning up.
494 g->cmdline[0] = g->qemu;
496 /* qemu sometimes needs this option to enable hardware
497 * virtualization, but some versions of 'qemu-kvm' will use KVM
498 * regardless (even where this option appears in the help text).
499 * It is rumoured that there are versions of qemu where supplying
500 * this option when hardware virtualization is not available will
501 * cause qemu to fail, so we we have to check at least that
502 * /dev/kvm is openable. That's not reliable, since /dev/kvm
503 * might be openable by qemu but not by us (think: SELinux) in
504 * which case the user would not get hardware virtualization,
505 * although at least shouldn't fail. A giant clusterfuck with the
506 * qemu command line, again.
508 if (qemu_supports (g, "-enable-kvm") &&
509 is_openable (g, "/dev/kvm", O_RDWR))
510 add_cmdline (g, "-enable-kvm");
512 /* Newer versions of qemu (from around 2009/12) changed the
513 * behaviour of monitors so that an implicit '-monitor stdio' is
514 * assumed if we are in -nographic mode and there is no other
515 * -monitor option. Only a single stdio device is allowed, so
516 * this broke the '-serial stdio' option. There is a new flag
517 * called -nodefaults which gets rid of all this default crud, so
518 * let's use that to avoid this and any future surprises.
520 if (qemu_supports (g, "-nodefaults"))
521 add_cmdline (g, "-nodefaults");
523 add_cmdline (g, "-nographic");
524 add_cmdline (g, "-serial");
525 add_cmdline (g, "stdio");
527 snprintf (buf, sizeof buf, "%d", g->memsize);
528 add_cmdline (g, "-m");
529 add_cmdline (g, buf);
531 /* Force exit instead of reboot on panic */
532 add_cmdline (g, "-no-reboot");
534 /* These options recommended by KVM developers to improve reliability. */
535 if (qemu_supports (g, "-no-hpet"))
536 add_cmdline (g, "-no-hpet");
538 if (qemu_supports (g, "-rtc-td-hack"))
539 add_cmdline (g, "-rtc-td-hack");
541 /* If qemu has SLIRP (user mode network) enabled then we can get
542 * away with "no vmchannel", where we just connect back to a random
545 if (null_vmchannel_sock) {
546 add_cmdline (g, "-net");
547 add_cmdline (g, "user,vlan=0,net=" NETWORK);
549 snprintf (buf, sizeof buf,
550 "guestfs_vmchannel=tcp:" ROUTER ":%d",
551 null_vmchannel_sock);
552 vmchannel = strdup (buf);
555 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
557 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
559 * The original suggested format doesn't work, see:
561 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
563 * However Gerd Hoffman privately suggested to me using -chardev
564 * instead, which does work.
566 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
567 snprintf (buf, sizeof buf,
568 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
570 add_cmdline (g, "-chardev");
571 add_cmdline (g, buf);
573 snprintf (buf, sizeof buf,
574 "user,vlan=0,net=" NETWORK ","
575 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
576 "-chardev:guestfsvmc");
578 add_cmdline (g, "-net");
579 add_cmdline (g, buf);
581 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
584 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
585 * syntax, or if not then we'll get a quick failure.
588 snprintf (buf, sizeof buf,
589 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
591 add_cmdline (g, "-net");
592 add_cmdline (g, buf);
593 add_cmdline (g, "-net");
594 add_cmdline (g, "user,vlan=0,net=" NETWORK);
596 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
598 add_cmdline (g, "-net");
599 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
601 #define LINUX_CMDLINE \
602 "panic=1 " /* force kernel to panic if daemon exits */ \
603 "console=ttyS0 " /* serial console */ \
604 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
605 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
606 "acpi=off " /* we don't need ACPI, turn it off */ \
607 "printk.time=1 " /* display timestamp before kernel messages */ \
608 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
610 /* Linux kernel command line. */
611 snprintf (buf, sizeof buf,
613 "%s " /* (selinux) */
614 "%s " /* (vmchannel) */
615 "%s " /* (verbose) */
616 "TERM=%s " /* (TERM environment variable) */
618 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
619 vmchannel ? vmchannel : "",
620 g->verbose ? "guestfs_verbose=1" : "",
621 getenv ("TERM") ? : "linux",
622 g->append ? g->append : "");
624 add_cmdline (g, "-kernel");
625 add_cmdline (g, (char *) kernel);
626 add_cmdline (g, "-initrd");
627 add_cmdline (g, (char *) initrd);
628 add_cmdline (g, "-append");
629 add_cmdline (g, buf);
631 /* Finish off the command line. */
632 incr_cmdline_size (g);
633 g->cmdline[g->cmdline_size-1] = NULL;
639 /* Set up stdin, stdout. */
645 if (dup (wfd[0]) == -1) {
647 perror ("dup failed");
648 _exit (EXIT_FAILURE);
650 if (dup (rfd[1]) == -1)
658 /* Set up a new process group, so we can signal this process
659 * and all subprocesses (eg. if qemu is really a shell script).
664 setenv ("LC_ALL", "C", 1);
666 execv (g->qemu, g->cmdline); /* Run qemu. */
668 _exit (EXIT_FAILURE);
671 /* Parent (library). */
679 /* Fork the recovery process off which will kill qemu if the parent
680 * process fails to do so (eg. if the parent segfaults).
683 if (g->recovery_proc) {
686 pid_t qemu_pid = g->pid;
687 pid_t parent_pid = getppid ();
689 /* Writing to argv is hideously complicated and error prone. See:
690 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
693 /* Loop around waiting for one or both of the other processes to
694 * disappear. It's fair to say this is very hairy. The PIDs that
695 * we are looking at might be reused by another process. We are
696 * effectively polling. Is the cure worse than the disease?
699 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
700 _exit (EXIT_SUCCESS);
701 if (kill (parent_pid, 0) == -1) {
702 /* Parent's gone away, qemu still around, so kill qemu. */
704 _exit (EXIT_SUCCESS);
710 /* Don't worry, if the fork failed, this will be -1. The recovery
711 * process isn't essential.
717 /* Close the other ends of the pipe. */
721 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
722 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
723 perrorf (g, "fcntl");
727 g->fd[0] = wfd[1]; /* stdin of child */
728 g->fd[1] = rfd[0]; /* stdout of child */
730 g->fd[0] = open ("/dev/null", O_RDWR);
731 if (g->fd[0] == -1) {
732 perrorf (g, "open /dev/null");
735 g->fd[1] = dup (g->fd[0]);
736 if (g->fd[1] == -1) {
743 if (null_vmchannel_sock) {
747 /* Null vmchannel implementation: We listen on g->sock for a
748 * connection. The connection could come from any local process
749 * so we must check it comes from the appliance (or at least
750 * from our UID) for security reasons.
753 sock = guestfs__accept_from_daemon (g);
757 if (check_peer_euid (g, sock, &uid) == -1)
759 if (uid != geteuid ()) {
761 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
762 uid, null_vmchannel_sock);
769 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
770 perrorf (g, "fcntl");
777 /* Other vmchannel. Open the Unix socket.
779 * The vmchannel implementation that got merged with qemu sucks in
780 * a number of ways. Both ends do connect(2), which means that no
781 * one knows what, if anything, is connected to the other end, or
782 * if it becomes disconnected. Even worse, we have to wait some
783 * indeterminate time for qemu to create the socket and connect to
784 * it (which happens very early in qemu's start-up), so any code
785 * that uses vmchannel is inherently racy. Hence this silly loop.
787 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
789 perrorf (g, "socket");
793 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
794 perrorf (g, "fcntl");
798 addr.sun_family = AF_UNIX;
799 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
800 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
803 /* Always sleep at least once to give qemu a small chance to start up. */
806 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
807 if ((r == -1 && errno == EINPROGRESS) || r == 0)
811 perrorf (g, "connect");
816 error (g, _("failed to connect to vmchannel socket"));
822 g->state = LAUNCHING;
824 /* Wait for qemu to start and to connect back to us via vmchannel and
825 * send the GUESTFS_LAUNCH_FLAG message.
829 r = guestfs__recv_from_daemon (g, &size, &buf);
832 if (r == -1) return -1;
834 if (size != GUESTFS_LAUNCH_FLAG) {
835 error (g, _("guestfs_launch failed, see earlier error messages"));
840 print_timestamped_message (g, "appliance is up");
842 /* This is possible in some really strange situations, such as
843 * guestfsd starts up OK but then qemu immediately exits. Check for
844 * it because the caller is probably expecting to be able to send
845 * commands after this function returns.
847 if (g->state != READY) {
848 error (g, _("qemu launched and contacted daemon, but state != READY"));
859 if (g->pid > 0) kill (g->pid, 9);
860 if (g->recoverypid > 0) kill (g->recoverypid, 9);
861 waitpid (g->pid, NULL, 0);
862 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
867 memset (&g->launch_t, 0, sizeof g->launch_t);
880 /* This function is used to print the qemu command line before it gets
881 * executed, when in verbose mode.
884 print_cmdline (guestfs_h *g)
889 while (g->cmdline[i]) {
890 if (g->cmdline[i][0] == '-') /* -option starts a new line */
891 fprintf (stderr, " \\\n ");
893 if (i > 0) fputc (' ', stderr);
895 /* Does it need shell quoting? This only deals with simple cases. */
896 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
898 if (needs_quote) fputc ('\'', stderr);
899 fprintf (stderr, "%s", g->cmdline[i]);
900 if (needs_quote) fputc ('\'', stderr);
904 fputc ('\n', stderr);
907 /* This function does the hard work of building the supermin appliance
908 * on the fly. 'path' is the directory containing the control files.
909 * 'kernel' and 'initrd' are where we will return the names of the
910 * kernel and initrd (only initrd is built). The work is done by
911 * an external script. We just tell it where to put the result.
914 build_supermin_appliance (guestfs_h *g, const char *path,
915 char **kernel, char **initrd)
921 print_timestamped_message (g, "begin building supermin appliance");
923 len = strlen (g->tmpdir);
924 *kernel = safe_malloc (g, len + 8);
925 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
926 *initrd = safe_malloc (g, len + 8);
927 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
929 /* Set a sensible umask in the subprocess, so kernel and initrd
930 * output files are world-readable (RHBZ#610880).
932 snprintf (cmd, sizeof cmd,
934 "febootstrap-supermin-helper%s "
935 "-k '%s/kmod.whitelist' "
939 g->verbose ? " --verbose" : "",
944 print_timestamped_message (g, "%s", cmd);
947 if (r == -1 || WEXITSTATUS(r) != 0) {
948 error (g, _("external command failed: %s"), cmd);
951 *kernel = *initrd = NULL;
956 print_timestamped_message (g, "finished building supermin appliance");
961 /* Compute Y - X and return the result in milliseconds.
962 * Approximately the same as this code:
963 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
966 timeval_diff (const struct timeval *x, const struct timeval *y)
970 msec = (y->tv_sec - x->tv_sec) * 1000;
971 msec += (y->tv_usec - x->tv_usec) / 1000;
976 print_timestamped_message (guestfs_h *g, const char *fs, ...)
984 err = vasprintf (&msg, fs, args);
989 gettimeofday (&tv, NULL);
991 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
992 timeval_diff (&g->launch_t, &tv), msg);
997 static int read_all (guestfs_h *g, FILE *fp, char **ret);
999 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1000 * 'qemu -version' so we know what options this qemu supports and
1004 test_qemu (guestfs_h *g)
1009 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1011 fp = popen (cmd, "r");
1012 /* qemu -help should always work (qemu -version OTOH wasn't
1013 * supported by qemu 0.9). If this command doesn't work then it
1014 * probably indicates that the qemu binary is missing.
1017 /* XXX This error is never printed, even if the qemu binary
1018 * doesn't exist. Why?
1021 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1025 if (read_all (g, fp, &g->qemu_help) == -1)
1028 if (pclose (fp) == -1)
1031 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1034 fp = popen (cmd, "r");
1036 /* Intentionally ignore errors. */
1037 read_all (g, fp, &g->qemu_version);
1045 read_all (guestfs_h *g, FILE *fp, char **ret)
1052 *ret = safe_realloc (g, *ret, n + 1);
1057 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1059 r = fread (p, 1, BUFSIZ, fp);
1061 perrorf (g, "read");
1068 /* Test if option is supported by qemu command line (just by grepping
1071 * The first time this is used, it has to run the external qemu
1072 * binary. If that fails, it returns -1.
1074 * To just do the first-time run of the qemu binary, call this with
1075 * option == NULL, in which case it will return -1 if there was an
1079 qemu_supports (guestfs_h *g, const char *option)
1081 if (!g->qemu_help) {
1082 if (test_qemu (g) == -1)
1089 return strstr (g->qemu_help, option) != NULL;
1092 /* Check if a file can be opened. */
1094 is_openable (guestfs_h *g, const char *path, int flags)
1096 int fd = open (path, flags);
1106 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1107 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1108 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1111 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1113 #if CAN_CHECK_PEER_EUID
1114 struct sockaddr_in peer;
1115 socklen_t addrlen = sizeof peer;
1117 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1118 perrorf (g, "getpeername");
1122 if (peer.sin_family != AF_INET ||
1123 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1124 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1125 peer.sin_family, inet_ntoa (peer.sin_addr));
1129 struct sockaddr_in our;
1130 addrlen = sizeof our;
1131 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1132 perrorf (g, "getsockname");
1136 FILE *fp = fopen ("/proc/net/tcp", "r");
1138 perrorf (g, "/proc/net/tcp");
1143 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1144 error (g, "unexpected end of file in /proc/net/tcp");
1149 while (fgets (line, sizeof line, fp) != NULL) {
1150 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1151 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1154 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1156 &line_our_addr, &line_our_port,
1157 &line_peer_addr, &line_peer_port,
1158 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1160 /* Note about /proc/net/tcp: local_address and rem_address are
1161 * always in network byte order. However the port part is
1162 * always in host byte order.
1164 * The sockname and peername that we got above are in network
1165 * byte order. So we have to byte swap the port but not the
1168 if (line_our_addr == our.sin_addr.s_addr &&
1169 line_our_port == ntohs (our.sin_port) &&
1170 line_peer_addr == peer.sin_addr.s_addr &&
1171 line_peer_port == ntohs (peer.sin_port)) {
1179 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1182 #else /* !CAN_CHECK_PEER_EUID */
1183 /* This function exists but should never be called in this
1187 #endif /* !CAN_CHECK_PEER_EUID */
1190 /* You had to call this function after launch in versions <= 1.0.70,
1191 * but it is now a no-op.
1194 guestfs__wait_ready (guestfs_h *g)
1196 if (g->state != READY) {
1197 error (g, _("qemu has not been launched yet"));
1205 guestfs__kill_subprocess (guestfs_h *g)
1207 if (g->state == CONFIG) {
1208 error (g, _("no subprocess to kill"));
1213 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1215 if (g->pid > 0) kill (g->pid, SIGTERM);
1216 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1221 /* Access current state. */
1223 guestfs__is_config (guestfs_h *g)
1225 return g->state == CONFIG;
1229 guestfs__is_launching (guestfs_h *g)
1231 return g->state == LAUNCHING;
1235 guestfs__is_ready (guestfs_h *g)
1237 return g->state == READY;
1241 guestfs__is_busy (guestfs_h *g)
1243 return g->state == BUSY;
1247 guestfs__get_state (guestfs_h *g)