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>
38 #include <rpc/types.h>
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
49 #ifdef HAVE_SYS_WAIT_H
53 #ifdef HAVE_SYS_SOCKET_H
54 #include <sys/socket.h>
61 #include <arpa/inet.h>
62 #include <netinet/in.h>
65 #include "glthread/lock.h"
66 #include "ignore-value.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__config (guestfs_h *g,
106 const char *qemu_param, const char *qemu_value)
108 if (qemu_param[0] != '-') {
109 error (g, _("guestfs_config: parameter must begin with '-' character"));
113 /* A bit fascist, but the user will probably break the extra
114 * parameters that we add if they try to set any of these.
116 if (STREQ (qemu_param, "-kernel") ||
117 STREQ (qemu_param, "-initrd") ||
118 STREQ (qemu_param, "-nographic") ||
119 STREQ (qemu_param, "-serial") ||
120 STREQ (qemu_param, "-full-screen") ||
121 STREQ (qemu_param, "-std-vga") ||
122 STREQ (qemu_param, "-vnc")) {
123 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
127 if (add_cmdline (g, qemu_param) != 0) return -1;
129 if (qemu_value != NULL) {
130 if (add_cmdline (g, qemu_value) != 0) return -1;
137 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
138 const char *drive_if)
140 size_t len = strlen (filename) + 64;
143 if (strchr (filename, ',') != NULL) {
144 error (g, _("filename cannot contain ',' (comma) character"));
148 /* cache=off improves reliability in the event of a host crash.
150 * However this option causes qemu to try to open the file with
151 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
152 * So we check if we can open the file with or without O_DIRECT,
153 * and use cache=off (or not) accordingly.
155 * This test also checks for the presence of the file, which
156 * is a documented semantic of this interface.
158 int fd = open (filename, O_RDONLY|O_DIRECT);
161 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
163 fd = open (filename, O_RDONLY);
166 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
168 perrorf (g, "%s", filename);
173 return guestfs__config (g, "-drive", buf);
177 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
178 const char *drive_if)
180 if (strchr (filename, ',') != NULL) {
181 error (g, _("filename cannot contain ',' (comma) character"));
185 if (access (filename, F_OK) == -1) {
186 perrorf (g, "%s", filename);
190 size_t len = strlen (filename) + 64;
193 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
195 return guestfs__config (g, "-drive", buf);
199 guestfs__add_drive (guestfs_h *g, const char *filename)
201 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
205 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
207 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
211 guestfs__add_cdrom (guestfs_h *g, const char *filename)
213 if (strchr (filename, ',') != NULL) {
214 error (g, _("filename cannot contain ',' (comma) character"));
218 if (access (filename, F_OK) == -1) {
219 perrorf (g, "%s", filename);
223 return guestfs__config (g, "-cdrom", filename);
226 static int is_openable (guestfs_h *g, const char *path, int flags);
227 static void print_cmdline (guestfs_h *g);
230 guestfs__launch (guestfs_h *g)
236 struct sockaddr_un addr;
240 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
244 if (g->state != CONFIG) {
245 error (g, _("the libguestfs handle has already been launched"));
249 /* Start the clock ... */
250 gettimeofday (&g->launch_t, NULL);
252 /* Make the temporary directory. */
254 const char *tmpdir = guestfs___tmpdir ();
255 char dir_template[strlen (tmpdir) + 32];
256 sprintf (dir_template, "%s/libguestfsXXXXXX", tmpdir);
258 g->tmpdir = safe_strdup (g, dir_template);
259 if (mkdtemp (g->tmpdir) == NULL) {
260 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
265 /* Allow anyone to read the temporary directory. The socket in this
266 * directory won't be readable but anyone can see it exists if they
267 * want. (RHBZ#610880).
269 if (chmod (g->tmpdir, 0755) == -1)
270 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
272 /* Locate and/or build the appliance. */
273 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
274 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
278 guestfs___print_timestamped_message (g, "begin testing qemu features");
280 /* Get qemu help text and version. */
281 if (qemu_supports (g, NULL) == -1)
284 /* Using virtio-serial, we need to create a local Unix domain socket
285 * for qemu to connect to.
287 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
290 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
292 perrorf (g, "socket");
296 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
297 perrorf (g, "fcntl");
301 addr.sun_family = AF_UNIX;
302 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
303 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
305 if (bind (g->sock, &addr, sizeof addr) == -1) {
310 if (listen (g->sock, 1) == -1) {
311 perrorf (g, "listen");
316 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
323 guestfs___print_timestamped_message (g, "finished testing qemu features");
337 if (r == 0) { /* Child (qemu). */
340 /* Set up the full command line. Do this in the subprocess so we
341 * don't need to worry about cleaning up.
343 g->cmdline[0] = g->qemu;
345 if (qemu_supports (g, "-nodefconfig"))
346 add_cmdline (g, "-nodefconfig");
348 /* qemu sometimes needs this option to enable hardware
349 * virtualization, but some versions of 'qemu-kvm' will use KVM
350 * regardless (even where this option appears in the help text).
351 * It is rumoured that there are versions of qemu where supplying
352 * this option when hardware virtualization is not available will
353 * cause qemu to fail, so we we have to check at least that
354 * /dev/kvm is openable. That's not reliable, since /dev/kvm
355 * might be openable by qemu but not by us (think: SELinux) in
356 * which case the user would not get hardware virtualization,
357 * although at least shouldn't fail. A giant clusterfuck with the
358 * qemu command line, again.
360 if (qemu_supports (g, "-enable-kvm") &&
361 is_openable (g, "/dev/kvm", O_RDWR))
362 add_cmdline (g, "-enable-kvm");
364 /* Newer versions of qemu (from around 2009/12) changed the
365 * behaviour of monitors so that an implicit '-monitor stdio' is
366 * assumed if we are in -nographic mode and there is no other
367 * -monitor option. Only a single stdio device is allowed, so
368 * this broke the '-serial stdio' option. There is a new flag
369 * called -nodefaults which gets rid of all this default crud, so
370 * let's use that to avoid this and any future surprises.
372 if (qemu_supports (g, "-nodefaults"))
373 add_cmdline (g, "-nodefaults");
375 add_cmdline (g, "-nographic");
377 snprintf (buf, sizeof buf, "%d", g->memsize);
378 add_cmdline (g, "-m");
379 add_cmdline (g, buf);
381 /* Force exit instead of reboot on panic */
382 add_cmdline (g, "-no-reboot");
384 /* These options recommended by KVM developers to improve reliability. */
385 if (qemu_supports (g, "-no-hpet"))
386 add_cmdline (g, "-no-hpet");
388 if (qemu_supports (g, "-rtc-td-hack"))
389 add_cmdline (g, "-rtc-td-hack");
391 /* Create the virtio serial bus. */
392 add_cmdline (g, "-device");
393 add_cmdline (g, "virtio-serial");
396 /* Use virtio-console (a variant form of virtio-serial) for the
397 * guest's serial console.
399 add_cmdline (g, "-chardev");
400 add_cmdline (g, "stdio,id=console");
401 add_cmdline (g, "-device");
402 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
404 /* When the above works ... until then: */
405 add_cmdline (g, "-serial");
406 add_cmdline (g, "stdio");
409 /* Set up virtio-serial for the communications channel. */
410 add_cmdline (g, "-chardev");
411 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
412 add_cmdline (g, buf);
413 add_cmdline (g, "-device");
414 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
416 /* Enable user networking. */
417 if (g->enable_network) {
418 add_cmdline (g, "-netdev");
419 add_cmdline (g, "user,id=usernet");
420 add_cmdline (g, "-device");
421 add_cmdline (g, NET_IF ",netdev=usernet");
424 #define LINUX_CMDLINE \
425 "panic=1 " /* force kernel to panic if daemon exits */ \
426 "console=ttyS0 " /* serial console */ \
427 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
428 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
429 "acpi=off " /* we don't need ACPI, turn it off */ \
430 "printk.time=1 " /* display timestamp before kernel messages */ \
431 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
433 /* Linux kernel command line. */
434 snprintf (buf, sizeof buf,
436 "%s " /* (selinux) */
437 "%s " /* (verbose) */
438 "TERM=%s " /* (TERM environment variable) */
440 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
441 g->verbose ? "guestfs_verbose=1" : "",
442 getenv ("TERM") ? : "linux",
443 g->append ? g->append : "");
445 add_cmdline (g, "-kernel");
446 add_cmdline (g, kernel);
447 add_cmdline (g, "-initrd");
448 add_cmdline (g, initrd);
449 add_cmdline (g, "-append");
450 add_cmdline (g, buf);
452 /* Add the ext2 appliance drive (last of all). */
454 const char *cachemode = "";
455 if (qemu_supports (g, "cache=")) {
456 if (qemu_supports (g, "unsafe"))
457 cachemode = ",cache=unsafe";
458 else if (qemu_supports (g, "writeback"))
459 cachemode = ",cache=writeback";
462 char buf2[PATH_MAX + 64];
463 add_cmdline (g, "-drive");
464 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
465 appliance, cachemode);
466 add_cmdline (g, buf2);
469 /* Finish off the command line. */
470 incr_cmdline_size (g);
471 g->cmdline[g->cmdline_size-1] = NULL;
477 /* Set up stdin, stdout. */
483 if (dup (wfd[0]) == -1) {
485 perror ("dup failed");
486 _exit (EXIT_FAILURE);
488 if (dup (rfd[1]) == -1)
496 /* Set up a new process group, so we can signal this process
497 * and all subprocesses (eg. if qemu is really a shell script).
502 setenv ("LC_ALL", "C", 1);
504 execv (g->qemu, g->cmdline); /* Run qemu. */
506 _exit (EXIT_FAILURE);
509 /* Parent (library). */
517 /* Fork the recovery process off which will kill qemu if the parent
518 * process fails to do so (eg. if the parent segfaults).
521 if (g->recovery_proc) {
524 pid_t qemu_pid = g->pid;
525 pid_t parent_pid = getppid ();
527 /* Writing to argv is hideously complicated and error prone. See:
528 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
531 /* Loop around waiting for one or both of the other processes to
532 * disappear. It's fair to say this is very hairy. The PIDs that
533 * we are looking at might be reused by another process. We are
534 * effectively polling. Is the cure worse than the disease?
537 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
538 _exit (EXIT_SUCCESS);
539 if (kill (parent_pid, 0) == -1) {
540 /* Parent's gone away, qemu still around, so kill qemu. */
542 _exit (EXIT_SUCCESS);
548 /* Don't worry, if the fork failed, this will be -1. The recovery
549 * process isn't essential.
555 /* Close the other ends of the pipe. */
559 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
560 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
561 perrorf (g, "fcntl");
565 g->fd[0] = wfd[1]; /* stdin of child */
566 g->fd[1] = rfd[0]; /* stdout of child */
568 g->fd[0] = open ("/dev/null", O_RDWR);
569 if (g->fd[0] == -1) {
570 perrorf (g, "open /dev/null");
573 g->fd[1] = dup (g->fd[0]);
574 if (g->fd[1] == -1) {
581 g->state = LAUNCHING;
583 /* Wait for qemu to start and to connect back to us via
584 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
586 r = guestfs___accept_from_daemon (g);
590 close (g->sock); /* Close the listening socket. */
591 g->sock = r; /* This is the accepted data socket. */
593 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
594 perrorf (g, "fcntl");
600 r = guestfs___recv_from_daemon (g, &size, &buf);
603 if (r == -1) return -1;
605 if (size != GUESTFS_LAUNCH_FLAG) {
606 error (g, _("guestfs_launch failed, see earlier error messages"));
611 guestfs___print_timestamped_message (g, "appliance is up");
613 /* This is possible in some really strange situations, such as
614 * guestfsd starts up OK but then qemu immediately exits. Check for
615 * it because the caller is probably expecting to be able to send
616 * commands after this function returns.
618 if (g->state != READY) {
619 error (g, _("qemu launched and contacted daemon, but state != READY"));
630 if (g->pid > 0) kill (g->pid, 9);
631 if (g->recoverypid > 0) kill (g->recoverypid, 9);
632 waitpid (g->pid, NULL, 0);
633 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
638 memset (&g->launch_t, 0, sizeof g->launch_t);
653 guestfs___tmpdir (void)
663 const char *t = getenv ("TMPDIR");
669 /* This function is used to print the qemu command line before it gets
670 * executed, when in verbose mode.
673 print_cmdline (guestfs_h *g)
678 while (g->cmdline[i]) {
679 if (g->cmdline[i][0] == '-') /* -option starts a new line */
680 fprintf (stderr, " \\\n ");
682 if (i > 0) fputc (' ', stderr);
684 /* Does it need shell quoting? This only deals with simple cases. */
685 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
687 if (needs_quote) fputc ('\'', stderr);
688 fprintf (stderr, "%s", g->cmdline[i]);
689 if (needs_quote) fputc ('\'', stderr);
693 fputc ('\n', stderr);
696 /* Compute Y - X and return the result in milliseconds.
697 * Approximately the same as this code:
698 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
701 timeval_diff (const struct timeval *x, const struct timeval *y)
705 msec = (y->tv_sec - x->tv_sec) * 1000;
706 msec += (y->tv_usec - x->tv_usec) / 1000;
711 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
719 err = vasprintf (&msg, fs, args);
724 gettimeofday (&tv, NULL);
726 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
727 timeval_diff (&g->launch_t, &tv), msg);
732 static int read_all (guestfs_h *g, FILE *fp, char **ret);
734 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
735 * 'qemu -version' so we know what options this qemu supports and
739 test_qemu (guestfs_h *g)
744 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
746 fp = popen (cmd, "r");
747 /* qemu -help should always work (qemu -version OTOH wasn't
748 * supported by qemu 0.9). If this command doesn't work then it
749 * probably indicates that the qemu binary is missing.
752 /* XXX This error is never printed, even if the qemu binary
753 * doesn't exist. Why?
756 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
760 if (read_all (g, fp, &g->qemu_help) == -1)
763 if (pclose (fp) == -1)
766 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
769 fp = popen (cmd, "r");
771 /* Intentionally ignore errors. */
772 read_all (g, fp, &g->qemu_version);
780 read_all (guestfs_h *g, FILE *fp, char **ret)
787 *ret = safe_realloc (g, *ret, n + 1);
792 *ret = safe_realloc (g, *ret, n + BUFSIZ);
794 r = fread (p, 1, BUFSIZ, fp);
803 /* Test if option is supported by qemu command line (just by grepping
806 * The first time this is used, it has to run the external qemu
807 * binary. If that fails, it returns -1.
809 * To just do the first-time run of the qemu binary, call this with
810 * option == NULL, in which case it will return -1 if there was an
814 qemu_supports (guestfs_h *g, const char *option)
817 if (test_qemu (g) == -1)
824 return strstr (g->qemu_help, option) != NULL;
827 /* Check if a file can be opened. */
829 is_openable (guestfs_h *g, const char *path, int flags)
831 int fd = open (path, flags);
841 /* You had to call this function after launch in versions <= 1.0.70,
842 * but it is now a no-op.
845 guestfs__wait_ready (guestfs_h *g)
847 if (g->state != READY) {
848 error (g, _("qemu has not been launched yet"));
856 guestfs__kill_subprocess (guestfs_h *g)
858 if (g->state == CONFIG) {
859 error (g, _("no subprocess to kill"));
864 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
866 if (g->pid > 0) kill (g->pid, SIGTERM);
867 if (g->recoverypid > 0) kill (g->recoverypid, 9);
872 /* Access current state. */
874 guestfs__is_config (guestfs_h *g)
876 return g->state == CONFIG;
880 guestfs__is_launching (guestfs_h *g)
882 return g->state == LAUNCHING;
886 guestfs__is_ready (guestfs_h *g)
888 return g->state == READY;
892 guestfs__is_busy (guestfs_h *g)
894 return g->state == BUSY;
898 guestfs__get_state (guestfs_h *g)