2 * Copyright (C) 2009-2011 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>
35 #include <sys/types.h>
41 #include <rpc/types.h>
48 #ifdef HAVE_SYS_TYPES_H
49 #include <sys/types.h>
52 #ifdef HAVE_SYS_WAIT_H
56 #ifdef HAVE_SYS_SOCKET_H
57 #include <sys/socket.h>
64 #include <arpa/inet.h>
65 #include <netinet/in.h>
68 #include "ignore-value.h"
69 #include "glthread/lock.h"
72 #include "guestfs-internal.h"
73 #include "guestfs-internal-actions.h"
74 #include "guestfs_protocol.h"
76 static int launch_appliance (guestfs_h *g);
77 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
78 static void print_qemu_command_line (guestfs_h *g, char **argv);
79 static int connect_unix_socket (guestfs_h *g, const char *sock);
80 static int qemu_supports (guestfs_h *g, const char *option);
81 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
84 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
86 static void compile_regexps (void) __attribute__((constructor));
87 static void free_regexps (void) __attribute__((destructor));
90 compile_regexps (void)
95 #define COMPILE(re,pattern,options) \
97 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
99 ignore_value (write (2, err, strlen (err))); \
111 /* Functions to add a string to the current command line. */
113 alloc_cmdline (guestfs_h *g)
115 if (g->cmdline == NULL) {
116 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
118 g->cmdline = safe_malloc (g, sizeof (char *));
119 g->cmdline[0] = NULL;
124 incr_cmdline_size (guestfs_h *g)
128 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
132 add_cmdline (guestfs_h *g, const char *str)
134 if (g->state != CONFIG) {
136 _("command line cannot be altered after qemu subprocess launched"));
140 incr_cmdline_size (g);
141 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
146 guestfs___checkpoint_drives (guestfs_h *g)
148 struct drive **i = &g->drives;
149 while (*i != NULL) i = &((*i)->next);
154 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
156 guestfs___free_drives(i);
159 /* Internal command to return the command line. */
161 guestfs__debug_cmdline (guestfs_h *g)
168 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
169 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
171 for (i = 1; i < g->cmdline_size; ++i)
172 r[i] = safe_strdup (g, g->cmdline[i]);
174 r[g->cmdline_size] = NULL;
176 return r; /* caller frees */
179 /* Internal command to return the list of drives. */
181 guestfs__debug_drives (guestfs_h *g)
187 for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
190 ret = safe_malloc (g, sizeof (char *) * (count + 1));
192 for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
193 ret[i] = qemu_drive_param (g, drv);
197 return ret; /* caller frees */
201 guestfs__config (guestfs_h *g,
202 const char *qemu_param, const char *qemu_value)
204 if (qemu_param[0] != '-') {
205 error (g, _("guestfs_config: parameter must begin with '-' character"));
209 /* A bit fascist, but the user will probably break the extra
210 * parameters that we add if they try to set any of these.
212 if (STREQ (qemu_param, "-kernel") ||
213 STREQ (qemu_param, "-initrd") ||
214 STREQ (qemu_param, "-nographic") ||
215 STREQ (qemu_param, "-serial") ||
216 STREQ (qemu_param, "-full-screen") ||
217 STREQ (qemu_param, "-std-vga") ||
218 STREQ (qemu_param, "-vnc")) {
219 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
223 if (add_cmdline (g, qemu_param) != 0) return -1;
225 if (qemu_value != NULL) {
226 if (add_cmdline (g, qemu_value) != 0) return -1;
232 /* cache=off improves reliability in the event of a host crash.
234 * However this option causes qemu to try to open the file with
235 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
236 * So we check if we can open the file with or without O_DIRECT,
237 * and use cache=off (or not) accordingly.
239 * NB: This function is only called on the !readonly path. We must
240 * try to open with O_RDWR to test that the file is readable and
244 test_cache_off (guestfs_h *g, const char *filename)
246 int fd = open (filename, O_RDWR|O_DIRECT);
252 fd = open (filename, O_RDWR);
258 perrorf (g, "%s", filename);
262 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
264 valid_format_iface (const char *str)
266 size_t len = strlen (str);
274 if (c != '-' && c != '_' && !c_isalnum (c))
281 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
282 const struct guestfs_add_drive_opts_argv *optargs)
290 if (strchr (filename, ',') != NULL) {
291 error (g, _("filename cannot contain ',' (comma) character"));
295 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
296 ? optargs->readonly : 0;
297 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
298 ? safe_strdup (g, optargs->format) : NULL;
299 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
300 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
301 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
302 ? safe_strdup (g, optargs->name) : NULL;
304 if (format && !valid_format_iface (format)) {
305 error (g, _("%s parameter is empty or contains disallowed characters"),
309 if (!valid_format_iface (iface)) {
310 error (g, _("%s parameter is empty or contains disallowed characters"),
315 /* For writable files, see if we can use cache=off. This also
316 * checks for the existence of the file. For readonly we have
317 * to do the check explicitly.
319 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
320 if (use_cache_off == -1)
324 if (access (filename, R_OK) == -1) {
325 perrorf (g, "%s", filename);
330 struct drive **i = &(g->drives);
331 while (*i != NULL) i = &((*i)->next);
333 *i = safe_malloc (g, sizeof (struct drive));
335 (*i)->path = safe_strdup (g, filename);
336 (*i)->readonly = readonly;
337 (*i)->format = format;
340 (*i)->use_cache_off = use_cache_off;
352 guestfs__add_drive (guestfs_h *g, const char *filename)
354 struct guestfs_add_drive_opts_argv optargs = {
358 return guestfs__add_drive_opts (g, filename, &optargs);
362 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
364 struct guestfs_add_drive_opts_argv optargs = {
365 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
369 return guestfs__add_drive_opts (g, filename, &optargs);
373 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
376 struct guestfs_add_drive_opts_argv optargs = {
377 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
381 return guestfs__add_drive_opts (g, filename, &optargs);
385 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
388 struct guestfs_add_drive_opts_argv optargs = {
389 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
390 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
395 return guestfs__add_drive_opts (g, filename, &optargs);
399 guestfs__add_cdrom (guestfs_h *g, const char *filename)
401 if (strchr (filename, ',') != NULL) {
402 error (g, _("filename cannot contain ',' (comma) character"));
406 if (access (filename, F_OK) == -1) {
407 perrorf (g, "%s", filename);
411 return guestfs__config (g, "-cdrom", filename);
414 static int is_openable (guestfs_h *g, const char *path, int flags);
417 guestfs__launch (guestfs_h *g)
420 if (g->state != CONFIG) {
421 error (g, _("the libguestfs handle has already been launched"));
425 TRACE0 (launch_start);
427 /* Make the temporary directory. */
429 TMP_TEMPLATE_ON_STACK (dir_template);
430 g->tmpdir = safe_strdup (g, dir_template);
431 if (mkdtemp (g->tmpdir) == NULL) {
432 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
437 /* Allow anyone to read the temporary directory. The socket in this
438 * directory won't be readable but anyone can see it exists if they
439 * want. (RHBZ#610880).
441 if (chmod (g->tmpdir, 0755) == -1)
442 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
444 /* Launch the appliance or attach to an existing daemon. */
445 switch (g->attach_method) {
446 case ATTACH_METHOD_APPLIANCE:
447 return launch_appliance (g);
449 case ATTACH_METHOD_UNIX:
450 return connect_unix_socket (g, g->attach_method_arg);
458 launch_appliance (guestfs_h *g)
462 char guestfsd_sock[256];
463 struct sockaddr_un addr;
465 /* At present you must add drives before starting the appliance. In
466 * future when we enable hotplugging you won't need to do this.
469 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
473 /* Start the clock ... */
474 gettimeofday (&g->launch_t, NULL);
475 guestfs___launch_send_progress (g, 0);
477 TRACE0 (launch_build_appliance_start);
479 /* Locate and/or build the appliance. */
480 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
481 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
484 TRACE0 (launch_build_appliance_end);
486 guestfs___launch_send_progress (g, 3);
489 guestfs___print_timestamped_message (g, "begin testing qemu features");
491 /* Get qemu help text and version. */
492 if (qemu_supports (g, NULL) == -1)
495 /* Using virtio-serial, we need to create a local Unix domain socket
496 * for qemu to connect to.
498 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
499 unlink (guestfsd_sock);
501 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
503 perrorf (g, "socket");
507 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
508 perrorf (g, "fcntl");
512 addr.sun_family = AF_UNIX;
513 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
514 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
516 if (bind (g->sock, &addr, sizeof addr) == -1) {
521 if (listen (g->sock, 1) == -1) {
522 perrorf (g, "listen");
527 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
534 guestfs___print_timestamped_message (g, "finished testing qemu features");
548 if (r == 0) { /* Child (qemu). */
551 /* Set up the full command line. Do this in the subprocess so we
552 * don't need to worry about cleaning up.
555 /* Set g->cmdline[0] to the name of the qemu process. However
556 * it is possible that no g->cmdline has been allocated yet so
557 * we must do that first.
560 g->cmdline[0] = g->qemu;
562 /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
563 * devices. The -global option must exist, but you can pass any
564 * strings to it so we don't need to check for the specific virtio
567 if (qemu_supports (g, "-global")) {
568 add_cmdline (g, "-global");
569 add_cmdline (g, "virtio-blk-pci.scsi=off");
573 struct drive *drv = g->drives;
574 while (drv != NULL) {
575 /* Construct the final -drive parameter. */
576 char *buf = qemu_drive_param (g, drv);
578 add_cmdline (g, "-drive");
579 add_cmdline (g, buf);
585 if (qemu_supports (g, "-nodefconfig"))
586 add_cmdline (g, "-nodefconfig");
588 /* The qemu -machine option (added 2010-12) is a bit more sane
589 * since it falls back through various different acceleration
590 * modes, so try that first (thanks Markus Armbruster).
592 if (qemu_supports (g, "-machine")) {
593 add_cmdline (g, "-machine");
594 #if QEMU_MACHINE_TYPE_IS_BROKEN
595 /* Workaround for qemu 0.15: We have to add the '[type=]pc'
596 * since there is no default. This is not a permanent solution
597 * because this only works on PC-like hardware. Other platforms
598 * like ppc would need a different machine type.
600 * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
601 * not a problem in qemu < 0.15.
603 add_cmdline (g, "pc,accel=kvm:tcg");
605 add_cmdline (g, "accel=kvm:tcg");
608 /* qemu sometimes needs this option to enable hardware
609 * virtualization, but some versions of 'qemu-kvm' will use KVM
610 * regardless (even where this option appears in the help text).
611 * It is rumoured that there are versions of qemu where supplying
612 * this option when hardware virtualization is not available will
613 * cause qemu to fail, so we we have to check at least that
614 * /dev/kvm is openable. That's not reliable, since /dev/kvm
615 * might be openable by qemu but not by us (think: SELinux) in
616 * which case the user would not get hardware virtualization,
617 * although at least shouldn't fail. A giant clusterfuck with the
618 * qemu command line, again.
620 if (qemu_supports (g, "-enable-kvm") &&
621 is_openable (g, "/dev/kvm", O_RDWR))
622 add_cmdline (g, "-enable-kvm");
625 /* Newer versions of qemu (from around 2009/12) changed the
626 * behaviour of monitors so that an implicit '-monitor stdio' is
627 * assumed if we are in -nographic mode and there is no other
628 * -monitor option. Only a single stdio device is allowed, so
629 * this broke the '-serial stdio' option. There is a new flag
630 * called -nodefaults which gets rid of all this default crud, so
631 * let's use that to avoid this and any future surprises.
633 if (qemu_supports (g, "-nodefaults"))
634 add_cmdline (g, "-nodefaults");
636 add_cmdline (g, "-nographic");
639 snprintf (buf, sizeof buf, "%d", g->smp);
640 add_cmdline (g, "-smp");
641 add_cmdline (g, buf);
644 snprintf (buf, sizeof buf, "%d", g->memsize);
645 add_cmdline (g, "-m");
646 add_cmdline (g, buf);
648 /* Force exit instead of reboot on panic */
649 add_cmdline (g, "-no-reboot");
651 /* These options recommended by KVM developers to improve reliability. */
652 if (qemu_supports (g, "-no-hpet"))
653 add_cmdline (g, "-no-hpet");
655 if (qemu_supports (g, "-rtc-td-hack"))
656 add_cmdline (g, "-rtc-td-hack");
658 /* Create the virtio serial bus. */
659 add_cmdline (g, "-device");
660 add_cmdline (g, "virtio-serial");
663 /* Use virtio-console (a variant form of virtio-serial) for the
664 * guest's serial console.
666 add_cmdline (g, "-chardev");
667 add_cmdline (g, "stdio,id=console");
668 add_cmdline (g, "-device");
669 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
671 /* When the above works ... until then: */
672 add_cmdline (g, "-serial");
673 add_cmdline (g, "stdio");
676 /* Set up virtio-serial for the communications channel. */
677 add_cmdline (g, "-chardev");
678 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
679 add_cmdline (g, buf);
680 add_cmdline (g, "-device");
681 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
683 /* Enable user networking. */
684 if (g->enable_network) {
685 add_cmdline (g, "-netdev");
686 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
687 add_cmdline (g, "-device");
688 add_cmdline (g, NET_IF ",netdev=usernet");
691 #define LINUX_CMDLINE \
692 "panic=1 " /* force kernel to panic if daemon exits */ \
693 "console=ttyS0 " /* serial console */ \
694 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
695 "no_timer_check " /* fix for RHBZ#502058 */ \
696 "acpi=off " /* we don't need ACPI, turn it off */ \
697 "printk.time=1 " /* display timestamp before kernel messages */ \
698 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
700 /* Linux kernel command line. */
701 snprintf (buf, sizeof buf,
703 "%s " /* (selinux) */
704 "%s " /* (verbose) */
705 "TERM=%s " /* (TERM environment variable) */
707 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
708 g->verbose ? "guestfs_verbose=1" : "",
709 getenv ("TERM") ? : "linux",
710 g->append ? g->append : "");
712 add_cmdline (g, "-kernel");
713 add_cmdline (g, kernel);
714 add_cmdline (g, "-initrd");
715 add_cmdline (g, initrd);
716 add_cmdline (g, "-append");
717 add_cmdline (g, buf);
719 /* Add the ext2 appliance drive (last of all). */
721 const char *cachemode = "";
722 if (qemu_supports (g, "cache=")) {
723 if (qemu_supports (g, "unsafe"))
724 cachemode = ",cache=unsafe";
725 else if (qemu_supports (g, "writeback"))
726 cachemode = ",cache=writeback";
729 char buf2[PATH_MAX + 64];
730 add_cmdline (g, "-drive");
731 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
732 appliance, cachemode);
733 add_cmdline (g, buf2);
736 /* Finish off the command line. */
737 incr_cmdline_size (g);
738 g->cmdline[g->cmdline_size-1] = NULL;
741 /* Set up stdin, stdout, stderr. */
748 if (dup (wfd[0]) == -1) {
750 perror ("dup failed");
751 _exit (EXIT_FAILURE);
754 if (dup (rfd[1]) == -1)
757 /* Particularly since qemu 0.15, qemu spews all sorts of debug
758 * information on stderr. It is useful to both capture this and
759 * not confuse casual users, so send stderr to the pipe as well.
762 if (dup (rfd[1]) == -1)
769 /* Dump the command line (after setting up stderr above). */
771 print_qemu_command_line (g, g->cmdline);
773 /* Put qemu in a new process group. */
777 setenv ("LC_ALL", "C", 1);
779 TRACE0 (launch_run_qemu);
781 execv (g->qemu, g->cmdline); /* Run qemu. */
783 _exit (EXIT_FAILURE);
786 /* Parent (library). */
796 /* Fork the recovery process off which will kill qemu if the parent
797 * process fails to do so (eg. if the parent segfaults).
800 if (g->recovery_proc) {
803 pid_t qemu_pid = g->pid;
804 pid_t parent_pid = getppid ();
806 /* It would be nice to be able to put this in the same process
807 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
808 * not possible because we don't have any guarantee here that
809 * the qemu process has started yet.
814 /* Writing to argv is hideously complicated and error prone. See:
815 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
818 /* Loop around waiting for one or both of the other processes to
819 * disappear. It's fair to say this is very hairy. The PIDs that
820 * we are looking at might be reused by another process. We are
821 * effectively polling. Is the cure worse than the disease?
824 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
825 _exit (EXIT_SUCCESS);
826 if (kill (parent_pid, 0) == -1) {
827 /* Parent's gone away, qemu still around, so kill qemu. */
829 _exit (EXIT_SUCCESS);
835 /* Don't worry, if the fork failed, this will be -1. The recovery
836 * process isn't essential.
842 /* Close the other ends of the pipe. */
846 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
847 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
848 perrorf (g, "fcntl");
852 g->fd[0] = wfd[1]; /* stdin of child */
853 g->fd[1] = rfd[0]; /* stdout of child */
855 g->fd[0] = open ("/dev/null", O_RDWR);
856 if (g->fd[0] == -1) {
857 perrorf (g, "open /dev/null");
860 g->fd[1] = dup (g->fd[0]);
861 if (g->fd[1] == -1) {
868 g->state = LAUNCHING;
870 /* Wait for qemu to start and to connect back to us via
871 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
873 r = guestfs___accept_from_daemon (g);
877 /* NB: We reach here just because qemu has opened the socket. It
878 * does not mean the daemon is up until we read the
879 * GUESTFS_LAUNCH_FLAG below. Failures in qemu startup can still
880 * happen even if we reach here, even early failures like not being
881 * able to open a drive.
884 close (g->sock); /* Close the listening socket. */
885 g->sock = r; /* This is the accepted data socket. */
887 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
888 perrorf (g, "fcntl");
894 r = guestfs___recv_from_daemon (g, &size, &buf);
897 if (r == -1) return -1;
899 if (size != GUESTFS_LAUNCH_FLAG) {
900 error (g, _("guestfs_launch failed, see earlier error messages"));
905 guestfs___print_timestamped_message (g, "appliance is up");
907 /* This is possible in some really strange situations, such as
908 * guestfsd starts up OK but then qemu immediately exits. Check for
909 * it because the caller is probably expecting to be able to send
910 * commands after this function returns.
912 if (g->state != READY) {
913 error (g, _("qemu launched and contacted daemon, but state != READY"));
919 guestfs___launch_send_progress (g, 12);
928 if (g->pid > 0) kill (g->pid, 9);
929 if (g->recoverypid > 0) kill (g->recoverypid, 9);
930 if (g->pid > 0) waitpid (g->pid, NULL, 0);
931 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
936 memset (&g->launch_t, 0, sizeof g->launch_t);
950 /* Alternate attach method: instead of launching the appliance,
951 * connect to an existing unix socket.
954 connect_unix_socket (guestfs_h *g, const char *sockpath)
957 struct sockaddr_un addr;
959 /* Start the clock ... */
960 gettimeofday (&g->launch_t, NULL);
962 /* Set these to nothing so we don't try to kill random processes or
963 * read from random file descriptors.
971 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
973 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
975 perrorf (g, "socket");
979 addr.sun_family = AF_UNIX;
980 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
981 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
983 g->state = LAUNCHING;
985 if (connect (g->sock, &addr, sizeof addr) == -1) {
990 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
991 perrorf (g, "fcntl");
997 r = guestfs___recv_from_daemon (g, &size, &buf);
1000 if (r == -1) return -1;
1002 if (size != GUESTFS_LAUNCH_FLAG) {
1003 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1008 guestfs___print_timestamped_message (g, "connected");
1010 if (g->state != READY) {
1011 error (g, _("contacted guestfsd, but state != READY"));
1022 /* launch (of the ordinary appliance) generates approximate progress
1023 * messages. Currently these are defined as follows:
1025 * 0 / 12: launch clock starts
1026 * 3 / 12: appliance created
1027 * 6 / 12: detected that guest kernel started
1028 * 9 / 12: detected that /init script is running
1029 * 12 / 12: launch completed successfully
1032 * (1) This is not a documented ABI and the behaviour may be changed
1033 * or removed in future.
1034 * (2) Messages are only sent if more than 5 seconds has elapsed
1035 * since the launch clock started.
1036 * (3) There is a gross hack in proto.c to make this work.
1039 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1043 gettimeofday (&tv, NULL);
1044 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1045 guestfs_progress progress_message =
1046 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1048 guestfs___progress_message_callback (g, &progress_message);
1052 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1053 * to override it at runtime using $TMPDIR.
1054 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1057 guestfs_tmpdir (void)
1067 const char *t = getenv ("TMPDIR");
1073 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1074 * allow users to override it at runtime using $TMPDIR.
1075 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1078 guestfs___persistent_tmpdir (void)
1082 tmpdir = "/var/tmp";
1084 const char *t = getenv ("TMPDIR");
1090 /* Recursively remove a temporary directory. If removal fails, just
1091 * return (it's a temporary directory so it'll eventually be cleaned
1092 * up by a temp cleaner). This is done using "rm -rf" because that's
1093 * simpler and safer, but we have to exec to ensure that paths don't
1094 * need to be quoted.
1097 guestfs___remove_tmpdir (const char *dir)
1099 pid_t pid = fork ();
1102 perror ("remove tmpdir: fork");
1106 execlp ("rm", "rm", "-rf", dir, NULL);
1107 perror ("remove tmpdir: exec: rm");
1108 _exit (EXIT_FAILURE);
1112 if (waitpid (pid, NULL, 0) == -1) {
1113 perror ("remove tmpdir: waitpid");
1118 /* Compute Y - X and return the result in milliseconds.
1119 * Approximately the same as this code:
1120 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1123 timeval_diff (const struct timeval *x, const struct timeval *y)
1127 msec = (y->tv_sec - x->tv_sec) * 1000;
1128 msec += (y->tv_usec - x->tv_usec) / 1000;
1132 /* Note that since this calls 'debug' it should only be called
1133 * from the parent process.
1136 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1143 va_start (args, fs);
1144 err = vasprintf (&msg, fs, args);
1147 if (err < 0) return;
1149 gettimeofday (&tv, NULL);
1151 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1156 /* This is called from the forked subprocess just before qemu runs, so
1157 * it can just print the message straight to stderr, where it will be
1158 * picked up and funnelled through the usual appliance event API.
1161 print_qemu_command_line (guestfs_h *g, char **argv)
1167 gettimeofday (&tv, NULL);
1168 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1171 if (argv[i][0] == '-') /* -option starts a new line */
1172 fprintf (stderr, " \\\n ");
1174 if (i > 0) fputc (' ', stderr);
1176 /* Does it need shell quoting? This only deals with simple cases. */
1177 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1179 if (needs_quote) fputc ('\'', stderr);
1180 fprintf (stderr, "%s", argv[i]);
1181 if (needs_quote) fputc ('\'', stderr);
1186 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1187 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1189 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1190 * 'qemu -version' so we know what options this qemu supports and
1194 test_qemu (guestfs_h *g)
1199 free (g->qemu_help);
1200 g->qemu_help = NULL;
1201 free (g->qemu_version);
1202 g->qemu_version = NULL;
1204 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1206 /* qemu -help should always work (qemu -version OTOH wasn't
1207 * supported by qemu 0.9). If this command doesn't work then it
1208 * probably indicates that the qemu binary is missing.
1210 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1211 error (g, _("command failed: %s\n\nIf qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU\nenvironment variable. There may also be errors printed above."),
1216 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1219 /* Intentionally ignore errors from qemu -version. */
1220 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1226 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1230 fp = popen (cmd, "r");
1234 if (read_all (g, fp, ret) == -1) {
1239 if (pclose (fp) != 0)
1246 read_all (guestfs_h *g, FILE *fp, char **ret)
1253 *ret = safe_realloc (g, *ret, n + 1);
1258 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1260 r = fread (p, 1, BUFSIZ, fp);
1262 perrorf (g, "read");
1269 /* Test if option is supported by qemu command line (just by grepping
1272 * The first time this is used, it has to run the external qemu
1273 * binary. If that fails, it returns -1.
1275 * To just do the first-time run of the qemu binary, call this with
1276 * option == NULL, in which case it will return -1 if there was an
1280 qemu_supports (guestfs_h *g, const char *option)
1282 if (!g->qemu_help) {
1283 if (test_qemu (g) == -1)
1290 return strstr (g->qemu_help, option) != NULL;
1294 /* As above but using a regex instead of a fixed string. */
1296 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1298 if (!g->qemu_help) {
1299 if (test_qemu (g) == -1)
1303 return match (g, g->qemu_help, option_regex);
1307 /* Check if a file can be opened. */
1309 is_openable (guestfs_h *g, const char *path, int flags)
1311 int fd = open (path, flags);
1313 debug (g, "is_openable: %s: %m", path);
1321 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1326 len += strlen (drv->path);
1327 len += strlen (drv->iface);
1329 len += strlen (drv->format);
1331 r = safe_malloc (g, len);
1333 snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1335 drv->readonly ? ",snapshot=on" : "",
1336 drv->use_cache_off ? ",cache=off" : "",
1337 drv->format ? ",format=" : "",
1338 drv->format ? drv->format : "",
1341 return r; /* caller frees */
1344 /* You had to call this function after launch in versions <= 1.0.70,
1345 * but it is now a no-op.
1348 guestfs__wait_ready (guestfs_h *g)
1350 if (g->state != READY) {
1351 error (g, _("qemu has not been launched yet"));
1359 guestfs__kill_subprocess (guestfs_h *g)
1361 if (g->state == CONFIG) {
1362 error (g, _("no subprocess to kill"));
1366 debug (g, "sending SIGTERM to process %d", g->pid);
1368 if (g->pid > 0) kill (g->pid, SIGTERM);
1369 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1374 /* Access current state. */
1376 guestfs__is_config (guestfs_h *g)
1378 return g->state == CONFIG;
1382 guestfs__is_launching (guestfs_h *g)
1384 return g->state == LAUNCHING;
1388 guestfs__is_ready (guestfs_h *g)
1390 return g->state == READY;
1394 guestfs__is_busy (guestfs_h *g)
1396 return g->state == BUSY;
1400 guestfs__get_state (guestfs_h *g)