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 if (qemu_supports (g, "-nodefconfig"))
489 add_cmdline (g, "-nodefconfig");
491 /* The qemu -machine option (added 2010-12) is a bit more sane
492 * since it falls back through various different acceleration
493 * modes, so try that first (thanks Markus Armbruster).
495 if (qemu_supports (g, "-machine")) {
496 add_cmdline (g, "-machine");
497 add_cmdline (g, "accel=kvm:tcg");
499 /* qemu sometimes needs this option to enable hardware
500 * virtualization, but some versions of 'qemu-kvm' will use KVM
501 * regardless (even where this option appears in the help text).
502 * It is rumoured that there are versions of qemu where supplying
503 * this option when hardware virtualization is not available will
504 * cause qemu to fail, so we we have to check at least that
505 * /dev/kvm is openable. That's not reliable, since /dev/kvm
506 * might be openable by qemu but not by us (think: SELinux) in
507 * which case the user would not get hardware virtualization,
508 * although at least shouldn't fail. A giant clusterfuck with the
509 * qemu command line, again.
511 if (qemu_supports (g, "-enable-kvm") &&
512 is_openable (g, "/dev/kvm", O_RDWR))
513 add_cmdline (g, "-enable-kvm");
516 /* Newer versions of qemu (from around 2009/12) changed the
517 * behaviour of monitors so that an implicit '-monitor stdio' is
518 * assumed if we are in -nographic mode and there is no other
519 * -monitor option. Only a single stdio device is allowed, so
520 * this broke the '-serial stdio' option. There is a new flag
521 * called -nodefaults which gets rid of all this default crud, so
522 * let's use that to avoid this and any future surprises.
524 if (qemu_supports (g, "-nodefaults"))
525 add_cmdline (g, "-nodefaults");
527 add_cmdline (g, "-nographic");
529 snprintf (buf, sizeof buf, "%d", g->memsize);
530 add_cmdline (g, "-m");
531 add_cmdline (g, buf);
533 /* Force exit instead of reboot on panic */
534 add_cmdline (g, "-no-reboot");
536 /* These options recommended by KVM developers to improve reliability. */
537 if (qemu_supports (g, "-no-hpet"))
538 add_cmdline (g, "-no-hpet");
540 if (qemu_supports (g, "-rtc-td-hack"))
541 add_cmdline (g, "-rtc-td-hack");
543 /* Create the virtio serial bus. */
544 add_cmdline (g, "-device");
545 add_cmdline (g, "virtio-serial");
548 /* Use virtio-console (a variant form of virtio-serial) for the
549 * guest's serial console.
551 add_cmdline (g, "-chardev");
552 add_cmdline (g, "stdio,id=console");
553 add_cmdline (g, "-device");
554 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
556 /* When the above works ... until then: */
557 add_cmdline (g, "-serial");
558 add_cmdline (g, "stdio");
561 /* Set up virtio-serial for the communications channel. */
562 add_cmdline (g, "-chardev");
563 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
564 add_cmdline (g, buf);
565 add_cmdline (g, "-device");
566 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
568 /* Enable user networking. */
569 if (g->enable_network) {
570 add_cmdline (g, "-netdev");
571 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
572 add_cmdline (g, "-device");
573 add_cmdline (g, NET_IF ",netdev=usernet");
576 #define LINUX_CMDLINE \
577 "panic=1 " /* force kernel to panic if daemon exits */ \
578 "console=ttyS0 " /* serial console */ \
579 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
580 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
581 "acpi=off " /* we don't need ACPI, turn it off */ \
582 "printk.time=1 " /* display timestamp before kernel messages */ \
583 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
585 /* Linux kernel command line. */
586 snprintf (buf, sizeof buf,
588 "%s " /* (selinux) */
589 "%s " /* (verbose) */
590 "TERM=%s " /* (TERM environment variable) */
592 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
593 g->verbose ? "guestfs_verbose=1" : "",
594 getenv ("TERM") ? : "linux",
595 g->append ? g->append : "");
597 add_cmdline (g, "-kernel");
598 add_cmdline (g, kernel);
599 add_cmdline (g, "-initrd");
600 add_cmdline (g, initrd);
601 add_cmdline (g, "-append");
602 add_cmdline (g, buf);
604 /* Add the ext2 appliance drive (last of all). */
606 const char *cachemode = "";
607 if (qemu_supports (g, "cache=")) {
608 if (qemu_supports (g, "unsafe"))
609 cachemode = ",cache=unsafe";
610 else if (qemu_supports (g, "writeback"))
611 cachemode = ",cache=writeback";
614 char buf2[PATH_MAX + 64];
615 add_cmdline (g, "-drive");
616 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
617 appliance, cachemode);
618 add_cmdline (g, buf2);
621 /* Finish off the command line. */
622 incr_cmdline_size (g);
623 g->cmdline[g->cmdline_size-1] = NULL;
626 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
629 /* Set up stdin, stdout, stderr. */
636 if (dup (wfd[0]) == -1) {
638 perror ("dup failed");
639 _exit (EXIT_FAILURE);
642 if (dup (rfd[1]) == -1)
645 /* Particularly since qemu 0.15, qemu spews all sorts of debug
646 * information on stderr. It is useful to both capture this and
647 * not confuse casual users, so send stderr to the pipe as well.
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). */
681 /* Fork the recovery process off which will kill qemu if the parent
682 * process fails to do so (eg. if the parent segfaults).
685 if (g->recovery_proc) {
688 pid_t qemu_pid = g->pid;
689 pid_t parent_pid = getppid ();
691 /* Writing to argv is hideously complicated and error prone. See:
692 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
695 /* Loop around waiting for one or both of the other processes to
696 * disappear. It's fair to say this is very hairy. The PIDs that
697 * we are looking at might be reused by another process. We are
698 * effectively polling. Is the cure worse than the disease?
701 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
702 _exit (EXIT_SUCCESS);
703 if (kill (parent_pid, 0) == -1) {
704 /* Parent's gone away, qemu still around, so kill qemu. */
706 _exit (EXIT_SUCCESS);
712 /* Don't worry, if the fork failed, this will be -1. The recovery
713 * process isn't essential.
719 /* Close the other ends of the pipe. */
723 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
724 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
725 perrorf (g, "fcntl");
729 g->fd[0] = wfd[1]; /* stdin of child */
730 g->fd[1] = rfd[0]; /* stdout of child */
732 g->fd[0] = open ("/dev/null", O_RDWR);
733 if (g->fd[0] == -1) {
734 perrorf (g, "open /dev/null");
737 g->fd[1] = dup (g->fd[0]);
738 if (g->fd[1] == -1) {
745 g->state = LAUNCHING;
747 /* Wait for qemu to start and to connect back to us via
748 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
750 r = guestfs___accept_from_daemon (g);
754 close (g->sock); /* Close the listening socket. */
755 g->sock = r; /* This is the accepted data socket. */
757 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
758 perrorf (g, "fcntl");
764 r = guestfs___recv_from_daemon (g, &size, &buf);
767 if (r == -1) return -1;
769 if (size != GUESTFS_LAUNCH_FLAG) {
770 error (g, _("guestfs_launch failed, see earlier error messages"));
775 guestfs___print_timestamped_message (g, "appliance is up");
777 /* This is possible in some really strange situations, such as
778 * guestfsd starts up OK but then qemu immediately exits. Check for
779 * it because the caller is probably expecting to be able to send
780 * commands after this function returns.
782 if (g->state != READY) {
783 error (g, _("qemu launched and contacted daemon, but state != READY"));
787 guestfs___launch_send_progress (g, 12);
796 if (g->pid > 0) kill (g->pid, 9);
797 if (g->recoverypid > 0) kill (g->recoverypid, 9);
798 if (g->pid > 0) waitpid (g->pid, NULL, 0);
799 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
804 memset (&g->launch_t, 0, sizeof g->launch_t);
818 /* Alternate attach method: instead of launching the appliance,
819 * connect to an existing unix socket.
822 connect_unix_socket (guestfs_h *g, const char *sockpath)
825 struct sockaddr_un addr;
827 /* Start the clock ... */
828 gettimeofday (&g->launch_t, NULL);
830 /* Set these to nothing so we don't try to kill random processes or
831 * read from random file descriptors.
839 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
841 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
843 perrorf (g, "socket");
847 addr.sun_family = AF_UNIX;
848 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
849 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
851 g->state = LAUNCHING;
853 if (connect (g->sock, &addr, sizeof addr) == -1) {
858 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
859 perrorf (g, "fcntl");
865 r = guestfs___recv_from_daemon (g, &size, &buf);
868 if (r == -1) return -1;
870 if (size != GUESTFS_LAUNCH_FLAG) {
871 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
876 guestfs___print_timestamped_message (g, "connected");
878 if (g->state != READY) {
879 error (g, _("contacted guestfsd, but state != READY"));
890 /* launch (of the ordinary appliance) generates approximate progress
891 * messages. Currently these are defined as follows:
893 * 0 / 12: launch clock starts
894 * 3 / 12: appliance created
895 * 6 / 12: detected that guest kernel started
896 * 9 / 12: detected that /init script is running
897 * 12 / 12: launch completed successfully
900 * (1) This is not a documented ABI and the behaviour may be changed
901 * or removed in future.
902 * (2) Messages are only sent if more than 5 seconds has elapsed
903 * since the launch clock started.
904 * (3) There is a gross hack in proto.c to make this work.
907 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
911 gettimeofday (&tv, NULL);
912 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
913 guestfs_progress progress_message =
914 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
916 guestfs___progress_message_callback (g, &progress_message);
920 /* Return the location of the tmpdir (eg. "/tmp") and allow users
921 * to override it at runtime using $TMPDIR.
922 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
925 guestfs_tmpdir (void)
935 const char *t = getenv ("TMPDIR");
941 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
942 * allow users to override it at runtime using $TMPDIR.
943 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
946 guestfs___persistent_tmpdir (void)
952 const char *t = getenv ("TMPDIR");
958 /* Compute Y - X and return the result in milliseconds.
959 * Approximately the same as this code:
960 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
963 timeval_diff (const struct timeval *x, const struct timeval *y)
967 msec = (y->tv_sec - x->tv_sec) * 1000;
968 msec += (y->tv_usec - x->tv_usec) / 1000;
973 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
981 fp = open_memstream (&buf, &len);
983 warning (g, "open_memstream: %m");
988 gettimeofday (&tv, NULL);
989 fprintf (fp, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
992 if (argv[i][0] == '-') /* -option starts a new line */
993 fprintf (fp, " \\\n ");
995 if (i > 0) fputc (' ', fp);
997 /* Does it need shell quoting? This only deals with simple cases. */
998 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1000 if (needs_quote) fputc ('\'', fp);
1001 fprintf (fp, "%s", argv[i]);
1002 if (needs_quote) fputc ('\'', fp);
1008 debug (g, "%s", buf);
1014 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1021 va_start (args, fs);
1022 err = vasprintf (&msg, fs, args);
1025 if (err < 0) return;
1027 gettimeofday (&tv, NULL);
1029 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1034 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1035 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1037 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1038 * 'qemu -version' so we know what options this qemu supports and
1042 test_qemu (guestfs_h *g)
1047 free (g->qemu_help);
1048 g->qemu_help = NULL;
1049 free (g->qemu_version);
1050 g->qemu_version = NULL;
1052 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1054 /* qemu -help should always work (qemu -version OTOH wasn't
1055 * supported by qemu 0.9). If this command doesn't work then it
1056 * probably indicates that the qemu binary is missing.
1058 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1059 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1063 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1066 /* Intentionally ignore errors from qemu -version. */
1067 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1073 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1077 fp = popen (cmd, "r");
1081 if (read_all (g, fp, ret) == -1) {
1086 if (pclose (fp) != 0)
1093 read_all (guestfs_h *g, FILE *fp, char **ret)
1100 *ret = safe_realloc (g, *ret, n + 1);
1105 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1107 r = fread (p, 1, BUFSIZ, fp);
1109 perrorf (g, "read");
1116 /* Test if option is supported by qemu command line (just by grepping
1119 * The first time this is used, it has to run the external qemu
1120 * binary. If that fails, it returns -1.
1122 * To just do the first-time run of the qemu binary, call this with
1123 * option == NULL, in which case it will return -1 if there was an
1127 qemu_supports (guestfs_h *g, const char *option)
1129 if (!g->qemu_help) {
1130 if (test_qemu (g) == -1)
1137 return strstr (g->qemu_help, option) != NULL;
1140 /* Check if a file can be opened. */
1142 is_openable (guestfs_h *g, const char *path, int flags)
1144 int fd = open (path, flags);
1146 debug (g, "is_openable: %s: %m", path);
1153 /* You had to call this function after launch in versions <= 1.0.70,
1154 * but it is now a no-op.
1157 guestfs__wait_ready (guestfs_h *g)
1159 if (g->state != READY) {
1160 error (g, _("qemu has not been launched yet"));
1168 guestfs__kill_subprocess (guestfs_h *g)
1170 if (g->state == CONFIG) {
1171 error (g, _("no subprocess to kill"));
1175 debug (g, "sending SIGTERM to process %d", g->pid);
1177 if (g->pid > 0) kill (g->pid, SIGTERM);
1178 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1183 /* Access current state. */
1185 guestfs__is_config (guestfs_h *g)
1187 return g->state == CONFIG;
1191 guestfs__is_launching (guestfs_h *g)
1193 return g->state == LAUNCHING;
1197 guestfs__is_ready (guestfs_h *g)
1199 return g->state == READY;
1203 guestfs__is_busy (guestfs_h *g)
1205 return g->state == BUSY;
1209 guestfs__get_state (guestfs_h *g)