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 /* Also in guestfsd.c */
114 #define GUESTFWD_ADDR "10.0.2.4"
115 #define GUESTFWD_PORT "6666"
117 /* GuestFS handle and connection. */
118 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
122 struct guestfs_h *next; /* Linked list of open handles. */
124 /* State: see the state machine diagram in the man page guestfs(3). */
127 int fd[2]; /* Stdin/stdout of qemu. */
128 int sock; /* Daemon communications socket. */
129 pid_t pid; /* Qemu PID. */
130 pid_t recoverypid; /* Recovery process PID. */
132 struct timeval launch_t; /* The time that we called guestfs_launch. */
134 char *tmpdir; /* Temporary directory containing socket. */
136 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
138 char **cmdline; /* Qemu command line. */
147 char *path; /* Path to kernel, initrd. */
148 char *qemu; /* Qemu binary. */
149 char *append; /* Append to kernel command line. */
151 int memsize; /* Size of RAM (megabytes). */
153 int selinux; /* selinux enabled? */
158 guestfs_abort_cb abort_cb;
159 guestfs_error_handler_cb error_cb;
160 void * error_cb_data;
161 guestfs_log_message_cb log_message_cb;
162 void * log_message_cb_data;
163 guestfs_subprocess_quit_cb subprocess_quit_cb;
164 void * subprocess_quit_cb_data;
165 guestfs_launch_done_cb launch_done_cb;
166 void * launch_done_cb_data;
171 gl_lock_define_initialized (static, handles_lock);
172 static guestfs_h *handles = NULL;
173 static int atexit_handler_set = 0;
176 guestfs_create (void)
181 g = malloc (sizeof (*g));
184 memset (g, 0, sizeof (*g));
193 g->error_cb = default_error_cb;
194 g->error_cb_data = NULL;
196 g->recovery_proc = 1;
198 str = getenv ("LIBGUESTFS_DEBUG");
199 g->verbose = str != NULL && STREQ (str, "1");
201 str = getenv ("LIBGUESTFS_TRACE");
202 g->trace = str != NULL && STREQ (str, "1");
204 str = getenv ("LIBGUESTFS_PATH");
205 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
206 if (!g->path) goto error;
208 str = getenv ("LIBGUESTFS_QEMU");
209 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
210 if (!g->qemu) goto error;
212 str = getenv ("LIBGUESTFS_APPEND");
214 g->append = strdup (str);
215 if (!g->append) goto error;
218 /* Choose a suitable memory size. Previously we tried to choose
219 * a minimal memory size, but this isn't really necessary since
220 * recent QEMU and KVM don't do anything nasty like locking
221 * memory into core any more. Thus we can safely choose a
222 * large, generous amount of memory, and it'll just get swapped
223 * on smaller systems.
225 str = getenv ("LIBGUESTFS_MEMSIZE");
227 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
228 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
234 /* Start with large serial numbers so they are easy to spot
235 * inside the protocol.
237 g->msg_next_serial = 0x00123400;
239 /* Link the handles onto a global list. */
240 gl_lock_lock (handles_lock);
243 if (!atexit_handler_set) {
244 atexit (close_handles);
245 atexit_handler_set = 1;
247 gl_lock_unlock (handles_lock);
250 fprintf (stderr, "new guestfs handle %p\n", g);
263 guestfs_close (guestfs_h *g)
269 if (g->state == NO_HANDLE) {
270 /* Not safe to call 'error' here, so ... */
271 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
276 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
278 /* Try to sync if autosync flag is set. */
279 if (g->autosync && g->state == READY) {
280 guestfs_umount_all (g);
284 /* Remove any handlers that might be called back before we kill the
287 g->log_message_cb = NULL;
289 if (g->state != CONFIG)
290 guestfs_kill_subprocess (g);
303 /* Wait for subprocess(es) to exit. */
304 waitpid (g->pid, NULL, 0);
305 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
307 /* Remove tmpfiles. */
309 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
312 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
315 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
324 for (i = 0; i < g->cmdline_size; ++i)
325 free (g->cmdline[i]);
329 /* Mark the handle as dead before freeing it. */
330 g->state = NO_HANDLE;
332 gl_lock_lock (handles_lock);
336 for (gg = handles; gg->next != g; gg = gg->next)
340 gl_lock_unlock (handles_lock);
342 free (g->last_error);
347 free (g->qemu_version);
351 /* Close all open handles (called from atexit(3)). */
355 while (handles) guestfs_close (handles);
359 guestfs_last_error (guestfs_h *g)
361 return g->last_error;
365 set_last_error (guestfs_h *g, const char *msg)
367 free (g->last_error);
368 g->last_error = strdup (msg);
372 default_error_cb (guestfs_h *g, void *data, const char *msg)
374 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
378 guestfs_error (guestfs_h *g, const char *fs, ...)
384 int err = vasprintf (&msg, fs, args);
389 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
390 set_last_error (g, msg);
396 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
403 int err = vasprintf (&msg, fs, args);
408 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
410 strerror_r (errnum, buf, sizeof buf);
414 buf = strerror_r (errnum, _buf, sizeof _buf);
417 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
421 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
422 set_last_error (g, msg);
428 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
430 void *ptr = malloc (nbytes);
431 if (nbytes > 0 && !ptr) g->abort_cb ();
435 /* Return 1 if an array of N objects, each of size S, cannot exist due
436 to size arithmetic overflow. S must be positive and N must be
437 nonnegative. This is a macro, not an inline function, so that it
438 works correctly even when SIZE_MAX < N.
440 By gnulib convention, SIZE_MAX represents overflow in size
441 calculations, so the conservative dividend to use here is
442 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
443 However, malloc (SIZE_MAX) fails on all known hosts where
444 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
445 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
446 branch when S is known to be 1. */
447 # define xalloc_oversized(n, s) \
448 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
450 /* Technically we should add an autoconf test for this, testing for the desired
451 functionality, like what's done in gnulib, but for now, this is fine. */
452 #if defined(__GLIBC__)
453 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
455 #define HAVE_GNU_CALLOC 0
458 /* Allocate zeroed memory for N elements of S bytes, with error
459 checking. S must be nonzero. */
461 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
463 /* From gnulib's calloc function in xmalloc.c. */
465 /* Test for overflow, since some calloc implementations don't have
466 proper overflow checks. But omit overflow and size-zero tests if
467 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
468 returns NULL if successful. */
469 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
470 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
476 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
478 void *p = realloc (ptr, nbytes);
479 if (nbytes > 0 && !p) g->abort_cb ();
484 guestfs_safe_strdup (guestfs_h *g, const char *str)
486 char *s = strdup (str);
487 if (!s) g->abort_cb ();
492 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
494 void *p = malloc (size);
495 if (!p) g->abort_cb ();
496 memcpy (p, ptr, size);
501 xwrite (int fd, const void *v_buf, size_t len)
503 const char *buf = v_buf;
507 r = write (fd, buf, len);
519 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
525 guestfs_get_out_of_memory_handler (guestfs_h *g)
531 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
534 g->error_cb_data = data;
537 guestfs_error_handler_cb
538 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
540 if (data_rtn) *data_rtn = g->error_cb_data;
545 guestfs__set_verbose (guestfs_h *g, int v)
552 guestfs__get_verbose (guestfs_h *g)
558 guestfs__set_autosync (guestfs_h *g, int a)
565 guestfs__get_autosync (guestfs_h *g)
571 guestfs__set_path (guestfs_h *g, const char *path)
578 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
583 guestfs__get_path (guestfs_h *g)
589 guestfs__set_qemu (guestfs_h *g, const char *qemu)
594 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
599 guestfs__get_qemu (guestfs_h *g)
605 guestfs__set_append (guestfs_h *g, const char *append)
610 g->append = append ? safe_strdup (g, append) : NULL;
615 guestfs__get_append (guestfs_h *g)
621 guestfs__set_memsize (guestfs_h *g, int memsize)
623 g->memsize = memsize;
628 guestfs__get_memsize (guestfs_h *g)
634 guestfs__set_selinux (guestfs_h *g, int selinux)
636 g->selinux = selinux;
641 guestfs__get_selinux (guestfs_h *g)
647 guestfs__get_pid (guestfs_h *g)
652 error (g, "get_pid: no qemu subprocess");
657 struct guestfs_version *
658 guestfs__version (guestfs_h *g)
660 struct guestfs_version *r;
662 r = safe_malloc (g, sizeof *r);
663 r->major = PACKAGE_VERSION_MAJOR;
664 r->minor = PACKAGE_VERSION_MINOR;
665 r->release = PACKAGE_VERSION_RELEASE;
666 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
671 guestfs__set_trace (guestfs_h *g, int t)
678 guestfs__get_trace (guestfs_h *g)
684 guestfs__set_direct (guestfs_h *g, int d)
691 guestfs__get_direct (guestfs_h *g)
697 guestfs__set_recovery_proc (guestfs_h *g, int f)
699 g->recovery_proc = !!f;
704 guestfs__get_recovery_proc (guestfs_h *g)
706 return g->recovery_proc;
709 /* Add a string to the current command line. */
711 incr_cmdline_size (guestfs_h *g)
713 if (g->cmdline == NULL) {
714 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
716 g->cmdline = safe_malloc (g, sizeof (char *));
717 g->cmdline[0] = NULL;
721 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
725 add_cmdline (guestfs_h *g, const char *str)
727 if (g->state != CONFIG) {
729 _("command line cannot be altered after qemu subprocess launched"));
733 incr_cmdline_size (g);
734 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
739 guestfs__config (guestfs_h *g,
740 const char *qemu_param, const char *qemu_value)
742 if (qemu_param[0] != '-') {
743 error (g, _("guestfs_config: parameter must begin with '-' character"));
747 /* A bit fascist, but the user will probably break the extra
748 * parameters that we add if they try to set any of these.
750 if (STREQ (qemu_param, "-kernel") ||
751 STREQ (qemu_param, "-initrd") ||
752 STREQ (qemu_param, "-nographic") ||
753 STREQ (qemu_param, "-serial") ||
754 STREQ (qemu_param, "-full-screen") ||
755 STREQ (qemu_param, "-std-vga") ||
756 STREQ (qemu_param, "-vnc")) {
757 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
761 if (add_cmdline (g, qemu_param) != 0) return -1;
763 if (qemu_value != NULL) {
764 if (add_cmdline (g, qemu_value) != 0) return -1;
771 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
772 const char *drive_if)
774 size_t len = strlen (filename) + 64;
777 if (strchr (filename, ',') != NULL) {
778 error (g, _("filename cannot contain ',' (comma) character"));
782 /* cache=off improves reliability in the event of a host crash.
784 * However this option causes qemu to try to open the file with
785 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
786 * So we check if we can open the file with or without O_DIRECT,
787 * and use cache=off (or not) accordingly.
789 * This test also checks for the presence of the file, which
790 * is a documented semantic of this interface.
792 int fd = open (filename, O_RDONLY|O_DIRECT);
795 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
797 fd = open (filename, O_RDONLY);
800 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
802 perrorf (g, "%s", filename);
807 return guestfs__config (g, "-drive", buf);
811 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
812 const char *drive_if)
814 if (strchr (filename, ',') != NULL) {
815 error (g, _("filename cannot contain ',' (comma) character"));
819 if (access (filename, F_OK) == -1) {
820 perrorf (g, "%s", filename);
824 if (qemu_supports (g, NULL) == -1)
827 /* Only SCSI and virtio drivers support readonly mode.
828 * This is only supported as a QEMU feature since 2010/01.
831 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
832 qemu_supports (g, "readonly=on"))
835 size_t len = strlen (filename) + 100;
838 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
840 supports_ro ? "readonly=on," : "",
843 return guestfs__config (g, "-drive", buf);
847 guestfs__add_drive (guestfs_h *g, const char *filename)
849 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
853 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
855 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
859 guestfs__add_cdrom (guestfs_h *g, const char *filename)
861 if (strchr (filename, ',') != NULL) {
862 error (g, _("filename cannot contain ',' (comma) character"));
866 if (access (filename, F_OK) == -1) {
867 perrorf (g, "%s", filename);
871 return guestfs__config (g, "-cdrom", filename);
874 /* Returns true iff file is contained in dir. */
876 dir_contains_file (const char *dir, const char *file)
878 int dirlen = strlen (dir);
879 int filelen = strlen (file);
880 int len = dirlen+filelen+2;
883 snprintf (path, len, "%s/%s", dir, file);
884 return access (path, F_OK) == 0;
887 /* Returns true iff every listed file is contained in 'dir'. */
889 dir_contains_files (const char *dir, ...)
894 va_start (args, dir);
895 while ((file = va_arg (args, const char *)) != NULL) {
896 if (!dir_contains_file (dir, file)) {
905 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
906 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
907 static int is_openable (guestfs_h *g, const char *path, int flags);
908 static void print_cmdline (guestfs_h *g);
910 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
911 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
912 static const char *supermin_name =
913 "initramfs." REPO "." host_cpu ".supermin.img";
914 static const char *supermin_hostfiles_name =
915 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
918 guestfs__launch (guestfs_h *g)
921 char dir_template[PATH_MAX];
926 char *path, *pelem, *pend;
927 char *kernel = NULL, *initrd = NULL;
928 int null_vmchannel_sock;
930 struct sockaddr_un addr;
932 /* Start the clock ... */
933 gettimeofday (&g->launch_t, NULL);
941 tmpdir = getenv ("TMPDIR") ? : tmpdir;
942 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
946 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
950 if (g->state != CONFIG) {
951 error (g, _("qemu has already been launched"));
955 /* Make the temporary directory. */
957 g->tmpdir = safe_strdup (g, dir_template);
958 if (mkdtemp (g->tmpdir) == NULL) {
959 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
964 /* First search g->path for the supermin appliance, and try to
965 * synthesize a kernel and initrd from that. If it fails, we
966 * try the path search again looking for a backup ordinary
969 pelem = path = safe_strdup (g, g->path);
971 pend = strchrnul (pelem, ':');
972 pmore = *pend == ':';
976 /* Empty element of "." means cwd. */
977 if (len == 0 || (len == 1 && *pelem == '.')) {
980 "looking for supermin appliance in current directory\n");
981 if (dir_contains_files (".",
982 supermin_name, supermin_hostfiles_name,
983 "kmod.whitelist", NULL)) {
984 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
989 /* Look at <path>/supermin* etc. */
992 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
994 if (dir_contains_files (pelem,
995 supermin_name, supermin_hostfiles_name,
996 "kmod.whitelist", NULL)) {
997 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1008 if (kernel == NULL || initrd == NULL) {
1009 /* Search g->path for the kernel and initrd. */
1010 pelem = path = safe_strdup (g, g->path);
1012 pend = strchrnul (pelem, ':');
1013 pmore = *pend == ':';
1017 /* Empty element or "." means cwd. */
1018 if (len == 0 || (len == 1 && *pelem == '.')) {
1021 "looking for appliance in current directory\n");
1022 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1023 kernel = safe_strdup (g, kernel_name);
1024 initrd = safe_strdup (g, initrd_name);
1028 /* Look at <path>/kernel etc. */
1031 fprintf (stderr, "looking for appliance in %s\n", pelem);
1033 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1034 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1035 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1036 sprintf (kernel, "%s/%s", pelem, kernel_name);
1037 sprintf (initrd, "%s/%s", pelem, initrd_name);
1048 if (kernel == NULL || initrd == NULL) {
1049 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1050 kernel_name, initrd_name, g->path);
1055 print_timestamped_message (g, "begin testing qemu features");
1057 /* Get qemu help text and version. */
1058 if (qemu_supports (g, NULL) == -1)
1061 /* Choose which vmchannel implementation to use. */
1062 if (CAN_CHECK_PEER_EUID && qemu_supports (g, "-net user")) {
1063 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1064 * networking in qemu) but no other vmchannel support. The daemon
1065 * will connect back to a random port number on localhost.
1067 struct sockaddr_in addr;
1068 socklen_t addrlen = sizeof addr;
1070 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1071 if (g->sock == -1) {
1072 perrorf (g, "socket");
1075 addr.sin_family = AF_INET;
1076 addr.sin_port = htons (0);
1077 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1078 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1079 perrorf (g, "bind");
1083 if (listen (g->sock, 256) == -1) {
1084 perrorf (g, "listen");
1088 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1089 perrorf (g, "getsockname");
1093 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1094 perrorf (g, "fcntl");
1098 null_vmchannel_sock = ntohs (addr.sin_port);
1100 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1102 /* Using some vmchannel impl. We need to create a local Unix
1103 * domain socket for qemu to use.
1105 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1107 null_vmchannel_sock = 0;
1111 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1112 perrorf (g, "pipe");
1118 print_timestamped_message (g, "finished testing qemu features");
1122 perrorf (g, "fork");
1132 if (r == 0) { /* Child (qemu). */
1134 const char *vmchannel = NULL;
1136 /* Set up the full command line. Do this in the subprocess so we
1137 * don't need to worry about cleaning up.
1139 g->cmdline[0] = g->qemu;
1141 /* qemu sometimes needs this option to enable hardware
1142 * virtualization, but some versions of 'qemu-kvm' will use KVM
1143 * regardless (even where this option appears in the help text).
1144 * It is rumoured that there are versions of qemu where supplying
1145 * this option when hardware virtualization is not available will
1146 * cause qemu to fail, so we we have to check at least that
1147 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1148 * might be openable by qemu but not by us (think: SELinux) in
1149 * which case the user would not get hardware virtualization,
1150 * although at least shouldn't fail. A giant clusterfuck with the
1151 * qemu command line, again.
1153 if (qemu_supports (g, "-enable-kvm") &&
1154 is_openable (g, "/dev/kvm", O_RDWR))
1155 add_cmdline (g, "-enable-kvm");
1157 /* Newer versions of qemu (from around 2009/12) changed the
1158 * behaviour of monitors so that an implicit '-monitor stdio' is
1159 * assumed if we are in -nographic mode and there is no other
1160 * -monitor option. Only a single stdio device is allowed, so
1161 * this broke the '-serial stdio' option. There is a new flag
1162 * called -nodefaults which gets rid of all this default crud, so
1163 * let's use that to avoid this and any future surprises.
1165 if (qemu_supports (g, "-nodefaults"))
1166 add_cmdline (g, "-nodefaults");
1168 add_cmdline (g, "-nographic");
1169 add_cmdline (g, "-serial");
1170 add_cmdline (g, "stdio");
1172 snprintf (buf, sizeof buf, "%d", g->memsize);
1173 add_cmdline (g, "-m");
1174 add_cmdline (g, buf);
1176 /* Force exit instead of reboot on panic */
1177 add_cmdline (g, "-no-reboot");
1179 /* These options recommended by KVM developers to improve reliability. */
1180 if (qemu_supports (g, "-no-hpet"))
1181 add_cmdline (g, "-no-hpet");
1183 if (qemu_supports (g, "-rtc-td-hack"))
1184 add_cmdline (g, "-rtc-td-hack");
1186 /* If qemu has SLIRP (user mode network) enabled then we can get
1187 * away with "no vmchannel", where we just connect back to a random
1190 if (null_vmchannel_sock) {
1191 add_cmdline (g, "-net");
1192 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1194 snprintf (buf, sizeof buf,
1195 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1196 vmchannel = strdup (buf);
1199 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1201 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1203 * The original suggested format doesn't work, see:
1205 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1207 * However Gerd Hoffman privately suggested to me using -chardev
1208 * instead, which does work.
1210 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1211 snprintf (buf, sizeof buf,
1212 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1214 add_cmdline (g, "-chardev");
1215 add_cmdline (g, buf);
1217 snprintf (buf, sizeof buf,
1218 "user,vlan=0,net=10.0.2.0/8,"
1219 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1220 "-chardev:guestfsvmc");
1222 add_cmdline (g, "-net");
1223 add_cmdline (g, buf);
1225 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1228 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1229 * syntax, or if not then we'll get a quick failure.
1232 snprintf (buf, sizeof buf,
1233 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1235 add_cmdline (g, "-net");
1236 add_cmdline (g, buf);
1237 add_cmdline (g, "-net");
1238 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1240 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1242 add_cmdline (g, "-net");
1243 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1245 #define LINUX_CMDLINE \
1246 "panic=1 " /* force kernel to panic if daemon exits */ \
1247 "console=ttyS0 " /* serial console */ \
1248 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1249 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1250 "acpi=off " /* we don't need ACPI, turn it off */ \
1251 "printk.time=1 " /* display timestamp before kernel messages */ \
1252 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1254 /* Linux kernel command line. */
1255 snprintf (buf, sizeof buf,
1257 "%s " /* (selinux) */
1258 "%s " /* (vmchannel) */
1259 "%s " /* (verbose) */
1260 "%s", /* (append) */
1261 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1262 vmchannel ? vmchannel : "",
1263 g->verbose ? "guestfs_verbose=1" : "",
1264 g->append ? g->append : "");
1266 add_cmdline (g, "-kernel");
1267 add_cmdline (g, (char *) kernel);
1268 add_cmdline (g, "-initrd");
1269 add_cmdline (g, (char *) initrd);
1270 add_cmdline (g, "-append");
1271 add_cmdline (g, buf);
1273 /* Finish off the command line. */
1274 incr_cmdline_size (g);
1275 g->cmdline[g->cmdline_size-1] = NULL;
1281 /* Set up stdin, stdout. */
1287 if (dup (wfd[0]) == -1) {
1289 perror ("dup failed");
1290 _exit (EXIT_FAILURE);
1292 if (dup (rfd[1]) == -1)
1300 /* Set up a new process group, so we can signal this process
1301 * and all subprocesses (eg. if qemu is really a shell script).
1306 setenv ("LC_ALL", "C", 1);
1308 execv (g->qemu, g->cmdline); /* Run qemu. */
1310 _exit (EXIT_FAILURE);
1313 /* Parent (library). */
1321 /* Fork the recovery process off which will kill qemu if the parent
1322 * process fails to do so (eg. if the parent segfaults).
1324 g->recoverypid = -1;
1325 if (g->recovery_proc) {
1328 pid_t qemu_pid = g->pid;
1329 pid_t parent_pid = getppid ();
1331 /* Writing to argv is hideously complicated and error prone. See:
1332 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1335 /* Loop around waiting for one or both of the other processes to
1336 * disappear. It's fair to say this is very hairy. The PIDs that
1337 * we are looking at might be reused by another process. We are
1338 * effectively polling. Is the cure worse than the disease?
1341 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1342 _exit (EXIT_SUCCESS);
1343 if (kill (parent_pid, 0) == -1) {
1344 /* Parent's gone away, qemu still around, so kill qemu. */
1346 _exit (EXIT_SUCCESS);
1352 /* Don't worry, if the fork failed, this will be -1. The recovery
1353 * process isn't essential.
1359 /* Close the other ends of the pipe. */
1363 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1364 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1365 perrorf (g, "fcntl");
1369 g->fd[0] = wfd[1]; /* stdin of child */
1370 g->fd[1] = rfd[0]; /* stdout of child */
1372 g->fd[0] = open ("/dev/null", O_RDWR);
1373 if (g->fd[0] == -1) {
1374 perrorf (g, "open /dev/null");
1377 g->fd[1] = dup (g->fd[0]);
1378 if (g->fd[1] == -1) {
1385 if (null_vmchannel_sock) {
1389 /* Null vmchannel implementation: We listen on g->sock for a
1390 * connection. The connection could come from any local process
1391 * so we must check it comes from the appliance (or at least
1392 * from our UID) for security reasons.
1394 while (sock == -1) {
1395 sock = accept_from_daemon (g);
1399 if (check_peer_euid (g, sock, &uid) == -1)
1401 if (uid != geteuid ()) {
1403 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1404 uid, null_vmchannel_sock);
1410 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1411 perrorf (g, "fcntl");
1418 /* Other vmchannel. Open the Unix socket.
1420 * The vmchannel implementation that got merged with qemu sucks in
1421 * a number of ways. Both ends do connect(2), which means that no
1422 * one knows what, if anything, is connected to the other end, or
1423 * if it becomes disconnected. Even worse, we have to wait some
1424 * indeterminate time for qemu to create the socket and connect to
1425 * it (which happens very early in qemu's start-up), so any code
1426 * that uses vmchannel is inherently racy. Hence this silly loop.
1428 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1429 if (g->sock == -1) {
1430 perrorf (g, "socket");
1434 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1435 perrorf (g, "fcntl");
1439 addr.sun_family = AF_UNIX;
1440 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1441 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1444 /* Always sleep at least once to give qemu a small chance to start up. */
1447 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1448 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1451 if (errno != ENOENT)
1452 perrorf (g, "connect");
1457 error (g, _("failed to connect to vmchannel socket"));
1463 g->state = LAUNCHING;
1465 /* Wait for qemu to start and to connect back to us via vmchannel and
1466 * send the GUESTFS_LAUNCH_FLAG message.
1470 r = recv_from_daemon (g, &size, &buf);
1473 if (r == -1) return -1;
1475 if (size != GUESTFS_LAUNCH_FLAG) {
1476 error (g, _("guestfs_launch failed, see earlier error messages"));
1481 print_timestamped_message (g, "appliance is up");
1483 /* This is possible in some really strange situations, such as
1484 * guestfsd starts up OK but then qemu immediately exits. Check for
1485 * it because the caller is probably expecting to be able to send
1486 * commands after this function returns.
1488 if (g->state != READY) {
1489 error (g, _("qemu launched and contacted daemon, but state != READY"));
1501 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1502 waitpid (g->pid, NULL, 0);
1503 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1508 memset (&g->launch_t, 0, sizeof g->launch_t);
1521 /* This function is used to print the qemu command line before it gets
1522 * executed, when in verbose mode.
1525 print_cmdline (guestfs_h *g)
1530 while (g->cmdline[i]) {
1531 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1532 fprintf (stderr, " \\\n ");
1534 if (i > 0) fputc (' ', stderr);
1536 /* Does it need shell quoting? This only deals with simple cases. */
1537 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1539 if (needs_quote) fputc ('\'', stderr);
1540 fprintf (stderr, "%s", g->cmdline[i]);
1541 if (needs_quote) fputc ('\'', stderr);
1545 fputc ('\n', stderr);
1548 /* This function does the hard work of building the supermin appliance
1549 * on the fly. 'path' is the directory containing the control files.
1550 * 'kernel' and 'initrd' are where we will return the names of the
1551 * kernel and initrd (only initrd is built). The work is done by
1552 * an external script. We just tell it where to put the result.
1555 build_supermin_appliance (guestfs_h *g, const char *path,
1556 char **kernel, char **initrd)
1562 print_timestamped_message (g, "begin building supermin appliance");
1564 len = strlen (g->tmpdir);
1565 *kernel = safe_malloc (g, len + 8);
1566 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1567 *initrd = safe_malloc (g, len + 8);
1568 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1570 snprintf (cmd, sizeof cmd,
1572 "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1574 g->verbose ? " --verbose" : "",
1575 path, *kernel, *initrd);
1577 print_timestamped_message (g, "%s", cmd);
1580 if (r == -1 || WEXITSTATUS(r) != 0) {
1581 error (g, _("external command failed: %s"), cmd);
1584 *kernel = *initrd = NULL;
1589 print_timestamped_message (g, "finished building supermin appliance");
1594 /* Compute Y - X and return the result in milliseconds.
1595 * Approximately the same as this code:
1596 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1599 timeval_diff (const struct timeval *x, const struct timeval *y)
1603 msec = (y->tv_sec - x->tv_sec) * 1000;
1604 msec += (y->tv_usec - x->tv_usec) / 1000;
1609 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1616 va_start (args, fs);
1617 err = vasprintf (&msg, fs, args);
1620 if (err < 0) return;
1622 gettimeofday (&tv, NULL);
1624 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1625 timeval_diff (&g->launch_t, &tv), msg);
1630 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1632 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1633 * 'qemu -version' so we know what options this qemu supports and
1637 test_qemu (guestfs_h *g)
1642 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1644 fp = popen (cmd, "r");
1645 /* qemu -help should always work (qemu -version OTOH wasn't
1646 * supported by qemu 0.9). If this command doesn't work then it
1647 * probably indicates that the qemu binary is missing.
1650 /* XXX This error is never printed, even if the qemu binary
1651 * doesn't exist. Why?
1654 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1658 if (read_all (g, fp, &g->qemu_help) == -1)
1661 if (pclose (fp) == -1)
1664 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1667 fp = popen (cmd, "r");
1669 /* Intentionally ignore errors. */
1670 read_all (g, fp, &g->qemu_version);
1678 read_all (guestfs_h *g, FILE *fp, char **ret)
1685 *ret = safe_realloc (g, *ret, n + 1);
1690 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1692 r = fread (p, 1, BUFSIZ, fp);
1694 perrorf (g, "read");
1701 /* Test if option is supported by qemu command line (just by grepping
1704 * The first time this is used, it has to run the external qemu
1705 * binary. If that fails, it returns -1.
1707 * To just do the first-time run of the qemu binary, call this with
1708 * option == NULL, in which case it will return -1 if there was an
1712 qemu_supports (guestfs_h *g, const char *option)
1714 if (!g->qemu_help) {
1715 if (test_qemu (g) == -1)
1722 return strstr (g->qemu_help, option) != NULL;
1725 /* Check if a file can be opened. */
1727 is_openable (guestfs_h *g, const char *path, int flags)
1729 int fd = open (path, flags);
1739 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1740 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1741 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1744 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1746 #if CAN_CHECK_PEER_EUID
1747 struct sockaddr_in peer;
1748 socklen_t addrlen = sizeof peer;
1750 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1751 perrorf (g, "getpeername");
1755 if (peer.sin_family != AF_INET ||
1756 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1757 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1758 peer.sin_family, inet_ntoa (peer.sin_addr));
1762 struct sockaddr_in our;
1763 addrlen = sizeof our;
1764 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1765 perrorf (g, "getsockname");
1769 FILE *fp = fopen ("/proc/net/tcp", "r");
1771 perrorf (g, "/proc/net/tcp");
1776 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1777 error (g, "unexpected end of file in /proc/net/tcp");
1782 while (fgets (line, sizeof line, fp) != NULL) {
1783 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1784 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1787 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1789 &line_our_addr, &line_our_port,
1790 &line_peer_addr, &line_peer_port,
1791 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1793 /* Note about /proc/net/tcp: local_address and rem_address are
1794 * always in network byte order. However the port part is
1795 * always in host byte order.
1797 * The sockname and peername that we got above are in network
1798 * byte order. So we have to byte swap the port but not the
1801 if (line_our_addr == our.sin_addr.s_addr &&
1802 line_our_port == ntohs (our.sin_port) &&
1803 line_peer_addr == peer.sin_addr.s_addr &&
1804 line_peer_port == ntohs (peer.sin_port)) {
1812 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1815 #else /* !CAN_CHECK_PEER_EUID */
1816 /* This function exists but should never be called in this
1820 #endif /* !CAN_CHECK_PEER_EUID */
1823 /* You had to call this function after launch in versions <= 1.0.70,
1824 * but it is now a no-op.
1827 guestfs__wait_ready (guestfs_h *g)
1829 if (g->state != READY) {
1830 error (g, _("qemu has not been launched yet"));
1838 guestfs__kill_subprocess (guestfs_h *g)
1840 if (g->state == CONFIG) {
1841 error (g, _("no subprocess to kill"));
1846 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1848 kill (g->pid, SIGTERM);
1849 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1854 /* Access current state. */
1856 guestfs__is_config (guestfs_h *g)
1858 return g->state == CONFIG;
1862 guestfs__is_launching (guestfs_h *g)
1864 return g->state == LAUNCHING;
1868 guestfs__is_ready (guestfs_h *g)
1870 return g->state == READY;
1874 guestfs__is_busy (guestfs_h *g)
1876 return g->state == BUSY;
1880 guestfs__get_state (guestfs_h *g)
1886 guestfs_set_log_message_callback (guestfs_h *g,
1887 guestfs_log_message_cb cb, void *opaque)
1889 g->log_message_cb = cb;
1890 g->log_message_cb_data = opaque;
1894 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1895 guestfs_subprocess_quit_cb cb, void *opaque)
1897 g->subprocess_quit_cb = cb;
1898 g->subprocess_quit_cb_data = opaque;
1902 guestfs_set_launch_done_callback (guestfs_h *g,
1903 guestfs_launch_done_cb cb, void *opaque)
1905 g->launch_done_cb = cb;
1906 g->launch_done_cb_data = opaque;
1909 /*----------------------------------------------------------------------*/
1911 /* This is the code used to send and receive RPC messages and (for
1912 * certain types of message) to perform file transfers. This code is
1913 * driven from the generated actions (src/guestfs-actions.c). There
1914 * are five different cases to consider:
1916 * (1) A non-daemon function. There is no RPC involved at all, it's
1917 * all handled inside the library.
1919 * (2) A simple RPC (eg. "mount"). We write the request, then read
1920 * the reply. The sequence of calls is:
1922 * guestfs___set_busy
1925 * guestfs___end_busy
1927 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1928 * request, then write the file(s), then read the reply. The sequence
1931 * guestfs___set_busy
1933 * guestfs___send_file (possibly multiple times)
1935 * guestfs___end_busy
1937 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1938 * request, then read the reply, then read the file(s). The sequence
1941 * guestfs___set_busy
1944 * guestfs___recv_file (possibly multiple times)
1945 * guestfs___end_busy
1947 * (5) Both FileOut and FileIn parameters. There are no calls like
1948 * this in the current API, but they would be implemented as a
1949 * combination of cases (3) and (4).
1951 * During all writes and reads, we also select(2) on qemu stdout
1952 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1953 * anything received is passed up through the log_message_cb. This is
1954 * also the reason why all the sockets are non-blocking. We also have
1955 * to check for EOF (qemu died). All of this is handled by the
1956 * functions send_to_daemon and recv_from_daemon.
1960 guestfs___set_busy (guestfs_h *g)
1962 if (g->state != READY) {
1963 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1972 guestfs___end_busy (guestfs_h *g)
1986 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1992 /* This is called if we detect EOF, ie. qemu died. */
1994 child_cleanup (guestfs_h *g)
1997 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1999 /*kill (g->pid, SIGTERM);*/
2000 if (g->recoverypid > 0) kill (g->recoverypid, 9);
2001 waitpid (g->pid, NULL, 0);
2002 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
2011 memset (&g->launch_t, 0, sizeof g->launch_t);
2013 if (g->subprocess_quit_cb)
2014 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2018 read_log_message_or_eof (guestfs_h *g, int fd)
2026 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2030 /* QEMU's console emulates a 16550A serial port. The real 16550A
2031 * device has a small FIFO buffer (16 bytes) which means here we see
2032 * lots of small reads of 1-16 bytes in length, usually single
2035 n = read (fd, buf, sizeof buf);
2037 /* Hopefully this indicates the qemu child process has died. */
2043 if (errno == EINTR || errno == EAGAIN)
2046 perrorf (g, "read");
2050 /* In verbose mode, copy all log messages to stderr. */
2052 ignore_value (write (STDERR_FILENO, buf, n));
2054 /* It's an actual log message, send it upwards if anyone is listening. */
2055 if (g->log_message_cb)
2056 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2062 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2071 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2074 n = read (fd, buf, 4);
2076 /* Hopefully this indicates the qemu child process has died. */
2082 if (errno == EINTR || errno == EAGAIN)
2085 perrorf (g, "read");
2089 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2090 xdr_uint32_t (&xdr, &flag);
2093 if (flag != GUESTFS_CANCEL_FLAG) {
2094 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2095 flag, GUESTFS_CANCEL_FLAG);
2102 /* This writes the whole N bytes of BUF to the daemon socket.
2104 * If the whole write is successful, it returns 0.
2105 * If there was an error, it returns -1.
2106 * If the daemon sent a cancellation message, it returns -2.
2108 * It also checks qemu stdout for log messages and passes those up
2109 * through log_message_cb.
2111 * It also checks for EOF (qemu died) and passes that up through the
2112 * child_cleanup function above.
2115 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2117 const char *buf = v_buf;
2123 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2128 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2129 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2130 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2132 int max_fd = MAX (g->sock, g->fd[1]);
2137 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2139 if (errno == EINTR || errno == EAGAIN)
2141 perrorf (g, "select");
2145 if (FD_ISSET (g->fd[1], &rset2)) {
2146 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2149 if (FD_ISSET (g->sock, &rset2)) {
2150 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2154 if (FD_ISSET (g->sock, &wset2)) {
2155 r = write (g->sock, buf, n);
2157 if (errno == EINTR || errno == EAGAIN)
2159 perrorf (g, "write");
2160 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2172 /* This reads a single message, file chunk, launch flag or
2173 * cancellation flag from the daemon. If something was read, it
2174 * returns 0, otherwise -1.
2176 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2178 * *size_rtn returns the size of the returned message or it may be
2179 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2181 * *buf_rtn is returned containing the message (if any) or will be set
2182 * to NULL. *buf_rtn must be freed by the caller.
2184 * It also checks qemu stdout for log messages and passes those up
2185 * through log_message_cb.
2187 * It also checks for EOF (qemu died) and passes that up through the
2188 * child_cleanup function above.
2191 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2197 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2198 g, g->state, size_rtn, buf_rtn);
2202 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2203 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2205 int max_fd = MAX (g->sock, g->fd[1]);
2211 /* nr is the size of the message, but we prime it as -4 because we
2212 * have to read the message length word first.
2216 while (nr < (ssize_t) *size_rtn) {
2218 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2220 if (errno == EINTR || errno == EAGAIN)
2222 perrorf (g, "select");
2228 if (FD_ISSET (g->fd[1], &rset2)) {
2229 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2235 if (FD_ISSET (g->sock, &rset2)) {
2236 if (nr < 0) { /* Have we read the message length word yet? */
2237 r = read (g->sock, lenbuf+nr+4, -nr);
2239 if (errno == EINTR || errno == EAGAIN)
2242 perrorf (g, "read");
2243 /* Under some circumstances we see "Connection reset by peer"
2244 * here when the child dies suddenly. Catch this and call
2245 * the cleanup function, same as for EOF.
2247 if (err == ECONNRESET)
2252 error (g, _("unexpected end of file when reading from daemon"));
2258 if (nr < 0) /* Still not got the whole length word. */
2262 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2263 xdr_uint32_t (&xdr, size_rtn);
2266 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2267 if (g->state != LAUNCHING)
2268 error (g, _("received magic signature from guestfsd, but in state %d"),
2272 if (g->launch_done_cb)
2273 g->launch_done_cb (g, g->launch_done_cb_data);
2277 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2279 /* If this happens, it's pretty bad and we've probably lost
2282 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2283 error (g, _("message length (%u) > maximum possible size (%d)"),
2284 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2288 /* Allocate the complete buffer, size now known. */
2289 *buf_rtn = safe_malloc (g, *size_rtn);
2293 size_t sizetoread = *size_rtn - nr;
2294 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2296 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2298 if (errno == EINTR || errno == EAGAIN)
2300 perrorf (g, "read");
2306 error (g, _("unexpected end of file when reading from daemon"));
2316 /* Got the full message, caller can start processing it. */
2317 #ifdef ENABLE_PACKET_DUMP
2321 for (i = 0; i < nr; i += 16) {
2322 printf ("%04zx: ", i);
2323 for (j = i; j < MIN (i+16, nr); ++j)
2324 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2325 for (; j < i+16; ++j)
2328 for (j = i; j < MIN (i+16, nr); ++j)
2329 if (c_isprint ((*(char **)buf_rtn)[j]))
2330 printf ("%c", (*(char **)buf_rtn)[j]);
2333 for (; j < i+16; ++j)
2343 /* This is very much like recv_from_daemon above, but g->sock is
2344 * a listening socket and we are accepting a new connection on
2345 * that socket instead of reading anything. Returns the newly
2349 accept_from_daemon (guestfs_h *g)
2355 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2359 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2360 FD_SET (g->sock, &rset); /* Read socket for accept. */
2362 int max_fd = MAX (g->sock, g->fd[1]);
2365 while (sock == -1) {
2367 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2369 if (errno == EINTR || errno == EAGAIN)
2371 perrorf (g, "select");
2375 if (FD_ISSET (g->fd[1], &rset2)) {
2376 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2379 if (FD_ISSET (g->sock, &rset2)) {
2380 sock = accept (g->sock, NULL, NULL);
2382 if (errno == EINTR || errno == EAGAIN)
2384 perrorf (g, "accept");
2394 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2396 struct guestfs_message_header hdr;
2399 int serial = g->msg_next_serial++;
2402 size_t msg_out_size;
2404 if (g->state != BUSY) {
2405 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2409 /* We have to allocate this message buffer on the heap because
2410 * it is quite large (although will be mostly unused). We
2411 * can't allocate it on the stack because in some environments
2412 * we have quite limited stack space available, notably when
2413 * running in the JVM.
2415 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2416 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2418 /* Serialize the header. */
2419 hdr.prog = GUESTFS_PROGRAM;
2420 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2422 hdr.direction = GUESTFS_DIRECTION_CALL;
2423 hdr.serial = serial;
2424 hdr.status = GUESTFS_STATUS_OK;
2426 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2427 error (g, _("xdr_guestfs_message_header failed"));
2431 /* Serialize the args. If any, because some message types
2432 * have no parameters.
2435 if (!(*xdrp) (&xdr, args)) {
2436 error (g, _("dispatch failed to marshal args"));
2441 /* Get the actual length of the message, resize the buffer to match
2442 * the actual length, and write the length word at the beginning.
2444 len = xdr_getpos (&xdr);
2447 msg_out = safe_realloc (g, msg_out, len + 4);
2448 msg_out_size = len + 4;
2450 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2451 xdr_uint32_t (&xdr, &len);
2454 r = send_to_daemon (g, msg_out, msg_out_size);
2455 if (r == -2) /* Ignore stray daemon cancellations. */
2468 static int cancel = 0; /* XXX Implement file cancellation. */
2469 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2470 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2471 static int send_file_cancellation (guestfs_h *g);
2472 static int send_file_complete (guestfs_h *g);
2478 * -2 daemon cancelled (we must read the error message)
2481 guestfs___send_file (guestfs_h *g, const char *filename)
2483 char buf[GUESTFS_MAX_CHUNK_SIZE];
2486 fd = open (filename, O_RDONLY);
2488 perrorf (g, "open: %s", filename);
2489 send_file_cancellation (g);
2490 /* Daemon sees cancellation and won't reply, so caller can
2496 /* Send file in chunked encoding. */
2498 r = read (fd, buf, sizeof buf);
2499 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2502 err = send_file_data (g, buf, r);
2504 if (err == -2) /* daemon sent cancellation */
2505 send_file_cancellation (g);
2510 if (cancel) { /* cancel from either end */
2511 send_file_cancellation (g);
2516 perrorf (g, "read: %s", filename);
2517 send_file_cancellation (g);
2521 /* End of file, but before we send that, we need to close
2522 * the file and check for errors.
2524 if (close (fd) == -1) {
2525 perrorf (g, "close: %s", filename);
2526 send_file_cancellation (g);
2530 return send_file_complete (g);
2533 /* Send a chunk of file data. */
2535 send_file_data (guestfs_h *g, const char *buf, size_t len)
2537 return send_file_chunk (g, 0, buf, len);
2540 /* Send a cancellation message. */
2542 send_file_cancellation (guestfs_h *g)
2544 return send_file_chunk (g, 1, NULL, 0);
2547 /* Send a file complete chunk. */
2549 send_file_complete (guestfs_h *g)
2552 return send_file_chunk (g, 0, buf, 0);
2556 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2560 guestfs_chunk chunk;
2563 size_t msg_out_size;
2565 if (g->state != BUSY) {
2566 error (g, _("send_file_chunk: state %d != READY"), g->state);
2570 /* Allocate the chunk buffer. Don't use the stack to avoid
2571 * excessive stack usage and unnecessary copies.
2573 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2574 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2576 /* Serialize the chunk. */
2577 chunk.cancel = cancel;
2578 chunk.data.data_len = buflen;
2579 chunk.data.data_val = (char *) buf;
2581 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2582 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2588 len = xdr_getpos (&xdr);
2591 /* Reduce the size of the outgoing message buffer to the real length. */
2592 msg_out = safe_realloc (g, msg_out, len + 4);
2593 msg_out_size = len + 4;
2595 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2596 xdr_uint32_t (&xdr, &len);
2598 r = send_to_daemon (g, msg_out, msg_out_size);
2600 /* Did the daemon send a cancellation message? */
2603 fprintf (stderr, "got daemon cancellation\n");
2619 /* Receive a reply. */
2621 guestfs___recv (guestfs_h *g, const char *fn,
2622 guestfs_message_header *hdr,
2623 guestfs_message_error *err,
2624 xdrproc_t xdrp, char *ret)
2632 r = recv_from_daemon (g, &size, &buf);
2636 /* This can happen if a cancellation happens right at the end
2637 * of us sending a FileIn parameter to the daemon. Discard. The
2638 * daemon should send us an error message next.
2640 if (size == GUESTFS_CANCEL_FLAG)
2643 if (size == GUESTFS_LAUNCH_FLAG) {
2644 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2648 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2650 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2651 error (g, "%s: failed to parse reply header", fn);
2656 if (hdr->status == GUESTFS_STATUS_ERROR) {
2657 if (!xdr_guestfs_message_error (&xdr, err)) {
2658 error (g, "%s: failed to parse reply error", fn);
2664 if (xdrp && ret && !xdrp (&xdr, ret)) {
2665 error (g, "%s: failed to parse reply", fn);
2677 /* Receive a file. */
2679 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2680 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2683 guestfs___recv_file (guestfs_h *g, const char *filename)
2688 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2690 perrorf (g, "open: %s", filename);
2694 /* Receive the file in chunked encoding. */
2695 while ((r = receive_file_data (g, &buf)) > 0) {
2696 if (xwrite (fd, buf, r) == -1) {
2697 perrorf (g, "%s: write", filename);
2705 error (g, _("%s: error in chunked encoding"), filename);
2709 if (close (fd) == -1) {
2710 perrorf (g, "close: %s", filename);
2717 /* Send cancellation message to daemon, then wait until it
2718 * cancels (just throwing away data).
2722 uint32_t flag = GUESTFS_CANCEL_FLAG;
2725 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2728 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2729 xdr_uint32_t (&xdr, &flag);
2732 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2733 perrorf (g, _("write to daemon socket"));
2737 while (receive_file_data (g, NULL) > 0)
2738 ; /* just discard it */
2743 /* Receive a chunk of file data. */
2744 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2746 receive_file_data (guestfs_h *g, void **buf_r)
2752 guestfs_chunk chunk;
2754 r = recv_from_daemon (g, &len, &buf);
2756 error (g, _("receive_file_data: parse error in reply callback"));
2760 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2761 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2765 memset (&chunk, 0, sizeof chunk);
2767 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2768 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2769 error (g, _("failed to parse file chunk"));
2774 /* After decoding, the original buffer is no longer used. */
2778 error (g, _("file receive cancelled by daemon"));
2779 free (chunk.data.data_val);
2783 if (chunk.data.data_len == 0) { /* end of transfer */
2784 free (chunk.data.data_val);
2788 if (buf_r) *buf_r = chunk.data.data_val;
2789 else free (chunk.data.data_val); /* else caller frees */
2791 return chunk.data.data_len;