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;
123 /* Internal command to return the command line. */
125 guestfs__debug_cmdline (guestfs_h *g)
130 if (g->cmdline == NULL) {
131 r = safe_malloc (g, sizeof (char *) * 1);
136 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
137 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
139 for (i = 1; i < g->cmdline_size; ++i)
140 r[i] = safe_strdup (g, g->cmdline[i]);
142 r[g->cmdline_size] = NULL;
144 return r; /* caller frees */
148 guestfs__config (guestfs_h *g,
149 const char *qemu_param, const char *qemu_value)
151 if (qemu_param[0] != '-') {
152 error (g, _("guestfs_config: parameter must begin with '-' character"));
156 /* A bit fascist, but the user will probably break the extra
157 * parameters that we add if they try to set any of these.
159 if (STREQ (qemu_param, "-kernel") ||
160 STREQ (qemu_param, "-initrd") ||
161 STREQ (qemu_param, "-nographic") ||
162 STREQ (qemu_param, "-serial") ||
163 STREQ (qemu_param, "-full-screen") ||
164 STREQ (qemu_param, "-std-vga") ||
165 STREQ (qemu_param, "-vnc")) {
166 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
170 if (add_cmdline (g, qemu_param) != 0) return -1;
172 if (qemu_value != NULL) {
173 if (add_cmdline (g, qemu_value) != 0) return -1;
179 /* cache=off improves reliability in the event of a host crash.
181 * However this option causes qemu to try to open the file with
182 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
183 * So we check if we can open the file with or without O_DIRECT,
184 * and use cache=off (or not) accordingly.
187 test_cache_off (guestfs_h *g, const char *filename)
189 int fd = open (filename, O_RDONLY|O_DIRECT);
195 fd = open (filename, O_RDONLY);
201 perrorf (g, "%s", filename);
205 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
207 valid_format_iface (const char *str)
209 size_t len = strlen (str);
217 if (c != '-' && c != '_' && !c_isalnum (c))
224 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
225 const struct guestfs_add_drive_opts_argv *optargs)
231 if (strchr (filename, ',') != NULL) {
232 error (g, _("filename cannot contain ',' (comma) character"));
236 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
237 ? optargs->readonly : 0;
238 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
239 ? optargs->format : NULL;
240 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
241 ? optargs->iface : DRIVE_IF;
243 if (format && !valid_format_iface (format)) {
244 error (g, _("%s parameter is empty or contains disallowed characters"),
248 if (!valid_format_iface (iface)) {
249 error (g, _("%s parameter is empty or contains disallowed characters"),
254 /* For writable files, see if we can use cache=off. This also
255 * checks for the existence of the file. For readonly we have
256 * to do the check explicitly.
258 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
259 if (use_cache_off == -1)
263 if (access (filename, F_OK) == -1) {
264 perrorf (g, "%s", filename);
269 /* Construct the final -drive parameter. */
270 size_t len = 64 + strlen (filename) + strlen (iface);
271 if (format) len += strlen (format);
274 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
276 readonly ? ",snapshot=on" : "",
277 use_cache_off ? ",cache=off" : "",
278 format ? ",format=" : "",
279 format ? format : "",
282 return guestfs__config (g, "-drive", buf);
286 guestfs__add_drive (guestfs_h *g, const char *filename)
288 struct guestfs_add_drive_opts_argv optargs = {
292 return guestfs__add_drive_opts (g, filename, &optargs);
296 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
298 struct guestfs_add_drive_opts_argv optargs = {
299 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
303 return guestfs__add_drive_opts (g, filename, &optargs);
307 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
310 struct guestfs_add_drive_opts_argv optargs = {
311 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
315 return guestfs__add_drive_opts (g, filename, &optargs);
319 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
322 struct guestfs_add_drive_opts_argv optargs = {
323 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
324 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
329 return guestfs__add_drive_opts (g, filename, &optargs);
333 guestfs__add_cdrom (guestfs_h *g, const char *filename)
335 if (strchr (filename, ',') != NULL) {
336 error (g, _("filename cannot contain ',' (comma) character"));
340 if (access (filename, F_OK) == -1) {
341 perrorf (g, "%s", filename);
345 return guestfs__config (g, "-cdrom", filename);
348 static int is_openable (guestfs_h *g, const char *path, int flags);
351 guestfs__launch (guestfs_h *g)
356 struct sockaddr_un addr;
360 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
364 if (g->state != CONFIG) {
365 error (g, _("the libguestfs handle has already been launched"));
369 /* Start the clock ... */
370 gettimeofday (&g->launch_t, NULL);
372 /* Make the temporary directory. */
374 TMP_TEMPLATE_ON_STACK (dir_template);
375 g->tmpdir = safe_strdup (g, dir_template);
376 if (mkdtemp (g->tmpdir) == NULL) {
377 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
382 /* Allow anyone to read the temporary directory. The socket in this
383 * directory won't be readable but anyone can see it exists if they
384 * want. (RHBZ#610880).
386 if (chmod (g->tmpdir, 0755) == -1)
387 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
389 /* Locate and/or build the appliance. */
390 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
391 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
395 guestfs___print_timestamped_message (g, "begin testing qemu features");
397 /* Get qemu help text and version. */
398 if (qemu_supports (g, NULL) == -1)
401 /* Using virtio-serial, we need to create a local Unix domain socket
402 * for qemu to connect to.
404 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
407 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
409 perrorf (g, "socket");
413 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
414 perrorf (g, "fcntl");
418 addr.sun_family = AF_UNIX;
419 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
420 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
422 if (bind (g->sock, &addr, sizeof addr) == -1) {
427 if (listen (g->sock, 1) == -1) {
428 perrorf (g, "listen");
433 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
440 guestfs___print_timestamped_message (g, "finished testing qemu features");
454 if (r == 0) { /* Child (qemu). */
457 /* Set up the full command line. Do this in the subprocess so we
458 * don't need to worry about cleaning up.
460 g->cmdline[0] = g->qemu;
462 if (qemu_supports (g, "-nodefconfig"))
463 add_cmdline (g, "-nodefconfig");
465 /* qemu sometimes needs this option to enable hardware
466 * virtualization, but some versions of 'qemu-kvm' will use KVM
467 * regardless (even where this option appears in the help text).
468 * It is rumoured that there are versions of qemu where supplying
469 * this option when hardware virtualization is not available will
470 * cause qemu to fail, so we we have to check at least that
471 * /dev/kvm is openable. That's not reliable, since /dev/kvm
472 * might be openable by qemu but not by us (think: SELinux) in
473 * which case the user would not get hardware virtualization,
474 * although at least shouldn't fail. A giant clusterfuck with the
475 * qemu command line, again.
477 if (qemu_supports (g, "-enable-kvm") &&
478 is_openable (g, "/dev/kvm", O_RDWR))
479 add_cmdline (g, "-enable-kvm");
481 /* Newer versions of qemu (from around 2009/12) changed the
482 * behaviour of monitors so that an implicit '-monitor stdio' is
483 * assumed if we are in -nographic mode and there is no other
484 * -monitor option. Only a single stdio device is allowed, so
485 * this broke the '-serial stdio' option. There is a new flag
486 * called -nodefaults which gets rid of all this default crud, so
487 * let's use that to avoid this and any future surprises.
489 if (qemu_supports (g, "-nodefaults"))
490 add_cmdline (g, "-nodefaults");
492 add_cmdline (g, "-nographic");
494 snprintf (buf, sizeof buf, "%d", g->memsize);
495 add_cmdline (g, "-m");
496 add_cmdline (g, buf);
498 /* Force exit instead of reboot on panic */
499 add_cmdline (g, "-no-reboot");
501 /* These options recommended by KVM developers to improve reliability. */
502 if (qemu_supports (g, "-no-hpet"))
503 add_cmdline (g, "-no-hpet");
505 if (qemu_supports (g, "-rtc-td-hack"))
506 add_cmdline (g, "-rtc-td-hack");
508 /* Create the virtio serial bus. */
509 add_cmdline (g, "-device");
510 add_cmdline (g, "virtio-serial");
513 /* Use virtio-console (a variant form of virtio-serial) for the
514 * guest's serial console.
516 add_cmdline (g, "-chardev");
517 add_cmdline (g, "stdio,id=console");
518 add_cmdline (g, "-device");
519 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
521 /* When the above works ... until then: */
522 add_cmdline (g, "-serial");
523 add_cmdline (g, "stdio");
526 /* Set up virtio-serial for the communications channel. */
527 add_cmdline (g, "-chardev");
528 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", unixsock);
529 add_cmdline (g, buf);
530 add_cmdline (g, "-device");
531 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
533 /* Enable user networking. */
534 if (g->enable_network) {
535 add_cmdline (g, "-netdev");
536 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
537 add_cmdline (g, "-device");
538 add_cmdline (g, NET_IF ",netdev=usernet");
541 #define LINUX_CMDLINE \
542 "panic=1 " /* force kernel to panic if daemon exits */ \
543 "console=ttyS0 " /* serial console */ \
544 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
545 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
546 "acpi=off " /* we don't need ACPI, turn it off */ \
547 "printk.time=1 " /* display timestamp before kernel messages */ \
548 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
550 /* Linux kernel command line. */
551 snprintf (buf, sizeof buf,
553 "%s " /* (selinux) */
554 "%s " /* (verbose) */
555 "TERM=%s " /* (TERM environment variable) */
557 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
558 g->verbose ? "guestfs_verbose=1" : "",
559 getenv ("TERM") ? : "linux",
560 g->append ? g->append : "");
562 add_cmdline (g, "-kernel");
563 add_cmdline (g, kernel);
564 add_cmdline (g, "-initrd");
565 add_cmdline (g, initrd);
566 add_cmdline (g, "-append");
567 add_cmdline (g, buf);
569 /* Add the ext2 appliance drive (last of all). */
571 const char *cachemode = "";
572 if (qemu_supports (g, "cache=")) {
573 if (qemu_supports (g, "unsafe"))
574 cachemode = ",cache=unsafe";
575 else if (qemu_supports (g, "writeback"))
576 cachemode = ",cache=writeback";
579 char buf2[PATH_MAX + 64];
580 add_cmdline (g, "-drive");
581 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
582 appliance, cachemode);
583 add_cmdline (g, buf2);
586 /* Finish off the command line. */
587 incr_cmdline_size (g);
588 g->cmdline[g->cmdline_size-1] = NULL;
591 guestfs___print_timestamped_argv (g, (const char **)g->cmdline);
594 /* Set up stdin, stdout. */
600 if (dup (wfd[0]) == -1) {
602 perror ("dup failed");
603 _exit (EXIT_FAILURE);
605 if (dup (rfd[1]) == -1)
613 /* Set up a new process group, so we can signal this process
614 * and all subprocesses (eg. if qemu is really a shell script).
619 setenv ("LC_ALL", "C", 1);
621 execv (g->qemu, g->cmdline); /* Run qemu. */
623 _exit (EXIT_FAILURE);
626 /* Parent (library). */
636 /* Fork the recovery process off which will kill qemu if the parent
637 * process fails to do so (eg. if the parent segfaults).
640 if (g->recovery_proc) {
643 pid_t qemu_pid = g->pid;
644 pid_t parent_pid = getppid ();
646 /* Writing to argv is hideously complicated and error prone. See:
647 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
650 /* Loop around waiting for one or both of the other processes to
651 * disappear. It's fair to say this is very hairy. The PIDs that
652 * we are looking at might be reused by another process. We are
653 * effectively polling. Is the cure worse than the disease?
656 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
657 _exit (EXIT_SUCCESS);
658 if (kill (parent_pid, 0) == -1) {
659 /* Parent's gone away, qemu still around, so kill qemu. */
661 _exit (EXIT_SUCCESS);
667 /* Don't worry, if the fork failed, this will be -1. The recovery
668 * process isn't essential.
674 /* Close the other ends of the pipe. */
678 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
679 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
680 perrorf (g, "fcntl");
684 g->fd[0] = wfd[1]; /* stdin of child */
685 g->fd[1] = rfd[0]; /* stdout of child */
687 g->fd[0] = open ("/dev/null", O_RDWR);
688 if (g->fd[0] == -1) {
689 perrorf (g, "open /dev/null");
692 g->fd[1] = dup (g->fd[0]);
693 if (g->fd[1] == -1) {
700 g->state = LAUNCHING;
702 /* Wait for qemu to start and to connect back to us via
703 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
705 r = guestfs___accept_from_daemon (g);
709 close (g->sock); /* Close the listening socket. */
710 g->sock = r; /* This is the accepted data socket. */
712 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
713 perrorf (g, "fcntl");
719 r = guestfs___recv_from_daemon (g, &size, &buf);
722 if (r == -1) return -1;
724 if (size != GUESTFS_LAUNCH_FLAG) {
725 error (g, _("guestfs_launch failed, see earlier error messages"));
730 guestfs___print_timestamped_message (g, "appliance is up");
732 /* This is possible in some really strange situations, such as
733 * guestfsd starts up OK but then qemu immediately exits. Check for
734 * it because the caller is probably expecting to be able to send
735 * commands after this function returns.
737 if (g->state != READY) {
738 error (g, _("qemu launched and contacted daemon, but state != READY"));
749 if (g->pid > 0) kill (g->pid, 9);
750 if (g->recoverypid > 0) kill (g->recoverypid, 9);
751 waitpid (g->pid, NULL, 0);
752 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
757 memset (&g->launch_t, 0, sizeof g->launch_t);
771 /* Return the location of the tmpdir (eg. "/tmp") and allow users
772 * to override it at runtime using $TMPDIR.
775 guestfs_tmpdir (void)
785 const char *t = getenv ("TMPDIR");
791 /* Compute Y - X and return the result in milliseconds.
792 * Approximately the same as this code:
793 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
796 timeval_diff (const struct timeval *x, const struct timeval *y)
800 msec = (y->tv_sec - x->tv_sec) * 1000;
801 msec += (y->tv_usec - x->tv_usec) / 1000;
806 guestfs___print_timestamped_argv (guestfs_h *g, const char * argv[])
812 gettimeofday (&tv, NULL);
813 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
816 if (argv[i][0] == '-') /* -option starts a new line */
817 fprintf (stderr, " \\\n ");
819 if (i > 0) fputc (' ', stderr);
821 /* Does it need shell quoting? This only deals with simple cases. */
822 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
824 if (needs_quote) fputc ('\'', stderr);
825 fprintf (stderr, "%s", argv[i]);
826 if (needs_quote) fputc ('\'', stderr);
830 fputc ('\n', stderr);
834 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
842 err = vasprintf (&msg, fs, args);
847 gettimeofday (&tv, NULL);
849 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
850 timeval_diff (&g->launch_t, &tv), msg);
855 static int read_all (guestfs_h *g, FILE *fp, char **ret);
857 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
858 * 'qemu -version' so we know what options this qemu supports and
862 test_qemu (guestfs_h *g)
867 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
869 fp = popen (cmd, "r");
870 /* qemu -help should always work (qemu -version OTOH wasn't
871 * supported by qemu 0.9). If this command doesn't work then it
872 * probably indicates that the qemu binary is missing.
875 /* XXX This error is never printed, even if the qemu binary
876 * doesn't exist. Why?
879 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
883 if (read_all (g, fp, &g->qemu_help) == -1)
886 if (pclose (fp) == -1)
889 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
892 fp = popen (cmd, "r");
894 /* Intentionally ignore errors. */
895 read_all (g, fp, &g->qemu_version);
903 read_all (guestfs_h *g, FILE *fp, char **ret)
910 *ret = safe_realloc (g, *ret, n + 1);
915 *ret = safe_realloc (g, *ret, n + BUFSIZ);
917 r = fread (p, 1, BUFSIZ, fp);
926 /* Test if option is supported by qemu command line (just by grepping
929 * The first time this is used, it has to run the external qemu
930 * binary. If that fails, it returns -1.
932 * To just do the first-time run of the qemu binary, call this with
933 * option == NULL, in which case it will return -1 if there was an
937 qemu_supports (guestfs_h *g, const char *option)
940 if (test_qemu (g) == -1)
947 return strstr (g->qemu_help, option) != NULL;
950 /* Check if a file can be opened. */
952 is_openable (guestfs_h *g, const char *path, int flags)
954 int fd = open (path, flags);
964 /* You had to call this function after launch in versions <= 1.0.70,
965 * but it is now a no-op.
968 guestfs__wait_ready (guestfs_h *g)
970 if (g->state != READY) {
971 error (g, _("qemu has not been launched yet"));
979 guestfs__kill_subprocess (guestfs_h *g)
981 if (g->state == CONFIG) {
982 error (g, _("no subprocess to kill"));
987 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
989 if (g->pid > 0) kill (g->pid, SIGTERM);
990 if (g->recoverypid > 0) kill (g->recoverypid, 9);
995 /* Access current state. */
997 guestfs__is_config (guestfs_h *g)
999 return g->state == CONFIG;
1003 guestfs__is_launching (guestfs_h *g)
1005 return g->state == LAUNCHING;
1009 guestfs__is_ready (guestfs_h *g)
1011 return g->state == READY;
1015 guestfs__is_busy (guestfs_h *g)
1017 return g->state == BUSY;
1021 guestfs__get_state (guestfs_h *g)