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"
69 #include "guestfs-internal.h"
70 #include "guestfs-internal-actions.h"
71 #include "guestfs_protocol.h"
73 static int launch_appliance (guestfs_h *g);
74 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
75 static int connect_unix_socket (guestfs_h *g, const char *sock);
76 static int qemu_supports (guestfs_h *g, const char *option);
78 /* Add a string to the current command line. */
80 incr_cmdline_size (guestfs_h *g)
82 if (g->cmdline == NULL) {
83 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
85 g->cmdline = safe_malloc (g, sizeof (char *));
90 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
94 add_cmdline (guestfs_h *g, const char *str)
96 if (g->state != CONFIG) {
98 _("command line cannot be altered after qemu subprocess launched"));
102 incr_cmdline_size (g);
103 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
108 guestfs___checkpoint_cmdline (guestfs_h *g)
110 return g->cmdline_size;
114 guestfs___rollback_cmdline (guestfs_h *g, size_t pos)
118 assert (g->cmdline_size >= pos);
120 for (i = pos; i < g->cmdline_size; ++i)
121 free (g->cmdline[i]);
123 g->cmdline_size = pos;
126 /* Internal command to return the command line. */
128 guestfs__debug_cmdline (guestfs_h *g)
133 if (g->cmdline == NULL) {
134 r = safe_malloc (g, sizeof (char *) * 1);
139 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
140 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
142 for (i = 1; i < g->cmdline_size; ++i)
143 r[i] = safe_strdup (g, g->cmdline[i]);
145 r[g->cmdline_size] = NULL;
147 return r; /* caller frees */
151 guestfs__config (guestfs_h *g,
152 const char *qemu_param, const char *qemu_value)
154 if (qemu_param[0] != '-') {
155 error (g, _("guestfs_config: parameter must begin with '-' character"));
159 /* A bit fascist, but the user will probably break the extra
160 * parameters that we add if they try to set any of these.
162 if (STREQ (qemu_param, "-kernel") ||
163 STREQ (qemu_param, "-initrd") ||
164 STREQ (qemu_param, "-nographic") ||
165 STREQ (qemu_param, "-serial") ||
166 STREQ (qemu_param, "-full-screen") ||
167 STREQ (qemu_param, "-std-vga") ||
168 STREQ (qemu_param, "-vnc")) {
169 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
173 if (add_cmdline (g, qemu_param) != 0) return -1;
175 if (qemu_value != NULL) {
176 if (add_cmdline (g, qemu_value) != 0) return -1;
182 /* cache=off improves reliability in the event of a host crash.
184 * However this option causes qemu to try to open the file with
185 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
186 * So we check if we can open the file with or without O_DIRECT,
187 * and use cache=off (or not) accordingly.
190 test_cache_off (guestfs_h *g, const char *filename)
192 int fd = open (filename, O_RDONLY|O_DIRECT);
198 fd = open (filename, O_RDONLY);
204 perrorf (g, "%s", filename);
208 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
210 valid_format_iface (const char *str)
212 size_t len = strlen (str);
220 if (c != '-' && c != '_' && !c_isalnum (c))
227 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
228 const struct guestfs_add_drive_opts_argv *optargs)
234 if (strchr (filename, ',') != NULL) {
235 error (g, _("filename cannot contain ',' (comma) character"));
239 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
240 ? optargs->readonly : 0;
241 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
242 ? optargs->format : NULL;
243 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
244 ? optargs->iface : DRIVE_IF;
246 if (format && !valid_format_iface (format)) {
247 error (g, _("%s parameter is empty or contains disallowed characters"),
251 if (!valid_format_iface (iface)) {
252 error (g, _("%s parameter is empty or contains disallowed characters"),
257 /* For writable files, see if we can use cache=off. This also
258 * checks for the existence of the file. For readonly we have
259 * to do the check explicitly.
261 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
262 if (use_cache_off == -1)
266 if (access (filename, F_OK) == -1) {
267 perrorf (g, "%s", filename);
272 /* Construct the final -drive parameter. */
273 size_t len = 64 + strlen (filename) + strlen (iface);
274 if (format) len += strlen (format);
277 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
279 readonly ? ",snapshot=on" : "",
280 use_cache_off ? ",cache=off" : "",
281 format ? ",format=" : "",
282 format ? format : "",
285 return guestfs__config (g, "-drive", buf);
289 guestfs__add_drive (guestfs_h *g, const char *filename)
291 struct guestfs_add_drive_opts_argv optargs = {
295 return guestfs__add_drive_opts (g, filename, &optargs);
299 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
301 struct guestfs_add_drive_opts_argv optargs = {
302 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
306 return guestfs__add_drive_opts (g, filename, &optargs);
310 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
313 struct guestfs_add_drive_opts_argv optargs = {
314 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
318 return guestfs__add_drive_opts (g, filename, &optargs);
322 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
325 struct guestfs_add_drive_opts_argv optargs = {
326 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
327 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
332 return guestfs__add_drive_opts (g, filename, &optargs);
336 guestfs__add_cdrom (guestfs_h *g, const char *filename)
338 if (strchr (filename, ',') != NULL) {
339 error (g, _("filename cannot contain ',' (comma) character"));
343 if (access (filename, F_OK) == -1) {
344 perrorf (g, "%s", filename);
348 return guestfs__config (g, "-cdrom", filename);
351 static int is_openable (guestfs_h *g, const char *path, int flags);
354 guestfs__launch (guestfs_h *g)
357 if (g->state != CONFIG) {
358 error (g, _("the libguestfs handle has already been launched"));
362 /* Make the temporary directory. */
364 TMP_TEMPLATE_ON_STACK (dir_template);
365 g->tmpdir = safe_strdup (g, dir_template);
366 if (mkdtemp (g->tmpdir) == NULL) {
367 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
372 /* Allow anyone to read the temporary directory. The socket in this
373 * directory won't be readable but anyone can see it exists if they
374 * want. (RHBZ#610880).
376 if (chmod (g->tmpdir, 0755) == -1)
377 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
379 /* Launch the appliance or attach to an existing daemon. */
380 switch (g->attach_method) {
381 case ATTACH_METHOD_APPLIANCE:
382 return launch_appliance (g);
384 case ATTACH_METHOD_UNIX:
385 return connect_unix_socket (g, g->attach_method_arg);
393 launch_appliance (guestfs_h *g)
397 char guestfsd_sock[256];
398 struct sockaddr_un addr;
400 /* At present you must add drives before starting the appliance. In
401 * future when we enable hotplugging you won't need to do this.
404 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
408 /* Start the clock ... */
409 gettimeofday (&g->launch_t, NULL);
410 guestfs___launch_send_progress (g, 0);
412 /* Locate and/or build the appliance. */
413 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
414 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
417 guestfs___launch_send_progress (g, 3);
420 guestfs___print_timestamped_message (g, "begin testing qemu features");
422 /* Get qemu help text and version. */
423 if (qemu_supports (g, NULL) == -1)
426 /* Using virtio-serial, we need to create a local Unix domain socket
427 * for qemu to connect to.
429 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
430 unlink (guestfsd_sock);
432 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
434 perrorf (g, "socket");
438 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
439 perrorf (g, "fcntl");
443 addr.sun_family = AF_UNIX;
444 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
445 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
447 if (bind (g->sock, &addr, sizeof addr) == -1) {
452 if (listen (g->sock, 1) == -1) {
453 perrorf (g, "listen");
458 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
465 guestfs___print_timestamped_message (g, "finished testing qemu features");
479 if (r == 0) { /* Child (qemu). */
482 /* Set up the full command line. Do this in the subprocess so we
483 * don't need to worry about cleaning up.
485 g->cmdline[0] = g->qemu;
487 if (qemu_supports (g, "-nodefconfig"))
488 add_cmdline (g, "-nodefconfig");
490 /* The qemu -machine option (added 2010-12) is a bit more sane
491 * since it falls back through various different acceleration
492 * modes, so try that first (thanks Markus Armbruster).
494 if (qemu_supports (g, "-machine")) {
495 add_cmdline (g, "-machine");
496 add_cmdline (g, "accel=kvm:tcg");
498 /* qemu sometimes needs this option to enable hardware
499 * virtualization, but some versions of 'qemu-kvm' will use KVM
500 * regardless (even where this option appears in the help text).
501 * It is rumoured that there are versions of qemu where supplying
502 * this option when hardware virtualization is not available will
503 * cause qemu to fail, so we we have to check at least that
504 * /dev/kvm is openable. That's not reliable, since /dev/kvm
505 * might be openable by qemu but not by us (think: SELinux) in
506 * which case the user would not get hardware virtualization,
507 * although at least shouldn't fail. A giant clusterfuck with the
508 * qemu command line, again.
510 if (qemu_supports (g, "-enable-kvm") &&
511 is_openable (g, "/dev/kvm", O_RDWR))
512 add_cmdline (g, "-enable-kvm");
515 /* Newer versions of qemu (from around 2009/12) changed the
516 * behaviour of monitors so that an implicit '-monitor stdio' is
517 * assumed if we are in -nographic mode and there is no other
518 * -monitor option. Only a single stdio device is allowed, so
519 * this broke the '-serial stdio' option. There is a new flag
520 * called -nodefaults which gets rid of all this default crud, so
521 * let's use that to avoid this and any future surprises.
523 if (qemu_supports (g, "-nodefaults"))
524 add_cmdline (g, "-nodefaults");
526 add_cmdline (g, "-nographic");
528 snprintf (buf, sizeof buf, "%d", g->memsize);
529 add_cmdline (g, "-m");
530 add_cmdline (g, buf);
532 /* Force exit instead of reboot on panic */
533 add_cmdline (g, "-no-reboot");
535 /* These options recommended by KVM developers to improve reliability. */
536 if (qemu_supports (g, "-no-hpet"))
537 add_cmdline (g, "-no-hpet");
539 if (qemu_supports (g, "-rtc-td-hack"))
540 add_cmdline (g, "-rtc-td-hack");
542 /* Create the virtio serial bus. */
543 add_cmdline (g, "-device");
544 add_cmdline (g, "virtio-serial");
547 /* Use virtio-console (a variant form of virtio-serial) for the
548 * guest's serial console.
550 add_cmdline (g, "-chardev");
551 add_cmdline (g, "stdio,id=console");
552 add_cmdline (g, "-device");
553 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
555 /* When the above works ... until then: */
556 add_cmdline (g, "-serial");
557 add_cmdline (g, "stdio");
560 /* Set up virtio-serial for the communications channel. */
561 add_cmdline (g, "-chardev");
562 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
563 add_cmdline (g, buf);
564 add_cmdline (g, "-device");
565 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
567 /* Enable user networking. */
568 if (g->enable_network) {
569 add_cmdline (g, "-netdev");
570 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
571 add_cmdline (g, "-device");
572 add_cmdline (g, NET_IF ",netdev=usernet");
575 #define LINUX_CMDLINE \
576 "panic=1 " /* force kernel to panic if daemon exits */ \
577 "console=ttyS0 " /* serial console */ \
578 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
579 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
580 "acpi=off " /* we don't need ACPI, turn it off */ \
581 "printk.time=1 " /* display timestamp before kernel messages */ \
582 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
584 /* Linux kernel command line. */
585 snprintf (buf, sizeof buf,
587 "%s " /* (selinux) */
588 "%s " /* (verbose) */
589 "TERM=%s " /* (TERM environment variable) */
591 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
592 g->verbose ? "guestfs_verbose=1" : "",
593 getenv ("TERM") ? : "linux",
594 g->append ? g->append : "");
596 add_cmdline (g, "-kernel");
597 add_cmdline (g, kernel);
598 add_cmdline (g, "-initrd");
599 add_cmdline (g, initrd);
600 add_cmdline (g, "-append");
601 add_cmdline (g, buf);
603 /* Add the ext2 appliance drive (last of all). */
605 const char *cachemode = "";
606 if (qemu_supports (g, "cache=")) {
607 if (qemu_supports (g, "unsafe"))
608 cachemode = ",cache=unsafe";
609 else if (qemu_supports (g, "writeback"))
610 cachemode = ",cache=writeback";
613 char buf2[PATH_MAX + 64];
614 add_cmdline (g, "-drive");
615 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
616 appliance, cachemode);
617 add_cmdline (g, buf2);
620 /* Finish off the command line. */
621 incr_cmdline_size (g);
622 g->cmdline[g->cmdline_size-1] = NULL;
625 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
628 /* Set up stdin, stdout, stderr. */
635 if (dup (wfd[0]) == -1) {
637 perror ("dup failed");
638 _exit (EXIT_FAILURE);
641 if (dup (rfd[1]) == -1)
644 /* Particularly since qemu 0.15, qemu spews all sorts of debug
645 * information on stderr. It is useful to both capture this and
646 * not confuse casual users, so send stderr to the pipe as well.
649 if (dup (rfd[1]) == -1)
657 /* Set up a new process group, so we can signal this process
658 * and all subprocesses (eg. if qemu is really a shell script).
663 setenv ("LC_ALL", "C", 1);
665 execv (g->qemu, g->cmdline); /* Run qemu. */
667 _exit (EXIT_FAILURE);
670 /* Parent (library). */
680 /* Fork the recovery process off which will kill qemu if the parent
681 * process fails to do so (eg. if the parent segfaults).
684 if (g->recovery_proc) {
687 pid_t qemu_pid = g->pid;
688 pid_t parent_pid = getppid ();
690 /* Writing to argv is hideously complicated and error prone. See:
691 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
694 /* Loop around waiting for one or both of the other processes to
695 * disappear. It's fair to say this is very hairy. The PIDs that
696 * we are looking at might be reused by another process. We are
697 * effectively polling. Is the cure worse than the disease?
700 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
701 _exit (EXIT_SUCCESS);
702 if (kill (parent_pid, 0) == -1) {
703 /* Parent's gone away, qemu still around, so kill qemu. */
705 _exit (EXIT_SUCCESS);
711 /* Don't worry, if the fork failed, this will be -1. The recovery
712 * process isn't essential.
718 /* Close the other ends of the pipe. */
722 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
723 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
724 perrorf (g, "fcntl");
728 g->fd[0] = wfd[1]; /* stdin of child */
729 g->fd[1] = rfd[0]; /* stdout of child */
731 g->fd[0] = open ("/dev/null", O_RDWR);
732 if (g->fd[0] == -1) {
733 perrorf (g, "open /dev/null");
736 g->fd[1] = dup (g->fd[0]);
737 if (g->fd[1] == -1) {
744 g->state = LAUNCHING;
746 /* Wait for qemu to start and to connect back to us via
747 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
749 r = guestfs___accept_from_daemon (g);
753 close (g->sock); /* Close the listening socket. */
754 g->sock = r; /* This is the accepted data socket. */
756 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
757 perrorf (g, "fcntl");
763 r = guestfs___recv_from_daemon (g, &size, &buf);
766 if (r == -1) return -1;
768 if (size != GUESTFS_LAUNCH_FLAG) {
769 error (g, _("guestfs_launch failed, see earlier error messages"));
774 guestfs___print_timestamped_message (g, "appliance is up");
776 /* This is possible in some really strange situations, such as
777 * guestfsd starts up OK but then qemu immediately exits. Check for
778 * it because the caller is probably expecting to be able to send
779 * commands after this function returns.
781 if (g->state != READY) {
782 error (g, _("qemu launched and contacted daemon, but state != READY"));
786 guestfs___launch_send_progress (g, 12);
795 if (g->pid > 0) kill (g->pid, 9);
796 if (g->recoverypid > 0) kill (g->recoverypid, 9);
797 if (g->pid > 0) waitpid (g->pid, NULL, 0);
798 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
803 memset (&g->launch_t, 0, sizeof g->launch_t);
817 /* Alternate attach method: instead of launching the appliance,
818 * connect to an existing unix socket.
821 connect_unix_socket (guestfs_h *g, const char *sockpath)
824 struct sockaddr_un addr;
826 /* Start the clock ... */
827 gettimeofday (&g->launch_t, NULL);
829 /* Set these to nothing so we don't try to kill random processes or
830 * read from random file descriptors.
838 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
840 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
842 perrorf (g, "socket");
846 addr.sun_family = AF_UNIX;
847 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
848 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
850 g->state = LAUNCHING;
852 if (connect (g->sock, &addr, sizeof addr) == -1) {
857 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
858 perrorf (g, "fcntl");
864 r = guestfs___recv_from_daemon (g, &size, &buf);
867 if (r == -1) return -1;
869 if (size != GUESTFS_LAUNCH_FLAG) {
870 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
875 guestfs___print_timestamped_message (g, "connected");
877 if (g->state != READY) {
878 error (g, _("contacted guestfsd, but state != READY"));
889 /* launch (of the ordinary appliance) generates approximate progress
890 * messages. Currently these are defined as follows:
892 * 0 / 12: launch clock starts
893 * 3 / 12: appliance created
894 * 6 / 12: detected that guest kernel started
895 * 9 / 12: detected that /init script is running
896 * 12 / 12: launch completed successfully
899 * (1) This is not a documented ABI and the behaviour may be changed
900 * or removed in future.
901 * (2) Messages are only sent if more than 5 seconds has elapsed
902 * since the launch clock started.
903 * (3) There is a gross hack in proto.c to make this work.
906 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
910 gettimeofday (&tv, NULL);
911 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
912 guestfs_progress progress_message =
913 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
915 guestfs___progress_message_callback (g, &progress_message);
919 /* Return the location of the tmpdir (eg. "/tmp") and allow users
920 * to override it at runtime using $TMPDIR.
921 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
924 guestfs_tmpdir (void)
934 const char *t = getenv ("TMPDIR");
940 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
941 * allow users to override it at runtime using $TMPDIR.
942 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
945 guestfs___persistent_tmpdir (void)
951 const char *t = getenv ("TMPDIR");
957 /* Compute Y - X and return the result in milliseconds.
958 * Approximately the same as this code:
959 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
962 timeval_diff (const struct timeval *x, const struct timeval *y)
966 msec = (y->tv_sec - x->tv_sec) * 1000;
967 msec += (y->tv_usec - x->tv_usec) / 1000;
972 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
980 fp = open_memstream (&buf, &len);
982 warning (g, "open_memstream: %m");
987 gettimeofday (&tv, NULL);
988 fprintf (fp, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
991 if (argv[i][0] == '-') /* -option starts a new line */
992 fprintf (fp, " \\\n ");
994 if (i > 0) fputc (' ', fp);
996 /* Does it need shell quoting? This only deals with simple cases. */
997 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
999 if (needs_quote) fputc ('\'', fp);
1000 fprintf (fp, "%s", argv[i]);
1001 if (needs_quote) fputc ('\'', fp);
1007 debug (g, "%s", buf);
1013 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1020 va_start (args, fs);
1021 err = vasprintf (&msg, fs, args);
1024 if (err < 0) return;
1026 gettimeofday (&tv, NULL);
1028 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1033 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1035 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1036 * 'qemu -version' so we know what options this qemu supports and
1040 test_qemu (guestfs_h *g)
1045 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1047 fp = popen (cmd, "r");
1048 /* qemu -help should always work (qemu -version OTOH wasn't
1049 * supported by qemu 0.9). If this command doesn't work then it
1050 * probably indicates that the qemu binary is missing.
1053 /* XXX This error is never printed, even if the qemu binary
1054 * doesn't exist. Why?
1057 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1061 if (read_all (g, fp, &g->qemu_help) == -1)
1064 if (pclose (fp) == -1)
1067 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1070 fp = popen (cmd, "r");
1072 /* Intentionally ignore errors. */
1073 read_all (g, fp, &g->qemu_version);
1081 read_all (guestfs_h *g, FILE *fp, char **ret)
1088 *ret = safe_realloc (g, *ret, n + 1);
1093 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1095 r = fread (p, 1, BUFSIZ, fp);
1097 perrorf (g, "read");
1104 /* Test if option is supported by qemu command line (just by grepping
1107 * The first time this is used, it has to run the external qemu
1108 * binary. If that fails, it returns -1.
1110 * To just do the first-time run of the qemu binary, call this with
1111 * option == NULL, in which case it will return -1 if there was an
1115 qemu_supports (guestfs_h *g, const char *option)
1117 if (!g->qemu_help) {
1118 if (test_qemu (g) == -1)
1125 return strstr (g->qemu_help, option) != NULL;
1128 /* Check if a file can be opened. */
1130 is_openable (guestfs_h *g, const char *path, int flags)
1132 int fd = open (path, flags);
1134 debug (g, "is_openable: %s: %m", path);
1141 /* You had to call this function after launch in versions <= 1.0.70,
1142 * but it is now a no-op.
1145 guestfs__wait_ready (guestfs_h *g)
1147 if (g->state != READY) {
1148 error (g, _("qemu has not been launched yet"));
1156 guestfs__kill_subprocess (guestfs_h *g)
1158 if (g->state == CONFIG) {
1159 error (g, _("no subprocess to kill"));
1163 debug (g, "sending SIGTERM to process %d", g->pid);
1165 if (g->pid > 0) kill (g->pid, SIGTERM);
1166 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1171 /* Access current state. */
1173 guestfs__is_config (guestfs_h *g)
1175 return g->state == CONFIG;
1179 guestfs__is_launching (guestfs_h *g)
1181 return g->state == LAUNCHING;
1185 guestfs__is_ready (guestfs_h *g)
1187 return g->state == READY;
1191 guestfs__is_busy (guestfs_h *g)
1193 return g->state == BUSY;
1197 guestfs__get_state (guestfs_h *g)