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"
75 #define _(str) dgettext(PACKAGE, (str))
76 //#define N_(str) dgettext(PACKAGE, (str))
82 #define error guestfs_error
83 #define perrorf guestfs_perrorf
84 #define safe_malloc guestfs_safe_malloc
85 #define safe_realloc guestfs_safe_realloc
86 #define safe_strdup guestfs_safe_strdup
87 //#define safe_memdup guestfs_safe_memdup
90 #define CAN_CHECK_PEER_EUID 1
92 #define CAN_CHECK_PEER_EUID 0
95 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
96 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
97 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
98 static int accept_from_daemon (guestfs_h *g);
99 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
100 static void close_handles (void);
101 static int qemu_supports (guestfs_h *g, const char *option);
103 #define UNIX_PATH_MAX 108
106 #define MAX(a,b) ((a)>(b)?(a):(b))
110 #define xdr_uint32_t xdr_u_int32_t
113 /* Network configuration of the appliance. Note these addresses are
114 * only meaningful within the context of the running appliance. QEMU
115 * translates network connections to these magic addresses into
116 * userspace calls on the host (eg. connect(2)). qemu-doc has a nice
117 * diagram which is also useful to refer to.
119 * NETWORK: The network.
121 * ROUTER: The address of the "host", ie. this library.
123 * [Note: If you change NETWORK and ROUTER then you also have to
124 * change the network configuration in appliance/init].
126 * GUESTFWD_ADDR, GUESTFWD_PORT: The guestfwd feature of qemu
127 * magically connects this pseudo-address to the guestfwd channel. In
128 * typical Linux configurations of libguestfs, guestfwd is not
129 * actually used any more.
131 #define NETWORK "169.254.0.0/16"
132 #define ROUTER "169.254.2.2"
133 #define GUESTFWD_ADDR "169.254.2.4"
134 #define GUESTFWD_PORT "6666"
136 /* GuestFS handle and connection. */
137 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
141 struct guestfs_h *next; /* Linked list of open handles. */
143 /* State: see the state machine diagram in the man page guestfs(3). */
146 int fd[2]; /* Stdin/stdout of qemu. */
147 int sock; /* Daemon communications socket. */
148 pid_t pid; /* Qemu PID. */
149 pid_t recoverypid; /* Recovery process PID. */
151 struct timeval launch_t; /* The time that we called guestfs_launch. */
153 char *tmpdir; /* Temporary directory containing socket. */
155 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
157 char **cmdline; /* Qemu command line. */
166 char *path; /* Path to kernel, initrd. */
167 char *qemu; /* Qemu binary. */
168 char *append; /* Append to kernel command line. */
170 int memsize; /* Size of RAM (megabytes). */
172 int selinux; /* selinux enabled? */
177 guestfs_abort_cb abort_cb;
178 guestfs_error_handler_cb error_cb;
179 void * error_cb_data;
180 guestfs_log_message_cb log_message_cb;
181 void * log_message_cb_data;
182 guestfs_subprocess_quit_cb subprocess_quit_cb;
183 void * subprocess_quit_cb_data;
184 guestfs_launch_done_cb launch_done_cb;
185 void * launch_done_cb_data;
186 guestfs_close_cb close_cb;
187 void * close_cb_data;
192 gl_lock_define_initialized (static, handles_lock);
193 static guestfs_h *handles = NULL;
194 static int atexit_handler_set = 0;
197 guestfs_create (void)
202 g = malloc (sizeof (*g));
205 memset (g, 0, sizeof (*g));
214 g->error_cb = default_error_cb;
215 g->error_cb_data = NULL;
217 g->recovery_proc = 1;
219 str = getenv ("LIBGUESTFS_DEBUG");
220 g->verbose = str != NULL && STREQ (str, "1");
222 str = getenv ("LIBGUESTFS_TRACE");
223 g->trace = str != NULL && STREQ (str, "1");
225 str = getenv ("LIBGUESTFS_PATH");
226 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
227 if (!g->path) goto error;
229 str = getenv ("LIBGUESTFS_QEMU");
230 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
231 if (!g->qemu) goto error;
233 str = getenv ("LIBGUESTFS_APPEND");
235 g->append = strdup (str);
236 if (!g->append) goto error;
239 /* Choose a suitable memory size. Previously we tried to choose
240 * a minimal memory size, but this isn't really necessary since
241 * recent QEMU and KVM don't do anything nasty like locking
242 * memory into core any more. Thus we can safely choose a
243 * large, generous amount of memory, and it'll just get swapped
244 * on smaller systems.
246 str = getenv ("LIBGUESTFS_MEMSIZE");
248 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
249 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
255 /* Start with large serial numbers so they are easy to spot
256 * inside the protocol.
258 g->msg_next_serial = 0x00123400;
260 /* Link the handles onto a global list. */
261 gl_lock_lock (handles_lock);
264 if (!atexit_handler_set) {
265 atexit (close_handles);
266 atexit_handler_set = 1;
268 gl_lock_unlock (handles_lock);
271 fprintf (stderr, "new guestfs handle %p\n", g);
284 guestfs_close (guestfs_h *g)
290 if (g->state == NO_HANDLE) {
291 /* Not safe to call 'error' here, so ... */
292 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
297 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
299 /* Run user close callback before anything else. */
301 g->close_cb (g, g->close_cb_data);
303 /* Try to sync if autosync flag is set. */
304 if (g->autosync && g->state == READY) {
305 guestfs_umount_all (g);
309 /* Remove any handlers that might be called back before we kill the
312 g->log_message_cb = NULL;
314 if (g->state != CONFIG)
315 guestfs_kill_subprocess (g);
328 /* Wait for subprocess(es) to exit. */
329 waitpid (g->pid, NULL, 0);
330 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
332 /* Remove tmpfiles. */
334 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
337 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
340 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
349 for (i = 0; i < g->cmdline_size; ++i)
350 free (g->cmdline[i]);
354 /* Mark the handle as dead before freeing it. */
355 g->state = NO_HANDLE;
357 gl_lock_lock (handles_lock);
361 for (gg = handles; gg->next != g; gg = gg->next)
365 gl_lock_unlock (handles_lock);
367 free (g->last_error);
372 free (g->qemu_version);
376 /* Close all open handles (called from atexit(3)). */
380 while (handles) guestfs_close (handles);
384 guestfs_last_error (guestfs_h *g)
386 return g->last_error;
390 set_last_error (guestfs_h *g, const char *msg)
392 free (g->last_error);
393 g->last_error = strdup (msg);
397 default_error_cb (guestfs_h *g, void *data, const char *msg)
399 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
403 guestfs_error (guestfs_h *g, const char *fs, ...)
409 int err = vasprintf (&msg, fs, args);
414 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
415 set_last_error (g, msg);
421 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
428 int err = vasprintf (&msg, fs, args);
433 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
435 strerror_r (errnum, buf, sizeof buf);
439 buf = strerror_r (errnum, _buf, sizeof _buf);
442 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
446 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
447 set_last_error (g, msg);
453 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
455 void *ptr = malloc (nbytes);
456 if (nbytes > 0 && !ptr) g->abort_cb ();
460 /* Return 1 if an array of N objects, each of size S, cannot exist due
461 to size arithmetic overflow. S must be positive and N must be
462 nonnegative. This is a macro, not an inline function, so that it
463 works correctly even when SIZE_MAX < N.
465 By gnulib convention, SIZE_MAX represents overflow in size
466 calculations, so the conservative dividend to use here is
467 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
468 However, malloc (SIZE_MAX) fails on all known hosts where
469 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
470 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
471 branch when S is known to be 1. */
472 # define xalloc_oversized(n, s) \
473 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
475 /* Technically we should add an autoconf test for this, testing for the desired
476 functionality, like what's done in gnulib, but for now, this is fine. */
477 #if defined(__GLIBC__)
478 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
480 #define HAVE_GNU_CALLOC 0
483 /* Allocate zeroed memory for N elements of S bytes, with error
484 checking. S must be nonzero. */
486 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
488 /* From gnulib's calloc function in xmalloc.c. */
490 /* Test for overflow, since some calloc implementations don't have
491 proper overflow checks. But omit overflow and size-zero tests if
492 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
493 returns NULL if successful. */
494 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
495 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
501 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
503 void *p = realloc (ptr, nbytes);
504 if (nbytes > 0 && !p) g->abort_cb ();
509 guestfs_safe_strdup (guestfs_h *g, const char *str)
511 char *s = strdup (str);
512 if (!s) g->abort_cb ();
517 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
519 void *p = malloc (size);
520 if (!p) g->abort_cb ();
521 memcpy (p, ptr, size);
526 xwrite (int fd, const void *v_buf, size_t len)
528 const char *buf = v_buf;
532 r = write (fd, buf, len);
544 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
550 guestfs_get_out_of_memory_handler (guestfs_h *g)
556 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
559 g->error_cb_data = data;
562 guestfs_error_handler_cb
563 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
565 if (data_rtn) *data_rtn = g->error_cb_data;
570 guestfs__set_verbose (guestfs_h *g, int v)
577 guestfs__get_verbose (guestfs_h *g)
583 guestfs__set_autosync (guestfs_h *g, int a)
590 guestfs__get_autosync (guestfs_h *g)
596 guestfs__set_path (guestfs_h *g, const char *path)
603 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
608 guestfs__get_path (guestfs_h *g)
614 guestfs__set_qemu (guestfs_h *g, const char *qemu)
619 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
624 guestfs__get_qemu (guestfs_h *g)
630 guestfs__set_append (guestfs_h *g, const char *append)
635 g->append = append ? safe_strdup (g, append) : NULL;
640 guestfs__get_append (guestfs_h *g)
646 guestfs__set_memsize (guestfs_h *g, int memsize)
648 g->memsize = memsize;
653 guestfs__get_memsize (guestfs_h *g)
659 guestfs__set_selinux (guestfs_h *g, int selinux)
661 g->selinux = selinux;
666 guestfs__get_selinux (guestfs_h *g)
672 guestfs__get_pid (guestfs_h *g)
677 error (g, "get_pid: no qemu subprocess");
682 struct guestfs_version *
683 guestfs__version (guestfs_h *g)
685 struct guestfs_version *r;
687 r = safe_malloc (g, sizeof *r);
688 r->major = PACKAGE_VERSION_MAJOR;
689 r->minor = PACKAGE_VERSION_MINOR;
690 r->release = PACKAGE_VERSION_RELEASE;
691 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
696 guestfs__set_trace (guestfs_h *g, int t)
703 guestfs__get_trace (guestfs_h *g)
709 guestfs__set_direct (guestfs_h *g, int d)
716 guestfs__get_direct (guestfs_h *g)
722 guestfs__set_recovery_proc (guestfs_h *g, int f)
724 g->recovery_proc = !!f;
729 guestfs__get_recovery_proc (guestfs_h *g)
731 return g->recovery_proc;
734 /* Add a string to the current command line. */
736 incr_cmdline_size (guestfs_h *g)
738 if (g->cmdline == NULL) {
739 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
741 g->cmdline = safe_malloc (g, sizeof (char *));
742 g->cmdline[0] = NULL;
746 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
750 add_cmdline (guestfs_h *g, const char *str)
752 if (g->state != CONFIG) {
754 _("command line cannot be altered after qemu subprocess launched"));
758 incr_cmdline_size (g);
759 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
764 guestfs__config (guestfs_h *g,
765 const char *qemu_param, const char *qemu_value)
767 if (qemu_param[0] != '-') {
768 error (g, _("guestfs_config: parameter must begin with '-' character"));
772 /* A bit fascist, but the user will probably break the extra
773 * parameters that we add if they try to set any of these.
775 if (STREQ (qemu_param, "-kernel") ||
776 STREQ (qemu_param, "-initrd") ||
777 STREQ (qemu_param, "-nographic") ||
778 STREQ (qemu_param, "-serial") ||
779 STREQ (qemu_param, "-full-screen") ||
780 STREQ (qemu_param, "-std-vga") ||
781 STREQ (qemu_param, "-vnc")) {
782 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
786 if (add_cmdline (g, qemu_param) != 0) return -1;
788 if (qemu_value != NULL) {
789 if (add_cmdline (g, qemu_value) != 0) return -1;
796 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
797 const char *drive_if)
799 size_t len = strlen (filename) + 64;
802 if (strchr (filename, ',') != NULL) {
803 error (g, _("filename cannot contain ',' (comma) character"));
807 /* cache=off improves reliability in the event of a host crash.
809 * However this option causes qemu to try to open the file with
810 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
811 * So we check if we can open the file with or without O_DIRECT,
812 * and use cache=off (or not) accordingly.
814 * This test also checks for the presence of the file, which
815 * is a documented semantic of this interface.
817 int fd = open (filename, O_RDONLY|O_DIRECT);
820 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
822 fd = open (filename, O_RDONLY);
825 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
827 perrorf (g, "%s", filename);
832 return guestfs__config (g, "-drive", buf);
836 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
837 const char *drive_if)
839 if (strchr (filename, ',') != NULL) {
840 error (g, _("filename cannot contain ',' (comma) character"));
844 if (access (filename, F_OK) == -1) {
845 perrorf (g, "%s", filename);
849 if (qemu_supports (g, NULL) == -1)
852 /* Only SCSI and virtio drivers support readonly mode.
853 * This is only supported as a QEMU feature since 2010/01.
856 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
857 qemu_supports (g, "readonly=on"))
860 size_t len = strlen (filename) + 100;
863 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
865 supports_ro ? "readonly=on," : "",
868 return guestfs__config (g, "-drive", buf);
872 guestfs__add_drive (guestfs_h *g, const char *filename)
874 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
878 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
880 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
884 guestfs__add_cdrom (guestfs_h *g, const char *filename)
886 if (strchr (filename, ',') != NULL) {
887 error (g, _("filename cannot contain ',' (comma) character"));
891 if (access (filename, F_OK) == -1) {
892 perrorf (g, "%s", filename);
896 return guestfs__config (g, "-cdrom", filename);
899 /* Returns true iff file is contained in dir. */
901 dir_contains_file (const char *dir, const char *file)
903 int dirlen = strlen (dir);
904 int filelen = strlen (file);
905 int len = dirlen+filelen+2;
908 snprintf (path, len, "%s/%s", dir, file);
909 return access (path, F_OK) == 0;
912 /* Returns true iff every listed file is contained in 'dir'. */
914 dir_contains_files (const char *dir, ...)
919 va_start (args, dir);
920 while ((file = va_arg (args, const char *)) != NULL) {
921 if (!dir_contains_file (dir, file)) {
930 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
931 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
932 static int is_openable (guestfs_h *g, const char *path, int flags);
933 static void print_cmdline (guestfs_h *g);
935 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
936 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
939 guestfs__launch (guestfs_h *g)
942 char dir_template[PATH_MAX];
947 char *path, *pelem, *pend;
948 char *kernel = NULL, *initrd = NULL;
949 int null_vmchannel_sock;
951 struct sockaddr_un addr;
955 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
959 if (g->state != CONFIG) {
960 error (g, _("the libguestfs handle has already been launched"));
964 /* Start the clock ... */
965 gettimeofday (&g->launch_t, NULL);
967 /* Make the temporary directory. */
974 tmpdir = getenv ("TMPDIR") ? : tmpdir;
975 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
978 g->tmpdir = safe_strdup (g, dir_template);
979 if (mkdtemp (g->tmpdir) == NULL) {
980 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
985 /* First search g->path for the supermin appliance, and try to
986 * synthesize a kernel and initrd from that. If it fails, we
987 * try the path search again looking for a backup ordinary
990 pelem = path = safe_strdup (g, g->path);
992 pend = strchrnul (pelem, ':');
993 pmore = *pend == ':';
997 /* Empty element of "." means cwd. */
998 if (len == 0 || (len == 1 && *pelem == '.')) {
1001 "looking for supermin appliance in current directory\n");
1002 if (dir_contains_files (".",
1003 "supermin.d", "kmod.whitelist", NULL)) {
1004 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
1009 /* Look at <path>/supermin* etc. */
1012 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
1014 if (dir_contains_files (pelem,
1015 "supermin.d", "kmod.whitelist", NULL)) {
1016 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1027 if (kernel == NULL || initrd == NULL) {
1028 /* Search g->path for the kernel and initrd. */
1029 pelem = path = safe_strdup (g, g->path);
1031 pend = strchrnul (pelem, ':');
1032 pmore = *pend == ':';
1036 /* Empty element or "." means cwd. */
1037 if (len == 0 || (len == 1 && *pelem == '.')) {
1040 "looking for appliance in current directory\n");
1041 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1042 kernel = safe_strdup (g, kernel_name);
1043 initrd = safe_strdup (g, initrd_name);
1047 /* Look at <path>/kernel etc. */
1050 fprintf (stderr, "looking for appliance in %s\n", pelem);
1052 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1053 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1054 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1055 sprintf (kernel, "%s/%s", pelem, kernel_name);
1056 sprintf (initrd, "%s/%s", pelem, initrd_name);
1067 if (kernel == NULL || initrd == NULL) {
1068 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1069 kernel_name, initrd_name, g->path);
1074 print_timestamped_message (g, "begin testing qemu features");
1076 /* Get qemu help text and version. */
1077 if (qemu_supports (g, NULL) == -1)
1080 /* Choose which vmchannel implementation to use. */
1081 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
1082 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1083 * networking in qemu) but no other vmchannel support. The daemon
1084 * will connect back to a random port number on localhost.
1086 struct sockaddr_in addr;
1087 socklen_t addrlen = sizeof addr;
1089 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1090 if (g->sock == -1) {
1091 perrorf (g, "socket");
1094 addr.sin_family = AF_INET;
1095 addr.sin_port = htons (0);
1096 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1097 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1098 perrorf (g, "bind");
1102 if (listen (g->sock, 256) == -1) {
1103 perrorf (g, "listen");
1107 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1108 perrorf (g, "getsockname");
1112 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1113 perrorf (g, "fcntl");
1117 null_vmchannel_sock = ntohs (addr.sin_port);
1119 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1121 /* Using some vmchannel impl. We need to create a local Unix
1122 * domain socket for qemu to use.
1124 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1126 null_vmchannel_sock = 0;
1130 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1131 perrorf (g, "pipe");
1137 print_timestamped_message (g, "finished testing qemu features");
1141 perrorf (g, "fork");
1151 if (r == 0) { /* Child (qemu). */
1153 const char *vmchannel = NULL;
1155 /* Set up the full command line. Do this in the subprocess so we
1156 * don't need to worry about cleaning up.
1158 g->cmdline[0] = g->qemu;
1160 /* qemu sometimes needs this option to enable hardware
1161 * virtualization, but some versions of 'qemu-kvm' will use KVM
1162 * regardless (even where this option appears in the help text).
1163 * It is rumoured that there are versions of qemu where supplying
1164 * this option when hardware virtualization is not available will
1165 * cause qemu to fail, so we we have to check at least that
1166 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1167 * might be openable by qemu but not by us (think: SELinux) in
1168 * which case the user would not get hardware virtualization,
1169 * although at least shouldn't fail. A giant clusterfuck with the
1170 * qemu command line, again.
1172 if (qemu_supports (g, "-enable-kvm") &&
1173 is_openable (g, "/dev/kvm", O_RDWR))
1174 add_cmdline (g, "-enable-kvm");
1176 /* Newer versions of qemu (from around 2009/12) changed the
1177 * behaviour of monitors so that an implicit '-monitor stdio' is
1178 * assumed if we are in -nographic mode and there is no other
1179 * -monitor option. Only a single stdio device is allowed, so
1180 * this broke the '-serial stdio' option. There is a new flag
1181 * called -nodefaults which gets rid of all this default crud, so
1182 * let's use that to avoid this and any future surprises.
1184 if (qemu_supports (g, "-nodefaults"))
1185 add_cmdline (g, "-nodefaults");
1187 add_cmdline (g, "-nographic");
1188 add_cmdline (g, "-serial");
1189 add_cmdline (g, "stdio");
1191 snprintf (buf, sizeof buf, "%d", g->memsize);
1192 add_cmdline (g, "-m");
1193 add_cmdline (g, buf);
1195 /* Force exit instead of reboot on panic */
1196 add_cmdline (g, "-no-reboot");
1198 /* These options recommended by KVM developers to improve reliability. */
1199 if (qemu_supports (g, "-no-hpet"))
1200 add_cmdline (g, "-no-hpet");
1202 if (qemu_supports (g, "-rtc-td-hack"))
1203 add_cmdline (g, "-rtc-td-hack");
1205 /* If qemu has SLIRP (user mode network) enabled then we can get
1206 * away with "no vmchannel", where we just connect back to a random
1209 if (null_vmchannel_sock) {
1210 add_cmdline (g, "-net");
1211 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1213 snprintf (buf, sizeof buf,
1214 "guestfs_vmchannel=tcp:" ROUTER ":%d",
1215 null_vmchannel_sock);
1216 vmchannel = strdup (buf);
1219 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1221 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1223 * The original suggested format doesn't work, see:
1225 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1227 * However Gerd Hoffman privately suggested to me using -chardev
1228 * instead, which does work.
1230 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1231 snprintf (buf, sizeof buf,
1232 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1234 add_cmdline (g, "-chardev");
1235 add_cmdline (g, buf);
1237 snprintf (buf, sizeof buf,
1238 "user,vlan=0,net=" NETWORK ","
1239 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1240 "-chardev:guestfsvmc");
1242 add_cmdline (g, "-net");
1243 add_cmdline (g, buf);
1245 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1248 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1249 * syntax, or if not then we'll get a quick failure.
1252 snprintf (buf, sizeof buf,
1253 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1255 add_cmdline (g, "-net");
1256 add_cmdline (g, buf);
1257 add_cmdline (g, "-net");
1258 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1260 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1262 add_cmdline (g, "-net");
1263 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1265 #define LINUX_CMDLINE \
1266 "panic=1 " /* force kernel to panic if daemon exits */ \
1267 "console=ttyS0 " /* serial console */ \
1268 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1269 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1270 "acpi=off " /* we don't need ACPI, turn it off */ \
1271 "printk.time=1 " /* display timestamp before kernel messages */ \
1272 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1274 /* Linux kernel command line. */
1275 snprintf (buf, sizeof buf,
1277 "%s " /* (selinux) */
1278 "%s " /* (vmchannel) */
1279 "%s " /* (verbose) */
1280 "TERM=%s " /* (TERM environment variable) */
1281 "%s", /* (append) */
1282 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1283 vmchannel ? vmchannel : "",
1284 g->verbose ? "guestfs_verbose=1" : "",
1285 getenv ("TERM") ? : "linux",
1286 g->append ? g->append : "");
1288 add_cmdline (g, "-kernel");
1289 add_cmdline (g, (char *) kernel);
1290 add_cmdline (g, "-initrd");
1291 add_cmdline (g, (char *) initrd);
1292 add_cmdline (g, "-append");
1293 add_cmdline (g, buf);
1295 /* Finish off the command line. */
1296 incr_cmdline_size (g);
1297 g->cmdline[g->cmdline_size-1] = NULL;
1303 /* Set up stdin, stdout. */
1309 if (dup (wfd[0]) == -1) {
1311 perror ("dup failed");
1312 _exit (EXIT_FAILURE);
1314 if (dup (rfd[1]) == -1)
1322 /* Set up a new process group, so we can signal this process
1323 * and all subprocesses (eg. if qemu is really a shell script).
1328 setenv ("LC_ALL", "C", 1);
1330 execv (g->qemu, g->cmdline); /* Run qemu. */
1332 _exit (EXIT_FAILURE);
1335 /* Parent (library). */
1343 /* Fork the recovery process off which will kill qemu if the parent
1344 * process fails to do so (eg. if the parent segfaults).
1346 g->recoverypid = -1;
1347 if (g->recovery_proc) {
1350 pid_t qemu_pid = g->pid;
1351 pid_t parent_pid = getppid ();
1353 /* Writing to argv is hideously complicated and error prone. See:
1354 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1357 /* Loop around waiting for one or both of the other processes to
1358 * disappear. It's fair to say this is very hairy. The PIDs that
1359 * we are looking at might be reused by another process. We are
1360 * effectively polling. Is the cure worse than the disease?
1363 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1364 _exit (EXIT_SUCCESS);
1365 if (kill (parent_pid, 0) == -1) {
1366 /* Parent's gone away, qemu still around, so kill qemu. */
1368 _exit (EXIT_SUCCESS);
1374 /* Don't worry, if the fork failed, this will be -1. The recovery
1375 * process isn't essential.
1381 /* Close the other ends of the pipe. */
1385 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1386 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1387 perrorf (g, "fcntl");
1391 g->fd[0] = wfd[1]; /* stdin of child */
1392 g->fd[1] = rfd[0]; /* stdout of child */
1394 g->fd[0] = open ("/dev/null", O_RDWR);
1395 if (g->fd[0] == -1) {
1396 perrorf (g, "open /dev/null");
1399 g->fd[1] = dup (g->fd[0]);
1400 if (g->fd[1] == -1) {
1407 if (null_vmchannel_sock) {
1411 /* Null vmchannel implementation: We listen on g->sock for a
1412 * connection. The connection could come from any local process
1413 * so we must check it comes from the appliance (or at least
1414 * from our UID) for security reasons.
1416 while (sock == -1) {
1417 sock = accept_from_daemon (g);
1421 if (check_peer_euid (g, sock, &uid) == -1)
1423 if (uid != geteuid ()) {
1425 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1426 uid, null_vmchannel_sock);
1433 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1434 perrorf (g, "fcntl");
1441 /* Other vmchannel. Open the Unix socket.
1443 * The vmchannel implementation that got merged with qemu sucks in
1444 * a number of ways. Both ends do connect(2), which means that no
1445 * one knows what, if anything, is connected to the other end, or
1446 * if it becomes disconnected. Even worse, we have to wait some
1447 * indeterminate time for qemu to create the socket and connect to
1448 * it (which happens very early in qemu's start-up), so any code
1449 * that uses vmchannel is inherently racy. Hence this silly loop.
1451 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1452 if (g->sock == -1) {
1453 perrorf (g, "socket");
1457 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1458 perrorf (g, "fcntl");
1462 addr.sun_family = AF_UNIX;
1463 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1464 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1467 /* Always sleep at least once to give qemu a small chance to start up. */
1470 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1471 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1474 if (errno != ENOENT)
1475 perrorf (g, "connect");
1480 error (g, _("failed to connect to vmchannel socket"));
1486 g->state = LAUNCHING;
1488 /* Wait for qemu to start and to connect back to us via vmchannel and
1489 * send the GUESTFS_LAUNCH_FLAG message.
1493 r = recv_from_daemon (g, &size, &buf);
1496 if (r == -1) return -1;
1498 if (size != GUESTFS_LAUNCH_FLAG) {
1499 error (g, _("guestfs_launch failed, see earlier error messages"));
1504 print_timestamped_message (g, "appliance is up");
1506 /* This is possible in some really strange situations, such as
1507 * guestfsd starts up OK but then qemu immediately exits. Check for
1508 * it because the caller is probably expecting to be able to send
1509 * commands after this function returns.
1511 if (g->state != READY) {
1512 error (g, _("qemu launched and contacted daemon, but state != READY"));
1523 if (g->pid > 0) kill (g->pid, 9);
1524 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1525 waitpid (g->pid, NULL, 0);
1526 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1531 memset (&g->launch_t, 0, sizeof g->launch_t);
1544 /* This function is used to print the qemu command line before it gets
1545 * executed, when in verbose mode.
1548 print_cmdline (guestfs_h *g)
1553 while (g->cmdline[i]) {
1554 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1555 fprintf (stderr, " \\\n ");
1557 if (i > 0) fputc (' ', stderr);
1559 /* Does it need shell quoting? This only deals with simple cases. */
1560 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1562 if (needs_quote) fputc ('\'', stderr);
1563 fprintf (stderr, "%s", g->cmdline[i]);
1564 if (needs_quote) fputc ('\'', stderr);
1568 fputc ('\n', stderr);
1571 /* This function does the hard work of building the supermin appliance
1572 * on the fly. 'path' is the directory containing the control files.
1573 * 'kernel' and 'initrd' are where we will return the names of the
1574 * kernel and initrd (only initrd is built). The work is done by
1575 * an external script. We just tell it where to put the result.
1578 build_supermin_appliance (guestfs_h *g, const char *path,
1579 char **kernel, char **initrd)
1585 print_timestamped_message (g, "begin building supermin appliance");
1587 len = strlen (g->tmpdir);
1588 *kernel = safe_malloc (g, len + 8);
1589 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1590 *initrd = safe_malloc (g, len + 8);
1591 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1593 snprintf (cmd, sizeof cmd,
1594 "febootstrap-supermin-helper%s "
1595 "-k '%s/kmod.whitelist' "
1599 g->verbose ? " --verbose" : "",
1604 print_timestamped_message (g, "%s", cmd);
1607 if (r == -1 || WEXITSTATUS(r) != 0) {
1608 error (g, _("external command failed: %s"), cmd);
1611 *kernel = *initrd = NULL;
1616 print_timestamped_message (g, "finished building supermin appliance");
1621 /* Compute Y - X and return the result in milliseconds.
1622 * Approximately the same as this code:
1623 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1626 timeval_diff (const struct timeval *x, const struct timeval *y)
1630 msec = (y->tv_sec - x->tv_sec) * 1000;
1631 msec += (y->tv_usec - x->tv_usec) / 1000;
1636 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1643 va_start (args, fs);
1644 err = vasprintf (&msg, fs, args);
1647 if (err < 0) return;
1649 gettimeofday (&tv, NULL);
1651 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1652 timeval_diff (&g->launch_t, &tv), msg);
1657 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1659 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1660 * 'qemu -version' so we know what options this qemu supports and
1664 test_qemu (guestfs_h *g)
1669 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1671 fp = popen (cmd, "r");
1672 /* qemu -help should always work (qemu -version OTOH wasn't
1673 * supported by qemu 0.9). If this command doesn't work then it
1674 * probably indicates that the qemu binary is missing.
1677 /* XXX This error is never printed, even if the qemu binary
1678 * doesn't exist. Why?
1681 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1685 if (read_all (g, fp, &g->qemu_help) == -1)
1688 if (pclose (fp) == -1)
1691 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1694 fp = popen (cmd, "r");
1696 /* Intentionally ignore errors. */
1697 read_all (g, fp, &g->qemu_version);
1705 read_all (guestfs_h *g, FILE *fp, char **ret)
1712 *ret = safe_realloc (g, *ret, n + 1);
1717 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1719 r = fread (p, 1, BUFSIZ, fp);
1721 perrorf (g, "read");
1728 /* Test if option is supported by qemu command line (just by grepping
1731 * The first time this is used, it has to run the external qemu
1732 * binary. If that fails, it returns -1.
1734 * To just do the first-time run of the qemu binary, call this with
1735 * option == NULL, in which case it will return -1 if there was an
1739 qemu_supports (guestfs_h *g, const char *option)
1741 if (!g->qemu_help) {
1742 if (test_qemu (g) == -1)
1749 return strstr (g->qemu_help, option) != NULL;
1752 /* Check if a file can be opened. */
1754 is_openable (guestfs_h *g, const char *path, int flags)
1756 int fd = open (path, flags);
1766 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1767 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1768 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1771 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1773 #if CAN_CHECK_PEER_EUID
1774 struct sockaddr_in peer;
1775 socklen_t addrlen = sizeof peer;
1777 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1778 perrorf (g, "getpeername");
1782 if (peer.sin_family != AF_INET ||
1783 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1784 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1785 peer.sin_family, inet_ntoa (peer.sin_addr));
1789 struct sockaddr_in our;
1790 addrlen = sizeof our;
1791 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1792 perrorf (g, "getsockname");
1796 FILE *fp = fopen ("/proc/net/tcp", "r");
1798 perrorf (g, "/proc/net/tcp");
1803 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1804 error (g, "unexpected end of file in /proc/net/tcp");
1809 while (fgets (line, sizeof line, fp) != NULL) {
1810 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1811 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1814 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1816 &line_our_addr, &line_our_port,
1817 &line_peer_addr, &line_peer_port,
1818 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1820 /* Note about /proc/net/tcp: local_address and rem_address are
1821 * always in network byte order. However the port part is
1822 * always in host byte order.
1824 * The sockname and peername that we got above are in network
1825 * byte order. So we have to byte swap the port but not the
1828 if (line_our_addr == our.sin_addr.s_addr &&
1829 line_our_port == ntohs (our.sin_port) &&
1830 line_peer_addr == peer.sin_addr.s_addr &&
1831 line_peer_port == ntohs (peer.sin_port)) {
1839 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1842 #else /* !CAN_CHECK_PEER_EUID */
1843 /* This function exists but should never be called in this
1847 #endif /* !CAN_CHECK_PEER_EUID */
1850 /* You had to call this function after launch in versions <= 1.0.70,
1851 * but it is now a no-op.
1854 guestfs__wait_ready (guestfs_h *g)
1856 if (g->state != READY) {
1857 error (g, _("qemu has not been launched yet"));
1865 guestfs__kill_subprocess (guestfs_h *g)
1867 if (g->state == CONFIG) {
1868 error (g, _("no subprocess to kill"));
1873 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1875 if (g->pid > 0) kill (g->pid, SIGTERM);
1876 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1881 /* Access current state. */
1883 guestfs__is_config (guestfs_h *g)
1885 return g->state == CONFIG;
1889 guestfs__is_launching (guestfs_h *g)
1891 return g->state == LAUNCHING;
1895 guestfs__is_ready (guestfs_h *g)
1897 return g->state == READY;
1901 guestfs__is_busy (guestfs_h *g)
1903 return g->state == BUSY;
1907 guestfs__get_state (guestfs_h *g)
1913 guestfs_set_log_message_callback (guestfs_h *g,
1914 guestfs_log_message_cb cb, void *opaque)
1916 g->log_message_cb = cb;
1917 g->log_message_cb_data = opaque;
1921 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1922 guestfs_subprocess_quit_cb cb, void *opaque)
1924 g->subprocess_quit_cb = cb;
1925 g->subprocess_quit_cb_data = opaque;
1929 guestfs_set_launch_done_callback (guestfs_h *g,
1930 guestfs_launch_done_cb cb, void *opaque)
1932 g->launch_done_cb = cb;
1933 g->launch_done_cb_data = opaque;
1937 guestfs_set_close_callback (guestfs_h *g,
1938 guestfs_close_cb cb, void *opaque)
1941 g->close_cb_data = opaque;
1944 /*----------------------------------------------------------------------*/
1946 /* This is the code used to send and receive RPC messages and (for
1947 * certain types of message) to perform file transfers. This code is
1948 * driven from the generated actions (src/guestfs-actions.c). There
1949 * are five different cases to consider:
1951 * (1) A non-daemon function. There is no RPC involved at all, it's
1952 * all handled inside the library.
1954 * (2) A simple RPC (eg. "mount"). We write the request, then read
1955 * the reply. The sequence of calls is:
1957 * guestfs___set_busy
1960 * guestfs___end_busy
1962 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1963 * request, then write the file(s), then read the reply. The sequence
1966 * guestfs___set_busy
1968 * guestfs___send_file (possibly multiple times)
1970 * guestfs___end_busy
1972 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1973 * request, then read the reply, then read the file(s). The sequence
1976 * guestfs___set_busy
1979 * guestfs___recv_file (possibly multiple times)
1980 * guestfs___end_busy
1982 * (5) Both FileOut and FileIn parameters. There are no calls like
1983 * this in the current API, but they would be implemented as a
1984 * combination of cases (3) and (4).
1986 * During all writes and reads, we also select(2) on qemu stdout
1987 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1988 * anything received is passed up through the log_message_cb. This is
1989 * also the reason why all the sockets are non-blocking. We also have
1990 * to check for EOF (qemu died). All of this is handled by the
1991 * functions send_to_daemon and recv_from_daemon.
1995 guestfs___set_busy (guestfs_h *g)
1997 if (g->state != READY) {
1998 error (g, _("guestfs_set_busy: called when in state %d != READY"),
2007 guestfs___end_busy (guestfs_h *g)
2021 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
2027 /* This is called if we detect EOF, ie. qemu died. */
2029 child_cleanup (guestfs_h *g)
2032 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
2034 /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
2035 if (g->recoverypid > 0) kill (g->recoverypid, 9);
2036 waitpid (g->pid, NULL, 0);
2037 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
2046 memset (&g->launch_t, 0, sizeof g->launch_t);
2048 if (g->subprocess_quit_cb)
2049 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2053 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
2061 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2065 /* QEMU's console emulates a 16550A serial port. The real 16550A
2066 * device has a small FIFO buffer (16 bytes) which means here we see
2067 * lots of small reads of 1-16 bytes in length, usually single
2070 n = read (fd, buf, sizeof buf);
2072 /* Hopefully this indicates the qemu child process has died. */
2076 /* We weren't expecting eof here (called from launch) so place
2077 * something in the error buffer. RHBZ#588851.
2079 error (g, "child process died unexpectedly");
2085 if (errno == EINTR || errno == EAGAIN)
2088 perrorf (g, "read");
2092 /* In verbose mode, copy all log messages to stderr. */
2094 ignore_value (write (STDERR_FILENO, buf, n));
2096 /* It's an actual log message, send it upwards if anyone is listening. */
2097 if (g->log_message_cb)
2098 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2104 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2113 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2116 n = read (fd, buf, 4);
2118 /* Hopefully this indicates the qemu child process has died. */
2124 if (errno == EINTR || errno == EAGAIN)
2127 perrorf (g, "read");
2131 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2132 xdr_uint32_t (&xdr, &flag);
2135 if (flag != GUESTFS_CANCEL_FLAG) {
2136 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2137 flag, GUESTFS_CANCEL_FLAG);
2144 /* This writes the whole N bytes of BUF to the daemon socket.
2146 * If the whole write is successful, it returns 0.
2147 * If there was an error, it returns -1.
2148 * If the daemon sent a cancellation message, it returns -2.
2150 * It also checks qemu stdout for log messages and passes those up
2151 * through log_message_cb.
2153 * It also checks for EOF (qemu died) and passes that up through the
2154 * child_cleanup function above.
2157 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2159 const char *buf = v_buf;
2165 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2170 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2171 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2172 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2174 int max_fd = MAX (g->sock, g->fd[1]);
2179 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2181 if (errno == EINTR || errno == EAGAIN)
2183 perrorf (g, "select");
2187 if (FD_ISSET (g->fd[1], &rset2)) {
2188 if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
2191 if (FD_ISSET (g->sock, &rset2)) {
2192 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2196 if (FD_ISSET (g->sock, &wset2)) {
2197 r = write (g->sock, buf, n);
2199 if (errno == EINTR || errno == EAGAIN)
2201 perrorf (g, "write");
2202 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2214 /* This reads a single message, file chunk, launch flag or
2215 * cancellation flag from the daemon. If something was read, it
2216 * returns 0, otherwise -1.
2218 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2220 * *size_rtn returns the size of the returned message or it may be
2221 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2223 * *buf_rtn is returned containing the message (if any) or will be set
2224 * to NULL. *buf_rtn must be freed by the caller.
2226 * It also checks qemu stdout for log messages and passes those up
2227 * through log_message_cb.
2229 * It also checks for EOF (qemu died) and passes that up through the
2230 * child_cleanup function above.
2233 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2239 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2240 g, g->state, size_rtn, buf_rtn);
2244 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2245 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2247 int max_fd = MAX (g->sock, g->fd[1]);
2253 /* nr is the size of the message, but we prime it as -4 because we
2254 * have to read the message length word first.
2258 while (nr < (ssize_t) *size_rtn) {
2260 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2262 if (errno == EINTR || errno == EAGAIN)
2264 perrorf (g, "select");
2270 if (FD_ISSET (g->fd[1], &rset2)) {
2271 if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
2277 if (FD_ISSET (g->sock, &rset2)) {
2278 if (nr < 0) { /* Have we read the message length word yet? */
2279 r = read (g->sock, lenbuf+nr+4, -nr);
2281 if (errno == EINTR || errno == EAGAIN)
2284 perrorf (g, "read");
2285 /* Under some circumstances we see "Connection reset by peer"
2286 * here when the child dies suddenly. Catch this and call
2287 * the cleanup function, same as for EOF.
2289 if (err == ECONNRESET)
2294 error (g, _("unexpected end of file when reading from daemon"));
2300 if (nr < 0) /* Still not got the whole length word. */
2304 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2305 xdr_uint32_t (&xdr, size_rtn);
2308 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2309 if (g->state != LAUNCHING)
2310 error (g, _("received magic signature from guestfsd, but in state %d"),
2314 if (g->launch_done_cb)
2315 g->launch_done_cb (g, g->launch_done_cb_data);
2319 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2321 /* If this happens, it's pretty bad and we've probably lost
2324 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2325 error (g, _("message length (%u) > maximum possible size (%d)"),
2326 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2330 /* Allocate the complete buffer, size now known. */
2331 *buf_rtn = safe_malloc (g, *size_rtn);
2335 size_t sizetoread = *size_rtn - nr;
2336 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2338 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2340 if (errno == EINTR || errno == EAGAIN)
2342 perrorf (g, "read");
2348 error (g, _("unexpected end of file when reading from daemon"));
2358 /* Got the full message, caller can start processing it. */
2359 #ifdef ENABLE_PACKET_DUMP
2363 for (i = 0; i < nr; i += 16) {
2364 printf ("%04zx: ", i);
2365 for (j = i; j < MIN (i+16, nr); ++j)
2366 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2367 for (; j < i+16; ++j)
2370 for (j = i; j < MIN (i+16, nr); ++j)
2371 if (c_isprint ((*(char **)buf_rtn)[j]))
2372 printf ("%c", (*(char **)buf_rtn)[j]);
2375 for (; j < i+16; ++j)
2385 /* This is very much like recv_from_daemon above, but g->sock is
2386 * a listening socket and we are accepting a new connection on
2387 * that socket instead of reading anything. Returns the newly
2391 accept_from_daemon (guestfs_h *g)
2397 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2401 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2402 FD_SET (g->sock, &rset); /* Read socket for accept. */
2404 int max_fd = MAX (g->sock, g->fd[1]);
2407 while (sock == -1) {
2408 /* If the qemu process has died, clean up the zombie (RHBZ#579155).
2409 * By partially polling in the select below we ensure that this
2410 * function will be called eventually.
2412 waitpid (g->pid, NULL, WNOHANG);
2416 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
2417 int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
2419 if (errno == EINTR || errno == EAGAIN)
2421 perrorf (g, "select");
2425 if (FD_ISSET (g->fd[1], &rset2)) {
2426 if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
2429 if (FD_ISSET (g->sock, &rset2)) {
2430 sock = accept (g->sock, NULL, NULL);
2432 if (errno == EINTR || errno == EAGAIN)
2434 perrorf (g, "accept");
2444 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2446 struct guestfs_message_header hdr;
2449 int serial = g->msg_next_serial++;
2452 size_t msg_out_size;
2454 if (g->state != BUSY) {
2455 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2459 /* We have to allocate this message buffer on the heap because
2460 * it is quite large (although will be mostly unused). We
2461 * can't allocate it on the stack because in some environments
2462 * we have quite limited stack space available, notably when
2463 * running in the JVM.
2465 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2466 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2468 /* Serialize the header. */
2469 hdr.prog = GUESTFS_PROGRAM;
2470 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2472 hdr.direction = GUESTFS_DIRECTION_CALL;
2473 hdr.serial = serial;
2474 hdr.status = GUESTFS_STATUS_OK;
2476 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2477 error (g, _("xdr_guestfs_message_header failed"));
2481 /* Serialize the args. If any, because some message types
2482 * have no parameters.
2485 if (!(*xdrp) (&xdr, args)) {
2486 error (g, _("dispatch failed to marshal args"));
2491 /* Get the actual length of the message, resize the buffer to match
2492 * the actual length, and write the length word at the beginning.
2494 len = xdr_getpos (&xdr);
2497 msg_out = safe_realloc (g, msg_out, len + 4);
2498 msg_out_size = len + 4;
2500 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2501 xdr_uint32_t (&xdr, &len);
2504 r = send_to_daemon (g, msg_out, msg_out_size);
2505 if (r == -2) /* Ignore stray daemon cancellations. */
2518 static int cancel = 0; /* XXX Implement file cancellation. */
2519 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2520 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2521 static int send_file_cancellation (guestfs_h *g);
2522 static int send_file_complete (guestfs_h *g);
2528 * -2 daemon cancelled (we must read the error message)
2531 guestfs___send_file (guestfs_h *g, const char *filename)
2533 char buf[GUESTFS_MAX_CHUNK_SIZE];
2536 fd = open (filename, O_RDONLY);
2538 perrorf (g, "open: %s", filename);
2539 send_file_cancellation (g);
2540 /* Daemon sees cancellation and won't reply, so caller can
2546 /* Send file in chunked encoding. */
2548 r = read (fd, buf, sizeof buf);
2549 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2552 err = send_file_data (g, buf, r);
2554 if (err == -2) /* daemon sent cancellation */
2555 send_file_cancellation (g);
2560 if (cancel) { /* cancel from either end */
2561 send_file_cancellation (g);
2566 perrorf (g, "read: %s", filename);
2567 send_file_cancellation (g);
2571 /* End of file, but before we send that, we need to close
2572 * the file and check for errors.
2574 if (close (fd) == -1) {
2575 perrorf (g, "close: %s", filename);
2576 send_file_cancellation (g);
2580 return send_file_complete (g);
2583 /* Send a chunk of file data. */
2585 send_file_data (guestfs_h *g, const char *buf, size_t len)
2587 return send_file_chunk (g, 0, buf, len);
2590 /* Send a cancellation message. */
2592 send_file_cancellation (guestfs_h *g)
2594 return send_file_chunk (g, 1, NULL, 0);
2597 /* Send a file complete chunk. */
2599 send_file_complete (guestfs_h *g)
2602 return send_file_chunk (g, 0, buf, 0);
2606 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2610 guestfs_chunk chunk;
2613 size_t msg_out_size;
2615 if (g->state != BUSY) {
2616 error (g, _("send_file_chunk: state %d != READY"), g->state);
2620 /* Allocate the chunk buffer. Don't use the stack to avoid
2621 * excessive stack usage and unnecessary copies.
2623 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2624 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2626 /* Serialize the chunk. */
2627 chunk.cancel = cancel;
2628 chunk.data.data_len = buflen;
2629 chunk.data.data_val = (char *) buf;
2631 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2632 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2638 len = xdr_getpos (&xdr);
2641 /* Reduce the size of the outgoing message buffer to the real length. */
2642 msg_out = safe_realloc (g, msg_out, len + 4);
2643 msg_out_size = len + 4;
2645 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2646 xdr_uint32_t (&xdr, &len);
2648 r = send_to_daemon (g, msg_out, msg_out_size);
2650 /* Did the daemon send a cancellation message? */
2653 fprintf (stderr, "got daemon cancellation\n");
2669 /* Receive a reply. */
2671 guestfs___recv (guestfs_h *g, const char *fn,
2672 guestfs_message_header *hdr,
2673 guestfs_message_error *err,
2674 xdrproc_t xdrp, char *ret)
2682 r = recv_from_daemon (g, &size, &buf);
2686 /* This can happen if a cancellation happens right at the end
2687 * of us sending a FileIn parameter to the daemon. Discard. The
2688 * daemon should send us an error message next.
2690 if (size == GUESTFS_CANCEL_FLAG)
2693 if (size == GUESTFS_LAUNCH_FLAG) {
2694 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2698 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2700 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2701 error (g, "%s: failed to parse reply header", fn);
2706 if (hdr->status == GUESTFS_STATUS_ERROR) {
2707 if (!xdr_guestfs_message_error (&xdr, err)) {
2708 error (g, "%s: failed to parse reply error", fn);
2714 if (xdrp && ret && !xdrp (&xdr, ret)) {
2715 error (g, "%s: failed to parse reply", fn);
2727 /* Receive a file. */
2729 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2730 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2733 guestfs___recv_file (guestfs_h *g, const char *filename)
2738 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2740 perrorf (g, "open: %s", filename);
2744 /* Receive the file in chunked encoding. */
2745 while ((r = receive_file_data (g, &buf)) > 0) {
2746 if (xwrite (fd, buf, r) == -1) {
2747 perrorf (g, "%s: write", filename);
2755 error (g, _("%s: error in chunked encoding"), filename);
2759 if (close (fd) == -1) {
2760 perrorf (g, "close: %s", filename);
2767 /* Send cancellation message to daemon, then wait until it
2768 * cancels (just throwing away data).
2772 uint32_t flag = GUESTFS_CANCEL_FLAG;
2775 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2778 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2779 xdr_uint32_t (&xdr, &flag);
2782 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2783 perrorf (g, _("write to daemon socket"));
2787 while (receive_file_data (g, NULL) > 0)
2788 ; /* just discard it */
2793 /* Receive a chunk of file data. */
2794 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2796 receive_file_data (guestfs_h *g, void **buf_r)
2802 guestfs_chunk chunk;
2804 r = recv_from_daemon (g, &len, &buf);
2806 error (g, _("receive_file_data: parse error in reply callback"));
2810 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2811 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2815 memset (&chunk, 0, sizeof chunk);
2817 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2818 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2819 error (g, _("failed to parse file chunk"));
2824 /* After decoding, the original buffer is no longer used. */
2828 error (g, _("file receive cancelled by daemon"));
2829 free (chunk.data.data_val);
2833 if (chunk.data.data_len == 0) { /* end of transfer */
2834 free (chunk.data.data_val);
2838 if (buf_r) *buf_r = chunk.data.data_val;
2839 else free (chunk.data.data_val); /* else caller frees */
2841 return chunk.data.data_len;