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;
124 guestfs__config (guestfs_h *g,
125 const char *qemu_param, const char *qemu_value)
127 if (qemu_param[0] != '-') {
128 error (g, _("guestfs_config: parameter must begin with '-' character"));
132 /* A bit fascist, but the user will probably break the extra
133 * parameters that we add if they try to set any of these.
135 if (STREQ (qemu_param, "-kernel") ||
136 STREQ (qemu_param, "-initrd") ||
137 STREQ (qemu_param, "-nographic") ||
138 STREQ (qemu_param, "-serial") ||
139 STREQ (qemu_param, "-full-screen") ||
140 STREQ (qemu_param, "-std-vga") ||
141 STREQ (qemu_param, "-vnc")) {
142 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
146 if (add_cmdline (g, qemu_param) != 0) return -1;
148 if (qemu_value != NULL) {
149 if (add_cmdline (g, qemu_value) != 0) return -1;
155 /* cache=off improves reliability in the event of a host crash.
157 * However this option causes qemu to try to open the file with
158 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
159 * So we check if we can open the file with or without O_DIRECT,
160 * and use cache=off (or not) accordingly.
163 test_cache_off (guestfs_h *g, const char *filename)
165 int fd = open (filename, O_RDONLY|O_DIRECT);
171 fd = open (filename, O_RDONLY);
177 perrorf (g, "%s", filename);
181 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
183 valid_format_iface (const char *str)
185 size_t len = strlen (str);
193 if (c != '-' && c != '_' && !c_isalnum (c))
200 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
201 const struct guestfs_add_drive_opts_argv *optargs)
207 if (strchr (filename, ',') != NULL) {
208 error (g, _("filename cannot contain ',' (comma) character"));
212 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
213 ? optargs->readonly : 0;
214 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
215 ? optargs->format : NULL;
216 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
217 ? optargs->iface : DRIVE_IF;
219 if (format && !valid_format_iface (format)) {
220 error (g, _("%s parameter is empty or contains disallowed characters"),
224 if (!valid_format_iface (iface)) {
225 error (g, _("%s parameter is empty or contains disallowed characters"),
230 /* For writable files, see if we can use cache=off. This also
231 * checks for the existence of the file. For readonly we have
232 * to do the check explicitly.
234 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
235 if (use_cache_off == -1)
239 if (access (filename, F_OK) == -1) {
240 perrorf (g, "%s", filename);
245 /* Construct the final -drive parameter. */
246 size_t len = 64 + strlen (filename) + strlen (iface);
247 if (format) len += strlen (format);
250 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
252 readonly ? ",snapshot=on" : "",
253 use_cache_off ? ",cache=off" : "",
254 format ? ",format=" : "",
255 format ? format : "",
258 return guestfs__config (g, "-drive", buf);
262 guestfs__add_drive (guestfs_h *g, const char *filename)
264 struct guestfs_add_drive_opts_argv optargs = {
268 return guestfs__add_drive_opts (g, filename, &optargs);
272 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
274 struct guestfs_add_drive_opts_argv optargs = {
275 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
279 return guestfs__add_drive_opts (g, filename, &optargs);
283 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
286 struct guestfs_add_drive_opts_argv optargs = {
287 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
291 return guestfs__add_drive_opts (g, filename, &optargs);
295 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
298 struct guestfs_add_drive_opts_argv optargs = {
299 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
300 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
305 return guestfs__add_drive_opts (g, filename, &optargs);
309 guestfs__add_cdrom (guestfs_h *g, const char *filename)
311 if (strchr (filename, ',') != NULL) {
312 error (g, _("filename cannot contain ',' (comma) character"));
316 if (access (filename, F_OK) == -1) {
317 perrorf (g, "%s", filename);
321 return guestfs__config (g, "-cdrom", filename);
324 static int is_openable (guestfs_h *g, const char *path, int flags);
327 guestfs__launch (guestfs_h *g)
333 struct sockaddr_un addr;
337 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
341 if (g->state != CONFIG) {
342 error (g, _("the libguestfs handle has already been launched"));
346 /* Start the clock ... */
347 gettimeofday (&g->launch_t, NULL);
349 /* Make the temporary directory. */
351 TMP_TEMPLATE_ON_STACK (dir_template);
352 g->tmpdir = safe_strdup (g, dir_template);
353 if (mkdtemp (g->tmpdir) == NULL) {
354 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
359 /* Allow anyone to read the temporary directory. The socket in this
360 * directory won't be readable but anyone can see it exists if they
361 * want. (RHBZ#610880).
363 if (chmod (g->tmpdir, 0755) == -1)
364 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
366 /* Locate and/or build the appliance. */
367 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
368 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
372 guestfs___print_timestamped_message (g, "begin testing qemu features");
374 /* Get qemu help text and version. */
375 if (qemu_supports (g, NULL) == -1)
378 /* Using virtio-serial, we need to create a local Unix domain socket
379 * for qemu to connect to.
381 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
384 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
386 perrorf (g, "socket");
390 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
391 perrorf (g, "fcntl");
395 addr.sun_family = AF_UNIX;
396 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
397 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
399 if (bind (g->sock, &addr, sizeof addr) == -1) {
404 if (listen (g->sock, 1) == -1) {
405 perrorf (g, "listen");
410 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
417 guestfs___print_timestamped_message (g, "finished testing qemu features");
431 if (r == 0) { /* Child (qemu). */
434 /* Set up the full command line. Do this in the subprocess so we
435 * don't need to worry about cleaning up.
437 g->cmdline[0] = g->qemu;
439 if (qemu_supports (g, "-nodefconfig"))
440 add_cmdline (g, "-nodefconfig");
442 /* qemu sometimes needs this option to enable hardware
443 * virtualization, but some versions of 'qemu-kvm' will use KVM
444 * regardless (even where this option appears in the help text).
445 * It is rumoured that there are versions of qemu where supplying
446 * this option when hardware virtualization is not available will
447 * cause qemu to fail, so we we have to check at least that
448 * /dev/kvm is openable. That's not reliable, since /dev/kvm
449 * might be openable by qemu but not by us (think: SELinux) in
450 * which case the user would not get hardware virtualization,
451 * although at least shouldn't fail. A giant clusterfuck with the
452 * qemu command line, again.
454 if (qemu_supports (g, "-enable-kvm") &&
455 is_openable (g, "/dev/kvm", O_RDWR))
456 add_cmdline (g, "-enable-kvm");
458 /* Newer versions of qemu (from around 2009/12) changed the
459 * behaviour of monitors so that an implicit '-monitor stdio' is
460 * assumed if we are in -nographic mode and there is no other
461 * -monitor option. Only a single stdio device is allowed, so
462 * this broke the '-serial stdio' option. There is a new flag
463 * called -nodefaults which gets rid of all this default crud, so
464 * let's use that to avoid this and any future surprises.
466 if (qemu_supports (g, "-nodefaults"))
467 add_cmdline (g, "-nodefaults");
469 add_cmdline (g, "-nographic");
471 snprintf (buf, sizeof buf, "%d", g->memsize);
472 add_cmdline (g, "-m");
473 add_cmdline (g, buf);
475 /* Force exit instead of reboot on panic */
476 add_cmdline (g, "-no-reboot");
478 /* These options recommended by KVM developers to improve reliability. */
479 if (qemu_supports (g, "-no-hpet"))
480 add_cmdline (g, "-no-hpet");
482 if (qemu_supports (g, "-rtc-td-hack"))
483 add_cmdline (g, "-rtc-td-hack");
485 /* Create the virtio serial bus. */
486 add_cmdline (g, "-device");
487 add_cmdline (g, "virtio-serial");
490 /* Use virtio-console (a variant form of virtio-serial) for the
491 * guest's serial console.
493 add_cmdline (g, "-chardev");
494 add_cmdline (g, "stdio,id=console");
495 add_cmdline (g, "-device");
496 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
498 /* When the above works ... until then: */
499 add_cmdline (g, "-serial");
500 add_cmdline (g, "stdio");
503 /* Set up virtio-serial for the communications channel. */
504 add_cmdline (g, "-chardev");
505 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
506 add_cmdline (g, buf);
507 add_cmdline (g, "-device");
508 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
510 /* Enable user networking. */
511 if (g->enable_network) {
512 add_cmdline (g, "-netdev");
513 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
514 add_cmdline (g, "-device");
515 add_cmdline (g, NET_IF ",netdev=usernet");
518 #define LINUX_CMDLINE \
519 "panic=1 " /* force kernel to panic if daemon exits */ \
520 "console=ttyS0 " /* serial console */ \
521 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
522 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
523 "acpi=off " /* we don't need ACPI, turn it off */ \
524 "printk.time=1 " /* display timestamp before kernel messages */ \
525 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
527 /* Linux kernel command line. */
528 snprintf (buf, sizeof buf,
530 "%s " /* (selinux) */
531 "%s " /* (verbose) */
532 "TERM=%s " /* (TERM environment variable) */
534 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
535 g->verbose ? "guestfs_verbose=1" : "",
536 getenv ("TERM") ? : "linux",
537 g->append ? g->append : "");
539 add_cmdline (g, "-kernel");
540 add_cmdline (g, kernel);
541 add_cmdline (g, "-initrd");
542 add_cmdline (g, initrd);
543 add_cmdline (g, "-append");
544 add_cmdline (g, buf);
546 /* Add the ext2 appliance drive (last of all). */
548 const char *cachemode = "";
549 if (qemu_supports (g, "cache=")) {
550 if (qemu_supports (g, "unsafe"))
551 cachemode = ",cache=unsafe";
552 else if (qemu_supports (g, "writeback"))
553 cachemode = ",cache=writeback";
556 char buf2[PATH_MAX + 64];
557 add_cmdline (g, "-drive");
558 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
559 appliance, cachemode);
560 add_cmdline (g, buf2);
563 /* Finish off the command line. */
564 incr_cmdline_size (g);
565 g->cmdline[g->cmdline_size-1] = NULL;
568 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
571 /* Set up stdin, stdout. */
577 if (dup (wfd[0]) == -1) {
579 perror ("dup failed");
580 _exit (EXIT_FAILURE);
582 if (dup (rfd[1]) == -1)
590 /* Set up a new process group, so we can signal this process
591 * and all subprocesses (eg. if qemu is really a shell script).
596 setenv ("LC_ALL", "C", 1);
598 execv (g->qemu, g->cmdline); /* Run qemu. */
600 _exit (EXIT_FAILURE);
603 /* Parent (library). */
613 /* Fork the recovery process off which will kill qemu if the parent
614 * process fails to do so (eg. if the parent segfaults).
617 if (g->recovery_proc) {
620 pid_t qemu_pid = g->pid;
621 pid_t parent_pid = getppid ();
623 /* Writing to argv is hideously complicated and error prone. See:
624 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
627 /* Loop around waiting for one or both of the other processes to
628 * disappear. It's fair to say this is very hairy. The PIDs that
629 * we are looking at might be reused by another process. We are
630 * effectively polling. Is the cure worse than the disease?
633 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
634 _exit (EXIT_SUCCESS);
635 if (kill (parent_pid, 0) == -1) {
636 /* Parent's gone away, qemu still around, so kill qemu. */
638 _exit (EXIT_SUCCESS);
644 /* Don't worry, if the fork failed, this will be -1. The recovery
645 * process isn't essential.
651 /* Close the other ends of the pipe. */
655 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
656 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
657 perrorf (g, "fcntl");
661 g->fd[0] = wfd[1]; /* stdin of child */
662 g->fd[1] = rfd[0]; /* stdout of child */
664 g->fd[0] = open ("/dev/null", O_RDWR);
665 if (g->fd[0] == -1) {
666 perrorf (g, "open /dev/null");
669 g->fd[1] = dup (g->fd[0]);
670 if (g->fd[1] == -1) {
677 g->state = LAUNCHING;
679 /* Wait for qemu to start and to connect back to us via
680 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
682 r = guestfs___accept_from_daemon (g);
686 close (g->sock); /* Close the listening socket. */
687 g->sock = r; /* This is the accepted data socket. */
689 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
690 perrorf (g, "fcntl");
696 r = guestfs___recv_from_daemon (g, &size, &buf);
699 if (r == -1) return -1;
701 if (size != GUESTFS_LAUNCH_FLAG) {
702 error (g, _("guestfs_launch failed, see earlier error messages"));
707 guestfs___print_timestamped_message (g, "appliance is up");
709 /* This is possible in some really strange situations, such as
710 * guestfsd starts up OK but then qemu immediately exits. Check for
711 * it because the caller is probably expecting to be able to send
712 * commands after this function returns.
714 if (g->state != READY) {
715 error (g, _("qemu launched and contacted daemon, but state != READY"));
726 if (g->pid > 0) kill (g->pid, 9);
727 if (g->recoverypid > 0) kill (g->recoverypid, 9);
728 waitpid (g->pid, NULL, 0);
729 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
734 memset (&g->launch_t, 0, sizeof g->launch_t);
748 /* Return the location of the tmpdir (eg. "/tmp") and allow users
749 * to override it at runtime using $TMPDIR.
752 guestfs_tmpdir (void)
762 const char *t = getenv ("TMPDIR");
768 /* Compute Y - X and return the result in milliseconds.
769 * Approximately the same as this code:
770 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
773 timeval_diff (const struct timeval *x, const struct timeval *y)
777 msec = (y->tv_sec - x->tv_sec) * 1000;
778 msec += (y->tv_usec - x->tv_usec) / 1000;
783 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
789 gettimeofday (&tv, NULL);
790 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
793 if (argv[i][0] == '-') /* -option starts a new line */
794 fprintf (stderr, " \\\n ");
796 if (i > 0) fputc (' ', stderr);
798 /* Does it need shell quoting? This only deals with simple cases. */
799 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
801 if (needs_quote) fputc ('\'', stderr);
802 fprintf (stderr, "%s", argv[i]);
803 if (needs_quote) fputc ('\'', stderr);
807 fputc ('\n', stderr);
811 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
819 err = vasprintf (&msg, fs, args);
824 gettimeofday (&tv, NULL);
826 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
827 timeval_diff (&g->launch_t, &tv), msg);
832 static int read_all (guestfs_h *g, FILE *fp, char **ret);
834 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
835 * 'qemu -version' so we know what options this qemu supports and
839 test_qemu (guestfs_h *g)
844 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
846 fp = popen (cmd, "r");
847 /* qemu -help should always work (qemu -version OTOH wasn't
848 * supported by qemu 0.9). If this command doesn't work then it
849 * probably indicates that the qemu binary is missing.
852 /* XXX This error is never printed, even if the qemu binary
853 * doesn't exist. Why?
856 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
860 if (read_all (g, fp, &g->qemu_help) == -1)
863 if (pclose (fp) == -1)
866 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
869 fp = popen (cmd, "r");
871 /* Intentionally ignore errors. */
872 read_all (g, fp, &g->qemu_version);
880 read_all (guestfs_h *g, FILE *fp, char **ret)
887 *ret = safe_realloc (g, *ret, n + 1);
892 *ret = safe_realloc (g, *ret, n + BUFSIZ);
894 r = fread (p, 1, BUFSIZ, fp);
903 /* Test if option is supported by qemu command line (just by grepping
906 * The first time this is used, it has to run the external qemu
907 * binary. If that fails, it returns -1.
909 * To just do the first-time run of the qemu binary, call this with
910 * option == NULL, in which case it will return -1 if there was an
914 qemu_supports (guestfs_h *g, const char *option)
917 if (test_qemu (g) == -1)
924 return strstr (g->qemu_help, option) != NULL;
927 /* Check if a file can be opened. */
929 is_openable (guestfs_h *g, const char *path, int flags)
931 int fd = open (path, flags);
941 /* You had to call this function after launch in versions <= 1.0.70,
942 * but it is now a no-op.
945 guestfs__wait_ready (guestfs_h *g)
947 if (g->state != READY) {
948 error (g, _("qemu has not been launched yet"));
956 guestfs__kill_subprocess (guestfs_h *g)
958 if (g->state == CONFIG) {
959 error (g, _("no subprocess to kill"));
964 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
966 if (g->pid > 0) kill (g->pid, SIGTERM);
967 if (g->recoverypid > 0) kill (g->recoverypid, 9);
972 /* Access current state. */
974 guestfs__is_config (guestfs_h *g)
976 return g->state == CONFIG;
980 guestfs__is_launching (guestfs_h *g)
982 return g->state == LAUNCHING;
986 guestfs__is_ready (guestfs_h *g)
988 return g->state == READY;
992 guestfs__is_busy (guestfs_h *g)
994 return g->state == BUSY;
998 guestfs__get_state (guestfs_h *g)