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 "ignore-value.h"
67 #include "glthread/lock.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);
80 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
82 static void compile_regexps (void) __attribute__((constructor));
83 static void free_regexps (void) __attribute__((destructor));
86 compile_regexps (void)
91 #define COMPILE(re,pattern,options) \
93 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
95 ignore_value (write (2, err, strlen (err))); \
107 /* Add a string to the current command line. */
109 incr_cmdline_size (guestfs_h *g)
111 if (g->cmdline == NULL) {
112 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
114 g->cmdline = safe_malloc (g, sizeof (char *));
115 g->cmdline[0] = NULL;
119 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
123 add_cmdline (guestfs_h *g, const char *str)
125 if (g->state != CONFIG) {
127 _("command line cannot be altered after qemu subprocess launched"));
131 incr_cmdline_size (g);
132 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
137 guestfs___checkpoint_cmdline (guestfs_h *g)
139 return g->cmdline_size;
143 guestfs___rollback_cmdline (guestfs_h *g, size_t pos)
147 assert (g->cmdline_size >= pos);
149 for (i = pos; i < g->cmdline_size; ++i)
150 free (g->cmdline[i]);
152 g->cmdline_size = pos;
155 /* Internal command to return the command line. */
157 guestfs__debug_cmdline (guestfs_h *g)
162 if (g->cmdline == NULL) {
163 r = safe_malloc (g, sizeof (char *) * 1);
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 */
180 guestfs__config (guestfs_h *g,
181 const char *qemu_param, const char *qemu_value)
183 if (qemu_param[0] != '-') {
184 error (g, _("guestfs_config: parameter must begin with '-' character"));
188 /* A bit fascist, but the user will probably break the extra
189 * parameters that we add if they try to set any of these.
191 if (STREQ (qemu_param, "-kernel") ||
192 STREQ (qemu_param, "-initrd") ||
193 STREQ (qemu_param, "-nographic") ||
194 STREQ (qemu_param, "-serial") ||
195 STREQ (qemu_param, "-full-screen") ||
196 STREQ (qemu_param, "-std-vga") ||
197 STREQ (qemu_param, "-vnc")) {
198 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
202 if (add_cmdline (g, qemu_param) != 0) return -1;
204 if (qemu_value != NULL) {
205 if (add_cmdline (g, qemu_value) != 0) return -1;
211 /* cache=off improves reliability in the event of a host crash.
213 * However this option causes qemu to try to open the file with
214 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
215 * So we check if we can open the file with or without O_DIRECT,
216 * and use cache=off (or not) accordingly.
219 test_cache_off (guestfs_h *g, const char *filename)
221 int fd = open (filename, O_RDONLY|O_DIRECT);
227 fd = open (filename, O_RDONLY);
233 perrorf (g, "%s", filename);
237 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
239 valid_format_iface (const char *str)
241 size_t len = strlen (str);
249 if (c != '-' && c != '_' && !c_isalnum (c))
256 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
257 const struct guestfs_add_drive_opts_argv *optargs)
263 if (strchr (filename, ',') != NULL) {
264 error (g, _("filename cannot contain ',' (comma) character"));
268 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
269 ? optargs->readonly : 0;
270 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
271 ? optargs->format : NULL;
272 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
273 ? optargs->iface : DRIVE_IF;
275 if (format && !valid_format_iface (format)) {
276 error (g, _("%s parameter is empty or contains disallowed characters"),
280 if (!valid_format_iface (iface)) {
281 error (g, _("%s parameter is empty or contains disallowed characters"),
286 /* For writable files, see if we can use cache=off. This also
287 * checks for the existence of the file. For readonly we have
288 * to do the check explicitly.
290 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
291 if (use_cache_off == -1)
295 if (access (filename, F_OK) == -1) {
296 perrorf (g, "%s", filename);
301 /* Construct the final -drive parameter. */
302 size_t len = 64 + strlen (filename) + strlen (iface);
303 if (format) len += strlen (format);
306 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
308 readonly ? ",snapshot=on" : "",
309 use_cache_off ? ",cache=off" : "",
310 format ? ",format=" : "",
311 format ? format : "",
314 return guestfs__config (g, "-drive", buf);
318 guestfs__add_drive (guestfs_h *g, const char *filename)
320 struct guestfs_add_drive_opts_argv optargs = {
324 return guestfs__add_drive_opts (g, filename, &optargs);
328 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
330 struct guestfs_add_drive_opts_argv optargs = {
331 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
335 return guestfs__add_drive_opts (g, filename, &optargs);
339 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
342 struct guestfs_add_drive_opts_argv optargs = {
343 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
347 return guestfs__add_drive_opts (g, filename, &optargs);
351 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
354 struct guestfs_add_drive_opts_argv optargs = {
355 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
356 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
361 return guestfs__add_drive_opts (g, filename, &optargs);
365 guestfs__add_cdrom (guestfs_h *g, const char *filename)
367 if (strchr (filename, ',') != NULL) {
368 error (g, _("filename cannot contain ',' (comma) character"));
372 if (access (filename, F_OK) == -1) {
373 perrorf (g, "%s", filename);
377 return guestfs__config (g, "-cdrom", filename);
380 static int is_openable (guestfs_h *g, const char *path, int flags);
383 guestfs__launch (guestfs_h *g)
386 if (g->state != CONFIG) {
387 error (g, _("the libguestfs handle has already been launched"));
391 /* Make the temporary directory. */
393 TMP_TEMPLATE_ON_STACK (dir_template);
394 g->tmpdir = safe_strdup (g, dir_template);
395 if (mkdtemp (g->tmpdir) == NULL) {
396 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
401 /* Allow anyone to read the temporary directory. The socket in this
402 * directory won't be readable but anyone can see it exists if they
403 * want. (RHBZ#610880).
405 if (chmod (g->tmpdir, 0755) == -1)
406 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
408 /* Launch the appliance or attach to an existing daemon. */
409 switch (g->attach_method) {
410 case ATTACH_METHOD_APPLIANCE:
411 return launch_appliance (g);
413 case ATTACH_METHOD_UNIX:
414 return connect_unix_socket (g, g->attach_method_arg);
422 launch_appliance (guestfs_h *g)
426 char guestfsd_sock[256];
427 struct sockaddr_un addr;
429 /* At present you must add drives before starting the appliance. In
430 * future when we enable hotplugging you won't need to do this.
433 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
437 /* Start the clock ... */
438 gettimeofday (&g->launch_t, NULL);
439 guestfs___launch_send_progress (g, 0);
441 /* Locate and/or build the appliance. */
442 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
443 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
446 guestfs___launch_send_progress (g, 3);
449 guestfs___print_timestamped_message (g, "begin testing qemu features");
451 /* Get qemu help text and version. */
452 if (qemu_supports (g, NULL) == -1)
455 /* Using virtio-serial, we need to create a local Unix domain socket
456 * for qemu to connect to.
458 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
459 unlink (guestfsd_sock);
461 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
463 perrorf (g, "socket");
467 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
468 perrorf (g, "fcntl");
472 addr.sun_family = AF_UNIX;
473 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
474 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
476 if (bind (g->sock, &addr, sizeof addr) == -1) {
481 if (listen (g->sock, 1) == -1) {
482 perrorf (g, "listen");
487 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
494 guestfs___print_timestamped_message (g, "finished testing qemu features");
508 if (r == 0) { /* Child (qemu). */
511 /* Set up the full command line. Do this in the subprocess so we
512 * don't need to worry about cleaning up.
514 g->cmdline[0] = g->qemu;
516 if (qemu_supports (g, "-nodefconfig"))
517 add_cmdline (g, "-nodefconfig");
519 /* The qemu -machine option (added 2010-12) is a bit more sane
520 * since it falls back through various different acceleration
521 * modes, so try that first (thanks Markus Armbruster).
523 if (qemu_supports (g, "-machine")) {
524 add_cmdline (g, "-machine");
525 add_cmdline (g, "accel=kvm:tcg");
527 /* qemu sometimes needs this option to enable hardware
528 * virtualization, but some versions of 'qemu-kvm' will use KVM
529 * regardless (even where this option appears in the help text).
530 * It is rumoured that there are versions of qemu where supplying
531 * this option when hardware virtualization is not available will
532 * cause qemu to fail, so we we have to check at least that
533 * /dev/kvm is openable. That's not reliable, since /dev/kvm
534 * might be openable by qemu but not by us (think: SELinux) in
535 * which case the user would not get hardware virtualization,
536 * although at least shouldn't fail. A giant clusterfuck with the
537 * qemu command line, again.
539 if (qemu_supports (g, "-enable-kvm") &&
540 is_openable (g, "/dev/kvm", O_RDWR))
541 add_cmdline (g, "-enable-kvm");
544 /* Newer versions of qemu (from around 2009/12) changed the
545 * behaviour of monitors so that an implicit '-monitor stdio' is
546 * assumed if we are in -nographic mode and there is no other
547 * -monitor option. Only a single stdio device is allowed, so
548 * this broke the '-serial stdio' option. There is a new flag
549 * called -nodefaults which gets rid of all this default crud, so
550 * let's use that to avoid this and any future surprises.
552 if (qemu_supports (g, "-nodefaults"))
553 add_cmdline (g, "-nodefaults");
555 add_cmdline (g, "-nographic");
557 snprintf (buf, sizeof buf, "%d", g->memsize);
558 add_cmdline (g, "-m");
559 add_cmdline (g, buf);
561 /* Force exit instead of reboot on panic */
562 add_cmdline (g, "-no-reboot");
564 /* These options recommended by KVM developers to improve reliability. */
565 if (qemu_supports (g, "-no-hpet"))
566 add_cmdline (g, "-no-hpet");
568 if (qemu_supports (g, "-rtc-td-hack"))
569 add_cmdline (g, "-rtc-td-hack");
571 /* Create the virtio serial bus. */
572 add_cmdline (g, "-device");
573 add_cmdline (g, "virtio-serial");
576 /* Use virtio-console (a variant form of virtio-serial) for the
577 * guest's serial console.
579 add_cmdline (g, "-chardev");
580 add_cmdline (g, "stdio,id=console");
581 add_cmdline (g, "-device");
582 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
584 /* When the above works ... until then: */
585 add_cmdline (g, "-serial");
586 add_cmdline (g, "stdio");
589 /* Set up virtio-serial for the communications channel. */
590 add_cmdline (g, "-chardev");
591 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
592 add_cmdline (g, buf);
593 add_cmdline (g, "-device");
594 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
596 /* Enable user networking. */
597 if (g->enable_network) {
598 add_cmdline (g, "-netdev");
599 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
600 add_cmdline (g, "-device");
601 add_cmdline (g, NET_IF ",netdev=usernet");
604 #define LINUX_CMDLINE \
605 "panic=1 " /* force kernel to panic if daemon exits */ \
606 "console=ttyS0 " /* serial console */ \
607 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
608 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
609 "acpi=off " /* we don't need ACPI, turn it off */ \
610 "printk.time=1 " /* display timestamp before kernel messages */ \
611 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
613 /* Linux kernel command line. */
614 snprintf (buf, sizeof buf,
616 "%s " /* (selinux) */
617 "%s " /* (verbose) */
618 "TERM=%s " /* (TERM environment variable) */
620 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
621 g->verbose ? "guestfs_verbose=1" : "",
622 getenv ("TERM") ? : "linux",
623 g->append ? g->append : "");
625 add_cmdline (g, "-kernel");
626 add_cmdline (g, kernel);
627 add_cmdline (g, "-initrd");
628 add_cmdline (g, initrd);
629 add_cmdline (g, "-append");
630 add_cmdline (g, buf);
632 /* Add the ext2 appliance drive (last of all). */
634 const char *cachemode = "";
635 if (qemu_supports (g, "cache=")) {
636 if (qemu_supports (g, "unsafe"))
637 cachemode = ",cache=unsafe";
638 else if (qemu_supports (g, "writeback"))
639 cachemode = ",cache=writeback";
642 char buf2[PATH_MAX + 64];
643 add_cmdline (g, "-drive");
644 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
645 appliance, cachemode);
646 add_cmdline (g, buf2);
649 /* Finish off the command line. */
650 incr_cmdline_size (g);
651 g->cmdline[g->cmdline_size-1] = NULL;
654 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
657 /* Set up stdin, stdout, stderr. */
664 if (dup (wfd[0]) == -1) {
666 perror ("dup failed");
667 _exit (EXIT_FAILURE);
670 if (dup (rfd[1]) == -1)
673 /* Particularly since qemu 0.15, qemu spews all sorts of debug
674 * information on stderr. It is useful to both capture this and
675 * not confuse casual users, so send stderr to the pipe as well.
678 if (dup (rfd[1]) == -1)
685 /* Put qemu in a new process group. */
689 setenv ("LC_ALL", "C", 1);
691 execv (g->qemu, g->cmdline); /* Run qemu. */
693 _exit (EXIT_FAILURE);
696 /* Parent (library). */
706 /* Fork the recovery process off which will kill qemu if the parent
707 * process fails to do so (eg. if the parent segfaults).
710 if (g->recovery_proc) {
713 pid_t qemu_pid = g->pid;
714 pid_t parent_pid = getppid ();
716 /* It would be nice to be able to put this in the same process
717 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
718 * not possible because we don't have any guarantee here that
719 * the qemu process has started yet.
724 /* Writing to argv is hideously complicated and error prone. See:
725 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
728 /* Loop around waiting for one or both of the other processes to
729 * disappear. It's fair to say this is very hairy. The PIDs that
730 * we are looking at might be reused by another process. We are
731 * effectively polling. Is the cure worse than the disease?
734 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
735 _exit (EXIT_SUCCESS);
736 if (kill (parent_pid, 0) == -1) {
737 /* Parent's gone away, qemu still around, so kill qemu. */
739 _exit (EXIT_SUCCESS);
745 /* Don't worry, if the fork failed, this will be -1. The recovery
746 * process isn't essential.
752 /* Close the other ends of the pipe. */
756 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
757 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
758 perrorf (g, "fcntl");
762 g->fd[0] = wfd[1]; /* stdin of child */
763 g->fd[1] = rfd[0]; /* stdout of child */
765 g->fd[0] = open ("/dev/null", O_RDWR);
766 if (g->fd[0] == -1) {
767 perrorf (g, "open /dev/null");
770 g->fd[1] = dup (g->fd[0]);
771 if (g->fd[1] == -1) {
778 g->state = LAUNCHING;
780 /* Wait for qemu to start and to connect back to us via
781 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
783 r = guestfs___accept_from_daemon (g);
787 close (g->sock); /* Close the listening socket. */
788 g->sock = r; /* This is the accepted data socket. */
790 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
791 perrorf (g, "fcntl");
797 r = guestfs___recv_from_daemon (g, &size, &buf);
800 if (r == -1) return -1;
802 if (size != GUESTFS_LAUNCH_FLAG) {
803 error (g, _("guestfs_launch failed, see earlier error messages"));
808 guestfs___print_timestamped_message (g, "appliance is up");
810 /* This is possible in some really strange situations, such as
811 * guestfsd starts up OK but then qemu immediately exits. Check for
812 * it because the caller is probably expecting to be able to send
813 * commands after this function returns.
815 if (g->state != READY) {
816 error (g, _("qemu launched and contacted daemon, but state != READY"));
820 guestfs___launch_send_progress (g, 12);
829 if (g->pid > 0) kill (g->pid, 9);
830 if (g->recoverypid > 0) kill (g->recoverypid, 9);
831 if (g->pid > 0) waitpid (g->pid, NULL, 0);
832 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
837 memset (&g->launch_t, 0, sizeof g->launch_t);
851 /* Alternate attach method: instead of launching the appliance,
852 * connect to an existing unix socket.
855 connect_unix_socket (guestfs_h *g, const char *sockpath)
858 struct sockaddr_un addr;
860 /* Start the clock ... */
861 gettimeofday (&g->launch_t, NULL);
863 /* Set these to nothing so we don't try to kill random processes or
864 * read from random file descriptors.
872 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
874 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
876 perrorf (g, "socket");
880 addr.sun_family = AF_UNIX;
881 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
882 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
884 g->state = LAUNCHING;
886 if (connect (g->sock, &addr, sizeof addr) == -1) {
891 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
892 perrorf (g, "fcntl");
898 r = guestfs___recv_from_daemon (g, &size, &buf);
901 if (r == -1) return -1;
903 if (size != GUESTFS_LAUNCH_FLAG) {
904 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
909 guestfs___print_timestamped_message (g, "connected");
911 if (g->state != READY) {
912 error (g, _("contacted guestfsd, but state != READY"));
923 /* launch (of the ordinary appliance) generates approximate progress
924 * messages. Currently these are defined as follows:
926 * 0 / 12: launch clock starts
927 * 3 / 12: appliance created
928 * 6 / 12: detected that guest kernel started
929 * 9 / 12: detected that /init script is running
930 * 12 / 12: launch completed successfully
933 * (1) This is not a documented ABI and the behaviour may be changed
934 * or removed in future.
935 * (2) Messages are only sent if more than 5 seconds has elapsed
936 * since the launch clock started.
937 * (3) There is a gross hack in proto.c to make this work.
940 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
944 gettimeofday (&tv, NULL);
945 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
946 guestfs_progress progress_message =
947 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
949 guestfs___progress_message_callback (g, &progress_message);
953 /* Return the location of the tmpdir (eg. "/tmp") and allow users
954 * to override it at runtime using $TMPDIR.
955 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
958 guestfs_tmpdir (void)
968 const char *t = getenv ("TMPDIR");
974 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
975 * allow users to override it at runtime using $TMPDIR.
976 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
979 guestfs___persistent_tmpdir (void)
985 const char *t = getenv ("TMPDIR");
991 /* Compute Y - X and return the result in milliseconds.
992 * Approximately the same as this code:
993 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
996 timeval_diff (const struct timeval *x, const struct timeval *y)
1000 msec = (y->tv_sec - x->tv_sec) * 1000;
1001 msec += (y->tv_usec - x->tv_usec) / 1000;
1006 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
1014 fp = open_memstream (&buf, &len);
1016 warning (g, "open_memstream: %m");
1021 gettimeofday (&tv, NULL);
1022 fprintf (fp, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1025 if (argv[i][0] == '-') /* -option starts a new line */
1026 fprintf (fp, " \\\n ");
1028 if (i > 0) fputc (' ', fp);
1030 /* Does it need shell quoting? This only deals with simple cases. */
1031 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1033 if (needs_quote) fputc ('\'', fp);
1034 fprintf (fp, "%s", argv[i]);
1035 if (needs_quote) fputc ('\'', fp);
1041 debug (g, "%s", buf);
1047 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1054 va_start (args, fs);
1055 err = vasprintf (&msg, fs, args);
1058 if (err < 0) return;
1060 gettimeofday (&tv, NULL);
1062 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1067 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1069 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1070 * 'qemu -version' so we know what options this qemu supports and
1074 test_qemu (guestfs_h *g)
1079 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1081 fp = popen (cmd, "r");
1082 /* qemu -help should always work (qemu -version OTOH wasn't
1083 * supported by qemu 0.9). If this command doesn't work then it
1084 * probably indicates that the qemu binary is missing.
1087 /* XXX This error is never printed, even if the qemu binary
1088 * doesn't exist. Why?
1091 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1095 if (read_all (g, fp, &g->qemu_help) == -1)
1098 if (pclose (fp) == -1)
1101 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1104 fp = popen (cmd, "r");
1106 /* Intentionally ignore errors. */
1107 read_all (g, fp, &g->qemu_version);
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;
1163 /* As above but using a regex instead of a fixed string. */
1165 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1167 if (!g->qemu_help) {
1168 if (test_qemu (g) == -1)
1172 return match (g, g->qemu_help, option_regex);
1176 /* Check if a file can be opened. */
1178 is_openable (guestfs_h *g, const char *path, int flags)
1180 int fd = open (path, flags);
1182 debug (g, "is_openable: %s: %m", path);
1189 /* You had to call this function after launch in versions <= 1.0.70,
1190 * but it is now a no-op.
1193 guestfs__wait_ready (guestfs_h *g)
1195 if (g->state != READY) {
1196 error (g, _("qemu has not been launched yet"));
1204 guestfs__kill_subprocess (guestfs_h *g)
1206 if (g->state == CONFIG) {
1207 error (g, _("no subprocess to kill"));
1211 debug (g, "sending SIGTERM to process %d", g->pid);
1213 if (g->pid > 0) kill (g->pid, SIGTERM);
1214 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1219 /* Access current state. */
1221 guestfs__is_config (guestfs_h *g)
1223 return g->state == CONFIG;
1227 guestfs__is_launching (guestfs_h *g)
1229 return g->state == LAUNCHING;
1233 guestfs__is_ready (guestfs_h *g)
1235 return g->state == READY;
1239 guestfs__is_busy (guestfs_h *g)
1241 return g->state == BUSY;
1245 guestfs__get_state (guestfs_h *g)