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 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
74 static int qemu_supports (guestfs_h *g, const char *option);
76 /* Add a string to the current command line. */
78 incr_cmdline_size (guestfs_h *g)
80 if (g->cmdline == NULL) {
81 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
83 g->cmdline = safe_malloc (g, sizeof (char *));
88 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
92 add_cmdline (guestfs_h *g, const char *str)
94 if (g->state != CONFIG) {
96 _("command line cannot be altered after qemu subprocess launched"));
100 incr_cmdline_size (g);
101 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
106 guestfs__config (guestfs_h *g,
107 const char *qemu_param, const char *qemu_value)
109 if (qemu_param[0] != '-') {
110 error (g, _("guestfs_config: parameter must begin with '-' character"));
114 /* A bit fascist, but the user will probably break the extra
115 * parameters that we add if they try to set any of these.
117 if (STREQ (qemu_param, "-kernel") ||
118 STREQ (qemu_param, "-initrd") ||
119 STREQ (qemu_param, "-nographic") ||
120 STREQ (qemu_param, "-serial") ||
121 STREQ (qemu_param, "-full-screen") ||
122 STREQ (qemu_param, "-std-vga") ||
123 STREQ (qemu_param, "-vnc")) {
124 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
128 if (add_cmdline (g, qemu_param) != 0) return -1;
130 if (qemu_value != NULL) {
131 if (add_cmdline (g, qemu_value) != 0) return -1;
138 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
139 const char *drive_if)
141 size_t len = strlen (filename) + 64;
144 if (strchr (filename, ',') != NULL) {
145 error (g, _("filename cannot contain ',' (comma) character"));
149 /* cache=off improves reliability in the event of a host crash.
151 * However this option causes qemu to try to open the file with
152 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
153 * So we check if we can open the file with or without O_DIRECT,
154 * and use cache=off (or not) accordingly.
156 * This test also checks for the presence of the file, which
157 * is a documented semantic of this interface.
159 int fd = open (filename, O_RDONLY|O_DIRECT);
162 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
164 fd = open (filename, O_RDONLY);
167 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
169 perrorf (g, "%s", filename);
174 return guestfs__config (g, "-drive", buf);
178 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
179 const char *drive_if)
181 if (strchr (filename, ',') != NULL) {
182 error (g, _("filename cannot contain ',' (comma) character"));
186 if (access (filename, F_OK) == -1) {
187 perrorf (g, "%s", filename);
191 size_t len = strlen (filename) + 64;
194 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
196 return guestfs__config (g, "-drive", buf);
200 guestfs__add_drive (guestfs_h *g, const char *filename)
202 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
206 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
208 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
212 guestfs__add_cdrom (guestfs_h *g, const char *filename)
214 if (strchr (filename, ',') != NULL) {
215 error (g, _("filename cannot contain ',' (comma) character"));
219 if (access (filename, F_OK) == -1) {
220 perrorf (g, "%s", filename);
224 return guestfs__config (g, "-cdrom", filename);
227 /* Returns true iff file is contained in dir. */
229 dir_contains_file (const char *dir, const char *file)
231 int dirlen = strlen (dir);
232 int filelen = strlen (file);
233 int len = dirlen+filelen+2;
236 snprintf (path, len, "%s/%s", dir, file);
237 return access (path, F_OK) == 0;
240 /* Returns true iff every listed file is contained in 'dir'. */
242 dir_contains_files (const char *dir, ...)
247 va_start (args, dir);
248 while ((file = va_arg (args, const char *)) != NULL) {
249 if (!dir_contains_file (dir, file)) {
258 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
259 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
260 static int is_openable (guestfs_h *g, const char *path, int flags);
261 static void print_cmdline (guestfs_h *g);
263 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
264 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
267 guestfs__launch (guestfs_h *g)
273 char *path, *pelem, *pend;
274 char *kernel = NULL, *initrd = NULL;
275 int null_vmchannel_sock;
277 struct sockaddr_un addr;
281 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
285 if (g->state != CONFIG) {
286 error (g, _("the libguestfs handle has already been launched"));
290 /* Start the clock ... */
291 gettimeofday (&g->launch_t, NULL);
293 /* Make the temporary directory. */
295 const char *tmpdir = guestfs___tmpdir ();
296 char dir_template[strlen (tmpdir) + 32];
297 sprintf (dir_template, "%s/libguestfsXXXXXX", tmpdir);
299 g->tmpdir = safe_strdup (g, dir_template);
300 if (mkdtemp (g->tmpdir) == NULL) {
301 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
306 /* Allow anyone to read the temporary directory. There are no
307 * secrets in the kernel or initrd files. The socket in this
308 * directory won't be readable but anyone can see it exists if they
309 * want. (RHBZ#610880).
311 if (chmod (g->tmpdir, 0755) == -1)
312 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
314 /* First search g->path for the supermin appliance, and try to
315 * synthesize a kernel and initrd from that. If it fails, we
316 * try the path search again looking for a backup ordinary
319 pelem = path = safe_strdup (g, g->path);
321 pend = strchrnul (pelem, ':');
322 pmore = *pend == ':';
326 /* Empty element of "." means cwd. */
327 if (len == 0 || (len == 1 && *pelem == '.')) {
330 "looking for supermin appliance in current directory\n");
331 if (dir_contains_files (".",
332 "supermin.d", "kmod.whitelist", NULL)) {
333 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
338 /* Look at <path>/supermin* etc. */
341 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
343 if (dir_contains_files (pelem,
344 "supermin.d", "kmod.whitelist", NULL)) {
345 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
356 if (kernel == NULL || initrd == NULL) {
357 /* Search g->path for the kernel and initrd. */
358 pelem = path = safe_strdup (g, g->path);
360 pend = strchrnul (pelem, ':');
361 pmore = *pend == ':';
365 /* Empty element or "." means cwd. */
366 if (len == 0 || (len == 1 && *pelem == '.')) {
369 "looking for appliance in current directory\n");
370 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
371 kernel = safe_strdup (g, kernel_name);
372 initrd = safe_strdup (g, initrd_name);
376 /* Look at <path>/kernel etc. */
379 fprintf (stderr, "looking for appliance in %s\n", pelem);
381 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
382 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
383 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
384 sprintf (kernel, "%s/%s", pelem, kernel_name);
385 sprintf (initrd, "%s/%s", pelem, initrd_name);
396 if (kernel == NULL || initrd == NULL) {
397 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
398 kernel_name, initrd_name, g->path);
403 print_timestamped_message (g, "begin testing qemu features");
405 /* Get qemu help text and version. */
406 if (qemu_supports (g, NULL) == -1)
409 /* Choose which vmchannel implementation to use. */
410 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
411 /* The "null vmchannel" implementation. Requires SLIRP (user mode
412 * networking in qemu) but no other vmchannel support. The daemon
413 * will connect back to a random port number on localhost.
415 struct sockaddr_in addr;
416 socklen_t addrlen = sizeof addr;
418 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
420 perrorf (g, "socket");
423 addr.sin_family = AF_INET;
424 addr.sin_port = htons (0);
425 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
426 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
431 if (listen (g->sock, 256) == -1) {
432 perrorf (g, "listen");
436 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
437 perrorf (g, "getsockname");
441 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
442 perrorf (g, "fcntl");
446 null_vmchannel_sock = ntohs (addr.sin_port);
448 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
450 /* Using some vmchannel impl. We need to create a local Unix
451 * domain socket for qemu to use.
453 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
455 null_vmchannel_sock = 0;
459 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
466 print_timestamped_message (g, "finished testing qemu features");
480 if (r == 0) { /* Child (qemu). */
482 const char *vmchannel = NULL;
484 /* Set up the full command line. Do this in the subprocess so we
485 * don't need to worry about cleaning up.
487 g->cmdline[0] = g->qemu;
489 /* qemu sometimes needs this option to enable hardware
490 * virtualization, but some versions of 'qemu-kvm' will use KVM
491 * regardless (even where this option appears in the help text).
492 * It is rumoured that there are versions of qemu where supplying
493 * this option when hardware virtualization is not available will
494 * cause qemu to fail, so we we have to check at least that
495 * /dev/kvm is openable. That's not reliable, since /dev/kvm
496 * might be openable by qemu but not by us (think: SELinux) in
497 * which case the user would not get hardware virtualization,
498 * although at least shouldn't fail. A giant clusterfuck with the
499 * qemu command line, again.
501 if (qemu_supports (g, "-enable-kvm") &&
502 is_openable (g, "/dev/kvm", O_RDWR))
503 add_cmdline (g, "-enable-kvm");
505 /* Newer versions of qemu (from around 2009/12) changed the
506 * behaviour of monitors so that an implicit '-monitor stdio' is
507 * assumed if we are in -nographic mode and there is no other
508 * -monitor option. Only a single stdio device is allowed, so
509 * this broke the '-serial stdio' option. There is a new flag
510 * called -nodefaults which gets rid of all this default crud, so
511 * let's use that to avoid this and any future surprises.
513 if (qemu_supports (g, "-nodefaults"))
514 add_cmdline (g, "-nodefaults");
516 add_cmdline (g, "-nographic");
517 add_cmdline (g, "-serial");
518 add_cmdline (g, "stdio");
520 snprintf (buf, sizeof buf, "%d", g->memsize);
521 add_cmdline (g, "-m");
522 add_cmdline (g, buf);
524 /* Force exit instead of reboot on panic */
525 add_cmdline (g, "-no-reboot");
527 /* These options recommended by KVM developers to improve reliability. */
528 if (qemu_supports (g, "-no-hpet"))
529 add_cmdline (g, "-no-hpet");
531 if (qemu_supports (g, "-rtc-td-hack"))
532 add_cmdline (g, "-rtc-td-hack");
534 /* If qemu has SLIRP (user mode network) enabled then we can get
535 * away with "no vmchannel", where we just connect back to a random
538 if (null_vmchannel_sock) {
539 add_cmdline (g, "-net");
540 add_cmdline (g, "user,vlan=0,net=" NETWORK);
542 snprintf (buf, sizeof buf,
543 "guestfs_vmchannel=tcp:" ROUTER ":%d",
544 null_vmchannel_sock);
545 vmchannel = strdup (buf);
548 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
550 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
552 * The original suggested format doesn't work, see:
554 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
556 * However Gerd Hoffman privately suggested to me using -chardev
557 * instead, which does work.
559 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
560 snprintf (buf, sizeof buf,
561 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
563 add_cmdline (g, "-chardev");
564 add_cmdline (g, buf);
566 snprintf (buf, sizeof buf,
567 "user,vlan=0,net=" NETWORK ","
568 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
569 "-chardev:guestfsvmc");
571 add_cmdline (g, "-net");
572 add_cmdline (g, buf);
574 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
577 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
578 * syntax, or if not then we'll get a quick failure.
581 snprintf (buf, sizeof buf,
582 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
584 add_cmdline (g, "-net");
585 add_cmdline (g, buf);
586 add_cmdline (g, "-net");
587 add_cmdline (g, "user,vlan=0,net=" NETWORK);
589 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
591 add_cmdline (g, "-net");
592 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
594 #define LINUX_CMDLINE \
595 "panic=1 " /* force kernel to panic if daemon exits */ \
596 "console=ttyS0 " /* serial console */ \
597 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
598 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
599 "acpi=off " /* we don't need ACPI, turn it off */ \
600 "printk.time=1 " /* display timestamp before kernel messages */ \
601 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
603 /* Linux kernel command line. */
604 snprintf (buf, sizeof buf,
606 "%s " /* (selinux) */
607 "%s " /* (vmchannel) */
608 "%s " /* (verbose) */
609 "TERM=%s " /* (TERM environment variable) */
611 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
612 vmchannel ? vmchannel : "",
613 g->verbose ? "guestfs_verbose=1" : "",
614 getenv ("TERM") ? : "linux",
615 g->append ? g->append : "");
617 add_cmdline (g, "-kernel");
618 add_cmdline (g, (char *) kernel);
619 add_cmdline (g, "-initrd");
620 add_cmdline (g, (char *) initrd);
621 add_cmdline (g, "-append");
622 add_cmdline (g, buf);
624 /* Finish off the command line. */
625 incr_cmdline_size (g);
626 g->cmdline[g->cmdline_size-1] = NULL;
632 /* Set up stdin, stdout. */
638 if (dup (wfd[0]) == -1) {
640 perror ("dup failed");
641 _exit (EXIT_FAILURE);
643 if (dup (rfd[1]) == -1)
651 /* Set up a new process group, so we can signal this process
652 * and all subprocesses (eg. if qemu is really a shell script).
657 setenv ("LC_ALL", "C", 1);
659 execv (g->qemu, g->cmdline); /* Run qemu. */
661 _exit (EXIT_FAILURE);
664 /* Parent (library). */
672 /* Fork the recovery process off which will kill qemu if the parent
673 * process fails to do so (eg. if the parent segfaults).
676 if (g->recovery_proc) {
679 pid_t qemu_pid = g->pid;
680 pid_t parent_pid = getppid ();
682 /* Writing to argv is hideously complicated and error prone. See:
683 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
686 /* Loop around waiting for one or both of the other processes to
687 * disappear. It's fair to say this is very hairy. The PIDs that
688 * we are looking at might be reused by another process. We are
689 * effectively polling. Is the cure worse than the disease?
692 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
693 _exit (EXIT_SUCCESS);
694 if (kill (parent_pid, 0) == -1) {
695 /* Parent's gone away, qemu still around, so kill qemu. */
697 _exit (EXIT_SUCCESS);
703 /* Don't worry, if the fork failed, this will be -1. The recovery
704 * process isn't essential.
710 /* Close the other ends of the pipe. */
714 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
715 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
716 perrorf (g, "fcntl");
720 g->fd[0] = wfd[1]; /* stdin of child */
721 g->fd[1] = rfd[0]; /* stdout of child */
723 g->fd[0] = open ("/dev/null", O_RDWR);
724 if (g->fd[0] == -1) {
725 perrorf (g, "open /dev/null");
728 g->fd[1] = dup (g->fd[0]);
729 if (g->fd[1] == -1) {
736 if (null_vmchannel_sock) {
740 /* Null vmchannel implementation: We listen on g->sock for a
741 * connection. The connection could come from any local process
742 * so we must check it comes from the appliance (or at least
743 * from our UID) for security reasons.
746 sock = guestfs___accept_from_daemon (g);
750 if (check_peer_euid (g, sock, &uid) == -1)
752 if (uid != geteuid ()) {
754 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
755 uid, null_vmchannel_sock);
762 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
763 perrorf (g, "fcntl");
770 /* Other vmchannel. Open the Unix socket.
772 * The vmchannel implementation that got merged with qemu sucks in
773 * a number of ways. Both ends do connect(2), which means that no
774 * one knows what, if anything, is connected to the other end, or
775 * if it becomes disconnected. Even worse, we have to wait some
776 * indeterminate time for qemu to create the socket and connect to
777 * it (which happens very early in qemu's start-up), so any code
778 * that uses vmchannel is inherently racy. Hence this silly loop.
780 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
782 perrorf (g, "socket");
786 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
787 perrorf (g, "fcntl");
791 addr.sun_family = AF_UNIX;
792 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
793 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
796 /* Always sleep at least once to give qemu a small chance to start up. */
799 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
800 if ((r == -1 && errno == EINPROGRESS) || r == 0)
804 perrorf (g, "connect");
809 error (g, _("failed to connect to vmchannel socket"));
815 g->state = LAUNCHING;
817 /* Wait for qemu to start and to connect back to us via vmchannel and
818 * send the GUESTFS_LAUNCH_FLAG message.
822 r = guestfs___recv_from_daemon (g, &size, &buf);
825 if (r == -1) return -1;
827 if (size != GUESTFS_LAUNCH_FLAG) {
828 error (g, _("guestfs_launch failed, see earlier error messages"));
833 print_timestamped_message (g, "appliance is up");
835 /* This is possible in some really strange situations, such as
836 * guestfsd starts up OK but then qemu immediately exits. Check for
837 * it because the caller is probably expecting to be able to send
838 * commands after this function returns.
840 if (g->state != READY) {
841 error (g, _("qemu launched and contacted daemon, but state != READY"));
852 if (g->pid > 0) kill (g->pid, 9);
853 if (g->recoverypid > 0) kill (g->recoverypid, 9);
854 waitpid (g->pid, NULL, 0);
855 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
860 memset (&g->launch_t, 0, sizeof g->launch_t);
874 guestfs___tmpdir (void)
884 const char *t = getenv ("TMPDIR");
890 /* This function is used to print the qemu command line before it gets
891 * executed, when in verbose mode.
894 print_cmdline (guestfs_h *g)
899 while (g->cmdline[i]) {
900 if (g->cmdline[i][0] == '-') /* -option starts a new line */
901 fprintf (stderr, " \\\n ");
903 if (i > 0) fputc (' ', stderr);
905 /* Does it need shell quoting? This only deals with simple cases. */
906 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
908 if (needs_quote) fputc ('\'', stderr);
909 fprintf (stderr, "%s", g->cmdline[i]);
910 if (needs_quote) fputc ('\'', stderr);
914 fputc ('\n', stderr);
917 /* This function does the hard work of building the supermin appliance
918 * on the fly. 'path' is the directory containing the control files.
919 * 'kernel' and 'initrd' are where we will return the names of the
920 * kernel and initrd (only initrd is built). The work is done by
921 * an external script. We just tell it where to put the result.
924 build_supermin_appliance (guestfs_h *g, const char *path,
925 char **kernel, char **initrd)
931 print_timestamped_message (g, "begin building supermin appliance");
933 len = strlen (g->tmpdir);
934 *kernel = safe_malloc (g, len + 8);
935 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
936 *initrd = safe_malloc (g, len + 8);
937 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
939 /* Set a sensible umask in the subprocess, so kernel and initrd
940 * output files are world-readable (RHBZ#610880).
942 snprintf (cmd, sizeof cmd,
944 "febootstrap-supermin-helper%s "
945 "-k '%s/kmod.whitelist' "
949 g->verbose ? " --verbose" : "",
954 print_timestamped_message (g, "%s", cmd);
957 if (r == -1 || WEXITSTATUS(r) != 0) {
958 error (g, _("external command failed: %s"), cmd);
961 *kernel = *initrd = NULL;
966 print_timestamped_message (g, "finished building supermin appliance");
971 /* Compute Y - X and return the result in milliseconds.
972 * Approximately the same as this code:
973 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
976 timeval_diff (const struct timeval *x, const struct timeval *y)
980 msec = (y->tv_sec - x->tv_sec) * 1000;
981 msec += (y->tv_usec - x->tv_usec) / 1000;
986 print_timestamped_message (guestfs_h *g, const char *fs, ...)
994 err = vasprintf (&msg, fs, args);
999 gettimeofday (&tv, NULL);
1001 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1002 timeval_diff (&g->launch_t, &tv), msg);
1007 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1009 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1010 * 'qemu -version' so we know what options this qemu supports and
1014 test_qemu (guestfs_h *g)
1019 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1021 fp = popen (cmd, "r");
1022 /* qemu -help should always work (qemu -version OTOH wasn't
1023 * supported by qemu 0.9). If this command doesn't work then it
1024 * probably indicates that the qemu binary is missing.
1027 /* XXX This error is never printed, even if the qemu binary
1028 * doesn't exist. Why?
1031 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1035 if (read_all (g, fp, &g->qemu_help) == -1)
1038 if (pclose (fp) == -1)
1041 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1044 fp = popen (cmd, "r");
1046 /* Intentionally ignore errors. */
1047 read_all (g, fp, &g->qemu_version);
1055 read_all (guestfs_h *g, FILE *fp, char **ret)
1062 *ret = safe_realloc (g, *ret, n + 1);
1067 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1069 r = fread (p, 1, BUFSIZ, fp);
1071 perrorf (g, "read");
1078 /* Test if option is supported by qemu command line (just by grepping
1081 * The first time this is used, it has to run the external qemu
1082 * binary. If that fails, it returns -1.
1084 * To just do the first-time run of the qemu binary, call this with
1085 * option == NULL, in which case it will return -1 if there was an
1089 qemu_supports (guestfs_h *g, const char *option)
1091 if (!g->qemu_help) {
1092 if (test_qemu (g) == -1)
1099 return strstr (g->qemu_help, option) != NULL;
1102 /* Check if a file can be opened. */
1104 is_openable (guestfs_h *g, const char *path, int flags)
1106 int fd = open (path, flags);
1116 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1117 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1118 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1121 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1123 #if CAN_CHECK_PEER_EUID
1124 struct sockaddr_in peer;
1125 socklen_t addrlen = sizeof peer;
1127 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1128 perrorf (g, "getpeername");
1132 if (peer.sin_family != AF_INET ||
1133 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1134 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1135 peer.sin_family, inet_ntoa (peer.sin_addr));
1139 struct sockaddr_in our;
1140 addrlen = sizeof our;
1141 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1142 perrorf (g, "getsockname");
1146 FILE *fp = fopen ("/proc/net/tcp", "r");
1148 perrorf (g, "/proc/net/tcp");
1153 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1154 error (g, "unexpected end of file in /proc/net/tcp");
1159 while (fgets (line, sizeof line, fp) != NULL) {
1160 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1161 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1164 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1166 &line_our_addr, &line_our_port,
1167 &line_peer_addr, &line_peer_port,
1168 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1170 /* Note about /proc/net/tcp: local_address and rem_address are
1171 * always in network byte order. However the port part is
1172 * always in host byte order.
1174 * The sockname and peername that we got above are in network
1175 * byte order. So we have to byte swap the port but not the
1178 if (line_our_addr == our.sin_addr.s_addr &&
1179 line_our_port == ntohs (our.sin_port) &&
1180 line_peer_addr == peer.sin_addr.s_addr &&
1181 line_peer_port == ntohs (peer.sin_port)) {
1189 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1192 #else /* !CAN_CHECK_PEER_EUID */
1193 /* This function exists but should never be called in this
1197 #endif /* !CAN_CHECK_PEER_EUID */
1200 /* You had to call this function after launch in versions <= 1.0.70,
1201 * but it is now a no-op.
1204 guestfs__wait_ready (guestfs_h *g)
1206 if (g->state != READY) {
1207 error (g, _("qemu has not been launched yet"));
1215 guestfs__kill_subprocess (guestfs_h *g)
1217 if (g->state == CONFIG) {
1218 error (g, _("no subprocess to kill"));
1223 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1225 if (g->pid > 0) kill (g->pid, SIGTERM);
1226 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1231 /* Access current state. */
1233 guestfs__is_config (guestfs_h *g)
1235 return g->state == CONFIG;
1239 guestfs__is_launching (guestfs_h *g)
1241 return g->state == LAUNCHING;
1245 guestfs__is_ready (guestfs_h *g)
1247 return g->state == READY;
1251 guestfs__is_busy (guestfs_h *g)
1253 return g->state == BUSY;
1257 guestfs__get_state (guestfs_h *g)