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);
307 guestfs__launch (guestfs_h *g)
313 struct sockaddr_un addr;
317 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
321 if (g->state != CONFIG) {
322 error (g, _("the libguestfs handle has already been launched"));
326 /* Start the clock ... */
327 gettimeofday (&g->launch_t, NULL);
329 /* Make the temporary directory. */
331 TMP_TEMPLATE_ON_STACK (dir_template);
332 g->tmpdir = safe_strdup (g, dir_template);
333 if (mkdtemp (g->tmpdir) == NULL) {
334 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
339 /* Allow anyone to read the temporary directory. The socket in this
340 * directory won't be readable but anyone can see it exists if they
341 * want. (RHBZ#610880).
343 if (chmod (g->tmpdir, 0755) == -1)
344 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
346 /* Locate and/or build the appliance. */
347 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
348 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
352 guestfs___print_timestamped_message (g, "begin testing qemu features");
354 /* Get qemu help text and version. */
355 if (qemu_supports (g, NULL) == -1)
358 /* Using virtio-serial, we need to create a local Unix domain socket
359 * for qemu to connect to.
361 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
364 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
366 perrorf (g, "socket");
370 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
371 perrorf (g, "fcntl");
375 addr.sun_family = AF_UNIX;
376 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
377 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
379 if (bind (g->sock, &addr, sizeof addr) == -1) {
384 if (listen (g->sock, 1) == -1) {
385 perrorf (g, "listen");
390 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
397 guestfs___print_timestamped_message (g, "finished testing qemu features");
411 if (r == 0) { /* Child (qemu). */
414 /* Set up the full command line. Do this in the subprocess so we
415 * don't need to worry about cleaning up.
417 g->cmdline[0] = g->qemu;
419 if (qemu_supports (g, "-nodefconfig"))
420 add_cmdline (g, "-nodefconfig");
422 /* qemu sometimes needs this option to enable hardware
423 * virtualization, but some versions of 'qemu-kvm' will use KVM
424 * regardless (even where this option appears in the help text).
425 * It is rumoured that there are versions of qemu where supplying
426 * this option when hardware virtualization is not available will
427 * cause qemu to fail, so we we have to check at least that
428 * /dev/kvm is openable. That's not reliable, since /dev/kvm
429 * might be openable by qemu but not by us (think: SELinux) in
430 * which case the user would not get hardware virtualization,
431 * although at least shouldn't fail. A giant clusterfuck with the
432 * qemu command line, again.
434 if (qemu_supports (g, "-enable-kvm") &&
435 is_openable (g, "/dev/kvm", O_RDWR))
436 add_cmdline (g, "-enable-kvm");
438 /* Newer versions of qemu (from around 2009/12) changed the
439 * behaviour of monitors so that an implicit '-monitor stdio' is
440 * assumed if we are in -nographic mode and there is no other
441 * -monitor option. Only a single stdio device is allowed, so
442 * this broke the '-serial stdio' option. There is a new flag
443 * called -nodefaults which gets rid of all this default crud, so
444 * let's use that to avoid this and any future surprises.
446 if (qemu_supports (g, "-nodefaults"))
447 add_cmdline (g, "-nodefaults");
449 add_cmdline (g, "-nographic");
451 snprintf (buf, sizeof buf, "%d", g->memsize);
452 add_cmdline (g, "-m");
453 add_cmdline (g, buf);
455 /* Force exit instead of reboot on panic */
456 add_cmdline (g, "-no-reboot");
458 /* These options recommended by KVM developers to improve reliability. */
459 if (qemu_supports (g, "-no-hpet"))
460 add_cmdline (g, "-no-hpet");
462 if (qemu_supports (g, "-rtc-td-hack"))
463 add_cmdline (g, "-rtc-td-hack");
465 /* Create the virtio serial bus. */
466 add_cmdline (g, "-device");
467 add_cmdline (g, "virtio-serial");
470 /* Use virtio-console (a variant form of virtio-serial) for the
471 * guest's serial console.
473 add_cmdline (g, "-chardev");
474 add_cmdline (g, "stdio,id=console");
475 add_cmdline (g, "-device");
476 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
478 /* When the above works ... until then: */
479 add_cmdline (g, "-serial");
480 add_cmdline (g, "stdio");
483 /* Set up virtio-serial for the communications channel. */
484 add_cmdline (g, "-chardev");
485 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
486 add_cmdline (g, buf);
487 add_cmdline (g, "-device");
488 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
490 /* Enable user networking. */
491 if (g->enable_network) {
492 add_cmdline (g, "-netdev");
493 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
494 add_cmdline (g, "-device");
495 add_cmdline (g, NET_IF ",netdev=usernet");
498 #define LINUX_CMDLINE \
499 "panic=1 " /* force kernel to panic if daemon exits */ \
500 "console=ttyS0 " /* serial console */ \
501 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
502 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
503 "acpi=off " /* we don't need ACPI, turn it off */ \
504 "printk.time=1 " /* display timestamp before kernel messages */ \
505 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
507 /* Linux kernel command line. */
508 snprintf (buf, sizeof buf,
510 "%s " /* (selinux) */
511 "%s " /* (verbose) */
512 "TERM=%s " /* (TERM environment variable) */
514 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
515 g->verbose ? "guestfs_verbose=1" : "",
516 getenv ("TERM") ? : "linux",
517 g->append ? g->append : "");
519 add_cmdline (g, "-kernel");
520 add_cmdline (g, kernel);
521 add_cmdline (g, "-initrd");
522 add_cmdline (g, initrd);
523 add_cmdline (g, "-append");
524 add_cmdline (g, buf);
526 /* Add the ext2 appliance drive (last of all). */
528 const char *cachemode = "";
529 if (qemu_supports (g, "cache=")) {
530 if (qemu_supports (g, "unsafe"))
531 cachemode = ",cache=unsafe";
532 else if (qemu_supports (g, "writeback"))
533 cachemode = ",cache=writeback";
536 char buf2[PATH_MAX + 64];
537 add_cmdline (g, "-drive");
538 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
539 appliance, cachemode);
540 add_cmdline (g, buf2);
543 /* Finish off the command line. */
544 incr_cmdline_size (g);
545 g->cmdline[g->cmdline_size-1] = NULL;
548 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
551 /* Set up stdin, stdout. */
557 if (dup (wfd[0]) == -1) {
559 perror ("dup failed");
560 _exit (EXIT_FAILURE);
562 if (dup (rfd[1]) == -1)
570 /* Set up a new process group, so we can signal this process
571 * and all subprocesses (eg. if qemu is really a shell script).
576 setenv ("LC_ALL", "C", 1);
578 execv (g->qemu, g->cmdline); /* Run qemu. */
580 _exit (EXIT_FAILURE);
583 /* Parent (library). */
593 /* Fork the recovery process off which will kill qemu if the parent
594 * process fails to do so (eg. if the parent segfaults).
597 if (g->recovery_proc) {
600 pid_t qemu_pid = g->pid;
601 pid_t parent_pid = getppid ();
603 /* Writing to argv is hideously complicated and error prone. See:
604 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
607 /* Loop around waiting for one or both of the other processes to
608 * disappear. It's fair to say this is very hairy. The PIDs that
609 * we are looking at might be reused by another process. We are
610 * effectively polling. Is the cure worse than the disease?
613 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
614 _exit (EXIT_SUCCESS);
615 if (kill (parent_pid, 0) == -1) {
616 /* Parent's gone away, qemu still around, so kill qemu. */
618 _exit (EXIT_SUCCESS);
624 /* Don't worry, if the fork failed, this will be -1. The recovery
625 * process isn't essential.
631 /* Close the other ends of the pipe. */
635 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
636 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
637 perrorf (g, "fcntl");
641 g->fd[0] = wfd[1]; /* stdin of child */
642 g->fd[1] = rfd[0]; /* stdout of child */
644 g->fd[0] = open ("/dev/null", O_RDWR);
645 if (g->fd[0] == -1) {
646 perrorf (g, "open /dev/null");
649 g->fd[1] = dup (g->fd[0]);
650 if (g->fd[1] == -1) {
657 g->state = LAUNCHING;
659 /* Wait for qemu to start and to connect back to us via
660 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
662 r = guestfs___accept_from_daemon (g);
666 close (g->sock); /* Close the listening socket. */
667 g->sock = r; /* This is the accepted data socket. */
669 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
670 perrorf (g, "fcntl");
676 r = guestfs___recv_from_daemon (g, &size, &buf);
679 if (r == -1) return -1;
681 if (size != GUESTFS_LAUNCH_FLAG) {
682 error (g, _("guestfs_launch failed, see earlier error messages"));
687 guestfs___print_timestamped_message (g, "appliance is up");
689 /* This is possible in some really strange situations, such as
690 * guestfsd starts up OK but then qemu immediately exits. Check for
691 * it because the caller is probably expecting to be able to send
692 * commands after this function returns.
694 if (g->state != READY) {
695 error (g, _("qemu launched and contacted daemon, but state != READY"));
706 if (g->pid > 0) kill (g->pid, 9);
707 if (g->recoverypid > 0) kill (g->recoverypid, 9);
708 waitpid (g->pid, NULL, 0);
709 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
714 memset (&g->launch_t, 0, sizeof g->launch_t);
728 /* Return the location of the tmpdir (eg. "/tmp") and allow users
729 * to override it at runtime using $TMPDIR.
732 guestfs_tmpdir (void)
742 const char *t = getenv ("TMPDIR");
748 /* Compute Y - X and return the result in milliseconds.
749 * Approximately the same as this code:
750 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
753 timeval_diff (const struct timeval *x, const struct timeval *y)
757 msec = (y->tv_sec - x->tv_sec) * 1000;
758 msec += (y->tv_usec - x->tv_usec) / 1000;
763 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
769 gettimeofday (&tv, NULL);
770 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
773 if (argv[i][0] == '-') /* -option starts a new line */
774 fprintf (stderr, " \\\n ");
776 if (i > 0) fputc (' ', stderr);
778 /* Does it need shell quoting? This only deals with simple cases. */
779 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
781 if (needs_quote) fputc ('\'', stderr);
782 fprintf (stderr, "%s", argv[i]);
783 if (needs_quote) fputc ('\'', stderr);
787 fputc ('\n', stderr);
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)