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)
288 char *abs_path = NULL;
291 if (strchr (filename, ',') != NULL) {
292 error (g, _("filename cannot contain ',' (comma) character"));
296 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
297 ? optargs->readonly : 0;
298 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
299 ? safe_strdup (g, optargs->format) : NULL;
300 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
301 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
302 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
303 ? safe_strdup (g, optargs->name) : NULL;
305 if (format && !valid_format_iface (format)) {
306 error (g, _("%s parameter is empty or contains disallowed characters"),
310 if (!valid_format_iface (iface)) {
311 error (g, _("%s parameter is empty or contains disallowed characters"),
316 /* For writable files, see if we can use cache=off. This also
317 * checks for the existence of the file. For readonly we have
318 * to do the check explicitly.
320 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
321 if (use_cache_off == -1)
325 if (access (filename, R_OK) == -1) {
326 perrorf (g, "%s", filename);
331 abs_path = realpath (filename, NULL);
332 struct drive **i = &(g->drives);
334 if (STREQ((*i)->path, abs_path)) {
335 error (g, _("drive %s can't be added twice"), abs_path);
341 *i = safe_malloc (g, sizeof (struct drive));
343 (*i)->path = safe_strdup (g, abs_path);
344 (*i)->readonly = readonly;
345 (*i)->format = format;
348 (*i)->use_cache_off = use_cache_off;
362 guestfs__add_drive (guestfs_h *g, const char *filename)
364 struct guestfs_add_drive_opts_argv optargs = {
368 return guestfs__add_drive_opts (g, filename, &optargs);
372 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
374 struct guestfs_add_drive_opts_argv optargs = {
375 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
379 return guestfs__add_drive_opts (g, filename, &optargs);
383 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
386 struct guestfs_add_drive_opts_argv optargs = {
387 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
391 return guestfs__add_drive_opts (g, filename, &optargs);
395 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
398 struct guestfs_add_drive_opts_argv optargs = {
399 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
400 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
405 return guestfs__add_drive_opts (g, filename, &optargs);
409 guestfs__add_cdrom (guestfs_h *g, const char *filename)
411 if (strchr (filename, ',') != NULL) {
412 error (g, _("filename cannot contain ',' (comma) character"));
416 if (access (filename, F_OK) == -1) {
417 perrorf (g, "%s", filename);
421 return guestfs__config (g, "-cdrom", filename);
424 static int is_openable (guestfs_h *g, const char *path, int flags);
427 guestfs__launch (guestfs_h *g)
430 if (g->state != CONFIG) {
431 error (g, _("the libguestfs handle has already been launched"));
435 TRACE0 (launch_start);
437 /* Make the temporary directory. */
439 TMP_TEMPLATE_ON_STACK (dir_template);
440 g->tmpdir = safe_strdup (g, dir_template);
441 if (mkdtemp (g->tmpdir) == NULL) {
442 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
447 /* Allow anyone to read the temporary directory. The socket in this
448 * directory won't be readable but anyone can see it exists if they
449 * want. (RHBZ#610880).
451 if (chmod (g->tmpdir, 0755) == -1)
452 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
454 /* Launch the appliance or attach to an existing daemon. */
455 switch (g->attach_method) {
456 case ATTACH_METHOD_APPLIANCE:
457 return launch_appliance (g);
459 case ATTACH_METHOD_UNIX:
460 return connect_unix_socket (g, g->attach_method_arg);
468 launch_appliance (guestfs_h *g)
472 char guestfsd_sock[256];
473 struct sockaddr_un addr;
475 /* At present you must add drives before starting the appliance. In
476 * future when we enable hotplugging you won't need to do this.
479 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
483 /* Start the clock ... */
484 gettimeofday (&g->launch_t, NULL);
485 guestfs___launch_send_progress (g, 0);
487 TRACE0 (launch_build_appliance_start);
489 /* Locate and/or build the appliance. */
490 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
491 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
494 TRACE0 (launch_build_appliance_end);
496 guestfs___launch_send_progress (g, 3);
499 guestfs___print_timestamped_message (g, "begin testing qemu features");
501 /* Get qemu help text and version. */
502 if (qemu_supports (g, NULL) == -1)
505 /* Using virtio-serial, we need to create a local Unix domain socket
506 * for qemu to connect to.
508 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
509 unlink (guestfsd_sock);
511 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
513 perrorf (g, "socket");
517 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
518 perrorf (g, "fcntl");
522 addr.sun_family = AF_UNIX;
523 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
524 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
526 if (bind (g->sock, &addr, sizeof addr) == -1) {
531 if (listen (g->sock, 1) == -1) {
532 perrorf (g, "listen");
537 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
544 guestfs___print_timestamped_message (g, "finished testing qemu features");
558 if (r == 0) { /* Child (qemu). */
561 /* Set up the full command line. Do this in the subprocess so we
562 * don't need to worry about cleaning up.
565 /* Set g->cmdline[0] to the name of the qemu process. However
566 * it is possible that no g->cmdline has been allocated yet so
567 * we must do that first.
570 g->cmdline[0] = g->qemu;
572 /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
573 * devices. The -global option must exist, but you can pass any
574 * strings to it so we don't need to check for the specific virtio
577 if (qemu_supports (g, "-global")) {
578 add_cmdline (g, "-global");
579 add_cmdline (g, "virtio-blk-pci.scsi=off");
583 struct drive *drv = g->drives;
584 while (drv != NULL) {
585 /* Construct the final -drive parameter. */
586 char *buf = qemu_drive_param (g, drv);
588 add_cmdline (g, "-drive");
589 add_cmdline (g, buf);
595 if (qemu_supports (g, "-nodefconfig"))
596 add_cmdline (g, "-nodefconfig");
598 /* The qemu -machine option (added 2010-12) is a bit more sane
599 * since it falls back through various different acceleration
600 * modes, so try that first (thanks Markus Armbruster).
602 if (qemu_supports (g, "-machine")) {
603 add_cmdline (g, "-machine");
604 #if QEMU_MACHINE_TYPE_IS_BROKEN
605 /* Workaround for qemu 0.15: We have to add the '[type=]pc'
606 * since there is no default. This is not a permanent solution
607 * because this only works on PC-like hardware. Other platforms
608 * like ppc would need a different machine type.
610 * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
611 * not a problem in qemu < 0.15.
613 add_cmdline (g, "pc,accel=kvm:tcg");
615 add_cmdline (g, "accel=kvm:tcg");
618 /* qemu sometimes needs this option to enable hardware
619 * virtualization, but some versions of 'qemu-kvm' will use KVM
620 * regardless (even where this option appears in the help text).
621 * It is rumoured that there are versions of qemu where supplying
622 * this option when hardware virtualization is not available will
623 * cause qemu to fail, so we we have to check at least that
624 * /dev/kvm is openable. That's not reliable, since /dev/kvm
625 * might be openable by qemu but not by us (think: SELinux) in
626 * which case the user would not get hardware virtualization,
627 * although at least shouldn't fail. A giant clusterfuck with the
628 * qemu command line, again.
630 if (qemu_supports (g, "-enable-kvm") &&
631 is_openable (g, "/dev/kvm", O_RDWR))
632 add_cmdline (g, "-enable-kvm");
635 /* Newer versions of qemu (from around 2009/12) changed the
636 * behaviour of monitors so that an implicit '-monitor stdio' is
637 * assumed if we are in -nographic mode and there is no other
638 * -monitor option. Only a single stdio device is allowed, so
639 * this broke the '-serial stdio' option. There is a new flag
640 * called -nodefaults which gets rid of all this default crud, so
641 * let's use that to avoid this and any future surprises.
643 if (qemu_supports (g, "-nodefaults"))
644 add_cmdline (g, "-nodefaults");
646 add_cmdline (g, "-nographic");
649 snprintf (buf, sizeof buf, "%d", g->smp);
650 add_cmdline (g, "-smp");
651 add_cmdline (g, buf);
654 snprintf (buf, sizeof buf, "%d", g->memsize);
655 add_cmdline (g, "-m");
656 add_cmdline (g, buf);
658 /* Force exit instead of reboot on panic */
659 add_cmdline (g, "-no-reboot");
661 /* These options recommended by KVM developers to improve reliability. */
662 if (qemu_supports (g, "-no-hpet"))
663 add_cmdline (g, "-no-hpet");
665 if (qemu_supports (g, "-rtc-td-hack"))
666 add_cmdline (g, "-rtc-td-hack");
668 /* Create the virtio serial bus. */
669 add_cmdline (g, "-device");
670 add_cmdline (g, "virtio-serial");
673 /* Use virtio-console (a variant form of virtio-serial) for the
674 * guest's serial console.
676 add_cmdline (g, "-chardev");
677 add_cmdline (g, "stdio,id=console");
678 add_cmdline (g, "-device");
679 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
681 /* When the above works ... until then: */
682 add_cmdline (g, "-serial");
683 add_cmdline (g, "stdio");
686 /* Set up virtio-serial for the communications channel. */
687 add_cmdline (g, "-chardev");
688 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
689 add_cmdline (g, buf);
690 add_cmdline (g, "-device");
691 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
693 /* Enable user networking. */
694 if (g->enable_network) {
695 add_cmdline (g, "-netdev");
696 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
697 add_cmdline (g, "-device");
698 add_cmdline (g, NET_IF ",netdev=usernet");
701 #define LINUX_CMDLINE \
702 "panic=1 " /* force kernel to panic if daemon exits */ \
703 "console=ttyS0 " /* serial console */ \
704 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
705 "no_timer_check " /* fix for RHBZ#502058 */ \
706 "acpi=off " /* we don't need ACPI, turn it off */ \
707 "printk.time=1 " /* display timestamp before kernel messages */ \
708 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
710 /* Linux kernel command line. */
711 snprintf (buf, sizeof buf,
713 "%s " /* (selinux) */
714 "%s " /* (verbose) */
715 "TERM=%s " /* (TERM environment variable) */
717 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
718 g->verbose ? "guestfs_verbose=1" : "",
719 getenv ("TERM") ? : "linux",
720 g->append ? g->append : "");
722 add_cmdline (g, "-kernel");
723 add_cmdline (g, kernel);
724 add_cmdline (g, "-initrd");
725 add_cmdline (g, initrd);
726 add_cmdline (g, "-append");
727 add_cmdline (g, buf);
729 /* Add the ext2 appliance drive (last of all). */
731 const char *cachemode = "";
732 if (qemu_supports (g, "cache=")) {
733 if (qemu_supports (g, "unsafe"))
734 cachemode = ",cache=unsafe";
735 else if (qemu_supports (g, "writeback"))
736 cachemode = ",cache=writeback";
739 char buf2[PATH_MAX + 64];
740 add_cmdline (g, "-drive");
741 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
742 appliance, cachemode);
743 add_cmdline (g, buf2);
746 /* Finish off the command line. */
747 incr_cmdline_size (g);
748 g->cmdline[g->cmdline_size-1] = NULL;
751 /* Set up stdin, stdout, stderr. */
758 if (dup (wfd[0]) == -1) {
760 perror ("dup failed");
761 _exit (EXIT_FAILURE);
764 if (dup (rfd[1]) == -1)
767 /* Particularly since qemu 0.15, qemu spews all sorts of debug
768 * information on stderr. It is useful to both capture this and
769 * not confuse casual users, so send stderr to the pipe as well.
772 if (dup (rfd[1]) == -1)
779 /* Dump the command line (after setting up stderr above). */
781 print_qemu_command_line (g, g->cmdline);
783 /* Put qemu in a new process group. */
787 setenv ("LC_ALL", "C", 1);
789 TRACE0 (launch_run_qemu);
791 execv (g->qemu, g->cmdline); /* Run qemu. */
793 _exit (EXIT_FAILURE);
796 /* Parent (library). */
806 /* Fork the recovery process off which will kill qemu if the parent
807 * process fails to do so (eg. if the parent segfaults).
810 if (g->recovery_proc) {
813 pid_t qemu_pid = g->pid;
814 pid_t parent_pid = getppid ();
816 /* It would be nice to be able to put this in the same process
817 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
818 * not possible because we don't have any guarantee here that
819 * the qemu process has started yet.
824 /* Writing to argv is hideously complicated and error prone. See:
825 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
828 /* Loop around waiting for one or both of the other processes to
829 * disappear. It's fair to say this is very hairy. The PIDs that
830 * we are looking at might be reused by another process. We are
831 * effectively polling. Is the cure worse than the disease?
834 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
835 _exit (EXIT_SUCCESS);
836 if (kill (parent_pid, 0) == -1) {
837 /* Parent's gone away, qemu still around, so kill qemu. */
839 _exit (EXIT_SUCCESS);
845 /* Don't worry, if the fork failed, this will be -1. The recovery
846 * process isn't essential.
852 /* Close the other ends of the pipe. */
856 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
857 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
858 perrorf (g, "fcntl");
862 g->fd[0] = wfd[1]; /* stdin of child */
863 g->fd[1] = rfd[0]; /* stdout of child */
865 g->fd[0] = open ("/dev/null", O_RDWR);
866 if (g->fd[0] == -1) {
867 perrorf (g, "open /dev/null");
870 g->fd[1] = dup (g->fd[0]);
871 if (g->fd[1] == -1) {
878 g->state = LAUNCHING;
880 /* Wait for qemu to start and to connect back to us via
881 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
883 r = guestfs___accept_from_daemon (g);
887 /* NB: We reach here just because qemu has opened the socket. It
888 * does not mean the daemon is up until we read the
889 * GUESTFS_LAUNCH_FLAG below. Failures in qemu startup can still
890 * happen even if we reach here, even early failures like not being
891 * able to open a drive.
894 close (g->sock); /* Close the listening socket. */
895 g->sock = r; /* This is the accepted data socket. */
897 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
898 perrorf (g, "fcntl");
904 r = guestfs___recv_from_daemon (g, &size, &buf);
907 if (r == -1) return -1;
909 if (size != GUESTFS_LAUNCH_FLAG) {
910 error (g, _("guestfs_launch failed, see earlier error messages"));
915 guestfs___print_timestamped_message (g, "appliance is up");
917 /* This is possible in some really strange situations, such as
918 * guestfsd starts up OK but then qemu immediately exits. Check for
919 * it because the caller is probably expecting to be able to send
920 * commands after this function returns.
922 if (g->state != READY) {
923 error (g, _("qemu launched and contacted daemon, but state != READY"));
929 guestfs___launch_send_progress (g, 12);
938 if (g->pid > 0) kill (g->pid, 9);
939 if (g->recoverypid > 0) kill (g->recoverypid, 9);
940 if (g->pid > 0) waitpid (g->pid, NULL, 0);
941 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
946 memset (&g->launch_t, 0, sizeof g->launch_t);
960 /* Alternate attach method: instead of launching the appliance,
961 * connect to an existing unix socket.
964 connect_unix_socket (guestfs_h *g, const char *sockpath)
967 struct sockaddr_un addr;
969 /* Start the clock ... */
970 gettimeofday (&g->launch_t, NULL);
972 /* Set these to nothing so we don't try to kill random processes or
973 * read from random file descriptors.
981 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
983 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
985 perrorf (g, "socket");
989 addr.sun_family = AF_UNIX;
990 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
991 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
993 g->state = LAUNCHING;
995 if (connect (g->sock, &addr, sizeof addr) == -1) {
1000 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1001 perrorf (g, "fcntl");
1007 r = guestfs___recv_from_daemon (g, &size, &buf);
1010 if (r == -1) return -1;
1012 if (size != GUESTFS_LAUNCH_FLAG) {
1013 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1018 guestfs___print_timestamped_message (g, "connected");
1020 if (g->state != READY) {
1021 error (g, _("contacted guestfsd, but state != READY"));
1032 /* launch (of the ordinary appliance) generates approximate progress
1033 * messages. Currently these are defined as follows:
1035 * 0 / 12: launch clock starts
1036 * 3 / 12: appliance created
1037 * 6 / 12: detected that guest kernel started
1038 * 9 / 12: detected that /init script is running
1039 * 12 / 12: launch completed successfully
1042 * (1) This is not a documented ABI and the behaviour may be changed
1043 * or removed in future.
1044 * (2) Messages are only sent if more than 5 seconds has elapsed
1045 * since the launch clock started.
1046 * (3) There is a gross hack in proto.c to make this work.
1049 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1053 gettimeofday (&tv, NULL);
1054 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1055 guestfs_progress progress_message =
1056 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1058 guestfs___progress_message_callback (g, &progress_message);
1062 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1063 * to override it at runtime using $TMPDIR.
1064 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1067 guestfs_tmpdir (void)
1077 const char *t = getenv ("TMPDIR");
1083 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1084 * allow users to override it at runtime using $TMPDIR.
1085 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1088 guestfs___persistent_tmpdir (void)
1092 tmpdir = "/var/tmp";
1094 const char *t = getenv ("TMPDIR");
1100 /* Recursively remove a temporary directory. If removal fails, just
1101 * return (it's a temporary directory so it'll eventually be cleaned
1102 * up by a temp cleaner). This is done using "rm -rf" because that's
1103 * simpler and safer, but we have to exec to ensure that paths don't
1104 * need to be quoted.
1107 guestfs___remove_tmpdir (const char *dir)
1109 pid_t pid = fork ();
1112 perror ("remove tmpdir: fork");
1116 execlp ("rm", "rm", "-rf", dir, NULL);
1117 perror ("remove tmpdir: exec: rm");
1118 _exit (EXIT_FAILURE);
1122 if (waitpid (pid, NULL, 0) == -1) {
1123 perror ("remove tmpdir: waitpid");
1128 /* Compute Y - X and return the result in milliseconds.
1129 * Approximately the same as this code:
1130 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1133 timeval_diff (const struct timeval *x, const struct timeval *y)
1137 msec = (y->tv_sec - x->tv_sec) * 1000;
1138 msec += (y->tv_usec - x->tv_usec) / 1000;
1142 /* Note that since this calls 'debug' it should only be called
1143 * from the parent process.
1146 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1153 va_start (args, fs);
1154 err = vasprintf (&msg, fs, args);
1157 if (err < 0) return;
1159 gettimeofday (&tv, NULL);
1161 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1166 /* This is called from the forked subprocess just before qemu runs, so
1167 * it can just print the message straight to stderr, where it will be
1168 * picked up and funnelled through the usual appliance event API.
1171 print_qemu_command_line (guestfs_h *g, char **argv)
1177 gettimeofday (&tv, NULL);
1178 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1181 if (argv[i][0] == '-') /* -option starts a new line */
1182 fprintf (stderr, " \\\n ");
1184 if (i > 0) fputc (' ', stderr);
1186 /* Does it need shell quoting? This only deals with simple cases. */
1187 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1189 if (needs_quote) fputc ('\'', stderr);
1190 fprintf (stderr, "%s", argv[i]);
1191 if (needs_quote) fputc ('\'', stderr);
1196 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1197 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1199 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1200 * 'qemu -version' so we know what options this qemu supports and
1204 test_qemu (guestfs_h *g)
1209 free (g->qemu_help);
1210 g->qemu_help = NULL;
1211 free (g->qemu_version);
1212 g->qemu_version = NULL;
1214 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1216 /* qemu -help should always work (qemu -version OTOH wasn't
1217 * supported by qemu 0.9). If this command doesn't work then it
1218 * probably indicates that the qemu binary is missing.
1220 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1221 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."),
1226 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1229 /* Intentionally ignore errors from qemu -version. */
1230 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1236 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1240 fp = popen (cmd, "r");
1244 if (read_all (g, fp, ret) == -1) {
1249 if (pclose (fp) != 0)
1256 read_all (guestfs_h *g, FILE *fp, char **ret)
1263 *ret = safe_realloc (g, *ret, n + 1);
1268 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1270 r = fread (p, 1, BUFSIZ, fp);
1272 perrorf (g, "read");
1279 /* Test if option is supported by qemu command line (just by grepping
1282 * The first time this is used, it has to run the external qemu
1283 * binary. If that fails, it returns -1.
1285 * To just do the first-time run of the qemu binary, call this with
1286 * option == NULL, in which case it will return -1 if there was an
1290 qemu_supports (guestfs_h *g, const char *option)
1292 if (!g->qemu_help) {
1293 if (test_qemu (g) == -1)
1300 return strstr (g->qemu_help, option) != NULL;
1304 /* As above but using a regex instead of a fixed string. */
1306 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1308 if (!g->qemu_help) {
1309 if (test_qemu (g) == -1)
1313 return match (g, g->qemu_help, option_regex);
1317 /* Check if a file can be opened. */
1319 is_openable (guestfs_h *g, const char *path, int flags)
1321 int fd = open (path, flags);
1323 debug (g, "is_openable: %s: %m", path);
1331 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1336 len += strlen (drv->path);
1337 len += strlen (drv->iface);
1339 len += strlen (drv->format);
1341 r = safe_malloc (g, len);
1343 snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1345 drv->readonly ? ",snapshot=on" : "",
1346 drv->use_cache_off ? ",cache=off" : "",
1347 drv->format ? ",format=" : "",
1348 drv->format ? drv->format : "",
1351 return r; /* caller frees */
1354 /* You had to call this function after launch in versions <= 1.0.70,
1355 * but it is now a no-op.
1358 guestfs__wait_ready (guestfs_h *g)
1360 if (g->state != READY) {
1361 error (g, _("qemu has not been launched yet"));
1369 guestfs__kill_subprocess (guestfs_h *g)
1371 if (g->state == CONFIG) {
1372 error (g, _("no subprocess to kill"));
1376 debug (g, "sending SIGTERM to process %d", g->pid);
1378 if (g->pid > 0) kill (g->pid, SIGTERM);
1379 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1384 /* Access current state. */
1386 guestfs__is_config (guestfs_h *g)
1388 return g->state == CONFIG;
1392 guestfs__is_launching (guestfs_h *g)
1394 return g->state == LAUNCHING;
1398 guestfs__is_ready (guestfs_h *g)
1400 return g->state == READY;
1404 guestfs__is_busy (guestfs_h *g)
1406 return g->state == BUSY;
1410 guestfs__get_state (guestfs_h *g)