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 void print_qemu_command_line (guestfs_h *g, char **argv);
77 static int connect_unix_socket (guestfs_h *g, const char *sock);
78 static int qemu_supports (guestfs_h *g, const char *option);
79 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
82 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
84 static void compile_regexps (void) __attribute__((constructor));
85 static void free_regexps (void) __attribute__((destructor));
88 compile_regexps (void)
93 #define COMPILE(re,pattern,options) \
95 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
97 ignore_value (write (2, err, strlen (err))); \
109 /* Functions to add a string to the current command line. */
111 alloc_cmdline (guestfs_h *g)
113 if (g->cmdline == NULL) {
114 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
116 g->cmdline = safe_malloc (g, sizeof (char *));
117 g->cmdline[0] = NULL;
122 incr_cmdline_size (guestfs_h *g)
126 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
130 add_cmdline (guestfs_h *g, const char *str)
132 if (g->state != CONFIG) {
134 _("command line cannot be altered after qemu subprocess launched"));
138 incr_cmdline_size (g);
139 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
144 guestfs___checkpoint_drives (guestfs_h *g)
146 struct drive **i = &g->drives;
147 while (*i != NULL) i = &((*i)->next);
152 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
154 guestfs___free_drives(i);
157 /* Internal command to return the command line. */
159 guestfs__debug_cmdline (guestfs_h *g)
166 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
167 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
169 for (i = 1; i < g->cmdline_size; ++i)
170 r[i] = safe_strdup (g, g->cmdline[i]);
172 r[g->cmdline_size] = NULL;
174 return r; /* caller frees */
177 /* Internal command to return the list of drives. */
179 guestfs__debug_drives (guestfs_h *g)
185 for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
188 ret = safe_malloc (g, sizeof (char *) * (count + 1));
190 for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
191 ret[i] = qemu_drive_param (g, drv);
195 return ret; /* caller frees */
199 guestfs__config (guestfs_h *g,
200 const char *qemu_param, const char *qemu_value)
202 if (qemu_param[0] != '-') {
203 error (g, _("guestfs_config: parameter must begin with '-' character"));
207 /* A bit fascist, but the user will probably break the extra
208 * parameters that we add if they try to set any of these.
210 if (STREQ (qemu_param, "-kernel") ||
211 STREQ (qemu_param, "-initrd") ||
212 STREQ (qemu_param, "-nographic") ||
213 STREQ (qemu_param, "-serial") ||
214 STREQ (qemu_param, "-full-screen") ||
215 STREQ (qemu_param, "-std-vga") ||
216 STREQ (qemu_param, "-vnc")) {
217 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
221 if (add_cmdline (g, qemu_param) != 0) return -1;
223 if (qemu_value != NULL) {
224 if (add_cmdline (g, qemu_value) != 0) return -1;
230 /* cache=off improves reliability in the event of a host crash.
232 * However this option causes qemu to try to open the file with
233 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
234 * So we check if we can open the file with or without O_DIRECT,
235 * and use cache=off (or not) accordingly.
238 test_cache_off (guestfs_h *g, const char *filename)
240 int fd = open (filename, O_RDONLY|O_DIRECT);
246 fd = open (filename, O_RDONLY);
252 perrorf (g, "%s", filename);
256 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
258 valid_format_iface (const char *str)
260 size_t len = strlen (str);
268 if (c != '-' && c != '_' && !c_isalnum (c))
275 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
276 const struct guestfs_add_drive_opts_argv *optargs)
284 if (strchr (filename, ',') != NULL) {
285 error (g, _("filename cannot contain ',' (comma) character"));
289 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
290 ? optargs->readonly : 0;
291 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
292 ? safe_strdup (g, optargs->format) : NULL;
293 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
294 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
295 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
296 ? safe_strdup (g, optargs->name) : NULL;
298 if (format && !valid_format_iface (format)) {
299 error (g, _("%s parameter is empty or contains disallowed characters"),
306 if (!valid_format_iface (iface)) {
307 error (g, _("%s parameter is empty or contains disallowed characters"),
315 /* For writable files, see if we can use cache=off. This also
316 * checks for the existence of the file. For readonly we have
317 * to do the check explicitly.
319 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
320 if (use_cache_off == -1) {
328 if (access (filename, F_OK) == -1) {
329 perrorf (g, "%s", filename);
337 struct drive **i = &(g->drives);
338 while (*i != NULL) i = &((*i)->next);
340 *i = safe_malloc (g, sizeof (struct drive));
342 (*i)->path = safe_strdup (g, filename);
343 (*i)->readonly = readonly;
344 (*i)->format = format;
347 (*i)->use_cache_off = use_cache_off;
353 guestfs__add_drive (guestfs_h *g, const char *filename)
355 struct guestfs_add_drive_opts_argv optargs = {
359 return guestfs__add_drive_opts (g, filename, &optargs);
363 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
365 struct guestfs_add_drive_opts_argv optargs = {
366 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
370 return guestfs__add_drive_opts (g, filename, &optargs);
374 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
377 struct guestfs_add_drive_opts_argv optargs = {
378 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
382 return guestfs__add_drive_opts (g, filename, &optargs);
386 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
389 struct guestfs_add_drive_opts_argv optargs = {
390 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
391 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
396 return guestfs__add_drive_opts (g, filename, &optargs);
400 guestfs__add_cdrom (guestfs_h *g, const char *filename)
402 if (strchr (filename, ',') != NULL) {
403 error (g, _("filename cannot contain ',' (comma) character"));
407 if (access (filename, F_OK) == -1) {
408 perrorf (g, "%s", filename);
412 return guestfs__config (g, "-cdrom", filename);
415 static int is_openable (guestfs_h *g, const char *path, int flags);
418 guestfs__launch (guestfs_h *g)
421 if (g->state != CONFIG) {
422 error (g, _("the libguestfs handle has already been launched"));
426 TRACE0 (launch_start);
428 /* Make the temporary directory. */
430 TMP_TEMPLATE_ON_STACK (dir_template);
431 g->tmpdir = safe_strdup (g, dir_template);
432 if (mkdtemp (g->tmpdir) == NULL) {
433 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
438 /* Allow anyone to read the temporary directory. The socket in this
439 * directory won't be readable but anyone can see it exists if they
440 * want. (RHBZ#610880).
442 if (chmod (g->tmpdir, 0755) == -1)
443 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
445 /* Launch the appliance or attach to an existing daemon. */
446 switch (g->attach_method) {
447 case ATTACH_METHOD_APPLIANCE:
448 return launch_appliance (g);
450 case ATTACH_METHOD_UNIX:
451 return connect_unix_socket (g, g->attach_method_arg);
459 launch_appliance (guestfs_h *g)
463 char guestfsd_sock[256];
464 struct sockaddr_un addr;
466 /* At present you must add drives before starting the appliance. In
467 * future when we enable hotplugging you won't need to do this.
470 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
474 /* Start the clock ... */
475 gettimeofday (&g->launch_t, NULL);
476 guestfs___launch_send_progress (g, 0);
478 TRACE0 (launch_build_appliance_start);
480 /* Locate and/or build the appliance. */
481 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
482 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
485 TRACE0 (launch_build_appliance_end);
487 guestfs___launch_send_progress (g, 3);
490 guestfs___print_timestamped_message (g, "begin testing qemu features");
492 /* Get qemu help text and version. */
493 if (qemu_supports (g, NULL) == -1)
496 /* Using virtio-serial, we need to create a local Unix domain socket
497 * for qemu to connect to.
499 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
500 unlink (guestfsd_sock);
502 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
504 perrorf (g, "socket");
508 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
509 perrorf (g, "fcntl");
513 addr.sun_family = AF_UNIX;
514 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
515 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
517 if (bind (g->sock, &addr, sizeof addr) == -1) {
522 if (listen (g->sock, 1) == -1) {
523 perrorf (g, "listen");
528 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
535 guestfs___print_timestamped_message (g, "finished testing qemu features");
549 if (r == 0) { /* Child (qemu). */
552 /* Set up the full command line. Do this in the subprocess so we
553 * don't need to worry about cleaning up.
556 /* Set g->cmdline[0] to the name of the qemu process. However
557 * it is possible that no g->cmdline has been allocated yet so
558 * we must do that first.
561 g->cmdline[0] = g->qemu;
564 struct drive *drv = g->drives;
565 while (drv != NULL) {
566 /* Construct the final -drive parameter. */
567 char *buf = qemu_drive_param (g, drv);
569 add_cmdline (g, "-drive");
570 add_cmdline (g, buf);
576 if (qemu_supports (g, "-nodefconfig"))
577 add_cmdline (g, "-nodefconfig");
579 /* The qemu -machine option (added 2010-12) is a bit more sane
580 * since it falls back through various different acceleration
581 * modes, so try that first (thanks Markus Armbruster).
583 if (qemu_supports (g, "-machine")) {
584 add_cmdline (g, "-machine");
585 add_cmdline (g, "accel=kvm:tcg");
587 /* qemu sometimes needs this option to enable hardware
588 * virtualization, but some versions of 'qemu-kvm' will use KVM
589 * regardless (even where this option appears in the help text).
590 * It is rumoured that there are versions of qemu where supplying
591 * this option when hardware virtualization is not available will
592 * cause qemu to fail, so we we have to check at least that
593 * /dev/kvm is openable. That's not reliable, since /dev/kvm
594 * might be openable by qemu but not by us (think: SELinux) in
595 * which case the user would not get hardware virtualization,
596 * although at least shouldn't fail. A giant clusterfuck with the
597 * qemu command line, again.
599 if (qemu_supports (g, "-enable-kvm") &&
600 is_openable (g, "/dev/kvm", O_RDWR))
601 add_cmdline (g, "-enable-kvm");
604 /* Newer versions of qemu (from around 2009/12) changed the
605 * behaviour of monitors so that an implicit '-monitor stdio' is
606 * assumed if we are in -nographic mode and there is no other
607 * -monitor option. Only a single stdio device is allowed, so
608 * this broke the '-serial stdio' option. There is a new flag
609 * called -nodefaults which gets rid of all this default crud, so
610 * let's use that to avoid this and any future surprises.
612 if (qemu_supports (g, "-nodefaults"))
613 add_cmdline (g, "-nodefaults");
615 add_cmdline (g, "-nographic");
618 snprintf (buf, sizeof buf, "%d", g->smp);
619 add_cmdline (g, "-smp");
620 add_cmdline (g, buf);
623 snprintf (buf, sizeof buf, "%d", g->memsize);
624 add_cmdline (g, "-m");
625 add_cmdline (g, buf);
627 /* Force exit instead of reboot on panic */
628 add_cmdline (g, "-no-reboot");
630 /* These options recommended by KVM developers to improve reliability. */
631 if (qemu_supports (g, "-no-hpet"))
632 add_cmdline (g, "-no-hpet");
634 if (qemu_supports (g, "-rtc-td-hack"))
635 add_cmdline (g, "-rtc-td-hack");
637 /* Create the virtio serial bus. */
638 add_cmdline (g, "-device");
639 add_cmdline (g, "virtio-serial");
642 /* Use virtio-console (a variant form of virtio-serial) for the
643 * guest's serial console.
645 add_cmdline (g, "-chardev");
646 add_cmdline (g, "stdio,id=console");
647 add_cmdline (g, "-device");
648 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
650 /* When the above works ... until then: */
651 add_cmdline (g, "-serial");
652 add_cmdline (g, "stdio");
655 /* Set up virtio-serial for the communications channel. */
656 add_cmdline (g, "-chardev");
657 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
658 add_cmdline (g, buf);
659 add_cmdline (g, "-device");
660 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
662 /* Enable user networking. */
663 if (g->enable_network) {
664 add_cmdline (g, "-netdev");
665 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
666 add_cmdline (g, "-device");
667 add_cmdline (g, NET_IF ",netdev=usernet");
670 #define LINUX_CMDLINE \
671 "panic=1 " /* force kernel to panic if daemon exits */ \
672 "console=ttyS0 " /* serial console */ \
673 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
674 "no_timer_check " /* fix for RHBZ#502058 */ \
675 "acpi=off " /* we don't need ACPI, turn it off */ \
676 "printk.time=1 " /* display timestamp before kernel messages */ \
677 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
679 /* Linux kernel command line. */
680 snprintf (buf, sizeof buf,
682 "%s " /* (selinux) */
683 "%s " /* (verbose) */
684 "TERM=%s " /* (TERM environment variable) */
686 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
687 g->verbose ? "guestfs_verbose=1" : "",
688 getenv ("TERM") ? : "linux",
689 g->append ? g->append : "");
691 add_cmdline (g, "-kernel");
692 add_cmdline (g, kernel);
693 add_cmdline (g, "-initrd");
694 add_cmdline (g, initrd);
695 add_cmdline (g, "-append");
696 add_cmdline (g, buf);
698 /* Add the ext2 appliance drive (last of all). */
700 const char *cachemode = "";
701 if (qemu_supports (g, "cache=")) {
702 if (qemu_supports (g, "unsafe"))
703 cachemode = ",cache=unsafe";
704 else if (qemu_supports (g, "writeback"))
705 cachemode = ",cache=writeback";
708 char buf2[PATH_MAX + 64];
709 add_cmdline (g, "-drive");
710 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
711 appliance, cachemode);
712 add_cmdline (g, buf2);
715 /* Finish off the command line. */
716 incr_cmdline_size (g);
717 g->cmdline[g->cmdline_size-1] = NULL;
720 /* Set up stdin, stdout, stderr. */
727 if (dup (wfd[0]) == -1) {
729 perror ("dup failed");
730 _exit (EXIT_FAILURE);
733 if (dup (rfd[1]) == -1)
736 /* Particularly since qemu 0.15, qemu spews all sorts of debug
737 * information on stderr. It is useful to both capture this and
738 * not confuse casual users, so send stderr to the pipe as well.
741 if (dup (rfd[1]) == -1)
748 /* Dump the command line (after setting up stderr above). */
750 print_qemu_command_line (g, g->cmdline);
752 /* Put qemu in a new process group. */
756 setenv ("LC_ALL", "C", 1);
758 TRACE0 (launch_run_qemu);
760 execv (g->qemu, g->cmdline); /* Run qemu. */
762 _exit (EXIT_FAILURE);
765 /* Parent (library). */
775 /* Fork the recovery process off which will kill qemu if the parent
776 * process fails to do so (eg. if the parent segfaults).
779 if (g->recovery_proc) {
782 pid_t qemu_pid = g->pid;
783 pid_t parent_pid = getppid ();
785 /* It would be nice to be able to put this in the same process
786 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
787 * not possible because we don't have any guarantee here that
788 * the qemu process has started yet.
793 /* Writing to argv is hideously complicated and error prone. See:
794 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
797 /* Loop around waiting for one or both of the other processes to
798 * disappear. It's fair to say this is very hairy. The PIDs that
799 * we are looking at might be reused by another process. We are
800 * effectively polling. Is the cure worse than the disease?
803 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
804 _exit (EXIT_SUCCESS);
805 if (kill (parent_pid, 0) == -1) {
806 /* Parent's gone away, qemu still around, so kill qemu. */
808 _exit (EXIT_SUCCESS);
814 /* Don't worry, if the fork failed, this will be -1. The recovery
815 * process isn't essential.
821 /* Close the other ends of the pipe. */
825 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
826 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
827 perrorf (g, "fcntl");
831 g->fd[0] = wfd[1]; /* stdin of child */
832 g->fd[1] = rfd[0]; /* stdout of child */
834 g->fd[0] = open ("/dev/null", O_RDWR);
835 if (g->fd[0] == -1) {
836 perrorf (g, "open /dev/null");
839 g->fd[1] = dup (g->fd[0]);
840 if (g->fd[1] == -1) {
847 g->state = LAUNCHING;
849 /* Wait for qemu to start and to connect back to us via
850 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
852 r = guestfs___accept_from_daemon (g);
856 close (g->sock); /* Close the listening socket. */
857 g->sock = r; /* This is the accepted data socket. */
859 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
860 perrorf (g, "fcntl");
866 r = guestfs___recv_from_daemon (g, &size, &buf);
869 if (r == -1) return -1;
871 if (size != GUESTFS_LAUNCH_FLAG) {
872 error (g, _("guestfs_launch failed, see earlier error messages"));
877 guestfs___print_timestamped_message (g, "appliance is up");
879 /* This is possible in some really strange situations, such as
880 * guestfsd starts up OK but then qemu immediately exits. Check for
881 * it because the caller is probably expecting to be able to send
882 * commands after this function returns.
884 if (g->state != READY) {
885 error (g, _("qemu launched and contacted daemon, but state != READY"));
891 guestfs___launch_send_progress (g, 12);
900 if (g->pid > 0) kill (g->pid, 9);
901 if (g->recoverypid > 0) kill (g->recoverypid, 9);
902 if (g->pid > 0) waitpid (g->pid, NULL, 0);
903 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
908 memset (&g->launch_t, 0, sizeof g->launch_t);
922 /* Alternate attach method: instead of launching the appliance,
923 * connect to an existing unix socket.
926 connect_unix_socket (guestfs_h *g, const char *sockpath)
929 struct sockaddr_un addr;
931 /* Start the clock ... */
932 gettimeofday (&g->launch_t, NULL);
934 /* Set these to nothing so we don't try to kill random processes or
935 * read from random file descriptors.
943 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
945 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
947 perrorf (g, "socket");
951 addr.sun_family = AF_UNIX;
952 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
953 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
955 g->state = LAUNCHING;
957 if (connect (g->sock, &addr, sizeof addr) == -1) {
962 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
963 perrorf (g, "fcntl");
969 r = guestfs___recv_from_daemon (g, &size, &buf);
972 if (r == -1) return -1;
974 if (size != GUESTFS_LAUNCH_FLAG) {
975 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
980 guestfs___print_timestamped_message (g, "connected");
982 if (g->state != READY) {
983 error (g, _("contacted guestfsd, but state != READY"));
994 /* launch (of the ordinary appliance) generates approximate progress
995 * messages. Currently these are defined as follows:
997 * 0 / 12: launch clock starts
998 * 3 / 12: appliance created
999 * 6 / 12: detected that guest kernel started
1000 * 9 / 12: detected that /init script is running
1001 * 12 / 12: launch completed successfully
1004 * (1) This is not a documented ABI and the behaviour may be changed
1005 * or removed in future.
1006 * (2) Messages are only sent if more than 5 seconds has elapsed
1007 * since the launch clock started.
1008 * (3) There is a gross hack in proto.c to make this work.
1011 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1015 gettimeofday (&tv, NULL);
1016 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1017 guestfs_progress progress_message =
1018 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1020 guestfs___progress_message_callback (g, &progress_message);
1024 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1025 * to override it at runtime using $TMPDIR.
1026 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1029 guestfs_tmpdir (void)
1039 const char *t = getenv ("TMPDIR");
1045 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1046 * allow users to override it at runtime using $TMPDIR.
1047 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1050 guestfs___persistent_tmpdir (void)
1054 tmpdir = "/var/tmp";
1056 const char *t = getenv ("TMPDIR");
1062 /* Compute Y - X and return the result in milliseconds.
1063 * Approximately the same as this code:
1064 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1067 timeval_diff (const struct timeval *x, const struct timeval *y)
1071 msec = (y->tv_sec - x->tv_sec) * 1000;
1072 msec += (y->tv_usec - x->tv_usec) / 1000;
1076 /* Note that since this calls 'debug' it should only be called
1077 * from the parent process.
1080 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1087 va_start (args, fs);
1088 err = vasprintf (&msg, fs, args);
1091 if (err < 0) return;
1093 gettimeofday (&tv, NULL);
1095 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1100 /* This is called from the forked subprocess just before qemu runs, so
1101 * it can just print the message straight to stderr, where it will be
1102 * picked up and funnelled through the usual appliance event API.
1105 print_qemu_command_line (guestfs_h *g, char **argv)
1111 gettimeofday (&tv, NULL);
1112 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1115 if (argv[i][0] == '-') /* -option starts a new line */
1116 fprintf (stderr, " \\\n ");
1118 if (i > 0) fputc (' ', stderr);
1120 /* Does it need shell quoting? This only deals with simple cases. */
1121 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1123 if (needs_quote) fputc ('\'', stderr);
1124 fprintf (stderr, "%s", argv[i]);
1125 if (needs_quote) fputc ('\'', stderr);
1130 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1131 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1133 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1134 * 'qemu -version' so we know what options this qemu supports and
1138 test_qemu (guestfs_h *g)
1143 free (g->qemu_help);
1144 g->qemu_help = NULL;
1145 free (g->qemu_version);
1146 g->qemu_version = NULL;
1148 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1150 /* qemu -help should always work (qemu -version OTOH wasn't
1151 * supported by qemu 0.9). If this command doesn't work then it
1152 * probably indicates that the qemu binary is missing.
1154 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1155 error (g, _("command failed: %s\n\nIf qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU\nenvironment variable. There may also be errors printed above."),
1160 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1163 /* Intentionally ignore errors from qemu -version. */
1164 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1170 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1174 fp = popen (cmd, "r");
1178 if (read_all (g, fp, ret) == -1) {
1183 if (pclose (fp) != 0)
1190 read_all (guestfs_h *g, FILE *fp, char **ret)
1197 *ret = safe_realloc (g, *ret, n + 1);
1202 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1204 r = fread (p, 1, BUFSIZ, fp);
1206 perrorf (g, "read");
1213 /* Test if option is supported by qemu command line (just by grepping
1216 * The first time this is used, it has to run the external qemu
1217 * binary. If that fails, it returns -1.
1219 * To just do the first-time run of the qemu binary, call this with
1220 * option == NULL, in which case it will return -1 if there was an
1224 qemu_supports (guestfs_h *g, const char *option)
1226 if (!g->qemu_help) {
1227 if (test_qemu (g) == -1)
1234 return strstr (g->qemu_help, option) != NULL;
1238 /* As above but using a regex instead of a fixed string. */
1240 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1242 if (!g->qemu_help) {
1243 if (test_qemu (g) == -1)
1247 return match (g, g->qemu_help, option_regex);
1251 /* Check if a file can be opened. */
1253 is_openable (guestfs_h *g, const char *path, int flags)
1255 int fd = open (path, flags);
1257 debug (g, "is_openable: %s: %m", path);
1265 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1270 len += strlen (drv->path);
1271 len += strlen (drv->iface);
1273 len += strlen (drv->format);
1275 r = safe_malloc (g, len);
1277 snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1279 drv->readonly ? ",snapshot=on" : "",
1280 drv->use_cache_off ? ",cache=off" : "",
1281 drv->format ? ",format=" : "",
1282 drv->format ? drv->format : "",
1285 return r; /* caller frees */
1288 /* You had to call this function after launch in versions <= 1.0.70,
1289 * but it is now a no-op.
1292 guestfs__wait_ready (guestfs_h *g)
1294 if (g->state != READY) {
1295 error (g, _("qemu has not been launched yet"));
1303 guestfs__kill_subprocess (guestfs_h *g)
1305 if (g->state == CONFIG) {
1306 error (g, _("no subprocess to kill"));
1310 debug (g, "sending SIGTERM to process %d", g->pid);
1312 if (g->pid > 0) kill (g->pid, SIGTERM);
1313 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1318 /* Access current state. */
1320 guestfs__is_config (guestfs_h *g)
1322 return g->state == CONFIG;
1326 guestfs__is_launching (guestfs_h *g)
1328 return g->state == LAUNCHING;
1332 guestfs__is_ready (guestfs_h *g)
1334 return g->state == READY;
1338 guestfs__is_busy (guestfs_h *g)
1340 return g->state == BUSY;
1344 guestfs__get_state (guestfs_h *g)