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 size_t len = strlen (filename) + 64;
852 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, drive_if);
854 return guestfs__config (g, "-drive", buf);
858 guestfs__add_drive (guestfs_h *g, const char *filename)
860 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
864 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
866 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
870 guestfs__add_cdrom (guestfs_h *g, const char *filename)
872 if (strchr (filename, ',') != NULL) {
873 error (g, _("filename cannot contain ',' (comma) character"));
877 if (access (filename, F_OK) == -1) {
878 perrorf (g, "%s", filename);
882 return guestfs__config (g, "-cdrom", filename);
885 /* Returns true iff file is contained in dir. */
887 dir_contains_file (const char *dir, const char *file)
889 int dirlen = strlen (dir);
890 int filelen = strlen (file);
891 int len = dirlen+filelen+2;
894 snprintf (path, len, "%s/%s", dir, file);
895 return access (path, F_OK) == 0;
898 /* Returns true iff every listed file is contained in 'dir'. */
900 dir_contains_files (const char *dir, ...)
905 va_start (args, dir);
906 while ((file = va_arg (args, const char *)) != NULL) {
907 if (!dir_contains_file (dir, file)) {
916 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
917 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
918 static int is_openable (guestfs_h *g, const char *path, int flags);
919 static void print_cmdline (guestfs_h *g);
921 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
922 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
925 guestfs__launch (guestfs_h *g)
928 char dir_template[PATH_MAX];
933 char *path, *pelem, *pend;
934 char *kernel = NULL, *initrd = NULL;
935 int null_vmchannel_sock;
937 struct sockaddr_un addr;
941 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
945 if (g->state != CONFIG) {
946 error (g, _("the libguestfs handle has already been launched"));
950 /* Start the clock ... */
951 gettimeofday (&g->launch_t, NULL);
953 /* Make the temporary directory. */
960 tmpdir = getenv ("TMPDIR") ? : tmpdir;
961 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
964 g->tmpdir = safe_strdup (g, dir_template);
965 if (mkdtemp (g->tmpdir) == NULL) {
966 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
971 /* Allow anyone to read the temporary directory. There are no
972 * secrets in the kernel or initrd files. The socket in this
973 * directory won't be readable but anyone can see it exists if they
974 * want. (RHBZ#610880).
976 if (chmod (g->tmpdir, 0755) == -1)
977 fprintf (stderr, "chmod: %s: %m (ignored)\n", g->tmpdir);
979 /* First search g->path for the supermin appliance, and try to
980 * synthesize a kernel and initrd from that. If it fails, we
981 * try the path search again looking for a backup ordinary
984 pelem = path = safe_strdup (g, g->path);
986 pend = strchrnul (pelem, ':');
987 pmore = *pend == ':';
991 /* Empty element of "." means cwd. */
992 if (len == 0 || (len == 1 && *pelem == '.')) {
995 "looking for supermin appliance in current directory\n");
996 if (dir_contains_files (".",
997 "supermin.d", "kmod.whitelist", NULL)) {
998 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
1003 /* Look at <path>/supermin* etc. */
1006 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
1008 if (dir_contains_files (pelem,
1009 "supermin.d", "kmod.whitelist", NULL)) {
1010 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1021 if (kernel == NULL || initrd == NULL) {
1022 /* Search g->path for the kernel and initrd. */
1023 pelem = path = safe_strdup (g, g->path);
1025 pend = strchrnul (pelem, ':');
1026 pmore = *pend == ':';
1030 /* Empty element or "." means cwd. */
1031 if (len == 0 || (len == 1 && *pelem == '.')) {
1034 "looking for appliance in current directory\n");
1035 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1036 kernel = safe_strdup (g, kernel_name);
1037 initrd = safe_strdup (g, initrd_name);
1041 /* Look at <path>/kernel etc. */
1044 fprintf (stderr, "looking for appliance in %s\n", pelem);
1046 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1047 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1048 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1049 sprintf (kernel, "%s/%s", pelem, kernel_name);
1050 sprintf (initrd, "%s/%s", pelem, initrd_name);
1061 if (kernel == NULL || initrd == NULL) {
1062 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1063 kernel_name, initrd_name, g->path);
1068 print_timestamped_message (g, "begin testing qemu features");
1070 /* Get qemu help text and version. */
1071 if (qemu_supports (g, NULL) == -1)
1074 /* Choose which vmchannel implementation to use. */
1075 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
1076 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1077 * networking in qemu) but no other vmchannel support. The daemon
1078 * will connect back to a random port number on localhost.
1080 struct sockaddr_in addr;
1081 socklen_t addrlen = sizeof addr;
1083 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1084 if (g->sock == -1) {
1085 perrorf (g, "socket");
1088 addr.sin_family = AF_INET;
1089 addr.sin_port = htons (0);
1090 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1091 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1092 perrorf (g, "bind");
1096 if (listen (g->sock, 256) == -1) {
1097 perrorf (g, "listen");
1101 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1102 perrorf (g, "getsockname");
1106 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1107 perrorf (g, "fcntl");
1111 null_vmchannel_sock = ntohs (addr.sin_port);
1113 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1115 /* Using some vmchannel impl. We need to create a local Unix
1116 * domain socket for qemu to use.
1118 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1120 null_vmchannel_sock = 0;
1124 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1125 perrorf (g, "pipe");
1131 print_timestamped_message (g, "finished testing qemu features");
1135 perrorf (g, "fork");
1145 if (r == 0) { /* Child (qemu). */
1147 const char *vmchannel = NULL;
1149 /* Set up the full command line. Do this in the subprocess so we
1150 * don't need to worry about cleaning up.
1152 g->cmdline[0] = g->qemu;
1154 /* qemu sometimes needs this option to enable hardware
1155 * virtualization, but some versions of 'qemu-kvm' will use KVM
1156 * regardless (even where this option appears in the help text).
1157 * It is rumoured that there are versions of qemu where supplying
1158 * this option when hardware virtualization is not available will
1159 * cause qemu to fail, so we we have to check at least that
1160 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1161 * might be openable by qemu but not by us (think: SELinux) in
1162 * which case the user would not get hardware virtualization,
1163 * although at least shouldn't fail. A giant clusterfuck with the
1164 * qemu command line, again.
1166 if (qemu_supports (g, "-enable-kvm") &&
1167 is_openable (g, "/dev/kvm", O_RDWR))
1168 add_cmdline (g, "-enable-kvm");
1170 /* Newer versions of qemu (from around 2009/12) changed the
1171 * behaviour of monitors so that an implicit '-monitor stdio' is
1172 * assumed if we are in -nographic mode and there is no other
1173 * -monitor option. Only a single stdio device is allowed, so
1174 * this broke the '-serial stdio' option. There is a new flag
1175 * called -nodefaults which gets rid of all this default crud, so
1176 * let's use that to avoid this and any future surprises.
1178 if (qemu_supports (g, "-nodefaults"))
1179 add_cmdline (g, "-nodefaults");
1181 add_cmdline (g, "-nographic");
1182 add_cmdline (g, "-serial");
1183 add_cmdline (g, "stdio");
1185 snprintf (buf, sizeof buf, "%d", g->memsize);
1186 add_cmdline (g, "-m");
1187 add_cmdline (g, buf);
1189 /* Force exit instead of reboot on panic */
1190 add_cmdline (g, "-no-reboot");
1192 /* These options recommended by KVM developers to improve reliability. */
1193 if (qemu_supports (g, "-no-hpet"))
1194 add_cmdline (g, "-no-hpet");
1196 if (qemu_supports (g, "-rtc-td-hack"))
1197 add_cmdline (g, "-rtc-td-hack");
1199 /* If qemu has SLIRP (user mode network) enabled then we can get
1200 * away with "no vmchannel", where we just connect back to a random
1203 if (null_vmchannel_sock) {
1204 add_cmdline (g, "-net");
1205 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1207 snprintf (buf, sizeof buf,
1208 "guestfs_vmchannel=tcp:" ROUTER ":%d",
1209 null_vmchannel_sock);
1210 vmchannel = strdup (buf);
1213 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1215 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1217 * The original suggested format doesn't work, see:
1219 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1221 * However Gerd Hoffman privately suggested to me using -chardev
1222 * instead, which does work.
1224 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1225 snprintf (buf, sizeof buf,
1226 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1228 add_cmdline (g, "-chardev");
1229 add_cmdline (g, buf);
1231 snprintf (buf, sizeof buf,
1232 "user,vlan=0,net=" NETWORK ","
1233 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1234 "-chardev:guestfsvmc");
1236 add_cmdline (g, "-net");
1237 add_cmdline (g, buf);
1239 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1242 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1243 * syntax, or if not then we'll get a quick failure.
1246 snprintf (buf, sizeof buf,
1247 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1249 add_cmdline (g, "-net");
1250 add_cmdline (g, buf);
1251 add_cmdline (g, "-net");
1252 add_cmdline (g, "user,vlan=0,net=" NETWORK);
1254 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1256 add_cmdline (g, "-net");
1257 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1259 #define LINUX_CMDLINE \
1260 "panic=1 " /* force kernel to panic if daemon exits */ \
1261 "console=ttyS0 " /* serial console */ \
1262 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1263 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1264 "acpi=off " /* we don't need ACPI, turn it off */ \
1265 "printk.time=1 " /* display timestamp before kernel messages */ \
1266 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1268 /* Linux kernel command line. */
1269 snprintf (buf, sizeof buf,
1271 "%s " /* (selinux) */
1272 "%s " /* (vmchannel) */
1273 "%s " /* (verbose) */
1274 "TERM=%s " /* (TERM environment variable) */
1275 "%s", /* (append) */
1276 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1277 vmchannel ? vmchannel : "",
1278 g->verbose ? "guestfs_verbose=1" : "",
1279 getenv ("TERM") ? : "linux",
1280 g->append ? g->append : "");
1282 add_cmdline (g, "-kernel");
1283 add_cmdline (g, (char *) kernel);
1284 add_cmdline (g, "-initrd");
1285 add_cmdline (g, (char *) initrd);
1286 add_cmdline (g, "-append");
1287 add_cmdline (g, buf);
1289 /* Finish off the command line. */
1290 incr_cmdline_size (g);
1291 g->cmdline[g->cmdline_size-1] = NULL;
1297 /* Set up stdin, stdout. */
1303 if (dup (wfd[0]) == -1) {
1305 perror ("dup failed");
1306 _exit (EXIT_FAILURE);
1308 if (dup (rfd[1]) == -1)
1316 /* Set up a new process group, so we can signal this process
1317 * and all subprocesses (eg. if qemu is really a shell script).
1322 setenv ("LC_ALL", "C", 1);
1324 execv (g->qemu, g->cmdline); /* Run qemu. */
1326 _exit (EXIT_FAILURE);
1329 /* Parent (library). */
1337 /* Fork the recovery process off which will kill qemu if the parent
1338 * process fails to do so (eg. if the parent segfaults).
1340 g->recoverypid = -1;
1341 if (g->recovery_proc) {
1344 pid_t qemu_pid = g->pid;
1345 pid_t parent_pid = getppid ();
1347 /* Writing to argv is hideously complicated and error prone. See:
1348 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1351 /* Loop around waiting for one or both of the other processes to
1352 * disappear. It's fair to say this is very hairy. The PIDs that
1353 * we are looking at might be reused by another process. We are
1354 * effectively polling. Is the cure worse than the disease?
1357 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1358 _exit (EXIT_SUCCESS);
1359 if (kill (parent_pid, 0) == -1) {
1360 /* Parent's gone away, qemu still around, so kill qemu. */
1362 _exit (EXIT_SUCCESS);
1368 /* Don't worry, if the fork failed, this will be -1. The recovery
1369 * process isn't essential.
1375 /* Close the other ends of the pipe. */
1379 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1380 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1381 perrorf (g, "fcntl");
1385 g->fd[0] = wfd[1]; /* stdin of child */
1386 g->fd[1] = rfd[0]; /* stdout of child */
1388 g->fd[0] = open ("/dev/null", O_RDWR);
1389 if (g->fd[0] == -1) {
1390 perrorf (g, "open /dev/null");
1393 g->fd[1] = dup (g->fd[0]);
1394 if (g->fd[1] == -1) {
1401 if (null_vmchannel_sock) {
1405 /* Null vmchannel implementation: We listen on g->sock for a
1406 * connection. The connection could come from any local process
1407 * so we must check it comes from the appliance (or at least
1408 * from our UID) for security reasons.
1410 while (sock == -1) {
1411 sock = accept_from_daemon (g);
1415 if (check_peer_euid (g, sock, &uid) == -1)
1417 if (uid != geteuid ()) {
1419 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1420 uid, null_vmchannel_sock);
1427 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1428 perrorf (g, "fcntl");
1435 /* Other vmchannel. Open the Unix socket.
1437 * The vmchannel implementation that got merged with qemu sucks in
1438 * a number of ways. Both ends do connect(2), which means that no
1439 * one knows what, if anything, is connected to the other end, or
1440 * if it becomes disconnected. Even worse, we have to wait some
1441 * indeterminate time for qemu to create the socket and connect to
1442 * it (which happens very early in qemu's start-up), so any code
1443 * that uses vmchannel is inherently racy. Hence this silly loop.
1445 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1446 if (g->sock == -1) {
1447 perrorf (g, "socket");
1451 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1452 perrorf (g, "fcntl");
1456 addr.sun_family = AF_UNIX;
1457 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1458 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1461 /* Always sleep at least once to give qemu a small chance to start up. */
1464 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1465 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1468 if (errno != ENOENT)
1469 perrorf (g, "connect");
1474 error (g, _("failed to connect to vmchannel socket"));
1480 g->state = LAUNCHING;
1482 /* Wait for qemu to start and to connect back to us via vmchannel and
1483 * send the GUESTFS_LAUNCH_FLAG message.
1487 r = recv_from_daemon (g, &size, &buf);
1490 if (r == -1) return -1;
1492 if (size != GUESTFS_LAUNCH_FLAG) {
1493 error (g, _("guestfs_launch failed, see earlier error messages"));
1498 print_timestamped_message (g, "appliance is up");
1500 /* This is possible in some really strange situations, such as
1501 * guestfsd starts up OK but then qemu immediately exits. Check for
1502 * it because the caller is probably expecting to be able to send
1503 * commands after this function returns.
1505 if (g->state != READY) {
1506 error (g, _("qemu launched and contacted daemon, but state != READY"));
1517 if (g->pid > 0) kill (g->pid, 9);
1518 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1519 waitpid (g->pid, NULL, 0);
1520 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1525 memset (&g->launch_t, 0, sizeof g->launch_t);
1538 /* This function is used to print the qemu command line before it gets
1539 * executed, when in verbose mode.
1542 print_cmdline (guestfs_h *g)
1547 while (g->cmdline[i]) {
1548 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1549 fprintf (stderr, " \\\n ");
1551 if (i > 0) fputc (' ', stderr);
1553 /* Does it need shell quoting? This only deals with simple cases. */
1554 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1556 if (needs_quote) fputc ('\'', stderr);
1557 fprintf (stderr, "%s", g->cmdline[i]);
1558 if (needs_quote) fputc ('\'', stderr);
1562 fputc ('\n', stderr);
1565 /* This function does the hard work of building the supermin appliance
1566 * on the fly. 'path' is the directory containing the control files.
1567 * 'kernel' and 'initrd' are where we will return the names of the
1568 * kernel and initrd (only initrd is built). The work is done by
1569 * an external script. We just tell it where to put the result.
1572 build_supermin_appliance (guestfs_h *g, const char *path,
1573 char **kernel, char **initrd)
1579 print_timestamped_message (g, "begin building supermin appliance");
1581 len = strlen (g->tmpdir);
1582 *kernel = safe_malloc (g, len + 8);
1583 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1584 *initrd = safe_malloc (g, len + 8);
1585 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1587 /* Set a sensible umask in the subprocess, so kernel and initrd
1588 * output files are world-readable (RHBZ#610880).
1590 snprintf (cmd, sizeof cmd,
1592 "febootstrap-supermin-helper%s "
1593 "-k '%s/kmod.whitelist' "
1597 g->verbose ? " --verbose" : "",
1602 print_timestamped_message (g, "%s", cmd);
1605 if (r == -1 || WEXITSTATUS(r) != 0) {
1606 error (g, _("external command failed: %s"), cmd);
1609 *kernel = *initrd = NULL;
1614 print_timestamped_message (g, "finished building supermin appliance");
1619 /* Compute Y - X and return the result in milliseconds.
1620 * Approximately the same as this code:
1621 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1624 timeval_diff (const struct timeval *x, const struct timeval *y)
1628 msec = (y->tv_sec - x->tv_sec) * 1000;
1629 msec += (y->tv_usec - x->tv_usec) / 1000;
1634 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1641 va_start (args, fs);
1642 err = vasprintf (&msg, fs, args);
1645 if (err < 0) return;
1647 gettimeofday (&tv, NULL);
1649 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1650 timeval_diff (&g->launch_t, &tv), msg);
1655 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1657 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1658 * 'qemu -version' so we know what options this qemu supports and
1662 test_qemu (guestfs_h *g)
1667 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1669 fp = popen (cmd, "r");
1670 /* qemu -help should always work (qemu -version OTOH wasn't
1671 * supported by qemu 0.9). If this command doesn't work then it
1672 * probably indicates that the qemu binary is missing.
1675 /* XXX This error is never printed, even if the qemu binary
1676 * doesn't exist. Why?
1679 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1683 if (read_all (g, fp, &g->qemu_help) == -1)
1686 if (pclose (fp) == -1)
1689 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1692 fp = popen (cmd, "r");
1694 /* Intentionally ignore errors. */
1695 read_all (g, fp, &g->qemu_version);
1703 read_all (guestfs_h *g, FILE *fp, char **ret)
1710 *ret = safe_realloc (g, *ret, n + 1);
1715 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1717 r = fread (p, 1, BUFSIZ, fp);
1719 perrorf (g, "read");
1726 /* Test if option is supported by qemu command line (just by grepping
1729 * The first time this is used, it has to run the external qemu
1730 * binary. If that fails, it returns -1.
1732 * To just do the first-time run of the qemu binary, call this with
1733 * option == NULL, in which case it will return -1 if there was an
1737 qemu_supports (guestfs_h *g, const char *option)
1739 if (!g->qemu_help) {
1740 if (test_qemu (g) == -1)
1747 return strstr (g->qemu_help, option) != NULL;
1750 /* Check if a file can be opened. */
1752 is_openable (guestfs_h *g, const char *path, int flags)
1754 int fd = open (path, flags);
1764 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1765 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1766 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1769 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1771 #if CAN_CHECK_PEER_EUID
1772 struct sockaddr_in peer;
1773 socklen_t addrlen = sizeof peer;
1775 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1776 perrorf (g, "getpeername");
1780 if (peer.sin_family != AF_INET ||
1781 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1782 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1783 peer.sin_family, inet_ntoa (peer.sin_addr));
1787 struct sockaddr_in our;
1788 addrlen = sizeof our;
1789 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1790 perrorf (g, "getsockname");
1794 FILE *fp = fopen ("/proc/net/tcp", "r");
1796 perrorf (g, "/proc/net/tcp");
1801 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1802 error (g, "unexpected end of file in /proc/net/tcp");
1807 while (fgets (line, sizeof line, fp) != NULL) {
1808 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1809 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1812 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1814 &line_our_addr, &line_our_port,
1815 &line_peer_addr, &line_peer_port,
1816 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1818 /* Note about /proc/net/tcp: local_address and rem_address are
1819 * always in network byte order. However the port part is
1820 * always in host byte order.
1822 * The sockname and peername that we got above are in network
1823 * byte order. So we have to byte swap the port but not the
1826 if (line_our_addr == our.sin_addr.s_addr &&
1827 line_our_port == ntohs (our.sin_port) &&
1828 line_peer_addr == peer.sin_addr.s_addr &&
1829 line_peer_port == ntohs (peer.sin_port)) {
1837 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1840 #else /* !CAN_CHECK_PEER_EUID */
1841 /* This function exists but should never be called in this
1845 #endif /* !CAN_CHECK_PEER_EUID */
1848 /* You had to call this function after launch in versions <= 1.0.70,
1849 * but it is now a no-op.
1852 guestfs__wait_ready (guestfs_h *g)
1854 if (g->state != READY) {
1855 error (g, _("qemu has not been launched yet"));
1863 guestfs__kill_subprocess (guestfs_h *g)
1865 if (g->state == CONFIG) {
1866 error (g, _("no subprocess to kill"));
1871 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1873 if (g->pid > 0) kill (g->pid, SIGTERM);
1874 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1879 /* Access current state. */
1881 guestfs__is_config (guestfs_h *g)
1883 return g->state == CONFIG;
1887 guestfs__is_launching (guestfs_h *g)
1889 return g->state == LAUNCHING;
1893 guestfs__is_ready (guestfs_h *g)
1895 return g->state == READY;
1899 guestfs__is_busy (guestfs_h *g)
1901 return g->state == BUSY;
1905 guestfs__get_state (guestfs_h *g)
1911 guestfs_set_log_message_callback (guestfs_h *g,
1912 guestfs_log_message_cb cb, void *opaque)
1914 g->log_message_cb = cb;
1915 g->log_message_cb_data = opaque;
1919 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1920 guestfs_subprocess_quit_cb cb, void *opaque)
1922 g->subprocess_quit_cb = cb;
1923 g->subprocess_quit_cb_data = opaque;
1927 guestfs_set_launch_done_callback (guestfs_h *g,
1928 guestfs_launch_done_cb cb, void *opaque)
1930 g->launch_done_cb = cb;
1931 g->launch_done_cb_data = opaque;
1935 guestfs_set_close_callback (guestfs_h *g,
1936 guestfs_close_cb cb, void *opaque)
1939 g->close_cb_data = opaque;
1942 /*----------------------------------------------------------------------*/
1944 /* This is the code used to send and receive RPC messages and (for
1945 * certain types of message) to perform file transfers. This code is
1946 * driven from the generated actions (src/actions.c). There
1947 * are five different cases to consider:
1949 * (1) A non-daemon function. There is no RPC involved at all, it's
1950 * all handled inside the library.
1952 * (2) A simple RPC (eg. "mount"). We write the request, then read
1953 * the reply. The sequence of calls is:
1955 * guestfs___set_busy
1958 * guestfs___end_busy
1960 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1961 * request, then write the file(s), then read the reply. The sequence
1964 * guestfs___set_busy
1966 * guestfs___send_file (possibly multiple times)
1968 * guestfs___end_busy
1970 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1971 * request, then read the reply, then read the file(s). The sequence
1974 * guestfs___set_busy
1977 * guestfs___recv_file (possibly multiple times)
1978 * guestfs___end_busy
1980 * (5) Both FileOut and FileIn parameters. There are no calls like
1981 * this in the current API, but they would be implemented as a
1982 * combination of cases (3) and (4).
1984 * During all writes and reads, we also select(2) on qemu stdout
1985 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1986 * anything received is passed up through the log_message_cb. This is
1987 * also the reason why all the sockets are non-blocking. We also have
1988 * to check for EOF (qemu died). All of this is handled by the
1989 * functions send_to_daemon and recv_from_daemon.
1993 guestfs___set_busy (guestfs_h *g)
1995 if (g->state != READY) {
1996 error (g, _("guestfs_set_busy: called when in state %d != READY"),
2005 guestfs___end_busy (guestfs_h *g)
2019 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
2025 /* This is called if we detect EOF, ie. qemu died. */
2027 child_cleanup (guestfs_h *g)
2030 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
2032 /*if (g->pid > 0) kill (g->pid, SIGTERM);*/
2033 if (g->recoverypid > 0) kill (g->recoverypid, 9);
2034 waitpid (g->pid, NULL, 0);
2035 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
2044 memset (&g->launch_t, 0, sizeof g->launch_t);
2046 if (g->subprocess_quit_cb)
2047 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2051 read_log_message_or_eof (guestfs_h *g, int fd, int error_if_eof)
2059 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2063 /* QEMU's console emulates a 16550A serial port. The real 16550A
2064 * device has a small FIFO buffer (16 bytes) which means here we see
2065 * lots of small reads of 1-16 bytes in length, usually single
2068 n = read (fd, buf, sizeof buf);
2070 /* Hopefully this indicates the qemu child process has died. */
2074 /* We weren't expecting eof here (called from launch) so place
2075 * something in the error buffer. RHBZ#588851.
2077 error (g, "child process died unexpectedly");
2083 if (errno == EINTR || errno == EAGAIN)
2086 perrorf (g, "read");
2090 /* In verbose mode, copy all log messages to stderr. */
2092 ignore_value (write (STDERR_FILENO, buf, n));
2094 /* It's an actual log message, send it upwards if anyone is listening. */
2095 if (g->log_message_cb)
2096 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2102 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2111 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2114 n = read (fd, buf, 4);
2116 /* Hopefully this indicates the qemu child process has died. */
2122 if (errno == EINTR || errno == EAGAIN)
2125 perrorf (g, "read");
2129 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2130 xdr_uint32_t (&xdr, &flag);
2133 if (flag != GUESTFS_CANCEL_FLAG) {
2134 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2135 flag, GUESTFS_CANCEL_FLAG);
2142 /* This writes the whole N bytes of BUF to the daemon socket.
2144 * If the whole write is successful, it returns 0.
2145 * If there was an error, it returns -1.
2146 * If the daemon sent a cancellation message, it returns -2.
2148 * It also checks qemu stdout for log messages and passes those up
2149 * through log_message_cb.
2151 * It also checks for EOF (qemu died) and passes that up through the
2152 * child_cleanup function above.
2155 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2157 const char *buf = v_buf;
2163 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2168 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2169 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2170 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2172 int max_fd = MAX (g->sock, g->fd[1]);
2177 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2179 if (errno == EINTR || errno == EAGAIN)
2181 perrorf (g, "select");
2185 if (FD_ISSET (g->fd[1], &rset2)) {
2186 if (read_log_message_or_eof (g, g->fd[1], 0) == -1)
2189 if (FD_ISSET (g->sock, &rset2)) {
2190 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2194 if (FD_ISSET (g->sock, &wset2)) {
2195 r = write (g->sock, buf, n);
2197 if (errno == EINTR || errno == EAGAIN)
2199 perrorf (g, "write");
2200 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2212 /* This reads a single message, file chunk, launch flag or
2213 * cancellation flag from the daemon. If something was read, it
2214 * returns 0, otherwise -1.
2216 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2218 * *size_rtn returns the size of the returned message or it may be
2219 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2221 * *buf_rtn is returned containing the message (if any) or will be set
2222 * to NULL. *buf_rtn must be freed by the caller.
2224 * It also checks qemu stdout for log messages and passes those up
2225 * through log_message_cb.
2227 * It also checks for EOF (qemu died) and passes that up through the
2228 * child_cleanup function above.
2231 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2237 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2238 g, g->state, size_rtn, buf_rtn);
2242 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2243 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2245 int max_fd = MAX (g->sock, g->fd[1]);
2251 /* nr is the size of the message, but we prime it as -4 because we
2252 * have to read the message length word first.
2256 while (nr < (ssize_t) *size_rtn) {
2258 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2260 if (errno == EINTR || errno == EAGAIN)
2262 perrorf (g, "select");
2268 if (FD_ISSET (g->fd[1], &rset2)) {
2269 if (read_log_message_or_eof (g, g->fd[1], 0) == -1) {
2275 if (FD_ISSET (g->sock, &rset2)) {
2276 if (nr < 0) { /* Have we read the message length word yet? */
2277 r = read (g->sock, lenbuf+nr+4, -nr);
2279 if (errno == EINTR || errno == EAGAIN)
2282 perrorf (g, "read");
2283 /* Under some circumstances we see "Connection reset by peer"
2284 * here when the child dies suddenly. Catch this and call
2285 * the cleanup function, same as for EOF.
2287 if (err == ECONNRESET)
2292 error (g, _("unexpected end of file when reading from daemon"));
2298 if (nr < 0) /* Still not got the whole length word. */
2302 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2303 xdr_uint32_t (&xdr, size_rtn);
2306 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2307 if (g->state != LAUNCHING)
2308 error (g, _("received magic signature from guestfsd, but in state %d"),
2312 if (g->launch_done_cb)
2313 g->launch_done_cb (g, g->launch_done_cb_data);
2317 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2319 /* If this happens, it's pretty bad and we've probably lost
2322 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2323 error (g, _("message length (%u) > maximum possible size (%d)"),
2324 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2328 /* Allocate the complete buffer, size now known. */
2329 *buf_rtn = safe_malloc (g, *size_rtn);
2333 size_t sizetoread = *size_rtn - nr;
2334 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2336 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2338 if (errno == EINTR || errno == EAGAIN)
2340 perrorf (g, "read");
2346 error (g, _("unexpected end of file when reading from daemon"));
2356 /* Got the full message, caller can start processing it. */
2357 #ifdef ENABLE_PACKET_DUMP
2361 for (i = 0; i < nr; i += 16) {
2362 printf ("%04zx: ", i);
2363 for (j = i; j < MIN (i+16, nr); ++j)
2364 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2365 for (; j < i+16; ++j)
2368 for (j = i; j < MIN (i+16, nr); ++j)
2369 if (c_isprint ((*(char **)buf_rtn)[j]))
2370 printf ("%c", (*(char **)buf_rtn)[j]);
2373 for (; j < i+16; ++j)
2383 /* This is very much like recv_from_daemon above, but g->sock is
2384 * a listening socket and we are accepting a new connection on
2385 * that socket instead of reading anything. Returns the newly
2389 accept_from_daemon (guestfs_h *g)
2395 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2399 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2400 FD_SET (g->sock, &rset); /* Read socket for accept. */
2402 int max_fd = MAX (g->sock, g->fd[1]);
2405 while (sock == -1) {
2406 /* If the qemu process has died, clean up the zombie (RHBZ#579155).
2407 * By partially polling in the select below we ensure that this
2408 * function will be called eventually.
2410 waitpid (g->pid, NULL, WNOHANG);
2414 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
2415 int r = select (max_fd+1, &rset2, NULL, NULL, &tv);
2417 if (errno == EINTR || errno == EAGAIN)
2419 perrorf (g, "select");
2423 if (FD_ISSET (g->fd[1], &rset2)) {
2424 if (read_log_message_or_eof (g, g->fd[1], 1) == -1)
2427 if (FD_ISSET (g->sock, &rset2)) {
2428 sock = accept (g->sock, NULL, NULL);
2430 if (errno == EINTR || errno == EAGAIN)
2432 perrorf (g, "accept");
2442 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2444 struct guestfs_message_header hdr;
2447 int serial = g->msg_next_serial++;
2450 size_t msg_out_size;
2452 if (g->state != BUSY) {
2453 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2457 /* We have to allocate this message buffer on the heap because
2458 * it is quite large (although will be mostly unused). We
2459 * can't allocate it on the stack because in some environments
2460 * we have quite limited stack space available, notably when
2461 * running in the JVM.
2463 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2464 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2466 /* Serialize the header. */
2467 hdr.prog = GUESTFS_PROGRAM;
2468 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2470 hdr.direction = GUESTFS_DIRECTION_CALL;
2471 hdr.serial = serial;
2472 hdr.status = GUESTFS_STATUS_OK;
2474 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2475 error (g, _("xdr_guestfs_message_header failed"));
2479 /* Serialize the args. If any, because some message types
2480 * have no parameters.
2483 if (!(*xdrp) (&xdr, args)) {
2484 error (g, _("dispatch failed to marshal args"));
2489 /* Get the actual length of the message, resize the buffer to match
2490 * the actual length, and write the length word at the beginning.
2492 len = xdr_getpos (&xdr);
2495 msg_out = safe_realloc (g, msg_out, len + 4);
2496 msg_out_size = len + 4;
2498 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2499 xdr_uint32_t (&xdr, &len);
2502 r = send_to_daemon (g, msg_out, msg_out_size);
2503 if (r == -2) /* Ignore stray daemon cancellations. */
2516 static int cancel = 0; /* XXX Implement file cancellation. */
2517 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2518 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2519 static int send_file_cancellation (guestfs_h *g);
2520 static int send_file_complete (guestfs_h *g);
2526 * -2 daemon cancelled (we must read the error message)
2529 guestfs___send_file (guestfs_h *g, const char *filename)
2531 char buf[GUESTFS_MAX_CHUNK_SIZE];
2534 fd = open (filename, O_RDONLY);
2536 perrorf (g, "open: %s", filename);
2537 send_file_cancellation (g);
2538 /* Daemon sees cancellation and won't reply, so caller can
2544 /* Send file in chunked encoding. */
2546 r = read (fd, buf, sizeof buf);
2547 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2550 err = send_file_data (g, buf, r);
2552 if (err == -2) /* daemon sent cancellation */
2553 send_file_cancellation (g);
2558 if (cancel) { /* cancel from either end */
2559 send_file_cancellation (g);
2564 perrorf (g, "read: %s", filename);
2565 send_file_cancellation (g);
2569 /* End of file, but before we send that, we need to close
2570 * the file and check for errors.
2572 if (close (fd) == -1) {
2573 perrorf (g, "close: %s", filename);
2574 send_file_cancellation (g);
2578 return send_file_complete (g);
2581 /* Send a chunk of file data. */
2583 send_file_data (guestfs_h *g, const char *buf, size_t len)
2585 return send_file_chunk (g, 0, buf, len);
2588 /* Send a cancellation message. */
2590 send_file_cancellation (guestfs_h *g)
2592 return send_file_chunk (g, 1, NULL, 0);
2595 /* Send a file complete chunk. */
2597 send_file_complete (guestfs_h *g)
2600 return send_file_chunk (g, 0, buf, 0);
2604 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2608 guestfs_chunk chunk;
2611 size_t msg_out_size;
2613 if (g->state != BUSY) {
2614 error (g, _("send_file_chunk: state %d != READY"), g->state);
2618 /* Allocate the chunk buffer. Don't use the stack to avoid
2619 * excessive stack usage and unnecessary copies.
2621 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2622 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2624 /* Serialize the chunk. */
2625 chunk.cancel = cancel;
2626 chunk.data.data_len = buflen;
2627 chunk.data.data_val = (char *) buf;
2629 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2630 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2636 len = xdr_getpos (&xdr);
2639 /* Reduce the size of the outgoing message buffer to the real length. */
2640 msg_out = safe_realloc (g, msg_out, len + 4);
2641 msg_out_size = len + 4;
2643 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2644 xdr_uint32_t (&xdr, &len);
2646 r = send_to_daemon (g, msg_out, msg_out_size);
2648 /* Did the daemon send a cancellation message? */
2651 fprintf (stderr, "got daemon cancellation\n");
2667 /* Receive a reply. */
2669 guestfs___recv (guestfs_h *g, const char *fn,
2670 guestfs_message_header *hdr,
2671 guestfs_message_error *err,
2672 xdrproc_t xdrp, char *ret)
2680 r = recv_from_daemon (g, &size, &buf);
2684 /* This can happen if a cancellation happens right at the end
2685 * of us sending a FileIn parameter to the daemon. Discard. The
2686 * daemon should send us an error message next.
2688 if (size == GUESTFS_CANCEL_FLAG)
2691 if (size == GUESTFS_LAUNCH_FLAG) {
2692 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2696 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2698 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2699 error (g, "%s: failed to parse reply header", fn);
2704 if (hdr->status == GUESTFS_STATUS_ERROR) {
2705 if (!xdr_guestfs_message_error (&xdr, err)) {
2706 error (g, "%s: failed to parse reply error", fn);
2712 if (xdrp && ret && !xdrp (&xdr, ret)) {
2713 error (g, "%s: failed to parse reply", fn);
2725 /* Receive a file. */
2727 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2728 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2731 guestfs___recv_file (guestfs_h *g, const char *filename)
2736 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2738 perrorf (g, "open: %s", filename);
2742 /* Receive the file in chunked encoding. */
2743 while ((r = receive_file_data (g, &buf)) > 0) {
2744 if (xwrite (fd, buf, r) == -1) {
2745 perrorf (g, "%s: write", filename);
2753 error (g, _("%s: error in chunked encoding"), filename);
2757 if (close (fd) == -1) {
2758 perrorf (g, "close: %s", filename);
2765 /* Send cancellation message to daemon, then wait until it
2766 * cancels (just throwing away data).
2770 uint32_t flag = GUESTFS_CANCEL_FLAG;
2773 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2776 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2777 xdr_uint32_t (&xdr, &flag);
2780 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2781 perrorf (g, _("write to daemon socket"));
2785 while (receive_file_data (g, NULL) > 0)
2786 ; /* just discard it */
2791 /* Receive a chunk of file data. */
2792 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2794 receive_file_data (guestfs_h *g, void **buf_r)
2800 guestfs_chunk chunk;
2802 r = recv_from_daemon (g, &len, &buf);
2804 error (g, _("receive_file_data: parse error in reply callback"));
2808 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2809 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2813 memset (&chunk, 0, sizeof chunk);
2815 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2816 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2817 error (g, _("failed to parse file chunk"));
2822 /* After decoding, the original buffer is no longer used. */
2826 error (g, _("file receive cancelled by daemon"));
2827 free (chunk.data.data_val);
2831 if (chunk.data.data_len == 0) { /* end of transfer */
2832 free (chunk.data.data_val);
2836 if (buf_r) *buf_r = chunk.data.data_val;
2837 else free (chunk.data.data_val); /* else caller frees */
2839 return chunk.data.data_len;