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
89 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
90 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
91 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
92 static int accept_from_daemon (guestfs_h *g);
93 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
94 static void close_handles (void);
95 static int qemu_supports (guestfs_h *g, const char *option);
97 #define UNIX_PATH_MAX 108
100 #define MAX(a,b) ((a)>(b)?(a):(b))
104 #define xdr_uint32_t xdr_u_int32_t
107 /* Also in guestfsd.c */
108 #define GUESTFWD_ADDR "10.0.2.4"
109 #define GUESTFWD_PORT "6666"
111 /* GuestFS handle and connection. */
112 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
116 struct guestfs_h *next; /* Linked list of open handles. */
118 /* State: see the state machine diagram in the man page guestfs(3). */
121 int fd[2]; /* Stdin/stdout of qemu. */
122 int sock; /* Daemon communications socket. */
123 pid_t pid; /* Qemu PID. */
124 pid_t recoverypid; /* Recovery process PID. */
126 struct timeval launch_t; /* The time that we called guestfs_launch. */
128 char *tmpdir; /* Temporary directory containing socket. */
130 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
132 char **cmdline; /* Qemu command line. */
141 char *path; /* Path to kernel, initrd. */
142 char *qemu; /* Qemu binary. */
143 char *append; /* Append to kernel command line. */
145 int memsize; /* Size of RAM (megabytes). */
147 int selinux; /* selinux enabled? */
152 guestfs_abort_cb abort_cb;
153 guestfs_error_handler_cb error_cb;
154 void * error_cb_data;
155 guestfs_log_message_cb log_message_cb;
156 void * log_message_cb_data;
157 guestfs_subprocess_quit_cb subprocess_quit_cb;
158 void * subprocess_quit_cb_data;
159 guestfs_launch_done_cb launch_done_cb;
160 void * launch_done_cb_data;
165 gl_lock_define_initialized (static, handles_lock);
166 static guestfs_h *handles = NULL;
167 static int atexit_handler_set = 0;
170 guestfs_create (void)
175 g = malloc (sizeof (*g));
178 memset (g, 0, sizeof (*g));
187 g->error_cb = default_error_cb;
188 g->error_cb_data = NULL;
190 g->recovery_proc = 1;
192 str = getenv ("LIBGUESTFS_DEBUG");
193 g->verbose = str != NULL && STREQ (str, "1");
195 str = getenv ("LIBGUESTFS_TRACE");
196 g->trace = str != NULL && STREQ (str, "1");
198 str = getenv ("LIBGUESTFS_PATH");
199 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
200 if (!g->path) goto error;
202 str = getenv ("LIBGUESTFS_QEMU");
203 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
204 if (!g->qemu) goto error;
206 str = getenv ("LIBGUESTFS_APPEND");
208 g->append = strdup (str);
209 if (!g->append) goto error;
212 /* Choose a suitable memory size. Previously we tried to choose
213 * a minimal memory size, but this isn't really necessary since
214 * recent QEMU and KVM don't do anything nasty like locking
215 * memory into core any more. Thus we can safely choose a
216 * large, generous amount of memory, and it'll just get swapped
217 * on smaller systems.
219 str = getenv ("LIBGUESTFS_MEMSIZE");
221 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
222 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
228 /* Start with large serial numbers so they are easy to spot
229 * inside the protocol.
231 g->msg_next_serial = 0x00123400;
233 /* Link the handles onto a global list. */
234 gl_lock_lock (handles_lock);
237 if (!atexit_handler_set) {
238 atexit (close_handles);
239 atexit_handler_set = 1;
241 gl_lock_unlock (handles_lock);
244 fprintf (stderr, "new guestfs handle %p\n", g);
257 guestfs_close (guestfs_h *g)
263 if (g->state == NO_HANDLE) {
264 /* Not safe to call 'error' here, so ... */
265 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
270 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
272 /* Try to sync if autosync flag is set. */
273 if (g->autosync && g->state == READY) {
274 guestfs_umount_all (g);
278 /* Remove any handlers that might be called back before we kill the
281 g->log_message_cb = NULL;
283 if (g->state != CONFIG)
284 guestfs_kill_subprocess (g);
297 /* Wait for subprocess(es) to exit. */
298 waitpid (g->pid, NULL, 0);
299 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
301 /* Remove tmpfiles. */
303 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
306 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
309 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
318 for (i = 0; i < g->cmdline_size; ++i)
319 free (g->cmdline[i]);
323 /* Mark the handle as dead before freeing it. */
324 g->state = NO_HANDLE;
326 gl_lock_lock (handles_lock);
330 for (gg = handles; gg->next != g; gg = gg->next)
334 gl_lock_unlock (handles_lock);
336 free (g->last_error);
341 free (g->qemu_version);
345 /* Close all open handles (called from atexit(3)). */
349 while (handles) guestfs_close (handles);
353 guestfs_last_error (guestfs_h *g)
355 return g->last_error;
359 set_last_error (guestfs_h *g, const char *msg)
361 free (g->last_error);
362 g->last_error = strdup (msg);
366 default_error_cb (guestfs_h *g, void *data, const char *msg)
368 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
372 guestfs_error (guestfs_h *g, const char *fs, ...)
378 int err = vasprintf (&msg, fs, args);
383 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
384 set_last_error (g, msg);
390 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
397 int err = vasprintf (&msg, fs, args);
402 #if !defined(_GNU_SOURCE) || defined(__APPLE__)
404 strerror_r (errnum, buf, sizeof buf);
408 buf = strerror_r (errnum, _buf, sizeof _buf);
411 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
415 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
416 set_last_error (g, msg);
422 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
424 void *ptr = malloc (nbytes);
425 if (nbytes > 0 && !ptr) g->abort_cb ();
429 /* Return 1 if an array of N objects, each of size S, cannot exist due
430 to size arithmetic overflow. S must be positive and N must be
431 nonnegative. This is a macro, not an inline function, so that it
432 works correctly even when SIZE_MAX < N.
434 By gnulib convention, SIZE_MAX represents overflow in size
435 calculations, so the conservative dividend to use here is
436 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
437 However, malloc (SIZE_MAX) fails on all known hosts where
438 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
439 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
440 branch when S is known to be 1. */
441 # define xalloc_oversized(n, s) \
442 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
444 /* Technically we should add an autoconf test for this, testing for the desired
445 functionality, like what's done in gnulib, but for now, this is fine. */
446 #if defined(__GLIBC__)
447 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
449 #define HAVE_GNU_CALLOC 0
452 /* Allocate zeroed memory for N elements of S bytes, with error
453 checking. S must be nonzero. */
455 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
457 /* From gnulib's calloc function in xmalloc.c. */
459 /* Test for overflow, since some calloc implementations don't have
460 proper overflow checks. But omit overflow and size-zero tests if
461 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
462 returns NULL if successful. */
463 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
464 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
470 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
472 void *p = realloc (ptr, nbytes);
473 if (nbytes > 0 && !p) g->abort_cb ();
478 guestfs_safe_strdup (guestfs_h *g, const char *str)
480 char *s = strdup (str);
481 if (!s) g->abort_cb ();
486 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
488 void *p = malloc (size);
489 if (!p) g->abort_cb ();
490 memcpy (p, ptr, size);
495 xwrite (int fd, const void *v_buf, size_t len)
497 const char *buf = v_buf;
501 r = write (fd, buf, len);
513 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
519 guestfs_get_out_of_memory_handler (guestfs_h *g)
525 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
528 g->error_cb_data = data;
531 guestfs_error_handler_cb
532 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
534 if (data_rtn) *data_rtn = g->error_cb_data;
539 guestfs__set_verbose (guestfs_h *g, int v)
546 guestfs__get_verbose (guestfs_h *g)
552 guestfs__set_autosync (guestfs_h *g, int a)
559 guestfs__get_autosync (guestfs_h *g)
565 guestfs__set_path (guestfs_h *g, const char *path)
572 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
577 guestfs__get_path (guestfs_h *g)
583 guestfs__set_qemu (guestfs_h *g, const char *qemu)
588 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
593 guestfs__get_qemu (guestfs_h *g)
599 guestfs__set_append (guestfs_h *g, const char *append)
604 g->append = append ? safe_strdup (g, append) : NULL;
609 guestfs__get_append (guestfs_h *g)
615 guestfs__set_memsize (guestfs_h *g, int memsize)
617 g->memsize = memsize;
622 guestfs__get_memsize (guestfs_h *g)
628 guestfs__set_selinux (guestfs_h *g, int selinux)
630 g->selinux = selinux;
635 guestfs__get_selinux (guestfs_h *g)
641 guestfs__get_pid (guestfs_h *g)
646 error (g, "get_pid: no qemu subprocess");
651 struct guestfs_version *
652 guestfs__version (guestfs_h *g)
654 struct guestfs_version *r;
656 r = safe_malloc (g, sizeof *r);
657 r->major = PACKAGE_VERSION_MAJOR;
658 r->minor = PACKAGE_VERSION_MINOR;
659 r->release = PACKAGE_VERSION_RELEASE;
660 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
665 guestfs__set_trace (guestfs_h *g, int t)
672 guestfs__get_trace (guestfs_h *g)
678 guestfs__set_direct (guestfs_h *g, int d)
685 guestfs__get_direct (guestfs_h *g)
691 guestfs__set_recovery_proc (guestfs_h *g, int f)
693 g->recovery_proc = !!f;
698 guestfs__get_recovery_proc (guestfs_h *g)
700 return g->recovery_proc;
703 /* Add a string to the current command line. */
705 incr_cmdline_size (guestfs_h *g)
707 if (g->cmdline == NULL) {
708 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
710 g->cmdline = safe_malloc (g, sizeof (char *));
711 g->cmdline[0] = NULL;
715 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
719 add_cmdline (guestfs_h *g, const char *str)
721 if (g->state != CONFIG) {
723 _("command line cannot be altered after qemu subprocess launched"));
727 incr_cmdline_size (g);
728 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
733 guestfs__config (guestfs_h *g,
734 const char *qemu_param, const char *qemu_value)
736 if (qemu_param[0] != '-') {
737 error (g, _("guestfs_config: parameter must begin with '-' character"));
741 /* A bit fascist, but the user will probably break the extra
742 * parameters that we add if they try to set any of these.
744 if (STREQ (qemu_param, "-kernel") ||
745 STREQ (qemu_param, "-initrd") ||
746 STREQ (qemu_param, "-nographic") ||
747 STREQ (qemu_param, "-serial") ||
748 STREQ (qemu_param, "-full-screen") ||
749 STREQ (qemu_param, "-std-vga") ||
750 STREQ (qemu_param, "-vnc")) {
751 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
755 if (add_cmdline (g, qemu_param) != 0) return -1;
757 if (qemu_value != NULL) {
758 if (add_cmdline (g, qemu_value) != 0) return -1;
765 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
766 const char *drive_if)
768 size_t len = strlen (filename) + 64;
771 if (strchr (filename, ',') != NULL) {
772 error (g, _("filename cannot contain ',' (comma) character"));
776 /* cache=off improves reliability in the event of a host crash.
778 * However this option causes qemu to try to open the file with
779 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
780 * So we check if we can open the file with or without O_DIRECT,
781 * and use cache=off (or not) accordingly.
783 * This test also checks for the presence of the file, which
784 * is a documented semantic of this interface.
786 int fd = open (filename, O_RDONLY|O_DIRECT);
789 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, drive_if);
791 fd = open (filename, O_RDONLY);
794 snprintf (buf, len, "file=%s,if=%s", filename, drive_if);
796 perrorf (g, "%s", filename);
801 return guestfs__config (g, "-drive", buf);
805 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
806 const char *drive_if)
808 if (strchr (filename, ',') != NULL) {
809 error (g, _("filename cannot contain ',' (comma) character"));
813 if (access (filename, F_OK) == -1) {
814 perrorf (g, "%s", filename);
818 if (qemu_supports (g, NULL) == -1)
821 /* Only SCSI and virtio drivers support readonly mode.
822 * This is only supported as a QEMU feature since 2010/01.
825 if ((STREQ (drive_if, "scsi") || STREQ (drive_if, "virtio")) &&
826 qemu_supports (g, "readonly=on"))
829 size_t len = strlen (filename) + 100;
832 snprintf (buf, len, "file=%s,snapshot=on,%sif=%s",
834 supports_ro ? "readonly=on," : "",
837 return guestfs__config (g, "-drive", buf);
841 guestfs__add_drive (guestfs_h *g, const char *filename)
843 return guestfs__add_drive_with_if (g, filename, DRIVE_IF);
847 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
849 return guestfs__add_drive_ro_with_if (g, filename, DRIVE_IF);
853 guestfs__add_cdrom (guestfs_h *g, const char *filename)
855 if (strchr (filename, ',') != NULL) {
856 error (g, _("filename cannot contain ',' (comma) character"));
860 if (access (filename, F_OK) == -1) {
861 perrorf (g, "%s", filename);
865 return guestfs__config (g, "-cdrom", filename);
868 /* Returns true iff file is contained in dir. */
870 dir_contains_file (const char *dir, const char *file)
872 int dirlen = strlen (dir);
873 int filelen = strlen (file);
874 int len = dirlen+filelen+2;
877 snprintf (path, len, "%s/%s", dir, file);
878 return access (path, F_OK) == 0;
881 /* Returns true iff every listed file is contained in 'dir'. */
883 dir_contains_files (const char *dir, ...)
888 va_start (args, dir);
889 while ((file = va_arg (args, const char *)) != NULL) {
890 if (!dir_contains_file (dir, file)) {
899 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
900 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
901 static int is_openable (guestfs_h *g, const char *path, int flags);
902 static void print_cmdline (guestfs_h *g);
904 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
905 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
906 static const char *supermin_name =
907 "initramfs." REPO "." host_cpu ".supermin.img";
908 static const char *supermin_hostfiles_name =
909 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
912 guestfs__launch (guestfs_h *g)
915 char dir_template[PATH_MAX];
920 char *path, *pelem, *pend;
921 char *kernel = NULL, *initrd = NULL;
922 int null_vmchannel_sock;
924 struct sockaddr_un addr;
926 /* Start the clock ... */
927 gettimeofday (&g->launch_t, NULL);
935 tmpdir = getenv ("TMPDIR") ? : tmpdir;
936 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
940 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
944 if (g->state != CONFIG) {
945 error (g, _("qemu has already been launched"));
949 /* Make the temporary directory. */
951 g->tmpdir = safe_strdup (g, dir_template);
952 if (mkdtemp (g->tmpdir) == NULL) {
953 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
958 /* First search g->path for the supermin appliance, and try to
959 * synthesize a kernel and initrd from that. If it fails, we
960 * try the path search again looking for a backup ordinary
963 pelem = path = safe_strdup (g, g->path);
965 pend = strchrnul (pelem, ':');
966 pmore = *pend == ':';
970 /* Empty element of "." means cwd. */
971 if (len == 0 || (len == 1 && *pelem == '.')) {
974 "looking for supermin appliance in current directory\n");
975 if (dir_contains_files (".",
976 supermin_name, supermin_hostfiles_name,
977 "kmod.whitelist", NULL)) {
978 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
983 /* Look at <path>/supermin* etc. */
986 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
988 if (dir_contains_files (pelem,
989 supermin_name, supermin_hostfiles_name,
990 "kmod.whitelist", NULL)) {
991 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1002 if (kernel == NULL || initrd == NULL) {
1003 /* Search g->path for the kernel and initrd. */
1004 pelem = path = safe_strdup (g, g->path);
1006 pend = strchrnul (pelem, ':');
1007 pmore = *pend == ':';
1011 /* Empty element or "." means cwd. */
1012 if (len == 0 || (len == 1 && *pelem == '.')) {
1015 "looking for appliance in current directory\n");
1016 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1017 kernel = safe_strdup (g, kernel_name);
1018 initrd = safe_strdup (g, initrd_name);
1022 /* Look at <path>/kernel etc. */
1025 fprintf (stderr, "looking for appliance in %s\n", pelem);
1027 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1028 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1029 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1030 sprintf (kernel, "%s/%s", pelem, kernel_name);
1031 sprintf (initrd, "%s/%s", pelem, initrd_name);
1042 if (kernel == NULL || initrd == NULL) {
1043 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1044 kernel_name, initrd_name, g->path);
1049 print_timestamped_message (g, "begin testing qemu features");
1051 /* Get qemu help text and version. */
1052 if (qemu_supports (g, NULL) == -1)
1055 /* Choose which vmchannel implementation to use. */
1056 if (qemu_supports (g, "-net user")) {
1057 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1058 * networking in qemu) but no other vmchannel support. The daemon
1059 * will connect back to a random port number on localhost.
1061 struct sockaddr_in addr;
1062 socklen_t addrlen = sizeof addr;
1064 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1065 if (g->sock == -1) {
1066 perrorf (g, "socket");
1069 addr.sin_family = AF_INET;
1070 addr.sin_port = htons (0);
1071 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1072 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1073 perrorf (g, "bind");
1077 if (listen (g->sock, 256) == -1) {
1078 perrorf (g, "listen");
1082 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1083 perrorf (g, "getsockname");
1087 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1088 perrorf (g, "fcntl");
1092 null_vmchannel_sock = ntohs (addr.sin_port);
1094 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1096 /* Using some vmchannel impl. We need to create a local Unix
1097 * domain socket for qemu to use.
1099 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1101 null_vmchannel_sock = 0;
1105 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1106 perrorf (g, "pipe");
1112 print_timestamped_message (g, "finished testing qemu features");
1116 perrorf (g, "fork");
1126 if (r == 0) { /* Child (qemu). */
1128 const char *vmchannel = NULL;
1130 /* Set up the full command line. Do this in the subprocess so we
1131 * don't need to worry about cleaning up.
1133 g->cmdline[0] = g->qemu;
1135 /* qemu sometimes needs this option to enable hardware
1136 * virtualization, but some versions of 'qemu-kvm' will use KVM
1137 * regardless (even where this option appears in the help text).
1138 * It is rumoured that there are versions of qemu where supplying
1139 * this option when hardware virtualization is not available will
1140 * cause qemu to fail, so we we have to check at least that
1141 * /dev/kvm is openable. That's not reliable, since /dev/kvm
1142 * might be openable by qemu but not by us (think: SELinux) in
1143 * which case the user would not get hardware virtualization,
1144 * although at least shouldn't fail. A giant clusterfuck with the
1145 * qemu command line, again.
1147 if (qemu_supports (g, "-enable-kvm") &&
1148 is_openable (g, "/dev/kvm", O_RDWR))
1149 add_cmdline (g, "-enable-kvm");
1151 /* Newer versions of qemu (from around 2009/12) changed the
1152 * behaviour of monitors so that an implicit '-monitor stdio' is
1153 * assumed if we are in -nographic mode and there is no other
1154 * -monitor option. Only a single stdio device is allowed, so
1155 * this broke the '-serial stdio' option. There is a new flag
1156 * called -nodefaults which gets rid of all this default crud, so
1157 * let's use that to avoid this and any future surprises.
1159 if (qemu_supports (g, "-nodefaults"))
1160 add_cmdline (g, "-nodefaults");
1162 add_cmdline (g, "-nographic");
1163 add_cmdline (g, "-serial");
1164 add_cmdline (g, "stdio");
1166 snprintf (buf, sizeof buf, "%d", g->memsize);
1167 add_cmdline (g, "-m");
1168 add_cmdline (g, buf);
1170 /* Force exit instead of reboot on panic */
1171 add_cmdline (g, "-no-reboot");
1173 /* These options recommended by KVM developers to improve reliability. */
1174 if (qemu_supports (g, "-no-hpet"))
1175 add_cmdline (g, "-no-hpet");
1177 if (qemu_supports (g, "-rtc-td-hack"))
1178 add_cmdline (g, "-rtc-td-hack");
1180 /* If qemu has SLIRP (user mode network) enabled then we can get
1181 * away with "no vmchannel", where we just connect back to a random
1184 if (null_vmchannel_sock) {
1185 add_cmdline (g, "-net");
1186 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1188 snprintf (buf, sizeof buf,
1189 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1190 vmchannel = strdup (buf);
1193 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1195 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1197 * The original suggested format doesn't work, see:
1199 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1201 * However Gerd Hoffman privately suggested to me using -chardev
1202 * instead, which does work.
1204 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1205 snprintf (buf, sizeof buf,
1206 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1208 add_cmdline (g, "-chardev");
1209 add_cmdline (g, buf);
1211 snprintf (buf, sizeof buf,
1212 "user,vlan=0,net=10.0.2.0/8,"
1213 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1214 "-chardev:guestfsvmc");
1216 add_cmdline (g, "-net");
1217 add_cmdline (g, buf);
1219 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1222 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1223 * syntax, or if not then we'll get a quick failure.
1226 snprintf (buf, sizeof buf,
1227 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1229 add_cmdline (g, "-net");
1230 add_cmdline (g, buf);
1231 add_cmdline (g, "-net");
1232 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1234 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1236 add_cmdline (g, "-net");
1237 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1239 #define LINUX_CMDLINE \
1240 "panic=1 " /* force kernel to panic if daemon exits */ \
1241 "console=ttyS0 " /* serial console */ \
1242 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1243 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1244 "acpi=off " /* we don't need ACPI, turn it off */ \
1245 "printk.time=1 " /* display timestamp before kernel messages */ \
1246 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1248 /* Linux kernel command line. */
1249 snprintf (buf, sizeof buf,
1251 "%s " /* (selinux) */
1252 "%s " /* (vmchannel) */
1253 "%s " /* (verbose) */
1254 "%s", /* (append) */
1255 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1256 vmchannel ? vmchannel : "",
1257 g->verbose ? "guestfs_verbose=1" : "",
1258 g->append ? g->append : "");
1260 add_cmdline (g, "-kernel");
1261 add_cmdline (g, (char *) kernel);
1262 add_cmdline (g, "-initrd");
1263 add_cmdline (g, (char *) initrd);
1264 add_cmdline (g, "-append");
1265 add_cmdline (g, buf);
1267 /* Finish off the command line. */
1268 incr_cmdline_size (g);
1269 g->cmdline[g->cmdline_size-1] = NULL;
1275 /* Set up stdin, stdout. */
1281 if (dup (wfd[0]) == -1) {
1283 perror ("dup failed");
1286 if (dup (rfd[1]) == -1)
1294 /* Set up a new process group, so we can signal this process
1295 * and all subprocesses (eg. if qemu is really a shell script).
1300 setenv ("LC_ALL", "C", 1);
1302 execv (g->qemu, g->cmdline); /* Run qemu. */
1307 /* Parent (library). */
1315 /* Fork the recovery process off which will kill qemu if the parent
1316 * process fails to do so (eg. if the parent segfaults).
1318 g->recoverypid = -1;
1319 if (g->recovery_proc) {
1322 pid_t qemu_pid = g->pid;
1323 pid_t parent_pid = getppid ();
1325 /* Writing to argv is hideously complicated and error prone. See:
1326 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1329 /* Loop around waiting for one or both of the other processes to
1330 * disappear. It's fair to say this is very hairy. The PIDs that
1331 * we are looking at might be reused by another process. We are
1332 * effectively polling. Is the cure worse than the disease?
1335 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1337 if (kill (parent_pid, 0) == -1) {
1338 /* Parent's gone away, qemu still around, so kill qemu. */
1346 /* Don't worry, if the fork failed, this will be -1. The recovery
1347 * process isn't essential.
1353 /* Close the other ends of the pipe. */
1357 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1358 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1359 perrorf (g, "fcntl");
1363 g->fd[0] = wfd[1]; /* stdin of child */
1364 g->fd[1] = rfd[0]; /* stdout of child */
1366 g->fd[0] = open ("/dev/null", O_RDWR);
1367 if (g->fd[0] == -1) {
1368 perrorf (g, "open /dev/null");
1371 g->fd[1] = dup (g->fd[0]);
1372 if (g->fd[1] == -1) {
1379 if (null_vmchannel_sock) {
1383 /* Null vmchannel implementation: We listen on g->sock for a
1384 * connection. The connection could come from any local process
1385 * so we must check it comes from the appliance (or at least
1386 * from our UID) for security reasons.
1388 while (sock == -1) {
1389 sock = accept_from_daemon (g);
1393 if (check_peer_euid (g, sock, &uid) == -1)
1395 if (uid != geteuid ()) {
1397 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1398 uid, null_vmchannel_sock);
1404 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1405 perrorf (g, "fcntl");
1412 /* Other vmchannel. Open the Unix socket.
1414 * The vmchannel implementation that got merged with qemu sucks in
1415 * a number of ways. Both ends do connect(2), which means that no
1416 * one knows what, if anything, is connected to the other end, or
1417 * if it becomes disconnected. Even worse, we have to wait some
1418 * indeterminate time for qemu to create the socket and connect to
1419 * it (which happens very early in qemu's start-up), so any code
1420 * that uses vmchannel is inherently racy. Hence this silly loop.
1422 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1423 if (g->sock == -1) {
1424 perrorf (g, "socket");
1428 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1429 perrorf (g, "fcntl");
1433 addr.sun_family = AF_UNIX;
1434 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1435 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1438 /* Always sleep at least once to give qemu a small chance to start up. */
1441 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1442 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1445 if (errno != ENOENT)
1446 perrorf (g, "connect");
1451 error (g, _("failed to connect to vmchannel socket"));
1457 g->state = LAUNCHING;
1459 /* Wait for qemu to start and to connect back to us via vmchannel and
1460 * send the GUESTFS_LAUNCH_FLAG message.
1464 r = recv_from_daemon (g, &size, &buf);
1467 if (r == -1) return -1;
1469 if (size != GUESTFS_LAUNCH_FLAG) {
1470 error (g, _("guestfs_launch failed, see earlier error messages"));
1475 print_timestamped_message (g, "appliance is up");
1477 /* This is possible in some really strange situations, such as
1478 * guestfsd starts up OK but then qemu immediately exits. Check for
1479 * it because the caller is probably expecting to be able to send
1480 * commands after this function returns.
1482 if (g->state != READY) {
1483 error (g, _("qemu launched and contacted daemon, but state != READY"));
1495 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1496 waitpid (g->pid, NULL, 0);
1497 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1502 memset (&g->launch_t, 0, sizeof g->launch_t);
1515 /* This function is used to print the qemu command line before it gets
1516 * executed, when in verbose mode.
1519 print_cmdline (guestfs_h *g)
1524 while (g->cmdline[i]) {
1525 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1526 fprintf (stderr, " \\\n ");
1528 if (i > 0) fputc (' ', stderr);
1530 /* Does it need shell quoting? This only deals with simple cases. */
1531 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1533 if (needs_quote) fputc ('\'', stderr);
1534 fprintf (stderr, "%s", g->cmdline[i]);
1535 if (needs_quote) fputc ('\'', stderr);
1539 fputc ('\n', stderr);
1542 /* This function does the hard work of building the supermin appliance
1543 * on the fly. 'path' is the directory containing the control files.
1544 * 'kernel' and 'initrd' are where we will return the names of the
1545 * kernel and initrd (only initrd is built). The work is done by
1546 * an external script. We just tell it where to put the result.
1549 build_supermin_appliance (guestfs_h *g, const char *path,
1550 char **kernel, char **initrd)
1556 print_timestamped_message (g, "begin building supermin appliance");
1558 len = strlen (g->tmpdir);
1559 *kernel = safe_malloc (g, len + 8);
1560 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1561 *initrd = safe_malloc (g, len + 8);
1562 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1564 snprintf (cmd, sizeof cmd,
1566 "libguestfs-supermin-helper%s '%s' " host_cpu " " REPO " %s %s",
1568 g->verbose ? " --verbose" : "",
1569 path, *kernel, *initrd);
1571 print_timestamped_message (g, "%s", cmd);
1574 if (r == -1 || WEXITSTATUS(r) != 0) {
1575 error (g, _("external command failed: %s"), cmd);
1578 *kernel = *initrd = NULL;
1583 print_timestamped_message (g, "finished building supermin appliance");
1588 /* Compute Y - X and return the result in milliseconds.
1589 * Approximately the same as this code:
1590 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1593 timeval_diff (const struct timeval *x, const struct timeval *y)
1597 msec = (y->tv_sec - x->tv_sec) * 1000;
1598 msec += (y->tv_usec - x->tv_usec) / 1000;
1603 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1610 va_start (args, fs);
1611 err = vasprintf (&msg, fs, args);
1614 if (err < 0) return;
1616 gettimeofday (&tv, NULL);
1618 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1619 timeval_diff (&g->launch_t, &tv), msg);
1624 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1626 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1627 * 'qemu -version' so we know what options this qemu supports and
1631 test_qemu (guestfs_h *g)
1636 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1638 fp = popen (cmd, "r");
1639 /* qemu -help should always work (qemu -version OTOH wasn't
1640 * supported by qemu 0.9). If this command doesn't work then it
1641 * probably indicates that the qemu binary is missing.
1644 /* XXX This error is never printed, even if the qemu binary
1645 * doesn't exist. Why?
1648 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1652 if (read_all (g, fp, &g->qemu_help) == -1)
1655 if (pclose (fp) == -1)
1658 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1661 fp = popen (cmd, "r");
1663 /* Intentionally ignore errors. */
1664 read_all (g, fp, &g->qemu_version);
1672 read_all (guestfs_h *g, FILE *fp, char **ret)
1679 *ret = safe_realloc (g, *ret, n + 1);
1684 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1686 r = fread (p, 1, BUFSIZ, fp);
1688 perrorf (g, "read");
1695 /* Test if option is supported by qemu command line (just by grepping
1698 * The first time this is used, it has to run the external qemu
1699 * binary. If that fails, it returns -1.
1701 * To just do the first-time run of the qemu binary, call this with
1702 * option == NULL, in which case it will return -1 if there was an
1706 qemu_supports (guestfs_h *g, const char *option)
1708 if (!g->qemu_help) {
1709 if (test_qemu (g) == -1)
1716 return strstr (g->qemu_help, option) != NULL;
1719 /* Check if a file can be opened. */
1721 is_openable (guestfs_h *g, const char *path, int flags)
1723 int fd = open (path, flags);
1733 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1734 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1735 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1738 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1740 struct sockaddr_in peer;
1741 socklen_t addrlen = sizeof peer;
1743 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1744 perrorf (g, "getpeername");
1748 if (peer.sin_family != AF_INET ||
1749 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1750 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1751 peer.sin_family, inet_ntoa (peer.sin_addr));
1755 struct sockaddr_in our;
1756 addrlen = sizeof our;
1757 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1758 perrorf (g, "getsockname");
1762 FILE *fp = fopen ("/proc/net/tcp", "r");
1764 perrorf (g, "/proc/net/tcp");
1769 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1770 error (g, "unexpected end of file in /proc/net/tcp");
1775 while (fgets (line, sizeof line, fp) != NULL) {
1776 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1777 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1780 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1782 &line_our_addr, &line_our_port,
1783 &line_peer_addr, &line_peer_port,
1784 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1786 /* Note about /proc/net/tcp: local_address and rem_address are
1787 * always in network byte order. However the port part is
1788 * always in host byte order.
1790 * The sockname and peername that we got above are in network
1791 * byte order. So we have to byte swap the port but not the
1794 if (line_our_addr == our.sin_addr.s_addr &&
1795 line_our_port == ntohs (our.sin_port) &&
1796 line_peer_addr == peer.sin_addr.s_addr &&
1797 line_peer_port == ntohs (peer.sin_port)) {
1805 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1810 /* You had to call this function after launch in versions <= 1.0.70,
1811 * but it is now a no-op.
1814 guestfs__wait_ready (guestfs_h *g)
1816 if (g->state != READY) {
1817 error (g, _("qemu has not been launched yet"));
1825 guestfs__kill_subprocess (guestfs_h *g)
1827 if (g->state == CONFIG) {
1828 error (g, _("no subprocess to kill"));
1833 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1835 kill (g->pid, SIGTERM);
1836 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1841 /* Access current state. */
1843 guestfs__is_config (guestfs_h *g)
1845 return g->state == CONFIG;
1849 guestfs__is_launching (guestfs_h *g)
1851 return g->state == LAUNCHING;
1855 guestfs__is_ready (guestfs_h *g)
1857 return g->state == READY;
1861 guestfs__is_busy (guestfs_h *g)
1863 return g->state == BUSY;
1867 guestfs__get_state (guestfs_h *g)
1873 guestfs_set_log_message_callback (guestfs_h *g,
1874 guestfs_log_message_cb cb, void *opaque)
1876 g->log_message_cb = cb;
1877 g->log_message_cb_data = opaque;
1881 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1882 guestfs_subprocess_quit_cb cb, void *opaque)
1884 g->subprocess_quit_cb = cb;
1885 g->subprocess_quit_cb_data = opaque;
1889 guestfs_set_launch_done_callback (guestfs_h *g,
1890 guestfs_launch_done_cb cb, void *opaque)
1892 g->launch_done_cb = cb;
1893 g->launch_done_cb_data = opaque;
1896 /*----------------------------------------------------------------------*/
1898 /* This is the code used to send and receive RPC messages and (for
1899 * certain types of message) to perform file transfers. This code is
1900 * driven from the generated actions (src/guestfs-actions.c). There
1901 * are five different cases to consider:
1903 * (1) A non-daemon function. There is no RPC involved at all, it's
1904 * all handled inside the library.
1906 * (2) A simple RPC (eg. "mount"). We write the request, then read
1907 * the reply. The sequence of calls is:
1909 * guestfs___set_busy
1912 * guestfs___end_busy
1914 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1915 * request, then write the file(s), then read the reply. The sequence
1918 * guestfs___set_busy
1920 * guestfs___send_file (possibly multiple times)
1922 * guestfs___end_busy
1924 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1925 * request, then read the reply, then read the file(s). The sequence
1928 * guestfs___set_busy
1931 * guestfs___recv_file (possibly multiple times)
1932 * guestfs___end_busy
1934 * (5) Both FileOut and FileIn parameters. There are no calls like
1935 * this in the current API, but they would be implemented as a
1936 * combination of cases (3) and (4).
1938 * During all writes and reads, we also select(2) on qemu stdout
1939 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1940 * anything received is passed up through the log_message_cb. This is
1941 * also the reason why all the sockets are non-blocking. We also have
1942 * to check for EOF (qemu died). All of this is handled by the
1943 * functions send_to_daemon and recv_from_daemon.
1947 guestfs___set_busy (guestfs_h *g)
1949 if (g->state != READY) {
1950 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1959 guestfs___end_busy (guestfs_h *g)
1973 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1979 /* This is called if we detect EOF, ie. qemu died. */
1981 child_cleanup (guestfs_h *g)
1984 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1986 /*kill (g->pid, SIGTERM);*/
1987 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1988 waitpid (g->pid, NULL, 0);
1989 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1998 memset (&g->launch_t, 0, sizeof g->launch_t);
2000 if (g->subprocess_quit_cb)
2001 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
2005 read_log_message_or_eof (guestfs_h *g, int fd)
2013 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
2017 /* QEMU's console emulates a 16550A serial port. The real 16550A
2018 * device has a small FIFO buffer (16 bytes) which means here we see
2019 * lots of small reads of 1-16 bytes in length, usually single
2022 n = read (fd, buf, sizeof buf);
2024 /* Hopefully this indicates the qemu child process has died. */
2030 if (errno == EINTR || errno == EAGAIN)
2033 perrorf (g, "read");
2037 /* In verbose mode, copy all log messages to stderr. */
2039 ignore_value (write (STDERR_FILENO, buf, n));
2041 /* It's an actual log message, send it upwards if anyone is listening. */
2042 if (g->log_message_cb)
2043 g->log_message_cb (g, g->log_message_cb_data, buf, n);
2049 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
2058 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
2061 n = read (fd, buf, 4);
2063 /* Hopefully this indicates the qemu child process has died. */
2069 if (errno == EINTR || errno == EAGAIN)
2072 perrorf (g, "read");
2076 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
2077 xdr_uint32_t (&xdr, &flag);
2080 if (flag != GUESTFS_CANCEL_FLAG) {
2081 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
2082 flag, GUESTFS_CANCEL_FLAG);
2089 /* This writes the whole N bytes of BUF to the daemon socket.
2091 * If the whole write is successful, it returns 0.
2092 * If there was an error, it returns -1.
2093 * If the daemon sent a cancellation message, it returns -2.
2095 * It also checks qemu stdout for log messages and passes those up
2096 * through log_message_cb.
2098 * It also checks for EOF (qemu died) and passes that up through the
2099 * child_cleanup function above.
2102 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2104 const char *buf = v_buf;
2110 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2115 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2116 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2117 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2119 int max_fd = MAX (g->sock, g->fd[1]);
2124 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2126 if (errno == EINTR || errno == EAGAIN)
2128 perrorf (g, "select");
2132 if (FD_ISSET (g->fd[1], &rset2)) {
2133 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2136 if (FD_ISSET (g->sock, &rset2)) {
2137 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2141 if (FD_ISSET (g->sock, &wset2)) {
2142 r = write (g->sock, buf, n);
2144 if (errno == EINTR || errno == EAGAIN)
2146 perrorf (g, "write");
2147 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2159 /* This reads a single message, file chunk, launch flag or
2160 * cancellation flag from the daemon. If something was read, it
2161 * returns 0, otherwise -1.
2163 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2165 * *size_rtn returns the size of the returned message or it may be
2166 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2168 * *buf_rtn is returned containing the message (if any) or will be set
2169 * to NULL. *buf_rtn must be freed by the caller.
2171 * It also checks qemu stdout for log messages and passes those up
2172 * through log_message_cb.
2174 * It also checks for EOF (qemu died) and passes that up through the
2175 * child_cleanup function above.
2178 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2184 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2185 g, g->state, size_rtn, buf_rtn);
2189 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2190 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2192 int max_fd = MAX (g->sock, g->fd[1]);
2198 /* nr is the size of the message, but we prime it as -4 because we
2199 * have to read the message length word first.
2203 while (nr < (ssize_t) *size_rtn) {
2205 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2207 if (errno == EINTR || errno == EAGAIN)
2209 perrorf (g, "select");
2215 if (FD_ISSET (g->fd[1], &rset2)) {
2216 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2222 if (FD_ISSET (g->sock, &rset2)) {
2223 if (nr < 0) { /* Have we read the message length word yet? */
2224 r = read (g->sock, lenbuf+nr+4, -nr);
2226 if (errno == EINTR || errno == EAGAIN)
2229 perrorf (g, "read");
2230 /* Under some circumstances we see "Connection reset by peer"
2231 * here when the child dies suddenly. Catch this and call
2232 * the cleanup function, same as for EOF.
2234 if (err == ECONNRESET)
2239 error (g, _("unexpected end of file when reading from daemon"));
2245 if (nr < 0) /* Still not got the whole length word. */
2249 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2250 xdr_uint32_t (&xdr, size_rtn);
2253 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2254 if (g->state != LAUNCHING)
2255 error (g, _("received magic signature from guestfsd, but in state %d"),
2259 if (g->launch_done_cb)
2260 g->launch_done_cb (g, g->launch_done_cb_data);
2264 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2266 /* If this happens, it's pretty bad and we've probably lost
2269 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2270 error (g, _("message length (%u) > maximum possible size (%d)"),
2271 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2275 /* Allocate the complete buffer, size now known. */
2276 *buf_rtn = safe_malloc (g, *size_rtn);
2280 size_t sizetoread = *size_rtn - nr;
2281 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2283 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2285 if (errno == EINTR || errno == EAGAIN)
2287 perrorf (g, "read");
2293 error (g, _("unexpected end of file when reading from daemon"));
2303 /* Got the full message, caller can start processing it. */
2304 #ifdef ENABLE_PACKET_DUMP
2308 for (i = 0; i < nr; i += 16) {
2309 printf ("%04zx: ", i);
2310 for (j = i; j < MIN (i+16, nr); ++j)
2311 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2312 for (; j < i+16; ++j)
2315 for (j = i; j < MIN (i+16, nr); ++j)
2316 if (c_isprint ((*(char **)buf_rtn)[j]))
2317 printf ("%c", (*(char **)buf_rtn)[j]);
2320 for (; j < i+16; ++j)
2330 /* This is very much like recv_from_daemon above, but g->sock is
2331 * a listening socket and we are accepting a new connection on
2332 * that socket instead of reading anything. Returns the newly
2336 accept_from_daemon (guestfs_h *g)
2342 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2346 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2347 FD_SET (g->sock, &rset); /* Read socket for accept. */
2349 int max_fd = MAX (g->sock, g->fd[1]);
2352 while (sock == -1) {
2354 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2356 if (errno == EINTR || errno == EAGAIN)
2358 perrorf (g, "select");
2362 if (FD_ISSET (g->fd[1], &rset2)) {
2363 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2366 if (FD_ISSET (g->sock, &rset2)) {
2367 sock = accept (g->sock, NULL, NULL);
2369 if (errno == EINTR || errno == EAGAIN)
2371 perrorf (g, "accept");
2381 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2383 struct guestfs_message_header hdr;
2386 int serial = g->msg_next_serial++;
2389 size_t msg_out_size;
2391 if (g->state != BUSY) {
2392 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2396 /* We have to allocate this message buffer on the heap because
2397 * it is quite large (although will be mostly unused). We
2398 * can't allocate it on the stack because in some environments
2399 * we have quite limited stack space available, notably when
2400 * running in the JVM.
2402 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2403 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2405 /* Serialize the header. */
2406 hdr.prog = GUESTFS_PROGRAM;
2407 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2409 hdr.direction = GUESTFS_DIRECTION_CALL;
2410 hdr.serial = serial;
2411 hdr.status = GUESTFS_STATUS_OK;
2413 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2414 error (g, _("xdr_guestfs_message_header failed"));
2418 /* Serialize the args. If any, because some message types
2419 * have no parameters.
2422 if (!(*xdrp) (&xdr, args)) {
2423 error (g, _("dispatch failed to marshal args"));
2428 /* Get the actual length of the message, resize the buffer to match
2429 * the actual length, and write the length word at the beginning.
2431 len = xdr_getpos (&xdr);
2434 msg_out = safe_realloc (g, msg_out, len + 4);
2435 msg_out_size = len + 4;
2437 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2438 xdr_uint32_t (&xdr, &len);
2441 r = send_to_daemon (g, msg_out, msg_out_size);
2442 if (r == -2) /* Ignore stray daemon cancellations. */
2455 static int cancel = 0; /* XXX Implement file cancellation. */
2456 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2457 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2458 static int send_file_cancellation (guestfs_h *g);
2459 static int send_file_complete (guestfs_h *g);
2465 * -2 daemon cancelled (we must read the error message)
2468 guestfs___send_file (guestfs_h *g, const char *filename)
2470 char buf[GUESTFS_MAX_CHUNK_SIZE];
2473 fd = open (filename, O_RDONLY);
2475 perrorf (g, "open: %s", filename);
2476 send_file_cancellation (g);
2477 /* Daemon sees cancellation and won't reply, so caller can
2483 /* Send file in chunked encoding. */
2485 r = read (fd, buf, sizeof buf);
2486 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2489 err = send_file_data (g, buf, r);
2491 if (err == -2) /* daemon sent cancellation */
2492 send_file_cancellation (g);
2497 if (cancel) { /* cancel from either end */
2498 send_file_cancellation (g);
2503 perrorf (g, "read: %s", filename);
2504 send_file_cancellation (g);
2508 /* End of file, but before we send that, we need to close
2509 * the file and check for errors.
2511 if (close (fd) == -1) {
2512 perrorf (g, "close: %s", filename);
2513 send_file_cancellation (g);
2517 return send_file_complete (g);
2520 /* Send a chunk of file data. */
2522 send_file_data (guestfs_h *g, const char *buf, size_t len)
2524 return send_file_chunk (g, 0, buf, len);
2527 /* Send a cancellation message. */
2529 send_file_cancellation (guestfs_h *g)
2531 return send_file_chunk (g, 1, NULL, 0);
2534 /* Send a file complete chunk. */
2536 send_file_complete (guestfs_h *g)
2539 return send_file_chunk (g, 0, buf, 0);
2543 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2547 guestfs_chunk chunk;
2550 size_t msg_out_size;
2552 if (g->state != BUSY) {
2553 error (g, _("send_file_chunk: state %d != READY"), g->state);
2557 /* Allocate the chunk buffer. Don't use the stack to avoid
2558 * excessive stack usage and unnecessary copies.
2560 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2561 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2563 /* Serialize the chunk. */
2564 chunk.cancel = cancel;
2565 chunk.data.data_len = buflen;
2566 chunk.data.data_val = (char *) buf;
2568 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2569 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2575 len = xdr_getpos (&xdr);
2578 /* Reduce the size of the outgoing message buffer to the real length. */
2579 msg_out = safe_realloc (g, msg_out, len + 4);
2580 msg_out_size = len + 4;
2582 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2583 xdr_uint32_t (&xdr, &len);
2585 r = send_to_daemon (g, msg_out, msg_out_size);
2587 /* Did the daemon send a cancellation message? */
2590 fprintf (stderr, "got daemon cancellation\n");
2606 /* Receive a reply. */
2608 guestfs___recv (guestfs_h *g, const char *fn,
2609 guestfs_message_header *hdr,
2610 guestfs_message_error *err,
2611 xdrproc_t xdrp, char *ret)
2619 r = recv_from_daemon (g, &size, &buf);
2623 /* This can happen if a cancellation happens right at the end
2624 * of us sending a FileIn parameter to the daemon. Discard. The
2625 * daemon should send us an error message next.
2627 if (size == GUESTFS_CANCEL_FLAG)
2630 if (size == GUESTFS_LAUNCH_FLAG) {
2631 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2635 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2637 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2638 error (g, "%s: failed to parse reply header", fn);
2643 if (hdr->status == GUESTFS_STATUS_ERROR) {
2644 if (!xdr_guestfs_message_error (&xdr, err)) {
2645 error (g, "%s: failed to parse reply error", fn);
2651 if (xdrp && ret && !xdrp (&xdr, ret)) {
2652 error (g, "%s: failed to parse reply", fn);
2664 /* Receive a file. */
2666 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2667 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2670 guestfs___recv_file (guestfs_h *g, const char *filename)
2675 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2677 perrorf (g, "open: %s", filename);
2681 /* Receive the file in chunked encoding. */
2682 while ((r = receive_file_data (g, &buf)) > 0) {
2683 if (xwrite (fd, buf, r) == -1) {
2684 perrorf (g, "%s: write", filename);
2692 error (g, _("%s: error in chunked encoding"), filename);
2696 if (close (fd) == -1) {
2697 perrorf (g, "close: %s", filename);
2704 /* Send cancellation message to daemon, then wait until it
2705 * cancels (just throwing away data).
2709 uint32_t flag = GUESTFS_CANCEL_FLAG;
2712 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2715 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2716 xdr_uint32_t (&xdr, &flag);
2719 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2720 perrorf (g, _("write to daemon socket"));
2724 while (receive_file_data (g, NULL) > 0)
2725 ; /* just discard it */
2730 /* Receive a chunk of file data. */
2731 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2733 receive_file_data (guestfs_h *g, void **buf_r)
2739 guestfs_chunk chunk;
2741 r = recv_from_daemon (g, &len, &buf);
2743 error (g, _("receive_file_data: parse error in reply callback"));
2747 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2748 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2752 memset (&chunk, 0, sizeof chunk);
2754 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2755 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2756 error (g, _("failed to parse file chunk"));
2761 /* After decoding, the original buffer is no longer used. */
2765 error (g, _("file receive cancelled by daemon"));
2766 free (chunk.data.data_val);
2770 if (chunk.data.data_len == 0) { /* end of transfer */
2771 free (chunk.data.data_val);
2775 if (buf_r) *buf_r = chunk.data.data_val;
2776 else free (chunk.data.data_val); /* else caller frees */
2778 return chunk.data.data_len;