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>
64 #include "glthread/lock.h"
65 #include "ignore-value.h"
68 #include "guestfs-internal.h"
69 #include "guestfs-internal-actions.h"
70 #include "guestfs_protocol.h"
72 static int qemu_supports (guestfs_h *g, const char *option);
74 /* Add a string to the current command line. */
76 incr_cmdline_size (guestfs_h *g)
78 if (g->cmdline == NULL) {
79 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
81 g->cmdline = safe_malloc (g, sizeof (char *));
86 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
90 add_cmdline (guestfs_h *g, const char *str)
92 if (g->state != CONFIG) {
94 _("command line cannot be altered after qemu subprocess launched"));
98 incr_cmdline_size (g);
99 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
104 guestfs__config (guestfs_h *g,
105 const char *qemu_param, const char *qemu_value)
107 if (qemu_param[0] != '-') {
108 error (g, _("guestfs_config: parameter must begin with '-' character"));
112 /* A bit fascist, but the user will probably break the extra
113 * parameters that we add if they try to set any of these.
115 if (STREQ (qemu_param, "-kernel") ||
116 STREQ (qemu_param, "-initrd") ||
117 STREQ (qemu_param, "-nographic") ||
118 STREQ (qemu_param, "-serial") ||
119 STREQ (qemu_param, "-full-screen") ||
120 STREQ (qemu_param, "-std-vga") ||
121 STREQ (qemu_param, "-vnc")) {
122 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
126 if (add_cmdline (g, qemu_param) != 0) return -1;
128 if (qemu_value != NULL) {
129 if (add_cmdline (g, qemu_value) != 0) return -1;
136 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
137 const char *drive_if)
139 size_t len = strlen (filename) + 64;
142 if (strchr (filename, ',') != NULL) {
143 error (g, _("filename cannot contain ',' (comma) character"));
147 /* cache=off improves reliability in the event of a host crash.
149 * However this option causes qemu to try to open the file with
150 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
151 * So we check if we can open the file with or without O_DIRECT,
152 * and use cache=off (or not) accordingly.
154 * This test also checks for the presence of the file, which
155 * is a documented semantic of this interface.
157 int fd = open (filename, O_RDONLY|O_DIRECT);
160 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
162 fd = open (filename, O_RDONLY);
165 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
167 perrorf (g, "%s", filename);
172 return guestfs__config (g, "-drive", buf);
176 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
177 const char *drive_if)
179 if (strchr (filename, ',') != NULL) {
180 error (g, _("filename cannot contain ',' (comma) character"));
184 if (access (filename, F_OK) == -1) {
185 perrorf (g, "%s", filename);
189 size_t len = strlen (filename) + 64;
192 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
194 return guestfs__config (g, "-drive", buf);
198 guestfs__add_drive (guestfs_h *g, const char *filename)
200 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
204 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
206 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
210 guestfs__add_cdrom (guestfs_h *g, const char *filename)
212 if (strchr (filename, ',') != NULL) {
213 error (g, _("filename cannot contain ',' (comma) character"));
217 if (access (filename, F_OK) == -1) {
218 perrorf (g, "%s", filename);
222 return guestfs__config (g, "-cdrom", filename);
225 static int is_openable (guestfs_h *g, const char *path, int flags);
226 static void print_cmdline (guestfs_h *g);
229 guestfs__launch (guestfs_h *g)
235 struct sockaddr_un addr;
239 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
243 if (g->state != CONFIG) {
244 error (g, _("the libguestfs handle has already been launched"));
248 /* Start the clock ... */
249 gettimeofday (&g->launch_t, NULL);
251 /* Make the temporary directory. */
253 const char *tmpdir = guestfs___tmpdir ();
254 char dir_template[strlen (tmpdir) + 32];
255 sprintf (dir_template, "%s/libguestfsXXXXXX", tmpdir);
257 g->tmpdir = safe_strdup (g, dir_template);
258 if (mkdtemp (g->tmpdir) == NULL) {
259 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
264 /* Allow anyone to read the temporary directory. The socket in this
265 * directory won't be readable but anyone can see it exists if they
266 * want. (RHBZ#610880).
268 if (chmod (g->tmpdir, 0755) == -1)
269 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
271 /* Locate and/or build the appliance. */
272 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
273 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
277 guestfs___print_timestamped_message (g, "begin testing qemu features");
279 /* Get qemu help text and version. */
280 if (qemu_supports (g, NULL) == -1)
283 /* Using virtio-serial, we need to create a local Unix domain socket
284 * for qemu to connect to.
286 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
289 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
291 perrorf (g, "socket");
295 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
296 perrorf (g, "fcntl");
300 addr.sun_family = AF_UNIX;
301 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
302 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
304 if (bind (g->sock, &addr, sizeof addr) == -1) {
309 if (listen (g->sock, 1) == -1) {
310 perrorf (g, "listen");
315 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
322 guestfs___print_timestamped_message (g, "finished testing qemu features");
336 if (r == 0) { /* Child (qemu). */
339 /* Set up the full command line. Do this in the subprocess so we
340 * don't need to worry about cleaning up.
342 g->cmdline[0] = g->qemu;
344 if (qemu_supports (g, "-nodefconfig"))
345 add_cmdline (g, "-nodefconfig");
347 /* qemu sometimes needs this option to enable hardware
348 * virtualization, but some versions of 'qemu-kvm' will use KVM
349 * regardless (even where this option appears in the help text).
350 * It is rumoured that there are versions of qemu where supplying
351 * this option when hardware virtualization is not available will
352 * cause qemu to fail, so we we have to check at least that
353 * /dev/kvm is openable. That's not reliable, since /dev/kvm
354 * might be openable by qemu but not by us (think: SELinux) in
355 * which case the user would not get hardware virtualization,
356 * although at least shouldn't fail. A giant clusterfuck with the
357 * qemu command line, again.
359 if (qemu_supports (g, "-enable-kvm") &&
360 is_openable (g, "/dev/kvm", O_RDWR))
361 add_cmdline (g, "-enable-kvm");
363 /* Newer versions of qemu (from around 2009/12) changed the
364 * behaviour of monitors so that an implicit '-monitor stdio' is
365 * assumed if we are in -nographic mode and there is no other
366 * -monitor option. Only a single stdio device is allowed, so
367 * this broke the '-serial stdio' option. There is a new flag
368 * called -nodefaults which gets rid of all this default crud, so
369 * let's use that to avoid this and any future surprises.
371 if (qemu_supports (g, "-nodefaults"))
372 add_cmdline (g, "-nodefaults");
374 add_cmdline (g, "-nographic");
376 snprintf (buf, sizeof buf, "%d", g->memsize);
377 add_cmdline (g, "-m");
378 add_cmdline (g, buf);
380 /* Force exit instead of reboot on panic */
381 add_cmdline (g, "-no-reboot");
383 /* These options recommended by KVM developers to improve reliability. */
384 if (qemu_supports (g, "-no-hpet"))
385 add_cmdline (g, "-no-hpet");
387 if (qemu_supports (g, "-rtc-td-hack"))
388 add_cmdline (g, "-rtc-td-hack");
390 /* Create the virtio serial bus. */
391 add_cmdline (g, "-device");
392 add_cmdline (g, "virtio-serial");
395 /* Use virtio-console (a variant form of virtio-serial) for the
396 * guest's serial console.
398 add_cmdline (g, "-chardev");
399 add_cmdline (g, "stdio,id=console");
400 add_cmdline (g, "-device");
401 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
403 /* When the above works ... until then: */
404 add_cmdline (g, "-serial");
405 add_cmdline (g, "stdio");
408 /* Set up virtio-serial for the communications channel. */
409 add_cmdline (g, "-chardev");
410 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
411 add_cmdline (g, buf);
412 add_cmdline (g, "-device");
413 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
415 /* Enable user networking. */
416 if (g->enable_network) {
417 add_cmdline (g, "-netdev");
418 add_cmdline (g, "user,id=usernet");
419 add_cmdline (g, "-device");
420 add_cmdline (g, NET_IF ",netdev=usernet");
423 #define LINUX_CMDLINE \
424 "panic=1 " /* force kernel to panic if daemon exits */ \
425 "console=ttyS0 " /* serial console */ \
426 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
427 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
428 "acpi=off " /* we don't need ACPI, turn it off */ \
429 "printk.time=1 " /* display timestamp before kernel messages */ \
430 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
432 /* Linux kernel command line. */
433 snprintf (buf, sizeof buf,
435 "%s " /* (selinux) */
436 "%s " /* (verbose) */
437 "TERM=%s " /* (TERM environment variable) */
439 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
440 g->verbose ? "guestfs_verbose=1" : "",
441 getenv ("TERM") ? : "linux",
442 g->append ? g->append : "");
444 add_cmdline (g, "-kernel");
445 add_cmdline (g, kernel);
446 add_cmdline (g, "-initrd");
447 add_cmdline (g, initrd);
448 add_cmdline (g, "-append");
449 add_cmdline (g, buf);
451 /* Add the ext2 appliance drive (last of all). */
453 const char *cachemode = "";
454 if (qemu_supports (g, "cache=")) {
455 if (qemu_supports (g, "unsafe"))
456 cachemode = ",cache=unsafe";
457 else if (qemu_supports (g, "writeback"))
458 cachemode = ",cache=writeback";
461 char buf2[PATH_MAX + 64];
462 add_cmdline (g, "-drive");
463 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
464 appliance, cachemode);
465 add_cmdline (g, buf2);
468 /* Finish off the command line. */
469 incr_cmdline_size (g);
470 g->cmdline[g->cmdline_size-1] = NULL;
476 /* Set up stdin, stdout. */
482 if (dup (wfd[0]) == -1) {
484 perror ("dup failed");
485 _exit (EXIT_FAILURE);
487 if (dup (rfd[1]) == -1)
495 /* Set up a new process group, so we can signal this process
496 * and all subprocesses (eg. if qemu is really a shell script).
501 setenv ("LC_ALL", "C", 1);
503 execv (g->qemu, g->cmdline); /* Run qemu. */
505 _exit (EXIT_FAILURE);
508 /* Parent (library). */
516 /* Fork the recovery process off which will kill qemu if the parent
517 * process fails to do so (eg. if the parent segfaults).
520 if (g->recovery_proc) {
523 pid_t qemu_pid = g->pid;
524 pid_t parent_pid = getppid ();
526 /* Writing to argv is hideously complicated and error prone. See:
527 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
530 /* Loop around waiting for one or both of the other processes to
531 * disappear. It's fair to say this is very hairy. The PIDs that
532 * we are looking at might be reused by another process. We are
533 * effectively polling. Is the cure worse than the disease?
536 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
537 _exit (EXIT_SUCCESS);
538 if (kill (parent_pid, 0) == -1) {
539 /* Parent's gone away, qemu still around, so kill qemu. */
541 _exit (EXIT_SUCCESS);
547 /* Don't worry, if the fork failed, this will be -1. The recovery
548 * process isn't essential.
554 /* Close the other ends of the pipe. */
558 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
559 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
560 perrorf (g, "fcntl");
564 g->fd[0] = wfd[1]; /* stdin of child */
565 g->fd[1] = rfd[0]; /* stdout of child */
567 g->fd[0] = open ("/dev/null", O_RDWR);
568 if (g->fd[0] == -1) {
569 perrorf (g, "open /dev/null");
572 g->fd[1] = dup (g->fd[0]);
573 if (g->fd[1] == -1) {
580 g->state = LAUNCHING;
582 /* Wait for qemu to start and to connect back to us via
583 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
585 r = guestfs___accept_from_daemon (g);
589 close (g->sock); /* Close the listening socket. */
590 g->sock = r; /* This is the accepted data socket. */
592 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
593 perrorf (g, "fcntl");
599 r = guestfs___recv_from_daemon (g, &size, &buf);
602 if (r == -1) return -1;
604 if (size != GUESTFS_LAUNCH_FLAG) {
605 error (g, _("guestfs_launch failed, see earlier error messages"));
610 guestfs___print_timestamped_message (g, "appliance is up");
612 /* This is possible in some really strange situations, such as
613 * guestfsd starts up OK but then qemu immediately exits. Check for
614 * it because the caller is probably expecting to be able to send
615 * commands after this function returns.
617 if (g->state != READY) {
618 error (g, _("qemu launched and contacted daemon, but state != READY"));
629 if (g->pid > 0) kill (g->pid, 9);
630 if (g->recoverypid > 0) kill (g->recoverypid, 9);
631 waitpid (g->pid, NULL, 0);
632 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
637 memset (&g->launch_t, 0, sizeof g->launch_t);
652 guestfs___tmpdir (void)
662 const char *t = getenv ("TMPDIR");
668 /* This function is used to print the qemu command line before it gets
669 * executed, when in verbose mode.
672 print_cmdline (guestfs_h *g)
677 while (g->cmdline[i]) {
678 if (g->cmdline[i][0] == '-') /* -option starts a new line */
679 fprintf (stderr, " \\\n ");
681 if (i > 0) fputc (' ', stderr);
683 /* Does it need shell quoting? This only deals with simple cases. */
684 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
686 if (needs_quote) fputc ('\'', stderr);
687 fprintf (stderr, "%s", g->cmdline[i]);
688 if (needs_quote) fputc ('\'', stderr);
692 fputc ('\n', stderr);
695 /* Compute Y - X and return the result in milliseconds.
696 * Approximately the same as this code:
697 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
700 timeval_diff (const struct timeval *x, const struct timeval *y)
704 msec = (y->tv_sec - x->tv_sec) * 1000;
705 msec += (y->tv_usec - x->tv_usec) / 1000;
710 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
718 err = vasprintf (&msg, fs, args);
723 gettimeofday (&tv, NULL);
725 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
726 timeval_diff (&g->launch_t, &tv), msg);
731 static int read_all (guestfs_h *g, FILE *fp, char **ret);
733 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
734 * 'qemu -version' so we know what options this qemu supports and
738 test_qemu (guestfs_h *g)
743 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
745 fp = popen (cmd, "r");
746 /* qemu -help should always work (qemu -version OTOH wasn't
747 * supported by qemu 0.9). If this command doesn't work then it
748 * probably indicates that the qemu binary is missing.
751 /* XXX This error is never printed, even if the qemu binary
752 * doesn't exist. Why?
755 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
759 if (read_all (g, fp, &g->qemu_help) == -1)
762 if (pclose (fp) == -1)
765 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
768 fp = popen (cmd, "r");
770 /* Intentionally ignore errors. */
771 read_all (g, fp, &g->qemu_version);
779 read_all (guestfs_h *g, FILE *fp, char **ret)
786 *ret = safe_realloc (g, *ret, n + 1);
791 *ret = safe_realloc (g, *ret, n + BUFSIZ);
793 r = fread (p, 1, BUFSIZ, fp);
802 /* Test if option is supported by qemu command line (just by grepping
805 * The first time this is used, it has to run the external qemu
806 * binary. If that fails, it returns -1.
808 * To just do the first-time run of the qemu binary, call this with
809 * option == NULL, in which case it will return -1 if there was an
813 qemu_supports (guestfs_h *g, const char *option)
816 if (test_qemu (g) == -1)
823 return strstr (g->qemu_help, option) != NULL;
826 /* Check if a file can be opened. */
828 is_openable (guestfs_h *g, const char *path, int flags)
830 int fd = open (path, flags);
840 /* You had to call this function after launch in versions <= 1.0.70,
841 * but it is now a no-op.
844 guestfs__wait_ready (guestfs_h *g)
846 if (g->state != READY) {
847 error (g, _("qemu has not been launched yet"));
855 guestfs__kill_subprocess (guestfs_h *g)
857 if (g->state == CONFIG) {
858 error (g, _("no subprocess to kill"));
863 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
865 if (g->pid > 0) kill (g->pid, SIGTERM);
866 if (g->recoverypid > 0) kill (g->recoverypid, 9);
871 /* Access current state. */
873 guestfs__is_config (guestfs_h *g)
875 return g->state == CONFIG;
879 guestfs__is_launching (guestfs_h *g)
881 return g->state == LAUNCHING;
885 guestfs__is_ready (guestfs_h *g)
887 return g->state == READY;
891 guestfs__is_busy (guestfs_h *g)
893 return g->state == BUSY;
897 guestfs__get_state (guestfs_h *g)