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"
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;
135 /* cache=off improves reliability in the event of a host crash.
137 * However this option causes qemu to try to open the file with
138 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
139 * So we check if we can open the file with or without O_DIRECT,
140 * and use cache=off (or not) accordingly.
143 test_cache_off (guestfs_h *g, const char *filename)
145 int fd = open (filename, O_RDONLY|O_DIRECT);
151 fd = open (filename, O_RDONLY);
157 perrorf (g, "%s", filename);
161 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
163 valid_format_iface (const char *str)
165 size_t len = strlen (str);
173 if (c != '-' && c != '_' && !c_isalnum (c))
180 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
181 const struct guestfs_add_drive_opts_argv *optargs)
187 if (strchr (filename, ',') != NULL) {
188 error (g, _("filename cannot contain ',' (comma) character"));
192 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
193 ? optargs->readonly : 0;
194 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
195 ? optargs->format : NULL;
196 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
197 ? optargs->iface : DRIVE_IF;
199 if (format && !valid_format_iface (format)) {
200 error (g, _("%s parameter is empty or contains disallowed characters"),
204 if (!valid_format_iface (iface)) {
205 error (g, _("%s parameter is empty or contains disallowed characters"),
210 /* For writable files, see if we can use cache=off. This also
211 * checks for the existence of the file. For readonly we have
212 * to do the check explicitly.
214 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
215 if (use_cache_off == -1)
219 if (access (filename, F_OK) == -1) {
220 perrorf (g, "%s", filename);
225 /* Construct the final -drive parameter. */
226 size_t len = 64 + strlen (filename) + strlen (iface);
227 if (format) len += strlen (format);
230 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
232 readonly ? ",snapshot=on" : "",
233 use_cache_off ? ",cache=off" : "",
234 format ? ",format=" : "",
235 format ? format : "",
238 return guestfs__config (g, "-drive", buf);
242 guestfs__add_drive (guestfs_h *g, const char *filename)
244 struct guestfs_add_drive_opts_argv optargs = {
248 return guestfs__add_drive_opts (g, filename, &optargs);
252 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
254 struct guestfs_add_drive_opts_argv optargs = {
255 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
259 return guestfs__add_drive_opts (g, filename, &optargs);
263 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
266 struct guestfs_add_drive_opts_argv optargs = {
267 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
271 return guestfs__add_drive_opts (g, filename, &optargs);
275 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
278 struct guestfs_add_drive_opts_argv optargs = {
279 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
280 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
285 return guestfs__add_drive_opts (g, filename, &optargs);
289 guestfs__add_cdrom (guestfs_h *g, const char *filename)
291 if (strchr (filename, ',') != NULL) {
292 error (g, _("filename cannot contain ',' (comma) character"));
296 if (access (filename, F_OK) == -1) {
297 perrorf (g, "%s", filename);
301 return guestfs__config (g, "-cdrom", filename);
304 static int is_openable (guestfs_h *g, const char *path, int flags);
305 static void print_cmdline (guestfs_h *g);
308 guestfs__launch (guestfs_h *g)
314 struct sockaddr_un addr;
318 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
322 if (g->state != CONFIG) {
323 error (g, _("the libguestfs handle has already been launched"));
327 /* Start the clock ... */
328 gettimeofday (&g->launch_t, NULL);
330 /* Make the temporary directory. */
332 TMP_TEMPLATE_ON_STACK (dir_template);
333 g->tmpdir = safe_strdup (g, dir_template);
334 if (mkdtemp (g->tmpdir) == NULL) {
335 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
340 /* Allow anyone to read the temporary directory. The socket in this
341 * directory won't be readable but anyone can see it exists if they
342 * want. (RHBZ#610880).
344 if (chmod (g->tmpdir, 0755) == -1)
345 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
347 /* Locate and/or build the appliance. */
348 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
349 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
353 guestfs___print_timestamped_message (g, "begin testing qemu features");
355 /* Get qemu help text and version. */
356 if (qemu_supports (g, NULL) == -1)
359 /* Using virtio-serial, we need to create a local Unix domain socket
360 * for qemu to connect to.
362 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
365 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
367 perrorf (g, "socket");
371 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
372 perrorf (g, "fcntl");
376 addr.sun_family = AF_UNIX;
377 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
378 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
380 if (bind (g->sock, &addr, sizeof addr) == -1) {
385 if (listen (g->sock, 1) == -1) {
386 perrorf (g, "listen");
391 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
398 guestfs___print_timestamped_message (g, "finished testing qemu features");
412 if (r == 0) { /* Child (qemu). */
415 /* Set up the full command line. Do this in the subprocess so we
416 * don't need to worry about cleaning up.
418 g->cmdline[0] = g->qemu;
420 if (qemu_supports (g, "-nodefconfig"))
421 add_cmdline (g, "-nodefconfig");
423 /* qemu sometimes needs this option to enable hardware
424 * virtualization, but some versions of 'qemu-kvm' will use KVM
425 * regardless (even where this option appears in the help text).
426 * It is rumoured that there are versions of qemu where supplying
427 * this option when hardware virtualization is not available will
428 * cause qemu to fail, so we we have to check at least that
429 * /dev/kvm is openable. That's not reliable, since /dev/kvm
430 * might be openable by qemu but not by us (think: SELinux) in
431 * which case the user would not get hardware virtualization,
432 * although at least shouldn't fail. A giant clusterfuck with the
433 * qemu command line, again.
435 if (qemu_supports (g, "-enable-kvm") &&
436 is_openable (g, "/dev/kvm", O_RDWR))
437 add_cmdline (g, "-enable-kvm");
439 /* Newer versions of qemu (from around 2009/12) changed the
440 * behaviour of monitors so that an implicit '-monitor stdio' is
441 * assumed if we are in -nographic mode and there is no other
442 * -monitor option. Only a single stdio device is allowed, so
443 * this broke the '-serial stdio' option. There is a new flag
444 * called -nodefaults which gets rid of all this default crud, so
445 * let's use that to avoid this and any future surprises.
447 if (qemu_supports (g, "-nodefaults"))
448 add_cmdline (g, "-nodefaults");
450 add_cmdline (g, "-nographic");
452 snprintf (buf, sizeof buf, "%d", g->memsize);
453 add_cmdline (g, "-m");
454 add_cmdline (g, buf);
456 /* Force exit instead of reboot on panic */
457 add_cmdline (g, "-no-reboot");
459 /* These options recommended by KVM developers to improve reliability. */
460 if (qemu_supports (g, "-no-hpet"))
461 add_cmdline (g, "-no-hpet");
463 if (qemu_supports (g, "-rtc-td-hack"))
464 add_cmdline (g, "-rtc-td-hack");
466 /* Create the virtio serial bus. */
467 add_cmdline (g, "-device");
468 add_cmdline (g, "virtio-serial");
471 /* Use virtio-console (a variant form of virtio-serial) for the
472 * guest's serial console.
474 add_cmdline (g, "-chardev");
475 add_cmdline (g, "stdio,id=console");
476 add_cmdline (g, "-device");
477 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
479 /* When the above works ... until then: */
480 add_cmdline (g, "-serial");
481 add_cmdline (g, "stdio");
484 /* Set up virtio-serial for the communications channel. */
485 add_cmdline (g, "-chardev");
486 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
487 add_cmdline (g, buf);
488 add_cmdline (g, "-device");
489 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
491 /* Enable user networking. */
492 if (g->enable_network) {
493 add_cmdline (g, "-netdev");
494 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
495 add_cmdline (g, "-device");
496 add_cmdline (g, NET_IF ",netdev=usernet");
499 #define LINUX_CMDLINE \
500 "panic=1 " /* force kernel to panic if daemon exits */ \
501 "console=ttyS0 " /* serial console */ \
502 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
503 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
504 "acpi=off " /* we don't need ACPI, turn it off */ \
505 "printk.time=1 " /* display timestamp before kernel messages */ \
506 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
508 /* Linux kernel command line. */
509 snprintf (buf, sizeof buf,
511 "%s " /* (selinux) */
512 "%s " /* (verbose) */
513 "TERM=%s " /* (TERM environment variable) */
515 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
516 g->verbose ? "guestfs_verbose=1" : "",
517 getenv ("TERM") ? : "linux",
518 g->append ? g->append : "");
520 add_cmdline (g, "-kernel");
521 add_cmdline (g, kernel);
522 add_cmdline (g, "-initrd");
523 add_cmdline (g, initrd);
524 add_cmdline (g, "-append");
525 add_cmdline (g, buf);
527 /* Add the ext2 appliance drive (last of all). */
529 const char *cachemode = "";
530 if (qemu_supports (g, "cache=")) {
531 if (qemu_supports (g, "unsafe"))
532 cachemode = ",cache=unsafe";
533 else if (qemu_supports (g, "writeback"))
534 cachemode = ",cache=writeback";
537 char buf2[PATH_MAX + 64];
538 add_cmdline (g, "-drive");
539 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
540 appliance, cachemode);
541 add_cmdline (g, buf2);
544 /* Finish off the command line. */
545 incr_cmdline_size (g);
546 g->cmdline[g->cmdline_size-1] = NULL;
552 /* Set up stdin, stdout. */
558 if (dup (wfd[0]) == -1) {
560 perror ("dup failed");
561 _exit (EXIT_FAILURE);
563 if (dup (rfd[1]) == -1)
571 /* Set up a new process group, so we can signal this process
572 * and all subprocesses (eg. if qemu is really a shell script).
577 setenv ("LC_ALL", "C", 1);
579 execv (g->qemu, g->cmdline); /* Run qemu. */
581 _exit (EXIT_FAILURE);
584 /* Parent (library). */
594 /* Fork the recovery process off which will kill qemu if the parent
595 * process fails to do so (eg. if the parent segfaults).
598 if (g->recovery_proc) {
601 pid_t qemu_pid = g->pid;
602 pid_t parent_pid = getppid ();
604 /* Writing to argv is hideously complicated and error prone. See:
605 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
608 /* Loop around waiting for one or both of the other processes to
609 * disappear. It's fair to say this is very hairy. The PIDs that
610 * we are looking at might be reused by another process. We are
611 * effectively polling. Is the cure worse than the disease?
614 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
615 _exit (EXIT_SUCCESS);
616 if (kill (parent_pid, 0) == -1) {
617 /* Parent's gone away, qemu still around, so kill qemu. */
619 _exit (EXIT_SUCCESS);
625 /* Don't worry, if the fork failed, this will be -1. The recovery
626 * process isn't essential.
632 /* Close the other ends of the pipe. */
636 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
637 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
638 perrorf (g, "fcntl");
642 g->fd[0] = wfd[1]; /* stdin of child */
643 g->fd[1] = rfd[0]; /* stdout of child */
645 g->fd[0] = open ("/dev/null", O_RDWR);
646 if (g->fd[0] == -1) {
647 perrorf (g, "open /dev/null");
650 g->fd[1] = dup (g->fd[0]);
651 if (g->fd[1] == -1) {
658 g->state = LAUNCHING;
660 /* Wait for qemu to start and to connect back to us via
661 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
663 r = guestfs___accept_from_daemon (g);
667 close (g->sock); /* Close the listening socket. */
668 g->sock = r; /* This is the accepted data socket. */
670 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
671 perrorf (g, "fcntl");
677 r = guestfs___recv_from_daemon (g, &size, &buf);
680 if (r == -1) return -1;
682 if (size != GUESTFS_LAUNCH_FLAG) {
683 error (g, _("guestfs_launch failed, see earlier error messages"));
688 guestfs___print_timestamped_message (g, "appliance is up");
690 /* This is possible in some really strange situations, such as
691 * guestfsd starts up OK but then qemu immediately exits. Check for
692 * it because the caller is probably expecting to be able to send
693 * commands after this function returns.
695 if (g->state != READY) {
696 error (g, _("qemu launched and contacted daemon, but state != READY"));
707 if (g->pid > 0) kill (g->pid, 9);
708 if (g->recoverypid > 0) kill (g->recoverypid, 9);
709 waitpid (g->pid, NULL, 0);
710 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
715 memset (&g->launch_t, 0, sizeof g->launch_t);
729 /* Return the location of the tmpdir (eg. "/tmp") and allow users
730 * to override it at runtime using $TMPDIR.
733 guestfs_tmpdir (void)
743 const char *t = getenv ("TMPDIR");
749 /* This function is used to print the qemu command line before it gets
750 * executed, when in verbose mode.
753 print_cmdline (guestfs_h *g)
758 while (g->cmdline[i]) {
759 if (g->cmdline[i][0] == '-') /* -option starts a new line */
760 fprintf (stderr, " \\\n ");
762 if (i > 0) fputc (' ', stderr);
764 /* Does it need shell quoting? This only deals with simple cases. */
765 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
767 if (needs_quote) fputc ('\'', stderr);
768 fprintf (stderr, "%s", g->cmdline[i]);
769 if (needs_quote) fputc ('\'', stderr);
773 fputc ('\n', stderr);
776 /* Compute Y - X and return the result in milliseconds.
777 * Approximately the same as this code:
778 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
781 timeval_diff (const struct timeval *x, const struct timeval *y)
785 msec = (y->tv_sec - x->tv_sec) * 1000;
786 msec += (y->tv_usec - x->tv_usec) / 1000;
791 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
799 err = vasprintf (&msg, fs, args);
804 gettimeofday (&tv, NULL);
806 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
807 timeval_diff (&g->launch_t, &tv), msg);
812 static int read_all (guestfs_h *g, FILE *fp, char **ret);
814 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
815 * 'qemu -version' so we know what options this qemu supports and
819 test_qemu (guestfs_h *g)
824 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
826 fp = popen (cmd, "r");
827 /* qemu -help should always work (qemu -version OTOH wasn't
828 * supported by qemu 0.9). If this command doesn't work then it
829 * probably indicates that the qemu binary is missing.
832 /* XXX This error is never printed, even if the qemu binary
833 * doesn't exist. Why?
836 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
840 if (read_all (g, fp, &g->qemu_help) == -1)
843 if (pclose (fp) == -1)
846 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
849 fp = popen (cmd, "r");
851 /* Intentionally ignore errors. */
852 read_all (g, fp, &g->qemu_version);
860 read_all (guestfs_h *g, FILE *fp, char **ret)
867 *ret = safe_realloc (g, *ret, n + 1);
872 *ret = safe_realloc (g, *ret, n + BUFSIZ);
874 r = fread (p, 1, BUFSIZ, fp);
883 /* Test if option is supported by qemu command line (just by grepping
886 * The first time this is used, it has to run the external qemu
887 * binary. If that fails, it returns -1.
889 * To just do the first-time run of the qemu binary, call this with
890 * option == NULL, in which case it will return -1 if there was an
894 qemu_supports (guestfs_h *g, const char *option)
897 if (test_qemu (g) == -1)
904 return strstr (g->qemu_help, option) != NULL;
907 /* Check if a file can be opened. */
909 is_openable (guestfs_h *g, const char *path, int flags)
911 int fd = open (path, flags);
921 /* You had to call this function after launch in versions <= 1.0.70,
922 * but it is now a no-op.
925 guestfs__wait_ready (guestfs_h *g)
927 if (g->state != READY) {
928 error (g, _("qemu has not been launched yet"));
936 guestfs__kill_subprocess (guestfs_h *g)
938 if (g->state == CONFIG) {
939 error (g, _("no subprocess to kill"));
944 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
946 if (g->pid > 0) kill (g->pid, SIGTERM);
947 if (g->recoverypid > 0) kill (g->recoverypid, 9);
952 /* Access current state. */
954 guestfs__is_config (guestfs_h *g)
956 return g->state == CONFIG;
960 guestfs__is_launching (guestfs_h *g)
962 return g->state == LAUNCHING;
966 guestfs__is_ready (guestfs_h *g)
968 return g->state == READY;
972 guestfs__is_busy (guestfs_h *g)
974 return g->state == BUSY;
978 guestfs__get_state (guestfs_h *g)