2 * Copyright (C) 2009-2010 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 qemu_supports (guestfs_h *g, const char *option);
75 /* Add a string to the current command line. */
77 incr_cmdline_size (guestfs_h *g)
79 if (g->cmdline == NULL) {
80 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
82 g->cmdline = safe_malloc (g, sizeof (char *));
87 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
91 add_cmdline (guestfs_h *g, const char *str)
93 if (g->state != CONFIG) {
95 _("command line cannot be altered after qemu subprocess launched"));
99 incr_cmdline_size (g);
100 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
105 guestfs___checkpoint_cmdline (guestfs_h *g)
107 return g->cmdline_size;
111 guestfs___rollback_cmdline (guestfs_h *g, int pos)
115 assert (g->cmdline_size >= pos);
117 for (i = g->cmdline_size - 1; i >= pos; --i)
118 free (g->cmdline[i]);
120 g->cmdline_size = pos;
123 /* Internal command to return the command line. */
125 guestfs__debug_cmdline (guestfs_h *g)
130 if (g->cmdline == NULL) {
131 r = safe_malloc (g, sizeof (char *) * 1);
136 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
137 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
139 for (i = 1; i < g->cmdline_size; ++i)
140 r[i] = safe_strdup (g, g->cmdline[i]);
142 r[g->cmdline_size] = NULL;
144 return r; /* caller frees */
148 guestfs__config (guestfs_h *g,
149 const char *qemu_param, const char *qemu_value)
151 if (qemu_param[0] != '-') {
152 error (g, _("guestfs_config: parameter must begin with '-' character"));
156 /* A bit fascist, but the user will probably break the extra
157 * parameters that we add if they try to set any of these.
159 if (STREQ (qemu_param, "-kernel") ||
160 STREQ (qemu_param, "-initrd") ||
161 STREQ (qemu_param, "-nographic") ||
162 STREQ (qemu_param, "-serial") ||
163 STREQ (qemu_param, "-full-screen") ||
164 STREQ (qemu_param, "-std-vga") ||
165 STREQ (qemu_param, "-vnc")) {
166 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
170 if (add_cmdline (g, qemu_param) != 0) return -1;
172 if (qemu_value != NULL) {
173 if (add_cmdline (g, qemu_value) != 0) return -1;
179 /* cache=off improves reliability in the event of a host crash.
181 * However this option causes qemu to try to open the file with
182 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
183 * So we check if we can open the file with or without O_DIRECT,
184 * and use cache=off (or not) accordingly.
187 test_cache_off (guestfs_h *g, const char *filename)
189 int fd = open (filename, O_RDONLY|O_DIRECT);
195 fd = open (filename, O_RDONLY);
201 perrorf (g, "%s", filename);
205 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
207 valid_format_iface (const char *str)
209 size_t len = strlen (str);
217 if (c != '-' && c != '_' && !c_isalnum (c))
224 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
225 const struct guestfs_add_drive_opts_argv *optargs)
231 if (strchr (filename, ',') != NULL) {
232 error (g, _("filename cannot contain ',' (comma) character"));
236 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
237 ? optargs->readonly : 0;
238 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
239 ? optargs->format : NULL;
240 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
241 ? optargs->iface : DRIVE_IF;
243 if (format && !valid_format_iface (format)) {
244 error (g, _("%s parameter is empty or contains disallowed characters"),
248 if (!valid_format_iface (iface)) {
249 error (g, _("%s parameter is empty or contains disallowed characters"),
254 /* For writable files, see if we can use cache=off. This also
255 * checks for the existence of the file. For readonly we have
256 * to do the check explicitly.
258 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
259 if (use_cache_off == -1)
263 if (access (filename, F_OK) == -1) {
264 perrorf (g, "%s", filename);
269 /* Construct the final -drive parameter. */
270 size_t len = 64 + strlen (filename) + strlen (iface);
271 if (format) len += strlen (format);
274 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
276 readonly ? ",snapshot=on" : "",
277 use_cache_off ? ",cache=off" : "",
278 format ? ",format=" : "",
279 format ? format : "",
282 return guestfs__config (g, "-drive", buf);
286 guestfs__add_drive (guestfs_h *g, const char *filename)
288 struct guestfs_add_drive_opts_argv optargs = {
292 return guestfs__add_drive_opts (g, filename, &optargs);
296 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
298 struct guestfs_add_drive_opts_argv optargs = {
299 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
303 return guestfs__add_drive_opts (g, filename, &optargs);
307 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
310 struct guestfs_add_drive_opts_argv optargs = {
311 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
315 return guestfs__add_drive_opts (g, filename, &optargs);
319 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
322 struct guestfs_add_drive_opts_argv optargs = {
323 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
324 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
329 return guestfs__add_drive_opts (g, filename, &optargs);
333 guestfs__add_cdrom (guestfs_h *g, const char *filename)
335 if (strchr (filename, ',') != NULL) {
336 error (g, _("filename cannot contain ',' (comma) character"));
340 if (access (filename, F_OK) == -1) {
341 perrorf (g, "%s", filename);
345 return guestfs__config (g, "-cdrom", filename);
348 static int is_openable (guestfs_h *g, const char *path, int flags);
351 guestfs__launch (guestfs_h *g)
357 struct sockaddr_un addr;
361 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
365 if (g->state != CONFIG) {
366 error (g, _("the libguestfs handle has already been launched"));
370 /* Start the clock ... */
371 gettimeofday (&g->launch_t, NULL);
373 /* Make the temporary directory. */
375 TMP_TEMPLATE_ON_STACK (dir_template);
376 g->tmpdir = safe_strdup (g, dir_template);
377 if (mkdtemp (g->tmpdir) == NULL) {
378 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
383 /* Allow anyone to read the temporary directory. The socket in this
384 * directory won't be readable but anyone can see it exists if they
385 * want. (RHBZ#610880).
387 if (chmod (g->tmpdir, 0755) == -1)
388 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
390 /* Locate and/or build the appliance. */
391 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
392 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
396 guestfs___print_timestamped_message (g, "begin testing qemu features");
398 /* Get qemu help text and version. */
399 if (qemu_supports (g, NULL) == -1)
402 /* Using virtio-serial, we need to create a local Unix domain socket
403 * for qemu to connect to.
405 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
408 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
410 perrorf (g, "socket");
414 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
415 perrorf (g, "fcntl");
419 addr.sun_family = AF_UNIX;
420 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
421 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
423 if (bind (g->sock, &addr, sizeof addr) == -1) {
428 if (listen (g->sock, 1) == -1) {
429 perrorf (g, "listen");
434 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
441 guestfs___print_timestamped_message (g, "finished testing qemu features");
455 if (r == 0) { /* Child (qemu). */
458 /* Set up the full command line. Do this in the subprocess so we
459 * don't need to worry about cleaning up.
461 g->cmdline[0] = g->qemu;
463 if (qemu_supports (g, "-nodefconfig"))
464 add_cmdline (g, "-nodefconfig");
466 /* qemu sometimes needs this option to enable hardware
467 * virtualization, but some versions of 'qemu-kvm' will use KVM
468 * regardless (even where this option appears in the help text).
469 * It is rumoured that there are versions of qemu where supplying
470 * this option when hardware virtualization is not available will
471 * cause qemu to fail, so we we have to check at least that
472 * /dev/kvm is openable. That's not reliable, since /dev/kvm
473 * might be openable by qemu but not by us (think: SELinux) in
474 * which case the user would not get hardware virtualization,
475 * although at least shouldn't fail. A giant clusterfuck with the
476 * qemu command line, again.
478 if (qemu_supports (g, "-enable-kvm") &&
479 is_openable (g, "/dev/kvm", O_RDWR))
480 add_cmdline (g, "-enable-kvm");
482 /* Newer versions of qemu (from around 2009/12) changed the
483 * behaviour of monitors so that an implicit '-monitor stdio' is
484 * assumed if we are in -nographic mode and there is no other
485 * -monitor option. Only a single stdio device is allowed, so
486 * this broke the '-serial stdio' option. There is a new flag
487 * called -nodefaults which gets rid of all this default crud, so
488 * let's use that to avoid this and any future surprises.
490 if (qemu_supports (g, "-nodefaults"))
491 add_cmdline (g, "-nodefaults");
493 add_cmdline (g, "-nographic");
495 snprintf (buf, sizeof buf, "%d", g->memsize);
496 add_cmdline (g, "-m");
497 add_cmdline (g, buf);
499 /* Force exit instead of reboot on panic */
500 add_cmdline (g, "-no-reboot");
502 /* These options recommended by KVM developers to improve reliability. */
503 if (qemu_supports (g, "-no-hpet"))
504 add_cmdline (g, "-no-hpet");
506 if (qemu_supports (g, "-rtc-td-hack"))
507 add_cmdline (g, "-rtc-td-hack");
509 /* Create the virtio serial bus. */
510 add_cmdline (g, "-device");
511 add_cmdline (g, "virtio-serial");
514 /* Use virtio-console (a variant form of virtio-serial) for the
515 * guest's serial console.
517 add_cmdline (g, "-chardev");
518 add_cmdline (g, "stdio,id=console");
519 add_cmdline (g, "-device");
520 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
522 /* When the above works ... until then: */
523 add_cmdline (g, "-serial");
524 add_cmdline (g, "stdio");
527 /* Set up virtio-serial for the communications channel. */
528 add_cmdline (g, "-chardev");
529 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
530 add_cmdline (g, buf);
531 add_cmdline (g, "-device");
532 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
534 /* Enable user networking. */
535 if (g->enable_network) {
536 add_cmdline (g, "-netdev");
537 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
538 add_cmdline (g, "-device");
539 add_cmdline (g, NET_IF ",netdev=usernet");
542 #define LINUX_CMDLINE \
543 "panic=1 " /* force kernel to panic if daemon exits */ \
544 "console=ttyS0 " /* serial console */ \
545 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
546 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
547 "acpi=off " /* we don't need ACPI, turn it off */ \
548 "printk.time=1 " /* display timestamp before kernel messages */ \
549 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
551 /* Linux kernel command line. */
552 snprintf (buf, sizeof buf,
554 "%s " /* (selinux) */
555 "%s " /* (verbose) */
556 "TERM=%s " /* (TERM environment variable) */
558 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
559 g->verbose ? "guestfs_verbose=1" : "",
560 getenv ("TERM") ? : "linux",
561 g->append ? g->append : "");
563 add_cmdline (g, "-kernel");
564 add_cmdline (g, kernel);
565 add_cmdline (g, "-initrd");
566 add_cmdline (g, initrd);
567 add_cmdline (g, "-append");
568 add_cmdline (g, buf);
570 /* Add the ext2 appliance drive (last of all). */
572 const char *cachemode = "";
573 if (qemu_supports (g, "cache=")) {
574 if (qemu_supports (g, "unsafe"))
575 cachemode = ",cache=unsafe";
576 else if (qemu_supports (g, "writeback"))
577 cachemode = ",cache=writeback";
580 char buf2[PATH_MAX + 64];
581 add_cmdline (g, "-drive");
582 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
583 appliance, cachemode);
584 add_cmdline (g, buf2);
587 /* Finish off the command line. */
588 incr_cmdline_size (g);
589 g->cmdline[g->cmdline_size-1] = NULL;
592 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
595 /* Set up stdin, stdout. */
601 if (dup (wfd[0]) == -1) {
603 perror ("dup failed");
604 _exit (EXIT_FAILURE);
606 if (dup (rfd[1]) == -1)
614 /* Set up a new process group, so we can signal this process
615 * and all subprocesses (eg. if qemu is really a shell script).
620 setenv ("LC_ALL", "C", 1);
622 execv (g->qemu, g->cmdline); /* Run qemu. */
624 _exit (EXIT_FAILURE);
627 /* Parent (library). */
637 /* Fork the recovery process off which will kill qemu if the parent
638 * process fails to do so (eg. if the parent segfaults).
641 if (g->recovery_proc) {
644 pid_t qemu_pid = g->pid;
645 pid_t parent_pid = getppid ();
647 /* Writing to argv is hideously complicated and error prone. See:
648 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
651 /* Loop around waiting for one or both of the other processes to
652 * disappear. It's fair to say this is very hairy. The PIDs that
653 * we are looking at might be reused by another process. We are
654 * effectively polling. Is the cure worse than the disease?
657 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
658 _exit (EXIT_SUCCESS);
659 if (kill (parent_pid, 0) == -1) {
660 /* Parent's gone away, qemu still around, so kill qemu. */
662 _exit (EXIT_SUCCESS);
668 /* Don't worry, if the fork failed, this will be -1. The recovery
669 * process isn't essential.
675 /* Close the other ends of the pipe. */
679 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
680 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
681 perrorf (g, "fcntl");
685 g->fd[0] = wfd[1]; /* stdin of child */
686 g->fd[1] = rfd[0]; /* stdout of child */
688 g->fd[0] = open ("/dev/null", O_RDWR);
689 if (g->fd[0] == -1) {
690 perrorf (g, "open /dev/null");
693 g->fd[1] = dup (g->fd[0]);
694 if (g->fd[1] == -1) {
701 g->state = LAUNCHING;
703 /* Wait for qemu to start and to connect back to us via
704 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
706 r = guestfs___accept_from_daemon (g);
710 close (g->sock); /* Close the listening socket. */
711 g->sock = r; /* This is the accepted data socket. */
713 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
714 perrorf (g, "fcntl");
720 r = guestfs___recv_from_daemon (g, &size, &buf);
723 if (r == -1) return -1;
725 if (size != GUESTFS_LAUNCH_FLAG) {
726 error (g, _("guestfs_launch failed, see earlier error messages"));
731 guestfs___print_timestamped_message (g, "appliance is up");
733 /* This is possible in some really strange situations, such as
734 * guestfsd starts up OK but then qemu immediately exits. Check for
735 * it because the caller is probably expecting to be able to send
736 * commands after this function returns.
738 if (g->state != READY) {
739 error (g, _("qemu launched and contacted daemon, but state != READY"));
750 if (g->pid > 0) kill (g->pid, 9);
751 if (g->recoverypid > 0) kill (g->recoverypid, 9);
752 waitpid (g->pid, NULL, 0);
753 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
758 memset (&g->launch_t, 0, sizeof g->launch_t);
772 /* Return the location of the tmpdir (eg. "/tmp") and allow users
773 * to override it at runtime using $TMPDIR.
776 guestfs_tmpdir (void)
786 const char *t = getenv ("TMPDIR");
792 /* Compute Y - X and return the result in milliseconds.
793 * Approximately the same as this code:
794 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
797 timeval_diff (const struct timeval *x, const struct timeval *y)
801 msec = (y->tv_sec - x->tv_sec) * 1000;
802 msec += (y->tv_usec - x->tv_usec) / 1000;
807 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
813 gettimeofday (&tv, NULL);
814 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
817 if (argv[i][0] == '-') /* -option starts a new line */
818 fprintf (stderr, " \\\n ");
820 if (i > 0) fputc (' ', stderr);
822 /* Does it need shell quoting? This only deals with simple cases. */
823 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
825 if (needs_quote) fputc ('\'', stderr);
826 fprintf (stderr, "%s", argv[i]);
827 if (needs_quote) fputc ('\'', stderr);
831 fputc ('\n', stderr);
835 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
843 err = vasprintf (&msg, fs, args);
848 gettimeofday (&tv, NULL);
850 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
851 timeval_diff (&g->launch_t, &tv), msg);
856 static int read_all (guestfs_h *g, FILE *fp, char **ret);
858 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
859 * 'qemu -version' so we know what options this qemu supports and
863 test_qemu (guestfs_h *g)
868 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
870 fp = popen (cmd, "r");
871 /* qemu -help should always work (qemu -version OTOH wasn't
872 * supported by qemu 0.9). If this command doesn't work then it
873 * probably indicates that the qemu binary is missing.
876 /* XXX This error is never printed, even if the qemu binary
877 * doesn't exist. Why?
880 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
884 if (read_all (g, fp, &g->qemu_help) == -1)
887 if (pclose (fp) == -1)
890 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
893 fp = popen (cmd, "r");
895 /* Intentionally ignore errors. */
896 read_all (g, fp, &g->qemu_version);
904 read_all (guestfs_h *g, FILE *fp, char **ret)
911 *ret = safe_realloc (g, *ret, n + 1);
916 *ret = safe_realloc (g, *ret, n + BUFSIZ);
918 r = fread (p, 1, BUFSIZ, fp);
927 /* Test if option is supported by qemu command line (just by grepping
930 * The first time this is used, it has to run the external qemu
931 * binary. If that fails, it returns -1.
933 * To just do the first-time run of the qemu binary, call this with
934 * option == NULL, in which case it will return -1 if there was an
938 qemu_supports (guestfs_h *g, const char *option)
941 if (test_qemu (g) == -1)
948 return strstr (g->qemu_help, option) != NULL;
951 /* Check if a file can be opened. */
953 is_openable (guestfs_h *g, const char *path, int flags)
955 int fd = open (path, flags);
965 /* You had to call this function after launch in versions <= 1.0.70,
966 * but it is now a no-op.
969 guestfs__wait_ready (guestfs_h *g)
971 if (g->state != READY) {
972 error (g, _("qemu has not been launched yet"));
980 guestfs__kill_subprocess (guestfs_h *g)
982 if (g->state == CONFIG) {
983 error (g, _("no subprocess to kill"));
988 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
990 if (g->pid > 0) kill (g->pid, SIGTERM);
991 if (g->recoverypid > 0) kill (g->recoverypid, 9);
996 /* Access current state. */
998 guestfs__is_config (guestfs_h *g)
1000 return g->state == CONFIG;
1004 guestfs__is_launching (guestfs_h *g)
1006 return g->state == LAUNCHING;
1010 guestfs__is_ready (guestfs_h *g)
1012 return g->state == READY;
1016 guestfs__is_busy (guestfs_h *g)
1018 return g->state == BUSY;
1022 guestfs__get_state (guestfs_h *g)