2 * Copyright (C) 2009 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 */
32 #include <sys/select.h>
35 #include <rpc/types.h>
42 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
46 #ifdef HAVE_SYS_WAIT_H
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
58 #include <arpa/inet.h>
59 #include <netinet/in.h>
62 #include "guestfs-internal-actions.h"
63 #include "guestfs_protocol.h"
65 #include "ignore-value.h"
69 #define _(str) dgettext(PACKAGE, (str))
70 //#define N_(str) dgettext(PACKAGE, (str))
76 #define error guestfs_error
77 #define perrorf guestfs_perrorf
78 #define safe_malloc guestfs_safe_malloc
79 #define safe_realloc guestfs_safe_realloc
80 #define safe_strdup guestfs_safe_strdup
81 //#define safe_memdup guestfs_safe_memdup
83 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
84 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
85 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
86 static int accept_from_daemon (guestfs_h *g);
87 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
88 static void close_handles (void);
90 #define UNIX_PATH_MAX 108
92 /* Also in guestfsd.c */
93 #define GUESTFWD_ADDR "10.0.2.4"
94 #define GUESTFWD_PORT "6666"
96 /* GuestFS handle and connection. */
97 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
101 struct guestfs_h *next; /* Linked list of open handles. */
103 /* State: see the state machine diagram in the man page guestfs(3). */
106 int fd[2]; /* Stdin/stdout of qemu. */
107 int sock; /* Daemon communications socket. */
108 pid_t pid; /* Qemu PID. */
109 pid_t recoverypid; /* Recovery process PID. */
110 time_t start_t; /* The time when we started qemu. */
112 char *tmpdir; /* Temporary directory containing socket. */
114 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
116 char **cmdline; /* Qemu command line. */
124 char *path; /* Path to kernel, initrd. */
125 char *qemu; /* Qemu binary. */
126 char *append; /* Append to kernel command line. */
128 int memsize; /* Size of RAM (megabytes). */
130 int selinux; /* selinux enabled? */
135 guestfs_abort_cb abort_cb;
136 guestfs_error_handler_cb error_cb;
137 void * error_cb_data;
138 guestfs_log_message_cb log_message_cb;
139 void * log_message_cb_data;
140 guestfs_subprocess_quit_cb subprocess_quit_cb;
141 void * subprocess_quit_cb_data;
142 guestfs_launch_done_cb launch_done_cb;
143 void * launch_done_cb_data;
148 static guestfs_h *handles = NULL;
149 static int atexit_handler_set = 0;
152 guestfs_create (void)
157 g = malloc (sizeof (*g));
160 memset (g, 0, sizeof (*g));
169 g->error_cb = default_error_cb;
170 g->error_cb_data = NULL;
172 str = getenv ("LIBGUESTFS_DEBUG");
173 g->verbose = str != NULL && strcmp (str, "1") == 0;
175 str = getenv ("LIBGUESTFS_TRACE");
176 g->trace = str != NULL && strcmp (str, "1") == 0;
178 str = getenv ("LIBGUESTFS_PATH");
179 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
180 if (!g->path) goto error;
182 str = getenv ("LIBGUESTFS_QEMU");
183 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
184 if (!g->qemu) goto error;
186 str = getenv ("LIBGUESTFS_APPEND");
188 g->append = strdup (str);
189 if (!g->append) goto error;
192 /* Choose a suitable memory size. Previously we tried to choose
193 * a minimal memory size, but this isn't really necessary since
194 * recent QEMU and KVM don't do anything nasty like locking
195 * memory into core any more. Thus we can safely choose a
196 * large, generous amount of memory, and it'll just get swapped
197 * on smaller systems.
199 str = getenv ("LIBGUESTFS_MEMSIZE");
201 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
202 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
208 /* Start with large serial numbers so they are easy to spot
209 * inside the protocol.
211 g->msg_next_serial = 0x00123400;
213 /* Link the handles onto a global list. This is the one area
214 * where the library needs to be made thread-safe. (XXX)
216 /* acquire mutex (XXX) */
219 if (!atexit_handler_set) {
220 atexit (close_handles);
221 atexit_handler_set = 1;
223 /* release mutex (XXX) */
226 fprintf (stderr, "new guestfs handle %p\n", g);
239 guestfs_close (guestfs_h *g)
245 if (g->state == NO_HANDLE) {
246 /* Not safe to call 'error' here, so ... */
247 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
252 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
254 /* Try to sync if autosync flag is set. */
255 if (g->autosync && g->state == READY) {
256 guestfs_umount_all (g);
260 /* Remove any handlers that might be called back before we kill the
263 g->log_message_cb = NULL;
265 if (g->state != CONFIG)
266 guestfs_kill_subprocess (g);
279 /* Wait for subprocess(es) to exit. */
280 waitpid (g->pid, NULL, 0);
281 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
283 /* Remove tmpfiles. */
285 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
288 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
291 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
300 for (i = 0; i < g->cmdline_size; ++i)
301 free (g->cmdline[i]);
305 /* Mark the handle as dead before freeing it. */
306 g->state = NO_HANDLE;
308 /* acquire mutex (XXX) */
312 for (gg = handles; gg->next != g; gg = gg->next)
316 /* release mutex (XXX) */
318 free (g->last_error);
323 free (g->qemu_version);
327 /* Close all open handles (called from atexit(3)). */
331 while (handles) guestfs_close (handles);
335 guestfs_last_error (guestfs_h *g)
337 return g->last_error;
341 set_last_error (guestfs_h *g, const char *msg)
343 free (g->last_error);
344 g->last_error = strdup (msg);
348 default_error_cb (guestfs_h *g, void *data, const char *msg)
350 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
354 guestfs_error (guestfs_h *g, const char *fs, ...)
360 int err = vasprintf (&msg, fs, args);
365 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
366 set_last_error (g, msg);
372 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
379 int err = vasprintf (&msg, fs, args);
386 strerror_r (errnum, buf, sizeof buf);
390 buf = strerror_r (errnum, _buf, sizeof _buf);
393 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
397 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
398 set_last_error (g, msg);
404 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
406 void *ptr = malloc (nbytes);
407 if (nbytes > 0 && !ptr) g->abort_cb ();
411 /* Return 1 if an array of N objects, each of size S, cannot exist due
412 to size arithmetic overflow. S must be positive and N must be
413 nonnegative. This is a macro, not an inline function, so that it
414 works correctly even when SIZE_MAX < N.
416 By gnulib convention, SIZE_MAX represents overflow in size
417 calculations, so the conservative dividend to use here is
418 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
419 However, malloc (SIZE_MAX) fails on all known hosts where
420 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
421 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
422 branch when S is known to be 1. */
423 # define xalloc_oversized(n, s) \
424 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
426 /* Technically we should add an autoconf test for this, testing for the desired
427 functionality, like what's done in gnulib, but for now, this is fine. */
428 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
430 /* Allocate zeroed memory for N elements of S bytes, with error
431 checking. S must be nonzero. */
433 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
435 /* From gnulib's calloc function in xmalloc.c. */
437 /* Test for overflow, since some calloc implementations don't have
438 proper overflow checks. But omit overflow and size-zero tests if
439 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
440 returns NULL if successful. */
441 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
442 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
448 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
450 void *p = realloc (ptr, nbytes);
451 if (nbytes > 0 && !p) g->abort_cb ();
456 guestfs_safe_strdup (guestfs_h *g, const char *str)
458 char *s = strdup (str);
459 if (!s) g->abort_cb ();
464 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
466 void *p = malloc (size);
467 if (!p) g->abort_cb ();
468 memcpy (p, ptr, size);
473 xwrite (int fd, const void *v_buf, size_t len)
475 const char *buf = v_buf;
479 r = write (fd, buf, len);
491 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
497 guestfs_get_out_of_memory_handler (guestfs_h *g)
503 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
506 g->error_cb_data = data;
509 guestfs_error_handler_cb
510 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
512 if (data_rtn) *data_rtn = g->error_cb_data;
517 guestfs__set_verbose (guestfs_h *g, int v)
524 guestfs__get_verbose (guestfs_h *g)
530 guestfs__set_autosync (guestfs_h *g, int a)
537 guestfs__get_autosync (guestfs_h *g)
543 guestfs__set_path (guestfs_h *g, const char *path)
550 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
555 guestfs__get_path (guestfs_h *g)
561 guestfs__set_qemu (guestfs_h *g, const char *qemu)
566 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
571 guestfs__get_qemu (guestfs_h *g)
577 guestfs__set_append (guestfs_h *g, const char *append)
582 g->append = append ? safe_strdup (g, append) : NULL;
587 guestfs__get_append (guestfs_h *g)
593 guestfs__set_memsize (guestfs_h *g, int memsize)
595 g->memsize = memsize;
600 guestfs__get_memsize (guestfs_h *g)
606 guestfs__set_selinux (guestfs_h *g, int selinux)
608 g->selinux = selinux;
613 guestfs__get_selinux (guestfs_h *g)
619 guestfs__get_pid (guestfs_h *g)
624 error (g, "get_pid: no qemu subprocess");
629 struct guestfs_version *
630 guestfs__version (guestfs_h *g)
632 struct guestfs_version *r;
634 r = safe_malloc (g, sizeof *r);
635 r->major = PACKAGE_VERSION_MAJOR;
636 r->minor = PACKAGE_VERSION_MINOR;
637 r->release = PACKAGE_VERSION_RELEASE;
638 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
643 guestfs__set_trace (guestfs_h *g, int t)
650 guestfs__get_trace (guestfs_h *g)
656 guestfs__set_direct (guestfs_h *g, int d)
663 guestfs__get_direct (guestfs_h *g)
668 /* Add a string to the current command line. */
670 incr_cmdline_size (guestfs_h *g)
672 if (g->cmdline == NULL) {
673 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
675 g->cmdline = safe_malloc (g, sizeof (char *));
676 g->cmdline[0] = NULL;
680 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
684 add_cmdline (guestfs_h *g, const char *str)
686 if (g->state != CONFIG) {
688 _("command line cannot be altered after qemu subprocess launched"));
692 incr_cmdline_size (g);
693 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
698 guestfs__config (guestfs_h *g,
699 const char *qemu_param, const char *qemu_value)
701 if (qemu_param[0] != '-') {
702 error (g, _("guestfs_config: parameter must begin with '-' character"));
706 /* A bit fascist, but the user will probably break the extra
707 * parameters that we add if they try to set any of these.
709 if (strcmp (qemu_param, "-kernel") == 0 ||
710 strcmp (qemu_param, "-initrd") == 0 ||
711 strcmp (qemu_param, "-nographic") == 0 ||
712 strcmp (qemu_param, "-serial") == 0 ||
713 strcmp (qemu_param, "-full-screen") == 0 ||
714 strcmp (qemu_param, "-std-vga") == 0 ||
715 strcmp (qemu_param, "-vnc") == 0) {
716 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
720 if (add_cmdline (g, qemu_param) != 0) return -1;
722 if (qemu_value != NULL) {
723 if (add_cmdline (g, qemu_value) != 0) return -1;
730 guestfs__add_drive (guestfs_h *g, const char *filename)
732 size_t len = strlen (filename) + 64;
735 if (strchr (filename, ',') != NULL) {
736 error (g, _("filename cannot contain ',' (comma) character"));
740 /* cache=off improves reliability in the event of a host crash.
742 * However this option causes qemu to try to open the file with
743 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
744 * So we check if we can open the file with or without O_DIRECT,
745 * and use cache=off (or not) accordingly.
747 * This test also checks for the presence of the file, which
748 * is a documented semantic of this interface.
750 int fd = open (filename, O_RDONLY|O_DIRECT);
753 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
755 fd = open (filename, O_RDONLY);
758 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
760 perrorf (g, "%s", filename);
765 return guestfs__config (g, "-drive", buf);
769 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
771 size_t len = strlen (filename) + 64;
774 if (strchr (filename, ',') != NULL) {
775 error (g, _("filename cannot contain ',' (comma) character"));
779 if (access (filename, F_OK) == -1) {
780 perrorf (g, "%s", filename);
784 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
786 return guestfs__config (g, "-drive", buf);
790 guestfs__add_cdrom (guestfs_h *g, const char *filename)
792 if (strchr (filename, ',') != NULL) {
793 error (g, _("filename cannot contain ',' (comma) character"));
797 if (access (filename, F_OK) == -1) {
798 perrorf (g, "%s", filename);
802 return guestfs__config (g, "-cdrom", filename);
805 /* Returns true iff file is contained in dir. */
807 dir_contains_file (const char *dir, const char *file)
809 int dirlen = strlen (dir);
810 int filelen = strlen (file);
811 int len = dirlen+filelen+2;
814 snprintf (path, len, "%s/%s", dir, file);
815 return access (path, F_OK) == 0;
818 /* Returns true iff every listed file is contained in 'dir'. */
820 dir_contains_files (const char *dir, ...)
825 va_start (args, dir);
826 while ((file = va_arg (args, const char *)) != NULL) {
827 if (!dir_contains_file (dir, file)) {
836 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
837 static int test_qemu (guestfs_h *g);
838 static int qemu_supports (guestfs_h *g, const char *option);
839 static void print_cmdline (guestfs_h *g);
841 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
842 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
843 static const char *supermin_name =
844 "initramfs." REPO "." host_cpu ".supermin.img";
845 static const char *supermin_hostfiles_name =
846 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
849 guestfs__launch (guestfs_h *g)
852 char dir_template[PATH_MAX];
857 char *path, *pelem, *pend;
858 char *kernel = NULL, *initrd = NULL;
859 int null_vmchannel_sock;
861 struct sockaddr_un addr;
869 tmpdir = getenv ("TMPDIR") ? : tmpdir;
870 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
874 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
878 if (g->state != CONFIG) {
879 error (g, _("qemu has already been launched"));
883 /* Make the temporary directory. */
885 g->tmpdir = safe_strdup (g, dir_template);
886 if (mkdtemp (g->tmpdir) == NULL) {
887 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
892 /* First search g->path for the supermin appliance, and try to
893 * synthesize a kernel and initrd from that. If it fails, we
894 * try the path search again looking for a backup ordinary
897 pelem = path = safe_strdup (g, g->path);
899 pend = strchrnul (pelem, ':');
900 pmore = *pend == ':';
904 /* Empty element of "." means cwd. */
905 if (len == 0 || (len == 1 && *pelem == '.')) {
908 "looking for supermin appliance in current directory\n");
909 if (dir_contains_files (".",
910 supermin_name, supermin_hostfiles_name,
911 "kmod.whitelist", NULL)) {
912 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
917 /* Look at <path>/supermin* etc. */
920 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
922 if (dir_contains_files (pelem,
923 supermin_name, supermin_hostfiles_name,
924 "kmod.whitelist", NULL)) {
925 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
936 if (kernel == NULL || initrd == NULL) {
937 /* Search g->path for the kernel and initrd. */
938 pelem = path = safe_strdup (g, g->path);
940 pend = strchrnul (pelem, ':');
941 pmore = *pend == ':';
945 /* Empty element or "." means cwd. */
946 if (len == 0 || (len == 1 && *pelem == '.')) {
949 "looking for appliance in current directory\n");
950 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
951 kernel = safe_strdup (g, kernel_name);
952 initrd = safe_strdup (g, initrd_name);
956 /* Look at <path>/kernel etc. */
959 fprintf (stderr, "looking for appliance in %s\n", pelem);
961 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
962 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
963 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
964 sprintf (kernel, "%s/%s", pelem, kernel_name);
965 sprintf (initrd, "%s/%s", pelem, initrd_name);
976 if (kernel == NULL || initrd == NULL) {
977 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
978 kernel_name, initrd_name, g->path);
982 /* Get qemu help text and version. */
983 if (test_qemu (g) == -1)
986 /* Choose which vmchannel implementation to use. */
987 if (qemu_supports (g, "-net user")) {
988 /* The "null vmchannel" implementation. Requires SLIRP (user mode
989 * networking in qemu) but no other vmchannel support. The daemon
990 * will connect back to a random port number on localhost.
992 struct sockaddr_in addr;
993 socklen_t addrlen = sizeof addr;
995 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
997 perrorf (g, "socket");
1000 addr.sin_family = AF_INET;
1001 addr.sin_port = htons (0);
1002 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1003 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1004 perrorf (g, "bind");
1008 if (listen (g->sock, 256) == -1) {
1009 perrorf (g, "listen");
1013 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1014 perrorf (g, "getsockname");
1018 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1019 perrorf (g, "fcntl");
1023 null_vmchannel_sock = ntohs (addr.sin_port);
1025 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1027 /* Using some vmchannel impl. We need to create a local Unix
1028 * domain socket for qemu to use.
1030 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1032 null_vmchannel_sock = 0;
1036 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1037 perrorf (g, "pipe");
1044 perrorf (g, "fork");
1054 if (r == 0) { /* Child (qemu). */
1056 const char *vmchannel = NULL;
1058 /* Set up the full command line. Do this in the subprocess so we
1059 * don't need to worry about cleaning up.
1061 g->cmdline[0] = g->qemu;
1063 snprintf (buf, sizeof buf, "%d", g->memsize);
1064 add_cmdline (g, "-m");
1065 add_cmdline (g, buf);
1067 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1068 add_cmdline (g, "-nographic");
1069 add_cmdline (g, "-serial");
1070 add_cmdline (g, "stdio");
1072 /* These options recommended by KVM developers to improve reliability. */
1073 if (qemu_supports (g, "-no-hpet"))
1074 add_cmdline (g, "-no-hpet");
1076 if (qemu_supports (g, "-rtc-td-hack"))
1077 add_cmdline (g, "-rtc-td-hack");
1079 /* If qemu has SLIRP (user mode network) enabled then we can get
1080 * away with "no vmchannel", where we just connect back to a random
1083 if (null_vmchannel_sock) {
1084 add_cmdline (g, "-net");
1085 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1087 snprintf (buf, sizeof buf,
1088 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1089 vmchannel = strdup (buf);
1092 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1094 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1096 * The original suggested format doesn't work, see:
1098 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1100 * However Gerd Hoffman privately suggested to me using -chardev
1101 * instead, which does work.
1103 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1104 snprintf (buf, sizeof buf,
1105 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1107 add_cmdline (g, "-chardev");
1108 add_cmdline (g, buf);
1110 snprintf (buf, sizeof buf,
1111 "user,vlan=0,net=10.0.2.0/8,"
1112 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1113 "-chardev:guestfsvmc");
1115 add_cmdline (g, "-net");
1116 add_cmdline (g, buf);
1118 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1121 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1122 * syntax, or if not then we'll get a quick failure.
1125 snprintf (buf, sizeof buf,
1126 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1128 add_cmdline (g, "-net");
1129 add_cmdline (g, buf);
1130 add_cmdline (g, "-net");
1131 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1133 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1135 add_cmdline (g, "-net");
1136 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1138 #define LINUX_CMDLINE \
1139 "panic=1 " /* force kernel to panic if daemon exits */ \
1140 "console=ttyS0 " /* serial console */ \
1141 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1142 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1143 "acpi=off " /* we don't need ACPI, turn it off */ \
1144 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1146 /* Linux kernel command line. */
1147 snprintf (buf, sizeof buf,
1149 "%s " /* (selinux) */
1150 "%s " /* (vmchannel) */
1151 "%s " /* (verbose) */
1152 "%s", /* (append) */
1153 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1154 vmchannel ? vmchannel : "",
1155 g->verbose ? "guestfs_verbose=1" : "",
1156 g->append ? g->append : "");
1158 add_cmdline (g, "-kernel");
1159 add_cmdline (g, (char *) kernel);
1160 add_cmdline (g, "-initrd");
1161 add_cmdline (g, (char *) initrd);
1162 add_cmdline (g, "-append");
1163 add_cmdline (g, buf);
1165 /* Finish off the command line. */
1166 incr_cmdline_size (g);
1167 g->cmdline[g->cmdline_size-1] = NULL;
1173 /* Set up stdin, stdout. */
1179 if (dup (wfd[0]) == -1) {
1181 perror ("dup failed");
1184 if (dup (rfd[1]) == -1)
1192 /* Set up a new process group, so we can signal this process
1193 * and all subprocesses (eg. if qemu is really a shell script).
1198 execv (g->qemu, g->cmdline); /* Run qemu. */
1203 /* Parent (library). */
1211 /* Fork the recovery process off which will kill qemu if the parent
1212 * process fails to do so (eg. if the parent segfaults).
1216 pid_t qemu_pid = g->pid;
1217 pid_t parent_pid = getppid ();
1219 /* Writing to argv is hideously complicated and error prone. See:
1220 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1223 /* Loop around waiting for one or both of the other processes to
1224 * disappear. It's fair to say this is very hairy. The PIDs that
1225 * we are looking at might be reused by another process. We are
1226 * effectively polling. Is the cure worse than the disease?
1229 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1231 if (kill (parent_pid, 0) == -1) {
1232 /* Parent's gone away, qemu still around, so kill qemu. */
1240 /* Don't worry, if the fork failed, this will be -1. The recovery
1241 * process isn't essential.
1245 /* Start the clock ... */
1249 /* Close the other ends of the pipe. */
1253 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1254 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1255 perrorf (g, "fcntl");
1259 g->fd[0] = wfd[1]; /* stdin of child */
1260 g->fd[1] = rfd[0]; /* stdout of child */
1262 g->fd[0] = open ("/dev/null", O_RDWR);
1263 if (g->fd[0] == -1) {
1264 perrorf (g, "open /dev/null");
1267 g->fd[1] = dup (g->fd[0]);
1268 if (g->fd[1] == -1) {
1275 if (null_vmchannel_sock) {
1279 /* Null vmchannel implementation: We listen on g->sock for a
1280 * connection. The connection could come from any local process
1281 * so we must check it comes from the appliance (or at least
1282 * from our UID) for security reasons.
1284 while (sock == -1) {
1285 sock = accept_from_daemon (g);
1289 if (check_peer_euid (g, sock, &uid) == -1)
1291 if (uid != geteuid ()) {
1293 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1294 uid, null_vmchannel_sock);
1300 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1301 perrorf (g, "fcntl");
1308 /* Other vmchannel. Open the Unix socket.
1310 * The vmchannel implementation that got merged with qemu sucks in
1311 * a number of ways. Both ends do connect(2), which means that no
1312 * one knows what, if anything, is connected to the other end, or
1313 * if it becomes disconnected. Even worse, we have to wait some
1314 * indeterminate time for qemu to create the socket and connect to
1315 * it (which happens very early in qemu's start-up), so any code
1316 * that uses vmchannel is inherently racy. Hence this silly loop.
1318 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1319 if (g->sock == -1) {
1320 perrorf (g, "socket");
1324 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1325 perrorf (g, "fcntl");
1329 addr.sun_family = AF_UNIX;
1330 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1331 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1334 /* Always sleep at least once to give qemu a small chance to start up. */
1337 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1338 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1341 if (errno != ENOENT)
1342 perrorf (g, "connect");
1347 error (g, _("failed to connect to vmchannel socket"));
1353 g->state = LAUNCHING;
1355 /* Wait for qemu to start and to connect back to us via vmchannel and
1356 * send the GUESTFS_LAUNCH_FLAG message.
1360 r = recv_from_daemon (g, &size, &buf);
1363 if (r == -1) return -1;
1365 if (size != GUESTFS_LAUNCH_FLAG) {
1366 error (g, _("guestfs_launch failed, see earlier error messages"));
1370 /* This is possible in some really strange situations, such as
1371 * guestfsd starts up OK but then qemu immediately exits. Check for
1372 * it because the caller is probably expecting to be able to send
1373 * commands after this function returns.
1375 if (g->state != READY) {
1376 error (g, _("qemu launched and contacted daemon, but state != READY"));
1388 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1389 waitpid (g->pid, NULL, 0);
1390 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1408 /* This function is used to print the qemu command line before it gets
1409 * executed, when in verbose mode.
1412 print_cmdline (guestfs_h *g)
1417 while (g->cmdline[i]) {
1418 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1419 fprintf (stderr, " \\\n ");
1421 if (i > 0) fputc (' ', stderr);
1423 /* Does it need shell quoting? This only deals with simple cases. */
1424 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1426 if (needs_quote) fputc ('\'', stderr);
1427 fprintf (stderr, "%s", g->cmdline[i]);
1428 if (needs_quote) fputc ('\'', stderr);
1432 fputc ('\n', stderr);
1435 /* This function does the hard work of building the supermin appliance
1436 * on the fly. 'path' is the directory containing the control files.
1437 * 'kernel' and 'initrd' are where we will return the names of the
1438 * kernel and initrd (only initrd is built). The work is done by
1439 * an external script. We just tell it where to put the result.
1442 build_supermin_appliance (guestfs_h *g, const char *path,
1443 char **kernel, char **initrd)
1448 len = strlen (g->tmpdir);
1449 *kernel = safe_malloc (g, len + 8);
1450 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1451 *initrd = safe_malloc (g, len + 8);
1452 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1454 snprintf (cmd, sizeof cmd,
1456 "libguestfs-supermin-helper '%s' %s %s",
1458 path, *kernel, *initrd);
1461 if (r == -1 || WEXITSTATUS(r) != 0) {
1462 error (g, _("external command failed: %s"), cmd);
1465 *kernel = *initrd = NULL;
1472 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1474 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1475 * 'qemu -version' so we know what options this qemu supports and
1479 test_qemu (guestfs_h *g)
1484 free (g->qemu_help);
1485 free (g->qemu_version);
1486 g->qemu_help = NULL;
1487 g->qemu_version = NULL;
1489 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1491 fp = popen (cmd, "r");
1492 /* qemu -help should always work (qemu -version OTOH wasn't
1493 * supported by qemu 0.9). If this command doesn't work then it
1494 * probably indicates that the qemu binary is missing.
1497 /* XXX This error is never printed, even if the qemu binary
1498 * doesn't exist. Why?
1501 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1505 if (read_all (g, fp, &g->qemu_help) == -1)
1508 if (pclose (fp) == -1)
1511 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1513 fp = popen (cmd, "r");
1515 /* Intentionally ignore errors. */
1516 read_all (g, fp, &g->qemu_version);
1524 read_all (guestfs_h *g, FILE *fp, char **ret)
1531 *ret = safe_realloc (g, *ret, n + 1);
1536 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1538 r = fread (p, 1, BUFSIZ, fp);
1540 perrorf (g, "read");
1547 /* Test if option is supported by qemu command line (just by grepping
1551 qemu_supports (guestfs_h *g, const char *option)
1553 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1556 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1557 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1558 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1561 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1563 struct sockaddr_in peer;
1564 socklen_t addrlen = sizeof peer;
1566 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1567 perrorf (g, "getpeername");
1571 if (peer.sin_family != AF_INET ||
1572 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1573 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1574 peer.sin_family, inet_ntoa (peer.sin_addr));
1578 struct sockaddr_in our;
1579 addrlen = sizeof our;
1580 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1581 perrorf (g, "getsockname");
1585 FILE *fp = fopen ("/proc/net/tcp", "r");
1587 perrorf (g, "/proc/net/tcp");
1592 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1593 error (g, "unexpected end of file in /proc/net/tcp");
1598 while (fgets (line, sizeof line, fp) != NULL) {
1599 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1600 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1603 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1605 &line_our_addr, &line_our_port,
1606 &line_peer_addr, &line_peer_port,
1607 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1609 /* Note about /proc/net/tcp: local_address and rem_address are
1610 * always in network byte order. However the port part is
1611 * always in host byte order.
1613 * The sockname and peername that we got above are in network
1614 * byte order. So we have to byte swap the port but not the
1617 if (line_our_addr == our.sin_addr.s_addr &&
1618 line_our_port == ntohs (our.sin_port) &&
1619 line_peer_addr == peer.sin_addr.s_addr &&
1620 line_peer_port == ntohs (peer.sin_port)) {
1628 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1633 /* You had to call this function after launch in versions <= 1.0.70,
1634 * but it is now a no-op.
1637 guestfs__wait_ready (guestfs_h *g)
1639 if (g->state != READY) {
1640 error (g, _("qemu has not been launched yet"));
1648 guestfs__kill_subprocess (guestfs_h *g)
1650 if (g->state == CONFIG) {
1651 error (g, _("no subprocess to kill"));
1656 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1658 kill (g->pid, SIGTERM);
1659 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1664 /* Access current state. */
1666 guestfs__is_config (guestfs_h *g)
1668 return g->state == CONFIG;
1672 guestfs__is_launching (guestfs_h *g)
1674 return g->state == LAUNCHING;
1678 guestfs__is_ready (guestfs_h *g)
1680 return g->state == READY;
1684 guestfs__is_busy (guestfs_h *g)
1686 return g->state == BUSY;
1690 guestfs__get_state (guestfs_h *g)
1696 guestfs_set_log_message_callback (guestfs_h *g,
1697 guestfs_log_message_cb cb, void *opaque)
1699 g->log_message_cb = cb;
1700 g->log_message_cb_data = opaque;
1704 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1705 guestfs_subprocess_quit_cb cb, void *opaque)
1707 g->subprocess_quit_cb = cb;
1708 g->subprocess_quit_cb_data = opaque;
1712 guestfs_set_launch_done_callback (guestfs_h *g,
1713 guestfs_launch_done_cb cb, void *opaque)
1715 g->launch_done_cb = cb;
1716 g->launch_done_cb_data = opaque;
1719 /*----------------------------------------------------------------------*/
1721 /* This is the code used to send and receive RPC messages and (for
1722 * certain types of message) to perform file transfers. This code is
1723 * driven from the generated actions (src/guestfs-actions.c). There
1724 * are five different cases to consider:
1726 * (1) A non-daemon function. There is no RPC involved at all, it's
1727 * all handled inside the library.
1729 * (2) A simple RPC (eg. "mount"). We write the request, then read
1730 * the reply. The sequence of calls is:
1732 * guestfs___set_busy
1735 * guestfs___end_busy
1737 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1738 * request, then write the file(s), then read the reply. The sequence
1741 * guestfs___set_busy
1743 * guestfs___send_file (possibly multiple times)
1745 * guestfs___end_busy
1747 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1748 * request, then read the reply, then read the file(s). The sequence
1751 * guestfs___set_busy
1754 * guestfs___recv_file (possibly multiple times)
1755 * guestfs___end_busy
1757 * (5) Both FileOut and FileIn parameters. There are no calls like
1758 * this in the current API, but they would be implemented as a
1759 * combination of cases (3) and (4).
1761 * During all writes and reads, we also select(2) on qemu stdout
1762 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1763 * anything received is passed up through the log_message_cb. This is
1764 * also the reason why all the sockets are non-blocking. We also have
1765 * to check for EOF (qemu died). All of this is handled by the
1766 * functions send_to_daemon and recv_from_daemon.
1770 guestfs___set_busy (guestfs_h *g)
1772 if (g->state != READY) {
1773 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1782 guestfs___end_busy (guestfs_h *g)
1796 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1802 /* This is called if we detect EOF, ie. qemu died. */
1804 child_cleanup (guestfs_h *g)
1807 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1809 /*kill (g->pid, SIGTERM);*/
1810 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1811 waitpid (g->pid, NULL, 0);
1812 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1823 if (g->subprocess_quit_cb)
1824 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1828 read_log_message_or_eof (guestfs_h *g, int fd)
1836 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1840 /* QEMU's console emulates a 16550A serial port. The real 16550A
1841 * device has a small FIFO buffer (16 bytes) which means here we see
1842 * lots of small reads of 1-16 bytes in length, usually single
1845 n = read (fd, buf, sizeof buf);
1847 /* Hopefully this indicates the qemu child process has died. */
1853 if (errno == EINTR || errno == EAGAIN)
1856 perrorf (g, "read");
1860 /* In verbose mode, copy all log messages to stderr. */
1862 ignore_value (write (STDERR_FILENO, buf, n));
1864 /* It's an actual log message, send it upwards if anyone is listening. */
1865 if (g->log_message_cb)
1866 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1872 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1881 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1884 n = read (fd, buf, 4);
1886 /* Hopefully this indicates the qemu child process has died. */
1892 if (errno == EINTR || errno == EAGAIN)
1895 perrorf (g, "read");
1899 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1900 xdr_uint32_t (&xdr, &flag);
1903 if (flag != GUESTFS_CANCEL_FLAG) {
1904 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1905 flag, GUESTFS_CANCEL_FLAG);
1912 /* This writes the whole N bytes of BUF to the daemon socket.
1914 * If the whole write is successful, it returns 0.
1915 * If there was an error, it returns -1.
1916 * If the daemon sent a cancellation message, it returns -2.
1918 * It also checks qemu stdout for log messages and passes those up
1919 * through log_message_cb.
1921 * It also checks for EOF (qemu died) and passes that up through the
1922 * child_cleanup function above.
1925 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1927 const char *buf = v_buf;
1933 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1938 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1939 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1940 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1942 int max_fd = MAX (g->sock, g->fd[1]);
1947 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1949 if (errno == EINTR || errno == EAGAIN)
1951 perrorf (g, "select");
1955 if (FD_ISSET (g->fd[1], &rset2)) {
1956 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1959 if (FD_ISSET (g->sock, &rset2)) {
1960 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1964 if (FD_ISSET (g->sock, &wset2)) {
1965 r = write (g->sock, buf, n);
1967 if (errno == EINTR || errno == EAGAIN)
1969 perrorf (g, "write");
1970 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1982 /* This reads a single message, file chunk, launch flag or
1983 * cancellation flag from the daemon. If something was read, it
1984 * returns 0, otherwise -1.
1986 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
1988 * *size_rtn returns the size of the returned message or it may be
1989 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
1991 * *buf_rtn is returned containing the message (if any) or will be set
1992 * to NULL. *buf_rtn must be freed by the caller.
1994 * It also checks qemu stdout for log messages and passes those up
1995 * through log_message_cb.
1997 * It also checks for EOF (qemu died) and passes that up through the
1998 * child_cleanup function above.
2001 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2007 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2008 g, g->state, size_rtn, buf_rtn);
2012 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2013 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2015 int max_fd = MAX (g->sock, g->fd[1]);
2021 /* nr is the size of the message, but we prime it as -4 because we
2022 * have to read the message length word first.
2026 while (nr < (ssize_t) *size_rtn) {
2028 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2030 if (errno == EINTR || errno == EAGAIN)
2032 perrorf (g, "select");
2038 if (FD_ISSET (g->fd[1], &rset2)) {
2039 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2045 if (FD_ISSET (g->sock, &rset2)) {
2046 if (nr < 0) { /* Have we read the message length word yet? */
2047 r = read (g->sock, lenbuf+nr+4, -nr);
2049 if (errno == EINTR || errno == EAGAIN)
2052 perrorf (g, "read");
2053 /* Under some circumstances we see "Connection reset by peer"
2054 * here when the child dies suddenly. Catch this and call
2055 * the cleanup function, same as for EOF.
2057 if (err == ECONNRESET)
2062 error (g, _("unexpected end of file when reading from daemon"));
2068 if (nr < 0) /* Still not got the whole length word. */
2072 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2073 xdr_uint32_t (&xdr, size_rtn);
2076 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2077 if (g->state != LAUNCHING)
2078 error (g, _("received magic signature from guestfsd, but in state %d"),
2082 if (g->launch_done_cb)
2083 g->launch_done_cb (g, g->launch_done_cb_data);
2087 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2089 /* If this happens, it's pretty bad and we've probably lost
2092 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2093 error (g, _("message length (%u) > maximum possible size (%d)"),
2094 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2098 /* Allocate the complete buffer, size now known. */
2099 *buf_rtn = safe_malloc (g, *size_rtn);
2103 size_t sizetoread = *size_rtn - nr;
2104 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2106 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2108 if (errno == EINTR || errno == EAGAIN)
2110 perrorf (g, "read");
2116 error (g, _("unexpected end of file when reading from daemon"));
2126 /* Got the full message, caller can start processing it. */
2127 #ifdef ENABLE_PACKET_DUMP
2131 for (i = 0; i < nr; i += 16) {
2132 printf ("%04zx: ", i);
2133 for (j = i; j < MIN (i+16, nr); ++j)
2134 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2135 for (; j < i+16; ++j)
2138 for (j = i; j < MIN (i+16, nr); ++j)
2139 if (c_isprint ((*(char **)buf_rtn)[j]))
2140 printf ("%c", (*(char **)buf_rtn)[j]);
2143 for (; j < i+16; ++j)
2153 /* This is very much like recv_from_daemon above, but g->sock is
2154 * a listening socket and we are accepting a new connection on
2155 * that socket instead of reading anything. Returns the newly
2159 accept_from_daemon (guestfs_h *g)
2165 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2169 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2170 FD_SET (g->sock, &rset); /* Read socket for accept. */
2172 int max_fd = MAX (g->sock, g->fd[1]);
2175 while (sock == -1) {
2177 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2179 if (errno == EINTR || errno == EAGAIN)
2181 perrorf (g, "select");
2185 if (FD_ISSET (g->fd[1], &rset2)) {
2186 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2189 if (FD_ISSET (g->sock, &rset2)) {
2190 sock = accept (g->sock, NULL, NULL);
2192 if (errno == EINTR || errno == EAGAIN)
2194 perrorf (g, "accept");
2204 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2206 struct guestfs_message_header hdr;
2209 int serial = g->msg_next_serial++;
2212 size_t msg_out_size;
2214 if (g->state != BUSY) {
2215 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2219 /* We have to allocate this message buffer on the heap because
2220 * it is quite large (although will be mostly unused). We
2221 * can't allocate it on the stack because in some environments
2222 * we have quite limited stack space available, notably when
2223 * running in the JVM.
2225 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2226 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2228 /* Serialize the header. */
2229 hdr.prog = GUESTFS_PROGRAM;
2230 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2232 hdr.direction = GUESTFS_DIRECTION_CALL;
2233 hdr.serial = serial;
2234 hdr.status = GUESTFS_STATUS_OK;
2236 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2237 error (g, _("xdr_guestfs_message_header failed"));
2241 /* Serialize the args. If any, because some message types
2242 * have no parameters.
2245 if (!(*xdrp) (&xdr, args)) {
2246 error (g, _("dispatch failed to marshal args"));
2251 /* Get the actual length of the message, resize the buffer to match
2252 * the actual length, and write the length word at the beginning.
2254 len = xdr_getpos (&xdr);
2257 msg_out = safe_realloc (g, msg_out, len + 4);
2258 msg_out_size = len + 4;
2260 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2261 xdr_uint32_t (&xdr, &len);
2264 r = send_to_daemon (g, msg_out, msg_out_size);
2265 if (r == -2) /* Ignore stray daemon cancellations. */
2278 static int cancel = 0; /* XXX Implement file cancellation. */
2279 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2280 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2281 static int send_file_cancellation (guestfs_h *g);
2282 static int send_file_complete (guestfs_h *g);
2288 * -2 daemon cancelled (we must read the error message)
2291 guestfs___send_file (guestfs_h *g, const char *filename)
2293 char buf[GUESTFS_MAX_CHUNK_SIZE];
2296 fd = open (filename, O_RDONLY);
2298 perrorf (g, "open: %s", filename);
2299 send_file_cancellation (g);
2300 /* Daemon sees cancellation and won't reply, so caller can
2306 /* Send file in chunked encoding. */
2308 r = read (fd, buf, sizeof buf);
2309 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2312 err = send_file_data (g, buf, r);
2314 if (err == -2) /* daemon sent cancellation */
2315 send_file_cancellation (g);
2320 if (cancel) { /* cancel from either end */
2321 send_file_cancellation (g);
2326 perrorf (g, "read: %s", filename);
2327 send_file_cancellation (g);
2331 /* End of file, but before we send that, we need to close
2332 * the file and check for errors.
2334 if (close (fd) == -1) {
2335 perrorf (g, "close: %s", filename);
2336 send_file_cancellation (g);
2340 return send_file_complete (g);
2343 /* Send a chunk of file data. */
2345 send_file_data (guestfs_h *g, const char *buf, size_t len)
2347 return send_file_chunk (g, 0, buf, len);
2350 /* Send a cancellation message. */
2352 send_file_cancellation (guestfs_h *g)
2354 return send_file_chunk (g, 1, NULL, 0);
2357 /* Send a file complete chunk. */
2359 send_file_complete (guestfs_h *g)
2362 return send_file_chunk (g, 0, buf, 0);
2366 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2370 guestfs_chunk chunk;
2373 size_t msg_out_size;
2375 if (g->state != BUSY) {
2376 error (g, _("send_file_chunk: state %d != READY"), g->state);
2380 /* Allocate the chunk buffer. Don't use the stack to avoid
2381 * excessive stack usage and unnecessary copies.
2383 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2384 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2386 /* Serialize the chunk. */
2387 chunk.cancel = cancel;
2388 chunk.data.data_len = buflen;
2389 chunk.data.data_val = (char *) buf;
2391 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2392 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2398 len = xdr_getpos (&xdr);
2401 /* Reduce the size of the outgoing message buffer to the real length. */
2402 msg_out = safe_realloc (g, msg_out, len + 4);
2403 msg_out_size = len + 4;
2405 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2406 xdr_uint32_t (&xdr, &len);
2408 r = send_to_daemon (g, msg_out, msg_out_size);
2410 /* Did the daemon send a cancellation message? */
2413 fprintf (stderr, "got daemon cancellation\n");
2429 /* Receive a reply. */
2431 guestfs___recv (guestfs_h *g, const char *fn,
2432 guestfs_message_header *hdr,
2433 guestfs_message_error *err,
2434 xdrproc_t xdrp, char *ret)
2442 r = recv_from_daemon (g, &size, &buf);
2446 /* This can happen if a cancellation happens right at the end
2447 * of us sending a FileIn parameter to the daemon. Discard. The
2448 * daemon should send us an error message next.
2450 if (size == GUESTFS_CANCEL_FLAG)
2453 if (size == GUESTFS_LAUNCH_FLAG) {
2454 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2458 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2460 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2461 error (g, "%s: failed to parse reply header", fn);
2466 if (hdr->status == GUESTFS_STATUS_ERROR) {
2467 if (!xdr_guestfs_message_error (&xdr, err)) {
2468 error (g, "%s: failed to parse reply error", fn);
2474 if (xdrp && ret && !xdrp (&xdr, ret)) {
2475 error (g, "%s: failed to parse reply", fn);
2487 /* Receive a file. */
2489 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2490 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2493 guestfs___recv_file (guestfs_h *g, const char *filename)
2499 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2501 perrorf (g, "open: %s", filename);
2505 /* Receive the file in chunked encoding. */
2506 while ((r = receive_file_data (g, &buf)) > 0) {
2507 if (xwrite (fd, buf, r) == -1) {
2508 perrorf (g, "%s: write", filename);
2516 error (g, _("%s: error in chunked encoding"), filename);
2520 if (close (fd) == -1) {
2521 perrorf (g, "close: %s", filename);
2528 /* Send cancellation message to daemon, then wait until it
2529 * cancels (just throwing away data).
2533 uint32_t flag = GUESTFS_CANCEL_FLAG;
2536 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2539 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2540 xdr_uint32_t (&xdr, &flag);
2543 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2544 perrorf (g, _("write to daemon socket"));
2548 while (receive_file_data (g, NULL) > 0)
2549 ; /* just discard it */
2554 /* Receive a chunk of file data. */
2555 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2557 receive_file_data (guestfs_h *g, void **buf_r)
2563 guestfs_chunk chunk;
2565 r = recv_from_daemon (g, &len, &buf);
2567 error (g, _("receive_file_data: parse error in reply callback"));
2571 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2572 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2576 memset (&chunk, 0, sizeof chunk);
2578 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2579 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2580 error (g, _("failed to parse file chunk"));
2585 /* After decoding, the original buffer is no longer used. */
2589 error (g, _("file receive cancelled by daemon"));
2590 free (chunk.data.data_val);
2594 if (chunk.data.data_len == 0) { /* end of transfer */
2595 free (chunk.data.data_val);
2599 if (buf_r) *buf_r = chunk.data.data_val;
2600 else free (chunk.data.data_val); /* else caller frees */
2602 return chunk.data.data_len;