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>
35 #include <sys/types.h>
41 #include <rpc/types.h>
48 #ifdef HAVE_SYS_TYPES_H
49 #include <sys/types.h>
52 #ifdef HAVE_SYS_WAIT_H
56 #ifdef HAVE_SYS_SOCKET_H
57 #include <sys/socket.h>
64 #include <arpa/inet.h>
65 #include <netinet/in.h>
68 #include "ignore-value.h"
69 #include "glthread/lock.h"
72 #include "guestfs-internal.h"
73 #include "guestfs-internal-actions.h"
74 #include "guestfs_protocol.h"
76 static int launch_appliance (guestfs_h *g);
77 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
78 static void print_qemu_command_line (guestfs_h *g, char **argv);
79 static int connect_unix_socket (guestfs_h *g, const char *sock);
80 static int qemu_supports (guestfs_h *g, const char *option);
81 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
84 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
86 static void compile_regexps (void) __attribute__((constructor));
87 static void free_regexps (void) __attribute__((destructor));
90 compile_regexps (void)
95 #define COMPILE(re,pattern,options) \
97 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
99 ignore_value (write (2, err, strlen (err))); \
111 /* Functions to add a string to the current command line. */
113 alloc_cmdline (guestfs_h *g)
115 if (g->cmdline == NULL) {
116 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
118 g->cmdline = safe_malloc (g, sizeof (char *));
119 g->cmdline[0] = NULL;
124 incr_cmdline_size (guestfs_h *g)
128 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
132 add_cmdline (guestfs_h *g, const char *str)
134 if (g->state != CONFIG) {
136 _("command line cannot be altered after qemu subprocess launched"));
140 incr_cmdline_size (g);
141 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
146 guestfs___checkpoint_drives (guestfs_h *g)
148 struct drive **i = &g->drives;
149 while (*i != NULL) i = &((*i)->next);
154 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
156 guestfs___free_drives(i);
159 /* Internal command to return the command line. */
161 guestfs__debug_cmdline (guestfs_h *g)
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 */
179 /* Internal command to return the list of drives. */
181 guestfs__debug_drives (guestfs_h *g)
187 for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
190 ret = safe_malloc (g, sizeof (char *) * (count + 1));
192 for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
193 ret[i] = qemu_drive_param (g, drv);
197 return ret; /* caller frees */
201 guestfs__config (guestfs_h *g,
202 const char *qemu_param, const char *qemu_value)
204 if (qemu_param[0] != '-') {
205 error (g, _("guestfs_config: parameter must begin with '-' character"));
209 /* A bit fascist, but the user will probably break the extra
210 * parameters that we add if they try to set any of these.
212 if (STREQ (qemu_param, "-kernel") ||
213 STREQ (qemu_param, "-initrd") ||
214 STREQ (qemu_param, "-nographic") ||
215 STREQ (qemu_param, "-serial") ||
216 STREQ (qemu_param, "-full-screen") ||
217 STREQ (qemu_param, "-std-vga") ||
218 STREQ (qemu_param, "-vnc")) {
219 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
223 if (add_cmdline (g, qemu_param) != 0) return -1;
225 if (qemu_value != NULL) {
226 if (add_cmdline (g, qemu_value) != 0) return -1;
232 /* cache=off improves reliability in the event of a host crash.
234 * However this option causes qemu to try to open the file with
235 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
236 * So we check if we can open the file with or without O_DIRECT,
237 * and use cache=off (or not) accordingly.
239 * NB: This function is only called on the !readonly path. We must
240 * try to open with O_RDWR to test that the file is readable and
244 test_cache_off (guestfs_h *g, const char *filename)
246 int fd = open (filename, O_RDWR|O_DIRECT);
252 fd = open (filename, O_RDWR);
258 perrorf (g, "%s", filename);
262 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
264 valid_format_iface (const char *str)
266 size_t len = strlen (str);
274 if (c != '-' && c != '_' && !c_isalnum (c))
281 check_path (guestfs_h *g, const char *filename)
283 if (strchr (filename, ',') != NULL) {
284 error (g, _("filename cannot contain ',' (comma) character"));
291 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
292 const struct guestfs_add_drive_opts_argv *optargs)
298 char *abs_path = NULL;
301 if (check_path(g, filename) == -1)
304 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
305 ? optargs->readonly : 0;
306 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
307 ? safe_strdup (g, optargs->format) : NULL;
308 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
309 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
310 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
311 ? safe_strdup (g, optargs->name) : NULL;
313 if (format && !valid_format_iface (format)) {
314 error (g, _("%s parameter is empty or contains disallowed characters"),
318 if (!valid_format_iface (iface)) {
319 error (g, _("%s parameter is empty or contains disallowed characters"),
324 /* For writable files, see if we can use cache=off. This also
325 * checks for the existence of the file. For readonly we have
326 * to do the check explicitly.
328 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
329 if (use_cache_off == -1)
333 if (access (filename, R_OK) == -1) {
334 perrorf (g, "%s", filename);
339 abs_path = realpath (filename, NULL);
340 struct drive **i = &(g->drives);
342 if (STREQ((*i)->path, abs_path)) {
343 error (g, _("drive %s can't be added twice"), abs_path);
349 *i = safe_malloc (g, sizeof (struct drive));
351 (*i)->path = safe_strdup (g, abs_path);
352 (*i)->readonly = readonly;
353 (*i)->format = format;
356 (*i)->use_cache_off = use_cache_off;
370 guestfs__add_drive (guestfs_h *g, const char *filename)
372 struct guestfs_add_drive_opts_argv optargs = {
376 return guestfs__add_drive_opts (g, filename, &optargs);
380 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
382 struct guestfs_add_drive_opts_argv optargs = {
383 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
387 return guestfs__add_drive_opts (g, filename, &optargs);
391 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
394 struct guestfs_add_drive_opts_argv optargs = {
395 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
399 return guestfs__add_drive_opts (g, filename, &optargs);
403 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
406 struct guestfs_add_drive_opts_argv optargs = {
407 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
408 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
413 return guestfs__add_drive_opts (g, filename, &optargs);
417 guestfs__add_cdrom (guestfs_h *g, const char *filename)
419 if (check_path(g, filename) == -1)
422 if (access (filename, F_OK) == -1) {
423 perrorf (g, "%s", filename);
427 return guestfs__config (g, "-cdrom", filename);
430 static int is_openable (guestfs_h *g, const char *path, int flags);
433 guestfs__launch (guestfs_h *g)
436 if (g->state != CONFIG) {
437 error (g, _("the libguestfs handle has already been launched"));
441 TRACE0 (launch_start);
443 /* Make the temporary directory. */
445 TMP_TEMPLATE_ON_STACK (dir_template);
446 g->tmpdir = safe_strdup (g, dir_template);
447 if (mkdtemp (g->tmpdir) == NULL) {
448 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
453 /* Allow anyone to read the temporary directory. The socket in this
454 * directory won't be readable but anyone can see it exists if they
455 * want. (RHBZ#610880).
457 if (chmod (g->tmpdir, 0755) == -1)
458 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
460 /* Launch the appliance or attach to an existing daemon. */
461 switch (g->attach_method) {
462 case ATTACH_METHOD_APPLIANCE:
463 return launch_appliance (g);
465 case ATTACH_METHOD_UNIX:
466 return connect_unix_socket (g, g->attach_method_arg);
474 launch_appliance (guestfs_h *g)
478 char guestfsd_sock[256];
479 struct sockaddr_un addr;
481 /* At present you must add drives before starting the appliance. In
482 * future when we enable hotplugging you won't need to do this.
485 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
489 /* Start the clock ... */
490 gettimeofday (&g->launch_t, NULL);
491 guestfs___launch_send_progress (g, 0);
493 TRACE0 (launch_build_appliance_start);
495 /* Locate and/or build the appliance. */
496 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
497 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
500 TRACE0 (launch_build_appliance_end);
502 guestfs___launch_send_progress (g, 3);
505 guestfs___print_timestamped_message (g, "begin testing qemu features");
507 /* Get qemu help text and version. */
508 if (qemu_supports (g, NULL) == -1)
511 /* Using virtio-serial, we need to create a local Unix domain socket
512 * for qemu to connect to.
514 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
515 unlink (guestfsd_sock);
517 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
519 perrorf (g, "socket");
523 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
524 perrorf (g, "fcntl");
528 addr.sun_family = AF_UNIX;
529 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
530 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
532 if (bind (g->sock, &addr, sizeof addr) == -1) {
537 if (listen (g->sock, 1) == -1) {
538 perrorf (g, "listen");
543 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
550 guestfs___print_timestamped_message (g, "finished testing qemu features");
564 if (r == 0) { /* Child (qemu). */
567 /* Set up the full command line. Do this in the subprocess so we
568 * don't need to worry about cleaning up.
571 /* Set g->cmdline[0] to the name of the qemu process. However
572 * it is possible that no g->cmdline has been allocated yet so
573 * we must do that first.
576 g->cmdline[0] = g->qemu;
578 /* CVE-2011-4127 mitigation: Disable SCSI ioctls on virtio-blk
579 * devices. The -global option must exist, but you can pass any
580 * strings to it so we don't need to check for the specific virtio
583 if (qemu_supports (g, "-global")) {
584 add_cmdline (g, "-global");
585 add_cmdline (g, "virtio-blk-pci.scsi=off");
589 struct drive *drv = g->drives;
590 while (drv != NULL) {
591 /* Construct the final -drive parameter. */
592 char *buf = qemu_drive_param (g, drv);
594 add_cmdline (g, "-drive");
595 add_cmdline (g, buf);
601 if (qemu_supports (g, "-nodefconfig"))
602 add_cmdline (g, "-nodefconfig");
604 /* The qemu -machine option (added 2010-12) is a bit more sane
605 * since it falls back through various different acceleration
606 * modes, so try that first (thanks Markus Armbruster).
608 if (qemu_supports (g, "-machine")) {
609 add_cmdline (g, "-machine");
610 #if QEMU_MACHINE_TYPE_IS_BROKEN
611 /* Workaround for qemu 0.15: We have to add the '[type=]pc'
612 * since there is no default. This is not a permanent solution
613 * because this only works on PC-like hardware. Other platforms
614 * like ppc would need a different machine type.
616 * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
617 * not a problem in qemu < 0.15.
619 add_cmdline (g, "pc,accel=kvm:tcg");
621 add_cmdline (g, "accel=kvm:tcg");
624 /* qemu sometimes needs this option to enable hardware
625 * virtualization, but some versions of 'qemu-kvm' will use KVM
626 * regardless (even where this option appears in the help text).
627 * It is rumoured that there are versions of qemu where supplying
628 * this option when hardware virtualization is not available will
629 * cause qemu to fail, so we we have to check at least that
630 * /dev/kvm is openable. That's not reliable, since /dev/kvm
631 * might be openable by qemu but not by us (think: SELinux) in
632 * which case the user would not get hardware virtualization,
633 * although at least shouldn't fail. A giant clusterfuck with the
634 * qemu command line, again.
636 if (qemu_supports (g, "-enable-kvm") &&
637 is_openable (g, "/dev/kvm", O_RDWR))
638 add_cmdline (g, "-enable-kvm");
641 /* Newer versions of qemu (from around 2009/12) changed the
642 * behaviour of monitors so that an implicit '-monitor stdio' is
643 * assumed if we are in -nographic mode and there is no other
644 * -monitor option. Only a single stdio device is allowed, so
645 * this broke the '-serial stdio' option. There is a new flag
646 * called -nodefaults which gets rid of all this default crud, so
647 * let's use that to avoid this and any future surprises.
649 if (qemu_supports (g, "-nodefaults"))
650 add_cmdline (g, "-nodefaults");
652 add_cmdline (g, "-nographic");
655 snprintf (buf, sizeof buf, "%d", g->smp);
656 add_cmdline (g, "-smp");
657 add_cmdline (g, buf);
660 snprintf (buf, sizeof buf, "%d", g->memsize);
661 add_cmdline (g, "-m");
662 add_cmdline (g, buf);
664 /* Force exit instead of reboot on panic */
665 add_cmdline (g, "-no-reboot");
667 /* These options recommended by KVM developers to improve reliability. */
668 if (qemu_supports (g, "-no-hpet"))
669 add_cmdline (g, "-no-hpet");
671 if (qemu_supports (g, "-rtc-td-hack"))
672 add_cmdline (g, "-rtc-td-hack");
674 /* Create the virtio serial bus. */
675 add_cmdline (g, "-device");
676 add_cmdline (g, "virtio-serial");
679 /* Use virtio-console (a variant form of virtio-serial) for the
680 * guest's serial console.
682 add_cmdline (g, "-chardev");
683 add_cmdline (g, "stdio,id=console");
684 add_cmdline (g, "-device");
685 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
687 /* When the above works ... until then: */
688 add_cmdline (g, "-serial");
689 add_cmdline (g, "stdio");
692 /* Set up virtio-serial for the communications channel. */
693 add_cmdline (g, "-chardev");
694 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
695 add_cmdline (g, buf);
696 add_cmdline (g, "-device");
697 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
699 /* Enable user networking. */
700 if (g->enable_network) {
701 add_cmdline (g, "-netdev");
702 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
703 add_cmdline (g, "-device");
704 add_cmdline (g, NET_IF ",netdev=usernet");
707 #define LINUX_CMDLINE \
708 "panic=1 " /* force kernel to panic if daemon exits */ \
709 "console=ttyS0 " /* serial console */ \
710 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
711 "no_timer_check " /* fix for RHBZ#502058 */ \
712 "acpi=off " /* we don't need ACPI, turn it off */ \
713 "printk.time=1 " /* display timestamp before kernel messages */ \
714 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
716 /* Linux kernel command line. */
717 snprintf (buf, sizeof buf,
719 "%s " /* (selinux) */
720 "%s " /* (verbose) */
721 "TERM=%s " /* (TERM environment variable) */
723 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
724 g->verbose ? "guestfs_verbose=1" : "",
725 getenv ("TERM") ? : "linux",
726 g->append ? g->append : "");
728 add_cmdline (g, "-kernel");
729 add_cmdline (g, kernel);
730 add_cmdline (g, "-initrd");
731 add_cmdline (g, initrd);
732 add_cmdline (g, "-append");
733 add_cmdline (g, buf);
735 /* Add the ext2 appliance drive (last of all). */
737 const char *cachemode = "";
738 if (qemu_supports (g, "cache=")) {
739 if (qemu_supports (g, "unsafe"))
740 cachemode = ",cache=unsafe";
741 else if (qemu_supports (g, "writeback"))
742 cachemode = ",cache=writeback";
745 char buf2[PATH_MAX + 64];
746 add_cmdline (g, "-drive");
747 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
748 appliance, cachemode);
749 add_cmdline (g, buf2);
752 /* Finish off the command line. */
753 incr_cmdline_size (g);
754 g->cmdline[g->cmdline_size-1] = NULL;
757 /* Set up stdin, stdout, stderr. */
764 if (dup (wfd[0]) == -1) {
766 perror ("dup failed");
767 _exit (EXIT_FAILURE);
770 if (dup (rfd[1]) == -1)
773 /* Particularly since qemu 0.15, qemu spews all sorts of debug
774 * information on stderr. It is useful to both capture this and
775 * not confuse casual users, so send stderr to the pipe as well.
778 if (dup (rfd[1]) == -1)
785 /* Dump the command line (after setting up stderr above). */
787 print_qemu_command_line (g, g->cmdline);
789 /* Put qemu in a new process group. */
793 setenv ("LC_ALL", "C", 1);
795 TRACE0 (launch_run_qemu);
797 execv (g->qemu, g->cmdline); /* Run qemu. */
799 _exit (EXIT_FAILURE);
802 /* Parent (library). */
812 /* Fork the recovery process off which will kill qemu if the parent
813 * process fails to do so (eg. if the parent segfaults).
816 if (g->recovery_proc) {
819 pid_t qemu_pid = g->pid;
820 pid_t parent_pid = getppid ();
822 /* It would be nice to be able to put this in the same process
823 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
824 * not possible because we don't have any guarantee here that
825 * the qemu process has started yet.
830 /* Writing to argv is hideously complicated and error prone. See:
831 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
834 /* Loop around waiting for one or both of the other processes to
835 * disappear. It's fair to say this is very hairy. The PIDs that
836 * we are looking at might be reused by another process. We are
837 * effectively polling. Is the cure worse than the disease?
840 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
841 _exit (EXIT_SUCCESS);
842 if (kill (parent_pid, 0) == -1) {
843 /* Parent's gone away, qemu still around, so kill qemu. */
845 _exit (EXIT_SUCCESS);
851 /* Don't worry, if the fork failed, this will be -1. The recovery
852 * process isn't essential.
858 /* Close the other ends of the pipe. */
862 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
863 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
864 perrorf (g, "fcntl");
868 g->fd[0] = wfd[1]; /* stdin of child */
869 g->fd[1] = rfd[0]; /* stdout of child */
871 g->fd[0] = open ("/dev/null", O_RDWR);
872 if (g->fd[0] == -1) {
873 perrorf (g, "open /dev/null");
876 g->fd[1] = dup (g->fd[0]);
877 if (g->fd[1] == -1) {
884 g->state = LAUNCHING;
886 /* Wait for qemu to start and to connect back to us via
887 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
889 r = guestfs___accept_from_daemon (g);
893 /* NB: We reach here just because qemu has opened the socket. It
894 * does not mean the daemon is up until we read the
895 * GUESTFS_LAUNCH_FLAG below. Failures in qemu startup can still
896 * happen even if we reach here, even early failures like not being
897 * able to open a drive.
900 close (g->sock); /* Close the listening socket. */
901 g->sock = r; /* This is the accepted data socket. */
903 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
904 perrorf (g, "fcntl");
910 r = guestfs___recv_from_daemon (g, &size, &buf);
913 if (r == -1) return -1;
915 if (size != GUESTFS_LAUNCH_FLAG) {
916 error (g, _("guestfs_launch failed, see earlier error messages"));
921 guestfs___print_timestamped_message (g, "appliance is up");
923 /* This is possible in some really strange situations, such as
924 * guestfsd starts up OK but then qemu immediately exits. Check for
925 * it because the caller is probably expecting to be able to send
926 * commands after this function returns.
928 if (g->state != READY) {
929 error (g, _("qemu launched and contacted daemon, but state != READY"));
935 guestfs___launch_send_progress (g, 12);
944 if (g->pid > 0) kill (g->pid, 9);
945 if (g->recoverypid > 0) kill (g->recoverypid, 9);
946 if (g->pid > 0) waitpid (g->pid, NULL, 0);
947 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
952 memset (&g->launch_t, 0, sizeof g->launch_t);
966 /* Alternate attach method: instead of launching the appliance,
967 * connect to an existing unix socket.
970 connect_unix_socket (guestfs_h *g, const char *sockpath)
973 struct sockaddr_un addr;
975 /* Start the clock ... */
976 gettimeofday (&g->launch_t, NULL);
978 /* Set these to nothing so we don't try to kill random processes or
979 * read from random file descriptors.
987 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
989 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
991 perrorf (g, "socket");
995 addr.sun_family = AF_UNIX;
996 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
997 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
999 g->state = LAUNCHING;
1001 if (connect (g->sock, &addr, sizeof addr) == -1) {
1002 perrorf (g, "bind");
1006 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1007 perrorf (g, "fcntl");
1013 r = guestfs___recv_from_daemon (g, &size, &buf);
1016 if (r == -1) return -1;
1018 if (size != GUESTFS_LAUNCH_FLAG) {
1019 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1024 guestfs___print_timestamped_message (g, "connected");
1026 if (g->state != READY) {
1027 error (g, _("contacted guestfsd, but state != READY"));
1038 /* launch (of the ordinary appliance) generates approximate progress
1039 * messages. Currently these are defined as follows:
1041 * 0 / 12: launch clock starts
1042 * 3 / 12: appliance created
1043 * 6 / 12: detected that guest kernel started
1044 * 9 / 12: detected that /init script is running
1045 * 12 / 12: launch completed successfully
1048 * (1) This is not a documented ABI and the behaviour may be changed
1049 * or removed in future.
1050 * (2) Messages are only sent if more than 5 seconds has elapsed
1051 * since the launch clock started.
1052 * (3) There is a gross hack in proto.c to make this work.
1055 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1059 gettimeofday (&tv, NULL);
1060 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1061 guestfs_progress progress_message =
1062 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1064 guestfs___progress_message_callback (g, &progress_message);
1068 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1069 * to override it at runtime using $TMPDIR.
1070 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1073 guestfs_tmpdir (void)
1083 const char *t = getenv ("TMPDIR");
1089 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1090 * allow users to override it at runtime using $TMPDIR.
1091 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1094 guestfs___persistent_tmpdir (void)
1098 tmpdir = "/var/tmp";
1100 const char *t = getenv ("TMPDIR");
1106 /* Recursively remove a temporary directory. If removal fails, just
1107 * return (it's a temporary directory so it'll eventually be cleaned
1108 * up by a temp cleaner). This is done using "rm -rf" because that's
1109 * simpler and safer, but we have to exec to ensure that paths don't
1110 * need to be quoted.
1113 guestfs___remove_tmpdir (const char *dir)
1115 pid_t pid = fork ();
1118 perror ("remove tmpdir: fork");
1122 execlp ("rm", "rm", "-rf", dir, NULL);
1123 perror ("remove tmpdir: exec: rm");
1124 _exit (EXIT_FAILURE);
1128 if (waitpid (pid, NULL, 0) == -1) {
1129 perror ("remove tmpdir: waitpid");
1134 /* Compute Y - X and return the result in milliseconds.
1135 * Approximately the same as this code:
1136 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1139 timeval_diff (const struct timeval *x, const struct timeval *y)
1143 msec = (y->tv_sec - x->tv_sec) * 1000;
1144 msec += (y->tv_usec - x->tv_usec) / 1000;
1148 /* Note that since this calls 'debug' it should only be called
1149 * from the parent process.
1152 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1159 va_start (args, fs);
1160 err = vasprintf (&msg, fs, args);
1163 if (err < 0) return;
1165 gettimeofday (&tv, NULL);
1167 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1172 /* This is called from the forked subprocess just before qemu runs, so
1173 * it can just print the message straight to stderr, where it will be
1174 * picked up and funnelled through the usual appliance event API.
1177 print_qemu_command_line (guestfs_h *g, char **argv)
1183 gettimeofday (&tv, NULL);
1184 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1187 if (argv[i][0] == '-') /* -option starts a new line */
1188 fprintf (stderr, " \\\n ");
1190 if (i > 0) fputc (' ', stderr);
1192 /* Does it need shell quoting? This only deals with simple cases. */
1193 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1195 if (needs_quote) fputc ('\'', stderr);
1196 fprintf (stderr, "%s", argv[i]);
1197 if (needs_quote) fputc ('\'', stderr);
1202 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1203 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1205 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1206 * 'qemu -version' so we know what options this qemu supports and
1210 test_qemu (guestfs_h *g)
1215 free (g->qemu_help);
1216 g->qemu_help = NULL;
1217 free (g->qemu_version);
1218 g->qemu_version = NULL;
1220 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1222 /* qemu -help should always work (qemu -version OTOH wasn't
1223 * supported by qemu 0.9). If this command doesn't work then it
1224 * probably indicates that the qemu binary is missing.
1226 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1227 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."),
1232 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1235 /* Intentionally ignore errors from qemu -version. */
1236 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1242 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1246 fp = popen (cmd, "r");
1250 if (read_all (g, fp, ret) == -1) {
1255 if (pclose (fp) != 0)
1262 read_all (guestfs_h *g, FILE *fp, char **ret)
1269 *ret = safe_realloc (g, *ret, n + 1);
1274 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1276 r = fread (p, 1, BUFSIZ, fp);
1278 perrorf (g, "read");
1285 /* Test if option is supported by qemu command line (just by grepping
1288 * The first time this is used, it has to run the external qemu
1289 * binary. If that fails, it returns -1.
1291 * To just do the first-time run of the qemu binary, call this with
1292 * option == NULL, in which case it will return -1 if there was an
1296 qemu_supports (guestfs_h *g, const char *option)
1298 if (!g->qemu_help) {
1299 if (test_qemu (g) == -1)
1306 return strstr (g->qemu_help, option) != NULL;
1310 /* As above but using a regex instead of a fixed string. */
1312 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1314 if (!g->qemu_help) {
1315 if (test_qemu (g) == -1)
1319 return match (g, g->qemu_help, option_regex);
1323 /* Check if a file can be opened. */
1325 is_openable (guestfs_h *g, const char *path, int flags)
1327 int fd = open (path, flags);
1329 debug (g, "is_openable: %s: %m", path);
1337 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1342 len += strlen (drv->path);
1343 len += strlen (drv->iface);
1345 len += strlen (drv->format);
1347 r = safe_malloc (g, len);
1349 snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1351 drv->readonly ? ",snapshot=on" : "",
1352 drv->use_cache_off ? ",cache=off" : "",
1353 drv->format ? ",format=" : "",
1354 drv->format ? drv->format : "",
1357 return r; /* caller frees */
1360 /* You had to call this function after launch in versions <= 1.0.70,
1361 * but it is now a no-op.
1364 guestfs__wait_ready (guestfs_h *g)
1366 if (g->state != READY) {
1367 error (g, _("qemu has not been launched yet"));
1375 guestfs__kill_subprocess (guestfs_h *g)
1377 if (g->state == CONFIG) {
1378 error (g, _("no subprocess to kill"));
1382 debug (g, "sending SIGTERM to process %d", g->pid);
1384 if (g->pid > 0) kill (g->pid, SIGTERM);
1385 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1390 /* Access current state. */
1392 guestfs__is_config (guestfs_h *g)
1394 return g->state == CONFIG;
1398 guestfs__is_launching (guestfs_h *g)
1400 return g->state == LAUNCHING;
1404 guestfs__is_ready (guestfs_h *g)
1406 return g->state == READY;
1410 guestfs__is_busy (guestfs_h *g)
1412 return g->state == BUSY;
1416 guestfs__get_state (guestfs_h *g)