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>
39 #include <rpc/types.h>
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
50 #ifdef HAVE_SYS_WAIT_H
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
66 #include "glthread/lock.h"
67 #include "ignore-value.h"
70 #include "guestfs-internal.h"
71 #include "guestfs-internal-actions.h"
72 #include "guestfs_protocol.h"
74 static int launch_appliance (guestfs_h *g);
75 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
76 static int connect_unix_socket (guestfs_h *g, const char *sock);
77 static int qemu_supports (guestfs_h *g, const char *option);
79 /* Add a string to the current command line. */
81 incr_cmdline_size (guestfs_h *g)
83 if (g->cmdline == NULL) {
84 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
86 g->cmdline = safe_malloc (g, sizeof (char *));
91 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
95 add_cmdline (guestfs_h *g, const char *str)
97 if (g->state != CONFIG) {
99 _("command line cannot be altered after qemu subprocess launched"));
103 incr_cmdline_size (g);
104 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
109 guestfs___checkpoint_cmdline (guestfs_h *g)
111 return g->cmdline_size;
115 guestfs___rollback_cmdline (guestfs_h *g, size_t pos)
119 assert (g->cmdline_size >= pos);
121 for (i = pos; i < g->cmdline_size; ++i)
122 free (g->cmdline[i]);
124 g->cmdline_size = pos;
127 /* Internal command to return the command line. */
129 guestfs__debug_cmdline (guestfs_h *g)
134 if (g->cmdline == NULL) {
135 r = safe_malloc (g, sizeof (char *) * 1);
140 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
141 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
143 for (i = 1; i < g->cmdline_size; ++i)
144 r[i] = safe_strdup (g, g->cmdline[i]);
146 r[g->cmdline_size] = NULL;
148 return r; /* caller frees */
152 guestfs__config (guestfs_h *g,
153 const char *qemu_param, const char *qemu_value)
155 if (qemu_param[0] != '-') {
156 error (g, _("guestfs_config: parameter must begin with '-' character"));
160 /* A bit fascist, but the user will probably break the extra
161 * parameters that we add if they try to set any of these.
163 if (STREQ (qemu_param, "-kernel") ||
164 STREQ (qemu_param, "-initrd") ||
165 STREQ (qemu_param, "-nographic") ||
166 STREQ (qemu_param, "-serial") ||
167 STREQ (qemu_param, "-full-screen") ||
168 STREQ (qemu_param, "-std-vga") ||
169 STREQ (qemu_param, "-vnc")) {
170 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
174 if (add_cmdline (g, qemu_param) != 0) return -1;
176 if (qemu_value != NULL) {
177 if (add_cmdline (g, qemu_value) != 0) return -1;
183 /* cache=off improves reliability in the event of a host crash.
185 * However this option causes qemu to try to open the file with
186 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
187 * So we check if we can open the file with or without O_DIRECT,
188 * and use cache=off (or not) accordingly.
191 test_cache_off (guestfs_h *g, const char *filename)
193 int fd = open (filename, O_RDONLY|O_DIRECT);
199 fd = open (filename, O_RDONLY);
205 perrorf (g, "%s", filename);
209 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
211 valid_format_iface (const char *str)
213 size_t len = strlen (str);
221 if (c != '-' && c != '_' && !c_isalnum (c))
228 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
229 const struct guestfs_add_drive_opts_argv *optargs)
235 if (strchr (filename, ',') != NULL) {
236 error (g, _("filename cannot contain ',' (comma) character"));
240 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
241 ? optargs->readonly : 0;
242 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
243 ? optargs->format : NULL;
244 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
245 ? optargs->iface : DRIVE_IF;
247 if (format && !valid_format_iface (format)) {
248 error (g, _("%s parameter is empty or contains disallowed characters"),
252 if (!valid_format_iface (iface)) {
253 error (g, _("%s parameter is empty or contains disallowed characters"),
258 /* For writable files, see if we can use cache=off. This also
259 * checks for the existence of the file. For readonly we have
260 * to do the check explicitly.
262 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
263 if (use_cache_off == -1)
267 if (access (filename, F_OK) == -1) {
268 perrorf (g, "%s", filename);
273 /* Construct the final -drive parameter. */
274 size_t len = 64 + strlen (filename) + strlen (iface);
275 if (format) len += strlen (format);
278 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
280 readonly ? ",snapshot=on" : "",
281 use_cache_off ? ",cache=off" : "",
282 format ? ",format=" : "",
283 format ? format : "",
286 return guestfs__config (g, "-drive", buf);
290 guestfs__add_drive (guestfs_h *g, const char *filename)
292 struct guestfs_add_drive_opts_argv optargs = {
296 return guestfs__add_drive_opts (g, filename, &optargs);
300 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
302 struct guestfs_add_drive_opts_argv optargs = {
303 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
307 return guestfs__add_drive_opts (g, filename, &optargs);
311 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
314 struct guestfs_add_drive_opts_argv optargs = {
315 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
319 return guestfs__add_drive_opts (g, filename, &optargs);
323 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
326 struct guestfs_add_drive_opts_argv optargs = {
327 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
328 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
333 return guestfs__add_drive_opts (g, filename, &optargs);
337 guestfs__add_cdrom (guestfs_h *g, const char *filename)
339 if (strchr (filename, ',') != NULL) {
340 error (g, _("filename cannot contain ',' (comma) character"));
344 if (access (filename, F_OK) == -1) {
345 perrorf (g, "%s", filename);
349 return guestfs__config (g, "-cdrom", filename);
352 static int is_openable (guestfs_h *g, const char *path, int flags);
355 guestfs__launch (guestfs_h *g)
358 if (g->state != CONFIG) {
359 error (g, _("the libguestfs handle has already been launched"));
363 /* Make the temporary directory. */
365 TMP_TEMPLATE_ON_STACK (dir_template);
366 g->tmpdir = safe_strdup (g, dir_template);
367 if (mkdtemp (g->tmpdir) == NULL) {
368 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
373 /* Allow anyone to read the temporary directory. The socket in this
374 * directory won't be readable but anyone can see it exists if they
375 * want. (RHBZ#610880).
377 if (chmod (g->tmpdir, 0755) == -1)
378 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
380 /* Launch the appliance or attach to an existing daemon. */
381 switch (g->attach_method) {
382 case ATTACH_METHOD_APPLIANCE:
383 return launch_appliance (g);
385 case ATTACH_METHOD_UNIX:
386 return connect_unix_socket (g, g->attach_method_arg);
394 launch_appliance (guestfs_h *g)
398 char guestfsd_sock[256];
399 struct sockaddr_un addr;
401 /* At present you must add drives before starting the appliance. In
402 * future when we enable hotplugging you won't need to do this.
405 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
409 /* Start the clock ... */
410 gettimeofday (&g->launch_t, NULL);
411 guestfs___launch_send_progress (g, 0);
413 /* Locate and/or build the appliance. */
414 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
415 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
418 guestfs___launch_send_progress (g, 3);
421 guestfs___print_timestamped_message (g, "begin testing qemu features");
423 /* Get qemu help text and version. */
424 if (qemu_supports (g, NULL) == -1)
427 /* Using virtio-serial, we need to create a local Unix domain socket
428 * for qemu to connect to.
430 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
431 unlink (guestfsd_sock);
433 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
435 perrorf (g, "socket");
439 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
440 perrorf (g, "fcntl");
444 addr.sun_family = AF_UNIX;
445 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
446 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
448 if (bind (g->sock, &addr, sizeof addr) == -1) {
453 if (listen (g->sock, 1) == -1) {
454 perrorf (g, "listen");
459 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
466 guestfs___print_timestamped_message (g, "finished testing qemu features");
480 if (r == 0) { /* Child (qemu). */
483 /* Set up the full command line. Do this in the subprocess so we
484 * don't need to worry about cleaning up.
486 g->cmdline[0] = g->qemu;
488 /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
489 * devices. The -global option must exist, but you can pass any
490 * strings to it so we don't need to check for the specific virtio
493 if (qemu_supports (g, "-global")) {
494 add_cmdline (g, "-global");
495 add_cmdline (g, "virtio-blk-pci.scsi=off");
498 if (qemu_supports (g, "-nodefconfig"))
499 add_cmdline (g, "-nodefconfig");
501 /* The qemu -machine option (added 2010-12) is a bit more sane
502 * since it falls back through various different acceleration
503 * modes, so try that first (thanks Markus Armbruster).
505 if (qemu_supports (g, "-machine")) {
506 add_cmdline (g, "-machine");
507 #if QEMU_MACHINE_TYPE_IS_BROKEN
508 /* Workaround for qemu 0.15: We have to add the '[type=]pc'
509 * since there is no default. This is not a permanent solution
510 * because this only works on PC-like hardware. Other platforms
511 * like ppc would need a different machine type.
513 * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
514 * not a problem in qemu < 0.15.
516 add_cmdline (g, "pc,accel=kvm:tcg");
518 add_cmdline (g, "accel=kvm:tcg");
521 /* qemu sometimes needs this option to enable hardware
522 * virtualization, but some versions of 'qemu-kvm' will use KVM
523 * regardless (even where this option appears in the help text).
524 * It is rumoured that there are versions of qemu where supplying
525 * this option when hardware virtualization is not available will
526 * cause qemu to fail, so we we have to check at least that
527 * /dev/kvm is openable. That's not reliable, since /dev/kvm
528 * might be openable by qemu but not by us (think: SELinux) in
529 * which case the user would not get hardware virtualization,
530 * although at least shouldn't fail. A giant clusterfuck with the
531 * qemu command line, again.
533 if (qemu_supports (g, "-enable-kvm") &&
534 is_openable (g, "/dev/kvm", O_RDWR))
535 add_cmdline (g, "-enable-kvm");
538 /* Newer versions of qemu (from around 2009/12) changed the
539 * behaviour of monitors so that an implicit '-monitor stdio' is
540 * assumed if we are in -nographic mode and there is no other
541 * -monitor option. Only a single stdio device is allowed, so
542 * this broke the '-serial stdio' option. There is a new flag
543 * called -nodefaults which gets rid of all this default crud, so
544 * let's use that to avoid this and any future surprises.
546 if (qemu_supports (g, "-nodefaults"))
547 add_cmdline (g, "-nodefaults");
549 add_cmdline (g, "-nographic");
551 snprintf (buf, sizeof buf, "%d", g->memsize);
552 add_cmdline (g, "-m");
553 add_cmdline (g, buf);
555 /* Force exit instead of reboot on panic */
556 add_cmdline (g, "-no-reboot");
558 /* These options recommended by KVM developers to improve reliability. */
559 if (qemu_supports (g, "-no-hpet"))
560 add_cmdline (g, "-no-hpet");
562 if (qemu_supports (g, "-rtc-td-hack"))
563 add_cmdline (g, "-rtc-td-hack");
565 /* Create the virtio serial bus. */
566 add_cmdline (g, "-device");
567 add_cmdline (g, "virtio-serial");
570 /* Use virtio-console (a variant form of virtio-serial) for the
571 * guest's serial console.
573 add_cmdline (g, "-chardev");
574 add_cmdline (g, "stdio,id=console");
575 add_cmdline (g, "-device");
576 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
578 /* When the above works ... until then: */
579 add_cmdline (g, "-serial");
580 add_cmdline (g, "stdio");
583 /* Set up virtio-serial for the communications channel. */
584 add_cmdline (g, "-chardev");
585 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
586 add_cmdline (g, buf);
587 add_cmdline (g, "-device");
588 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
590 /* Enable user networking. */
591 if (g->enable_network) {
592 add_cmdline (g, "-netdev");
593 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
594 add_cmdline (g, "-device");
595 add_cmdline (g, NET_IF ",netdev=usernet");
598 #define LINUX_CMDLINE \
599 "panic=1 " /* force kernel to panic if daemon exits */ \
600 "console=ttyS0 " /* serial console */ \
601 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
602 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
603 "acpi=off " /* we don't need ACPI, turn it off */ \
604 "printk.time=1 " /* display timestamp before kernel messages */ \
605 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
607 /* Linux kernel command line. */
608 snprintf (buf, sizeof buf,
610 "%s " /* (selinux) */
611 "%s " /* (verbose) */
612 "TERM=%s " /* (TERM environment variable) */
614 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
615 g->verbose ? "guestfs_verbose=1" : "",
616 getenv ("TERM") ? : "linux",
617 g->append ? g->append : "");
619 add_cmdline (g, "-kernel");
620 add_cmdline (g, kernel);
621 add_cmdline (g, "-initrd");
622 add_cmdline (g, initrd);
623 add_cmdline (g, "-append");
624 add_cmdline (g, buf);
626 /* Add the ext2 appliance drive (last of all). */
628 const char *cachemode = "";
629 if (qemu_supports (g, "cache=")) {
630 if (qemu_supports (g, "unsafe"))
631 cachemode = ",cache=unsafe";
632 else if (qemu_supports (g, "writeback"))
633 cachemode = ",cache=writeback";
636 char buf2[PATH_MAX + 64];
637 add_cmdline (g, "-drive");
638 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
639 appliance, cachemode);
640 add_cmdline (g, buf2);
643 /* Finish off the command line. */
644 incr_cmdline_size (g);
645 g->cmdline[g->cmdline_size-1] = NULL;
648 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
651 /* Set up stdin, stdout, stderr. */
658 if (dup (wfd[0]) == -1) {
660 perror ("dup failed");
661 _exit (EXIT_FAILURE);
664 if (dup (rfd[1]) == -1)
667 /* Particularly since qemu 0.15, qemu spews all sorts of debug
668 * information on stderr. It is useful to both capture this and
669 * not confuse casual users, so send stderr to the pipe as well.
672 if (dup (rfd[1]) == -1)
680 /* Set up a new process group, so we can signal this process
681 * and all subprocesses (eg. if qemu is really a shell script).
686 setenv ("LC_ALL", "C", 1);
688 execv (g->qemu, g->cmdline); /* Run qemu. */
690 _exit (EXIT_FAILURE);
693 /* Parent (library). */
703 /* Fork the recovery process off which will kill qemu if the parent
704 * process fails to do so (eg. if the parent segfaults).
707 if (g->recovery_proc) {
710 pid_t qemu_pid = g->pid;
711 pid_t parent_pid = getppid ();
713 /* Writing to argv is hideously complicated and error prone. See:
714 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
717 /* Loop around waiting for one or both of the other processes to
718 * disappear. It's fair to say this is very hairy. The PIDs that
719 * we are looking at might be reused by another process. We are
720 * effectively polling. Is the cure worse than the disease?
723 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
724 _exit (EXIT_SUCCESS);
725 if (kill (parent_pid, 0) == -1) {
726 /* Parent's gone away, qemu still around, so kill qemu. */
728 _exit (EXIT_SUCCESS);
734 /* Don't worry, if the fork failed, this will be -1. The recovery
735 * process isn't essential.
741 /* Close the other ends of the pipe. */
745 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
746 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
747 perrorf (g, "fcntl");
751 g->fd[0] = wfd[1]; /* stdin of child */
752 g->fd[1] = rfd[0]; /* stdout of child */
754 g->fd[0] = open ("/dev/null", O_RDWR);
755 if (g->fd[0] == -1) {
756 perrorf (g, "open /dev/null");
759 g->fd[1] = dup (g->fd[0]);
760 if (g->fd[1] == -1) {
767 g->state = LAUNCHING;
769 /* Wait for qemu to start and to connect back to us via
770 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
772 r = guestfs___accept_from_daemon (g);
776 close (g->sock); /* Close the listening socket. */
777 g->sock = r; /* This is the accepted data socket. */
779 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
780 perrorf (g, "fcntl");
786 r = guestfs___recv_from_daemon (g, &size, &buf);
789 if (r == -1) return -1;
791 if (size != GUESTFS_LAUNCH_FLAG) {
792 error (g, _("guestfs_launch failed, see earlier error messages"));
797 guestfs___print_timestamped_message (g, "appliance is up");
799 /* This is possible in some really strange situations, such as
800 * guestfsd starts up OK but then qemu immediately exits. Check for
801 * it because the caller is probably expecting to be able to send
802 * commands after this function returns.
804 if (g->state != READY) {
805 error (g, _("qemu launched and contacted daemon, but state != READY"));
809 guestfs___launch_send_progress (g, 12);
818 if (g->pid > 0) kill (g->pid, 9);
819 if (g->recoverypid > 0) kill (g->recoverypid, 9);
820 if (g->pid > 0) waitpid (g->pid, NULL, 0);
821 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
826 memset (&g->launch_t, 0, sizeof g->launch_t);
840 /* Alternate attach method: instead of launching the appliance,
841 * connect to an existing unix socket.
844 connect_unix_socket (guestfs_h *g, const char *sockpath)
847 struct sockaddr_un addr;
849 /* Start the clock ... */
850 gettimeofday (&g->launch_t, NULL);
852 /* Set these to nothing so we don't try to kill random processes or
853 * read from random file descriptors.
861 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
863 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
865 perrorf (g, "socket");
869 addr.sun_family = AF_UNIX;
870 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
871 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
873 g->state = LAUNCHING;
875 if (connect (g->sock, &addr, sizeof addr) == -1) {
880 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
881 perrorf (g, "fcntl");
887 r = guestfs___recv_from_daemon (g, &size, &buf);
890 if (r == -1) return -1;
892 if (size != GUESTFS_LAUNCH_FLAG) {
893 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
898 guestfs___print_timestamped_message (g, "connected");
900 if (g->state != READY) {
901 error (g, _("contacted guestfsd, but state != READY"));
912 /* launch (of the ordinary appliance) generates approximate progress
913 * messages. Currently these are defined as follows:
915 * 0 / 12: launch clock starts
916 * 3 / 12: appliance created
917 * 6 / 12: detected that guest kernel started
918 * 9 / 12: detected that /init script is running
919 * 12 / 12: launch completed successfully
922 * (1) This is not a documented ABI and the behaviour may be changed
923 * or removed in future.
924 * (2) Messages are only sent if more than 5 seconds has elapsed
925 * since the launch clock started.
926 * (3) There is a gross hack in proto.c to make this work.
929 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
933 gettimeofday (&tv, NULL);
934 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
935 guestfs_progress progress_message =
936 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
938 guestfs___progress_message_callback (g, &progress_message);
942 /* Return the location of the tmpdir (eg. "/tmp") and allow users
943 * to override it at runtime using $TMPDIR.
944 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
947 guestfs_tmpdir (void)
957 const char *t = getenv ("TMPDIR");
963 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
964 * allow users to override it at runtime using $TMPDIR.
965 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
968 guestfs___persistent_tmpdir (void)
974 const char *t = getenv ("TMPDIR");
980 /* Compute Y - X and return the result in milliseconds.
981 * Approximately the same as this code:
982 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
985 timeval_diff (const struct timeval *x, const struct timeval *y)
989 msec = (y->tv_sec - x->tv_sec) * 1000;
990 msec += (y->tv_usec - x->tv_usec) / 1000;
995 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
1003 fp = open_memstream (&buf, &len);
1005 warning (g, "open_memstream: %m");
1010 gettimeofday (&tv, NULL);
1011 fprintf (fp, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1014 if (argv[i][0] == '-') /* -option starts a new line */
1015 fprintf (fp, " \\\n ");
1017 if (i > 0) fputc (' ', fp);
1019 /* Does it need shell quoting? This only deals with simple cases. */
1020 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1022 if (needs_quote) fputc ('\'', fp);
1023 fprintf (fp, "%s", argv[i]);
1024 if (needs_quote) fputc ('\'', fp);
1030 debug (g, "%s", buf);
1036 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1043 va_start (args, fs);
1044 err = vasprintf (&msg, fs, args);
1047 if (err < 0) return;
1049 gettimeofday (&tv, NULL);
1051 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1056 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1057 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1059 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1060 * 'qemu -version' so we know what options this qemu supports and
1064 test_qemu (guestfs_h *g)
1069 free (g->qemu_help);
1070 g->qemu_help = NULL;
1071 free (g->qemu_version);
1072 g->qemu_version = NULL;
1074 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1076 /* qemu -help should always work (qemu -version OTOH wasn't
1077 * supported by qemu 0.9). If this command doesn't work then it
1078 * probably indicates that the qemu binary is missing.
1080 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1081 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1085 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1088 /* Intentionally ignore errors from qemu -version. */
1089 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1095 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1099 fp = popen (cmd, "r");
1103 if (read_all (g, fp, ret) == -1) {
1108 if (pclose (fp) != 0)
1115 read_all (guestfs_h *g, FILE *fp, char **ret)
1122 *ret = safe_realloc (g, *ret, n + 1);
1127 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1129 r = fread (p, 1, BUFSIZ, fp);
1131 perrorf (g, "read");
1138 /* Test if option is supported by qemu command line (just by grepping
1141 * The first time this is used, it has to run the external qemu
1142 * binary. If that fails, it returns -1.
1144 * To just do the first-time run of the qemu binary, call this with
1145 * option == NULL, in which case it will return -1 if there was an
1149 qemu_supports (guestfs_h *g, const char *option)
1151 if (!g->qemu_help) {
1152 if (test_qemu (g) == -1)
1159 return strstr (g->qemu_help, option) != NULL;
1162 /* Check if a file can be opened. */
1164 is_openable (guestfs_h *g, const char *path, int flags)
1166 int fd = open (path, flags);
1168 debug (g, "is_openable: %s: %m", path);
1175 /* You had to call this function after launch in versions <= 1.0.70,
1176 * but it is now a no-op.
1179 guestfs__wait_ready (guestfs_h *g)
1181 if (g->state != READY) {
1182 error (g, _("qemu has not been launched yet"));
1190 guestfs__kill_subprocess (guestfs_h *g)
1192 if (g->state == CONFIG) {
1193 error (g, _("no subprocess to kill"));
1197 debug (g, "sending SIGTERM to process %d", g->pid);
1199 if (g->pid > 0) kill (g->pid, SIGTERM);
1200 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1205 /* Access current state. */
1207 guestfs__is_config (guestfs_h *g)
1209 return g->state == CONFIG;
1213 guestfs__is_launching (guestfs_h *g)
1215 return g->state == LAUNCHING;
1219 guestfs__is_ready (guestfs_h *g)
1221 return g->state == READY;
1225 guestfs__is_busy (guestfs_h *g)
1227 return g->state == BUSY;
1231 guestfs__get_state (guestfs_h *g)