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. */
125 char *path; /* Path to kernel, initrd. */
126 char *qemu; /* Qemu binary. */
127 char *append; /* Append to kernel command line. */
129 int memsize; /* Size of RAM (megabytes). */
131 int selinux; /* selinux enabled? */
136 guestfs_abort_cb abort_cb;
137 guestfs_error_handler_cb error_cb;
138 void * error_cb_data;
139 guestfs_log_message_cb log_message_cb;
140 void * log_message_cb_data;
141 guestfs_subprocess_quit_cb subprocess_quit_cb;
142 void * subprocess_quit_cb_data;
143 guestfs_launch_done_cb launch_done_cb;
144 void * launch_done_cb_data;
149 static guestfs_h *handles = NULL;
150 static int atexit_handler_set = 0;
153 guestfs_create (void)
158 g = malloc (sizeof (*g));
161 memset (g, 0, sizeof (*g));
170 g->error_cb = default_error_cb;
171 g->error_cb_data = NULL;
173 g->recovery_proc = 1;
175 str = getenv ("LIBGUESTFS_DEBUG");
176 g->verbose = str != NULL && STREQ (str, "1");
178 str = getenv ("LIBGUESTFS_TRACE");
179 g->trace = str != NULL && STREQ (str, "1");
181 str = getenv ("LIBGUESTFS_PATH");
182 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
183 if (!g->path) goto error;
185 str = getenv ("LIBGUESTFS_QEMU");
186 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
187 if (!g->qemu) goto error;
189 str = getenv ("LIBGUESTFS_APPEND");
191 g->append = strdup (str);
192 if (!g->append) goto error;
195 /* Choose a suitable memory size. Previously we tried to choose
196 * a minimal memory size, but this isn't really necessary since
197 * recent QEMU and KVM don't do anything nasty like locking
198 * memory into core any more. Thus we can safely choose a
199 * large, generous amount of memory, and it'll just get swapped
200 * on smaller systems.
202 str = getenv ("LIBGUESTFS_MEMSIZE");
204 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
205 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
211 /* Start with large serial numbers so they are easy to spot
212 * inside the protocol.
214 g->msg_next_serial = 0x00123400;
216 /* Link the handles onto a global list. This is the one area
217 * where the library needs to be made thread-safe. (XXX)
219 /* acquire mutex (XXX) */
222 if (!atexit_handler_set) {
223 atexit (close_handles);
224 atexit_handler_set = 1;
226 /* release mutex (XXX) */
229 fprintf (stderr, "new guestfs handle %p\n", g);
242 guestfs_close (guestfs_h *g)
248 if (g->state == NO_HANDLE) {
249 /* Not safe to call 'error' here, so ... */
250 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
255 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
257 /* Try to sync if autosync flag is set. */
258 if (g->autosync && g->state == READY) {
259 guestfs_umount_all (g);
263 /* Remove any handlers that might be called back before we kill the
266 g->log_message_cb = NULL;
268 if (g->state != CONFIG)
269 guestfs_kill_subprocess (g);
282 /* Wait for subprocess(es) to exit. */
283 waitpid (g->pid, NULL, 0);
284 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
286 /* Remove tmpfiles. */
288 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
291 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
294 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
303 for (i = 0; i < g->cmdline_size; ++i)
304 free (g->cmdline[i]);
308 /* Mark the handle as dead before freeing it. */
309 g->state = NO_HANDLE;
311 /* acquire mutex (XXX) */
315 for (gg = handles; gg->next != g; gg = gg->next)
319 /* release mutex (XXX) */
321 free (g->last_error);
326 free (g->qemu_version);
330 /* Close all open handles (called from atexit(3)). */
334 while (handles) guestfs_close (handles);
338 guestfs_last_error (guestfs_h *g)
340 return g->last_error;
344 set_last_error (guestfs_h *g, const char *msg)
346 free (g->last_error);
347 g->last_error = strdup (msg);
351 default_error_cb (guestfs_h *g, void *data, const char *msg)
353 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
357 guestfs_error (guestfs_h *g, const char *fs, ...)
363 int err = vasprintf (&msg, fs, args);
368 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
369 set_last_error (g, msg);
375 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
382 int err = vasprintf (&msg, fs, args);
389 strerror_r (errnum, buf, sizeof buf);
393 buf = strerror_r (errnum, _buf, sizeof _buf);
396 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
400 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
401 set_last_error (g, msg);
407 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
409 void *ptr = malloc (nbytes);
410 if (nbytes > 0 && !ptr) g->abort_cb ();
414 /* Return 1 if an array of N objects, each of size S, cannot exist due
415 to size arithmetic overflow. S must be positive and N must be
416 nonnegative. This is a macro, not an inline function, so that it
417 works correctly even when SIZE_MAX < N.
419 By gnulib convention, SIZE_MAX represents overflow in size
420 calculations, so the conservative dividend to use here is
421 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
422 However, malloc (SIZE_MAX) fails on all known hosts where
423 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
424 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
425 branch when S is known to be 1. */
426 # define xalloc_oversized(n, s) \
427 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
429 /* Technically we should add an autoconf test for this, testing for the desired
430 functionality, like what's done in gnulib, but for now, this is fine. */
431 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
433 /* Allocate zeroed memory for N elements of S bytes, with error
434 checking. S must be nonzero. */
436 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
438 /* From gnulib's calloc function in xmalloc.c. */
440 /* Test for overflow, since some calloc implementations don't have
441 proper overflow checks. But omit overflow and size-zero tests if
442 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
443 returns NULL if successful. */
444 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
445 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
451 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
453 void *p = realloc (ptr, nbytes);
454 if (nbytes > 0 && !p) g->abort_cb ();
459 guestfs_safe_strdup (guestfs_h *g, const char *str)
461 char *s = strdup (str);
462 if (!s) g->abort_cb ();
467 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
469 void *p = malloc (size);
470 if (!p) g->abort_cb ();
471 memcpy (p, ptr, size);
476 xwrite (int fd, const void *v_buf, size_t len)
478 const char *buf = v_buf;
482 r = write (fd, buf, len);
494 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
500 guestfs_get_out_of_memory_handler (guestfs_h *g)
506 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
509 g->error_cb_data = data;
512 guestfs_error_handler_cb
513 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
515 if (data_rtn) *data_rtn = g->error_cb_data;
520 guestfs__set_verbose (guestfs_h *g, int v)
527 guestfs__get_verbose (guestfs_h *g)
533 guestfs__set_autosync (guestfs_h *g, int a)
540 guestfs__get_autosync (guestfs_h *g)
546 guestfs__set_path (guestfs_h *g, const char *path)
553 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
558 guestfs__get_path (guestfs_h *g)
564 guestfs__set_qemu (guestfs_h *g, const char *qemu)
569 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
574 guestfs__get_qemu (guestfs_h *g)
580 guestfs__set_append (guestfs_h *g, const char *append)
585 g->append = append ? safe_strdup (g, append) : NULL;
590 guestfs__get_append (guestfs_h *g)
596 guestfs__set_memsize (guestfs_h *g, int memsize)
598 g->memsize = memsize;
603 guestfs__get_memsize (guestfs_h *g)
609 guestfs__set_selinux (guestfs_h *g, int selinux)
611 g->selinux = selinux;
616 guestfs__get_selinux (guestfs_h *g)
622 guestfs__get_pid (guestfs_h *g)
627 error (g, "get_pid: no qemu subprocess");
632 struct guestfs_version *
633 guestfs__version (guestfs_h *g)
635 struct guestfs_version *r;
637 r = safe_malloc (g, sizeof *r);
638 r->major = PACKAGE_VERSION_MAJOR;
639 r->minor = PACKAGE_VERSION_MINOR;
640 r->release = PACKAGE_VERSION_RELEASE;
641 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
646 guestfs__set_trace (guestfs_h *g, int t)
653 guestfs__get_trace (guestfs_h *g)
659 guestfs__set_direct (guestfs_h *g, int d)
666 guestfs__get_direct (guestfs_h *g)
672 guestfs__set_recovery_proc (guestfs_h *g, int f)
674 g->recovery_proc = !!f;
679 guestfs__get_recovery_proc (guestfs_h *g)
681 return g->recovery_proc;
684 /* Add a string to the current command line. */
686 incr_cmdline_size (guestfs_h *g)
688 if (g->cmdline == NULL) {
689 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
691 g->cmdline = safe_malloc (g, sizeof (char *));
692 g->cmdline[0] = NULL;
696 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
700 add_cmdline (guestfs_h *g, const char *str)
702 if (g->state != CONFIG) {
704 _("command line cannot be altered after qemu subprocess launched"));
708 incr_cmdline_size (g);
709 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
714 guestfs__config (guestfs_h *g,
715 const char *qemu_param, const char *qemu_value)
717 if (qemu_param[0] != '-') {
718 error (g, _("guestfs_config: parameter must begin with '-' character"));
722 /* A bit fascist, but the user will probably break the extra
723 * parameters that we add if they try to set any of these.
725 if (STREQ (qemu_param, "-kernel") ||
726 STREQ (qemu_param, "-initrd") ||
727 STREQ (qemu_param, "-nographic") ||
728 STREQ (qemu_param, "-serial") ||
729 STREQ (qemu_param, "-full-screen") ||
730 STREQ (qemu_param, "-std-vga") ||
731 STREQ (qemu_param, "-vnc")) {
732 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
736 if (add_cmdline (g, qemu_param) != 0) return -1;
738 if (qemu_value != NULL) {
739 if (add_cmdline (g, qemu_value) != 0) return -1;
746 guestfs__add_drive (guestfs_h *g, const char *filename)
748 size_t len = strlen (filename) + 64;
751 if (strchr (filename, ',') != NULL) {
752 error (g, _("filename cannot contain ',' (comma) character"));
756 /* cache=off improves reliability in the event of a host crash.
758 * However this option causes qemu to try to open the file with
759 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
760 * So we check if we can open the file with or without O_DIRECT,
761 * and use cache=off (or not) accordingly.
763 * This test also checks for the presence of the file, which
764 * is a documented semantic of this interface.
766 int fd = open (filename, O_RDONLY|O_DIRECT);
769 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
771 fd = open (filename, O_RDONLY);
774 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
776 perrorf (g, "%s", filename);
781 return guestfs__config (g, "-drive", buf);
785 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
787 size_t len = strlen (filename) + 64;
790 if (strchr (filename, ',') != NULL) {
791 error (g, _("filename cannot contain ',' (comma) character"));
795 if (access (filename, F_OK) == -1) {
796 perrorf (g, "%s", filename);
800 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
802 return guestfs__config (g, "-drive", buf);
806 guestfs__add_cdrom (guestfs_h *g, const char *filename)
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 return guestfs__config (g, "-cdrom", filename);
821 /* Returns true iff file is contained in dir. */
823 dir_contains_file (const char *dir, const char *file)
825 int dirlen = strlen (dir);
826 int filelen = strlen (file);
827 int len = dirlen+filelen+2;
830 snprintf (path, len, "%s/%s", dir, file);
831 return access (path, F_OK) == 0;
834 /* Returns true iff every listed file is contained in 'dir'. */
836 dir_contains_files (const char *dir, ...)
841 va_start (args, dir);
842 while ((file = va_arg (args, const char *)) != NULL) {
843 if (!dir_contains_file (dir, file)) {
852 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
853 static int test_qemu (guestfs_h *g);
854 static int qemu_supports (guestfs_h *g, const char *option);
855 static void print_cmdline (guestfs_h *g);
857 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
858 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
859 static const char *supermin_name =
860 "initramfs." REPO "." host_cpu ".supermin.img";
861 static const char *supermin_hostfiles_name =
862 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
865 guestfs__launch (guestfs_h *g)
868 char dir_template[PATH_MAX];
873 char *path, *pelem, *pend;
874 char *kernel = NULL, *initrd = NULL;
875 int null_vmchannel_sock;
877 struct sockaddr_un addr;
885 tmpdir = getenv ("TMPDIR") ? : tmpdir;
886 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
890 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
894 if (g->state != CONFIG) {
895 error (g, _("qemu has already been launched"));
899 /* Make the temporary directory. */
901 g->tmpdir = safe_strdup (g, dir_template);
902 if (mkdtemp (g->tmpdir) == NULL) {
903 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
908 /* First search g->path for the supermin appliance, and try to
909 * synthesize a kernel and initrd from that. If it fails, we
910 * try the path search again looking for a backup ordinary
913 pelem = path = safe_strdup (g, g->path);
915 pend = strchrnul (pelem, ':');
916 pmore = *pend == ':';
920 /* Empty element of "." means cwd. */
921 if (len == 0 || (len == 1 && *pelem == '.')) {
924 "looking for supermin appliance in current directory\n");
925 if (dir_contains_files (".",
926 supermin_name, supermin_hostfiles_name,
927 "kmod.whitelist", NULL)) {
928 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
933 /* Look at <path>/supermin* etc. */
936 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
938 if (dir_contains_files (pelem,
939 supermin_name, supermin_hostfiles_name,
940 "kmod.whitelist", NULL)) {
941 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
952 if (kernel == NULL || initrd == NULL) {
953 /* Search g->path for the kernel and initrd. */
954 pelem = path = safe_strdup (g, g->path);
956 pend = strchrnul (pelem, ':');
957 pmore = *pend == ':';
961 /* Empty element or "." means cwd. */
962 if (len == 0 || (len == 1 && *pelem == '.')) {
965 "looking for appliance in current directory\n");
966 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
967 kernel = safe_strdup (g, kernel_name);
968 initrd = safe_strdup (g, initrd_name);
972 /* Look at <path>/kernel etc. */
975 fprintf (stderr, "looking for appliance in %s\n", pelem);
977 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
978 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
979 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
980 sprintf (kernel, "%s/%s", pelem, kernel_name);
981 sprintf (initrd, "%s/%s", pelem, initrd_name);
992 if (kernel == NULL || initrd == NULL) {
993 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
994 kernel_name, initrd_name, g->path);
998 /* Get qemu help text and version. */
999 if (test_qemu (g) == -1)
1002 /* Choose which vmchannel implementation to use. */
1003 if (qemu_supports (g, "-net user")) {
1004 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1005 * networking in qemu) but no other vmchannel support. The daemon
1006 * will connect back to a random port number on localhost.
1008 struct sockaddr_in addr;
1009 socklen_t addrlen = sizeof addr;
1011 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1012 if (g->sock == -1) {
1013 perrorf (g, "socket");
1016 addr.sin_family = AF_INET;
1017 addr.sin_port = htons (0);
1018 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1019 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1020 perrorf (g, "bind");
1024 if (listen (g->sock, 256) == -1) {
1025 perrorf (g, "listen");
1029 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1030 perrorf (g, "getsockname");
1034 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1035 perrorf (g, "fcntl");
1039 null_vmchannel_sock = ntohs (addr.sin_port);
1041 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1043 /* Using some vmchannel impl. We need to create a local Unix
1044 * domain socket for qemu to use.
1046 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1048 null_vmchannel_sock = 0;
1052 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1053 perrorf (g, "pipe");
1060 perrorf (g, "fork");
1070 if (r == 0) { /* Child (qemu). */
1072 const char *vmchannel = NULL;
1074 /* Set up the full command line. Do this in the subprocess so we
1075 * don't need to worry about cleaning up.
1077 g->cmdline[0] = g->qemu;
1079 snprintf (buf, sizeof buf, "%d", g->memsize);
1080 add_cmdline (g, "-m");
1081 add_cmdline (g, buf);
1083 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1084 add_cmdline (g, "-nographic");
1085 add_cmdline (g, "-serial");
1086 add_cmdline (g, "stdio");
1088 /* These options recommended by KVM developers to improve reliability. */
1089 if (qemu_supports (g, "-no-hpet"))
1090 add_cmdline (g, "-no-hpet");
1092 if (qemu_supports (g, "-rtc-td-hack"))
1093 add_cmdline (g, "-rtc-td-hack");
1095 /* If qemu has SLIRP (user mode network) enabled then we can get
1096 * away with "no vmchannel", where we just connect back to a random
1099 if (null_vmchannel_sock) {
1100 add_cmdline (g, "-net");
1101 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1103 snprintf (buf, sizeof buf,
1104 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1105 vmchannel = strdup (buf);
1108 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1110 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1112 * The original suggested format doesn't work, see:
1114 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1116 * However Gerd Hoffman privately suggested to me using -chardev
1117 * instead, which does work.
1119 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1120 snprintf (buf, sizeof buf,
1121 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1123 add_cmdline (g, "-chardev");
1124 add_cmdline (g, buf);
1126 snprintf (buf, sizeof buf,
1127 "user,vlan=0,net=10.0.2.0/8,"
1128 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1129 "-chardev:guestfsvmc");
1131 add_cmdline (g, "-net");
1132 add_cmdline (g, buf);
1134 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1137 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1138 * syntax, or if not then we'll get a quick failure.
1141 snprintf (buf, sizeof buf,
1142 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1144 add_cmdline (g, "-net");
1145 add_cmdline (g, buf);
1146 add_cmdline (g, "-net");
1147 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1149 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1151 add_cmdline (g, "-net");
1152 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1154 #define LINUX_CMDLINE \
1155 "panic=1 " /* force kernel to panic if daemon exits */ \
1156 "console=ttyS0 " /* serial console */ \
1157 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1158 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1159 "acpi=off " /* we don't need ACPI, turn it off */ \
1160 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1162 /* Linux kernel command line. */
1163 snprintf (buf, sizeof buf,
1165 "%s " /* (selinux) */
1166 "%s " /* (vmchannel) */
1167 "%s " /* (verbose) */
1168 "%s", /* (append) */
1169 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1170 vmchannel ? vmchannel : "",
1171 g->verbose ? "guestfs_verbose=1" : "",
1172 g->append ? g->append : "");
1174 add_cmdline (g, "-kernel");
1175 add_cmdline (g, (char *) kernel);
1176 add_cmdline (g, "-initrd");
1177 add_cmdline (g, (char *) initrd);
1178 add_cmdline (g, "-append");
1179 add_cmdline (g, buf);
1181 /* Finish off the command line. */
1182 incr_cmdline_size (g);
1183 g->cmdline[g->cmdline_size-1] = NULL;
1189 /* Set up stdin, stdout. */
1195 if (dup (wfd[0]) == -1) {
1197 perror ("dup failed");
1200 if (dup (rfd[1]) == -1)
1208 /* Set up a new process group, so we can signal this process
1209 * and all subprocesses (eg. if qemu is really a shell script).
1214 setenv ("LC_ALL", "C", 1);
1216 execv (g->qemu, g->cmdline); /* Run qemu. */
1221 /* Parent (library). */
1229 /* Fork the recovery process off which will kill qemu if the parent
1230 * process fails to do so (eg. if the parent segfaults).
1232 g->recoverypid = -1;
1233 if (g->recovery_proc) {
1236 pid_t qemu_pid = g->pid;
1237 pid_t parent_pid = getppid ();
1239 /* Writing to argv is hideously complicated and error prone. See:
1240 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1243 /* Loop around waiting for one or both of the other processes to
1244 * disappear. It's fair to say this is very hairy. The PIDs that
1245 * we are looking at might be reused by another process. We are
1246 * effectively polling. Is the cure worse than the disease?
1249 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1251 if (kill (parent_pid, 0) == -1) {
1252 /* Parent's gone away, qemu still around, so kill qemu. */
1260 /* Don't worry, if the fork failed, this will be -1. The recovery
1261 * process isn't essential.
1266 /* Start the clock ... */
1270 /* Close the other ends of the pipe. */
1274 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1275 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1276 perrorf (g, "fcntl");
1280 g->fd[0] = wfd[1]; /* stdin of child */
1281 g->fd[1] = rfd[0]; /* stdout of child */
1283 g->fd[0] = open ("/dev/null", O_RDWR);
1284 if (g->fd[0] == -1) {
1285 perrorf (g, "open /dev/null");
1288 g->fd[1] = dup (g->fd[0]);
1289 if (g->fd[1] == -1) {
1296 if (null_vmchannel_sock) {
1300 /* Null vmchannel implementation: We listen on g->sock for a
1301 * connection. The connection could come from any local process
1302 * so we must check it comes from the appliance (or at least
1303 * from our UID) for security reasons.
1305 while (sock == -1) {
1306 sock = accept_from_daemon (g);
1310 if (check_peer_euid (g, sock, &uid) == -1)
1312 if (uid != geteuid ()) {
1314 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1315 uid, null_vmchannel_sock);
1321 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1322 perrorf (g, "fcntl");
1329 /* Other vmchannel. Open the Unix socket.
1331 * The vmchannel implementation that got merged with qemu sucks in
1332 * a number of ways. Both ends do connect(2), which means that no
1333 * one knows what, if anything, is connected to the other end, or
1334 * if it becomes disconnected. Even worse, we have to wait some
1335 * indeterminate time for qemu to create the socket and connect to
1336 * it (which happens very early in qemu's start-up), so any code
1337 * that uses vmchannel is inherently racy. Hence this silly loop.
1339 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1340 if (g->sock == -1) {
1341 perrorf (g, "socket");
1345 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1346 perrorf (g, "fcntl");
1350 addr.sun_family = AF_UNIX;
1351 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1352 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1355 /* Always sleep at least once to give qemu a small chance to start up. */
1358 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1359 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1362 if (errno != ENOENT)
1363 perrorf (g, "connect");
1368 error (g, _("failed to connect to vmchannel socket"));
1374 g->state = LAUNCHING;
1376 /* Wait for qemu to start and to connect back to us via vmchannel and
1377 * send the GUESTFS_LAUNCH_FLAG message.
1381 r = recv_from_daemon (g, &size, &buf);
1384 if (r == -1) return -1;
1386 if (size != GUESTFS_LAUNCH_FLAG) {
1387 error (g, _("guestfs_launch failed, see earlier error messages"));
1391 /* This is possible in some really strange situations, such as
1392 * guestfsd starts up OK but then qemu immediately exits. Check for
1393 * it because the caller is probably expecting to be able to send
1394 * commands after this function returns.
1396 if (g->state != READY) {
1397 error (g, _("qemu launched and contacted daemon, but state != READY"));
1409 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1410 waitpid (g->pid, NULL, 0);
1411 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1429 /* This function is used to print the qemu command line before it gets
1430 * executed, when in verbose mode.
1433 print_cmdline (guestfs_h *g)
1438 while (g->cmdline[i]) {
1439 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1440 fprintf (stderr, " \\\n ");
1442 if (i > 0) fputc (' ', stderr);
1444 /* Does it need shell quoting? This only deals with simple cases. */
1445 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1447 if (needs_quote) fputc ('\'', stderr);
1448 fprintf (stderr, "%s", g->cmdline[i]);
1449 if (needs_quote) fputc ('\'', stderr);
1453 fputc ('\n', stderr);
1456 /* This function does the hard work of building the supermin appliance
1457 * on the fly. 'path' is the directory containing the control files.
1458 * 'kernel' and 'initrd' are where we will return the names of the
1459 * kernel and initrd (only initrd is built). The work is done by
1460 * an external script. We just tell it where to put the result.
1463 build_supermin_appliance (guestfs_h *g, const char *path,
1464 char **kernel, char **initrd)
1469 len = strlen (g->tmpdir);
1470 *kernel = safe_malloc (g, len + 8);
1471 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1472 *initrd = safe_malloc (g, len + 8);
1473 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1475 snprintf (cmd, sizeof cmd,
1477 "libguestfs-supermin-helper '%s' %s %s",
1479 path, *kernel, *initrd);
1482 if (r == -1 || WEXITSTATUS(r) != 0) {
1483 error (g, _("external command failed: %s"), cmd);
1486 *kernel = *initrd = NULL;
1493 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1495 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1496 * 'qemu -version' so we know what options this qemu supports and
1500 test_qemu (guestfs_h *g)
1505 free (g->qemu_help);
1506 free (g->qemu_version);
1507 g->qemu_help = NULL;
1508 g->qemu_version = NULL;
1510 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1512 fp = popen (cmd, "r");
1513 /* qemu -help should always work (qemu -version OTOH wasn't
1514 * supported by qemu 0.9). If this command doesn't work then it
1515 * probably indicates that the qemu binary is missing.
1518 /* XXX This error is never printed, even if the qemu binary
1519 * doesn't exist. Why?
1522 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1526 if (read_all (g, fp, &g->qemu_help) == -1)
1529 if (pclose (fp) == -1)
1532 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1534 fp = popen (cmd, "r");
1536 /* Intentionally ignore errors. */
1537 read_all (g, fp, &g->qemu_version);
1545 read_all (guestfs_h *g, FILE *fp, char **ret)
1552 *ret = safe_realloc (g, *ret, n + 1);
1557 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1559 r = fread (p, 1, BUFSIZ, fp);
1561 perrorf (g, "read");
1568 /* Test if option is supported by qemu command line (just by grepping
1572 qemu_supports (guestfs_h *g, const char *option)
1574 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1577 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1578 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1579 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1582 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1584 struct sockaddr_in peer;
1585 socklen_t addrlen = sizeof peer;
1587 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1588 perrorf (g, "getpeername");
1592 if (peer.sin_family != AF_INET ||
1593 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1594 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1595 peer.sin_family, inet_ntoa (peer.sin_addr));
1599 struct sockaddr_in our;
1600 addrlen = sizeof our;
1601 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1602 perrorf (g, "getsockname");
1606 FILE *fp = fopen ("/proc/net/tcp", "r");
1608 perrorf (g, "/proc/net/tcp");
1613 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1614 error (g, "unexpected end of file in /proc/net/tcp");
1619 while (fgets (line, sizeof line, fp) != NULL) {
1620 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1621 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1624 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1626 &line_our_addr, &line_our_port,
1627 &line_peer_addr, &line_peer_port,
1628 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1630 /* Note about /proc/net/tcp: local_address and rem_address are
1631 * always in network byte order. However the port part is
1632 * always in host byte order.
1634 * The sockname and peername that we got above are in network
1635 * byte order. So we have to byte swap the port but not the
1638 if (line_our_addr == our.sin_addr.s_addr &&
1639 line_our_port == ntohs (our.sin_port) &&
1640 line_peer_addr == peer.sin_addr.s_addr &&
1641 line_peer_port == ntohs (peer.sin_port)) {
1649 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1654 /* You had to call this function after launch in versions <= 1.0.70,
1655 * but it is now a no-op.
1658 guestfs__wait_ready (guestfs_h *g)
1660 if (g->state != READY) {
1661 error (g, _("qemu has not been launched yet"));
1669 guestfs__kill_subprocess (guestfs_h *g)
1671 if (g->state == CONFIG) {
1672 error (g, _("no subprocess to kill"));
1677 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1679 kill (g->pid, SIGTERM);
1680 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1685 /* Access current state. */
1687 guestfs__is_config (guestfs_h *g)
1689 return g->state == CONFIG;
1693 guestfs__is_launching (guestfs_h *g)
1695 return g->state == LAUNCHING;
1699 guestfs__is_ready (guestfs_h *g)
1701 return g->state == READY;
1705 guestfs__is_busy (guestfs_h *g)
1707 return g->state == BUSY;
1711 guestfs__get_state (guestfs_h *g)
1717 guestfs_set_log_message_callback (guestfs_h *g,
1718 guestfs_log_message_cb cb, void *opaque)
1720 g->log_message_cb = cb;
1721 g->log_message_cb_data = opaque;
1725 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1726 guestfs_subprocess_quit_cb cb, void *opaque)
1728 g->subprocess_quit_cb = cb;
1729 g->subprocess_quit_cb_data = opaque;
1733 guestfs_set_launch_done_callback (guestfs_h *g,
1734 guestfs_launch_done_cb cb, void *opaque)
1736 g->launch_done_cb = cb;
1737 g->launch_done_cb_data = opaque;
1740 /*----------------------------------------------------------------------*/
1742 /* This is the code used to send and receive RPC messages and (for
1743 * certain types of message) to perform file transfers. This code is
1744 * driven from the generated actions (src/guestfs-actions.c). There
1745 * are five different cases to consider:
1747 * (1) A non-daemon function. There is no RPC involved at all, it's
1748 * all handled inside the library.
1750 * (2) A simple RPC (eg. "mount"). We write the request, then read
1751 * the reply. The sequence of calls is:
1753 * guestfs___set_busy
1756 * guestfs___end_busy
1758 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1759 * request, then write the file(s), then read the reply. The sequence
1762 * guestfs___set_busy
1764 * guestfs___send_file (possibly multiple times)
1766 * guestfs___end_busy
1768 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1769 * request, then read the reply, then read the file(s). The sequence
1772 * guestfs___set_busy
1775 * guestfs___recv_file (possibly multiple times)
1776 * guestfs___end_busy
1778 * (5) Both FileOut and FileIn parameters. There are no calls like
1779 * this in the current API, but they would be implemented as a
1780 * combination of cases (3) and (4).
1782 * During all writes and reads, we also select(2) on qemu stdout
1783 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1784 * anything received is passed up through the log_message_cb. This is
1785 * also the reason why all the sockets are non-blocking. We also have
1786 * to check for EOF (qemu died). All of this is handled by the
1787 * functions send_to_daemon and recv_from_daemon.
1791 guestfs___set_busy (guestfs_h *g)
1793 if (g->state != READY) {
1794 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1803 guestfs___end_busy (guestfs_h *g)
1817 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1823 /* This is called if we detect EOF, ie. qemu died. */
1825 child_cleanup (guestfs_h *g)
1828 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1830 /*kill (g->pid, SIGTERM);*/
1831 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1832 waitpid (g->pid, NULL, 0);
1833 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1844 if (g->subprocess_quit_cb)
1845 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1849 read_log_message_or_eof (guestfs_h *g, int fd)
1857 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1861 /* QEMU's console emulates a 16550A serial port. The real 16550A
1862 * device has a small FIFO buffer (16 bytes) which means here we see
1863 * lots of small reads of 1-16 bytes in length, usually single
1866 n = read (fd, buf, sizeof buf);
1868 /* Hopefully this indicates the qemu child process has died. */
1874 if (errno == EINTR || errno == EAGAIN)
1877 perrorf (g, "read");
1881 /* In verbose mode, copy all log messages to stderr. */
1883 ignore_value (write (STDERR_FILENO, buf, n));
1885 /* It's an actual log message, send it upwards if anyone is listening. */
1886 if (g->log_message_cb)
1887 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1893 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1902 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1905 n = read (fd, buf, 4);
1907 /* Hopefully this indicates the qemu child process has died. */
1913 if (errno == EINTR || errno == EAGAIN)
1916 perrorf (g, "read");
1920 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1921 xdr_uint32_t (&xdr, &flag);
1924 if (flag != GUESTFS_CANCEL_FLAG) {
1925 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1926 flag, GUESTFS_CANCEL_FLAG);
1933 /* This writes the whole N bytes of BUF to the daemon socket.
1935 * If the whole write is successful, it returns 0.
1936 * If there was an error, it returns -1.
1937 * If the daemon sent a cancellation message, it returns -2.
1939 * It also checks qemu stdout for log messages and passes those up
1940 * through log_message_cb.
1942 * It also checks for EOF (qemu died) and passes that up through the
1943 * child_cleanup function above.
1946 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1948 const char *buf = v_buf;
1954 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1959 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1960 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1961 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1963 int max_fd = MAX (g->sock, g->fd[1]);
1968 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1970 if (errno == EINTR || errno == EAGAIN)
1972 perrorf (g, "select");
1976 if (FD_ISSET (g->fd[1], &rset2)) {
1977 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1980 if (FD_ISSET (g->sock, &rset2)) {
1981 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1985 if (FD_ISSET (g->sock, &wset2)) {
1986 r = write (g->sock, buf, n);
1988 if (errno == EINTR || errno == EAGAIN)
1990 perrorf (g, "write");
1991 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2003 /* This reads a single message, file chunk, launch flag or
2004 * cancellation flag from the daemon. If something was read, it
2005 * returns 0, otherwise -1.
2007 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2009 * *size_rtn returns the size of the returned message or it may be
2010 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2012 * *buf_rtn is returned containing the message (if any) or will be set
2013 * to NULL. *buf_rtn must be freed by the caller.
2015 * It also checks qemu stdout for log messages and passes those up
2016 * through log_message_cb.
2018 * It also checks for EOF (qemu died) and passes that up through the
2019 * child_cleanup function above.
2022 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2028 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2029 g, g->state, size_rtn, buf_rtn);
2033 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2034 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2036 int max_fd = MAX (g->sock, g->fd[1]);
2042 /* nr is the size of the message, but we prime it as -4 because we
2043 * have to read the message length word first.
2047 while (nr < (ssize_t) *size_rtn) {
2049 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2051 if (errno == EINTR || errno == EAGAIN)
2053 perrorf (g, "select");
2059 if (FD_ISSET (g->fd[1], &rset2)) {
2060 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2066 if (FD_ISSET (g->sock, &rset2)) {
2067 if (nr < 0) { /* Have we read the message length word yet? */
2068 r = read (g->sock, lenbuf+nr+4, -nr);
2070 if (errno == EINTR || errno == EAGAIN)
2073 perrorf (g, "read");
2074 /* Under some circumstances we see "Connection reset by peer"
2075 * here when the child dies suddenly. Catch this and call
2076 * the cleanup function, same as for EOF.
2078 if (err == ECONNRESET)
2083 error (g, _("unexpected end of file when reading from daemon"));
2089 if (nr < 0) /* Still not got the whole length word. */
2093 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2094 xdr_uint32_t (&xdr, size_rtn);
2097 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2098 if (g->state != LAUNCHING)
2099 error (g, _("received magic signature from guestfsd, but in state %d"),
2103 if (g->launch_done_cb)
2104 g->launch_done_cb (g, g->launch_done_cb_data);
2108 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2110 /* If this happens, it's pretty bad and we've probably lost
2113 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2114 error (g, _("message length (%u) > maximum possible size (%d)"),
2115 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2119 /* Allocate the complete buffer, size now known. */
2120 *buf_rtn = safe_malloc (g, *size_rtn);
2124 size_t sizetoread = *size_rtn - nr;
2125 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2127 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2129 if (errno == EINTR || errno == EAGAIN)
2131 perrorf (g, "read");
2137 error (g, _("unexpected end of file when reading from daemon"));
2147 /* Got the full message, caller can start processing it. */
2148 #ifdef ENABLE_PACKET_DUMP
2152 for (i = 0; i < nr; i += 16) {
2153 printf ("%04zx: ", i);
2154 for (j = i; j < MIN (i+16, nr); ++j)
2155 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2156 for (; j < i+16; ++j)
2159 for (j = i; j < MIN (i+16, nr); ++j)
2160 if (c_isprint ((*(char **)buf_rtn)[j]))
2161 printf ("%c", (*(char **)buf_rtn)[j]);
2164 for (; j < i+16; ++j)
2174 /* This is very much like recv_from_daemon above, but g->sock is
2175 * a listening socket and we are accepting a new connection on
2176 * that socket instead of reading anything. Returns the newly
2180 accept_from_daemon (guestfs_h *g)
2186 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2190 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2191 FD_SET (g->sock, &rset); /* Read socket for accept. */
2193 int max_fd = MAX (g->sock, g->fd[1]);
2196 while (sock == -1) {
2198 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2200 if (errno == EINTR || errno == EAGAIN)
2202 perrorf (g, "select");
2206 if (FD_ISSET (g->fd[1], &rset2)) {
2207 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2210 if (FD_ISSET (g->sock, &rset2)) {
2211 sock = accept (g->sock, NULL, NULL);
2213 if (errno == EINTR || errno == EAGAIN)
2215 perrorf (g, "accept");
2225 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2227 struct guestfs_message_header hdr;
2230 int serial = g->msg_next_serial++;
2233 size_t msg_out_size;
2235 if (g->state != BUSY) {
2236 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2240 /* We have to allocate this message buffer on the heap because
2241 * it is quite large (although will be mostly unused). We
2242 * can't allocate it on the stack because in some environments
2243 * we have quite limited stack space available, notably when
2244 * running in the JVM.
2246 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2247 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2249 /* Serialize the header. */
2250 hdr.prog = GUESTFS_PROGRAM;
2251 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2253 hdr.direction = GUESTFS_DIRECTION_CALL;
2254 hdr.serial = serial;
2255 hdr.status = GUESTFS_STATUS_OK;
2257 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2258 error (g, _("xdr_guestfs_message_header failed"));
2262 /* Serialize the args. If any, because some message types
2263 * have no parameters.
2266 if (!(*xdrp) (&xdr, args)) {
2267 error (g, _("dispatch failed to marshal args"));
2272 /* Get the actual length of the message, resize the buffer to match
2273 * the actual length, and write the length word at the beginning.
2275 len = xdr_getpos (&xdr);
2278 msg_out = safe_realloc (g, msg_out, len + 4);
2279 msg_out_size = len + 4;
2281 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2282 xdr_uint32_t (&xdr, &len);
2285 r = send_to_daemon (g, msg_out, msg_out_size);
2286 if (r == -2) /* Ignore stray daemon cancellations. */
2299 static int cancel = 0; /* XXX Implement file cancellation. */
2300 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2301 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2302 static int send_file_cancellation (guestfs_h *g);
2303 static int send_file_complete (guestfs_h *g);
2309 * -2 daemon cancelled (we must read the error message)
2312 guestfs___send_file (guestfs_h *g, const char *filename)
2314 char buf[GUESTFS_MAX_CHUNK_SIZE];
2317 fd = open (filename, O_RDONLY);
2319 perrorf (g, "open: %s", filename);
2320 send_file_cancellation (g);
2321 /* Daemon sees cancellation and won't reply, so caller can
2327 /* Send file in chunked encoding. */
2329 r = read (fd, buf, sizeof buf);
2330 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2333 err = send_file_data (g, buf, r);
2335 if (err == -2) /* daemon sent cancellation */
2336 send_file_cancellation (g);
2341 if (cancel) { /* cancel from either end */
2342 send_file_cancellation (g);
2347 perrorf (g, "read: %s", filename);
2348 send_file_cancellation (g);
2352 /* End of file, but before we send that, we need to close
2353 * the file and check for errors.
2355 if (close (fd) == -1) {
2356 perrorf (g, "close: %s", filename);
2357 send_file_cancellation (g);
2361 return send_file_complete (g);
2364 /* Send a chunk of file data. */
2366 send_file_data (guestfs_h *g, const char *buf, size_t len)
2368 return send_file_chunk (g, 0, buf, len);
2371 /* Send a cancellation message. */
2373 send_file_cancellation (guestfs_h *g)
2375 return send_file_chunk (g, 1, NULL, 0);
2378 /* Send a file complete chunk. */
2380 send_file_complete (guestfs_h *g)
2383 return send_file_chunk (g, 0, buf, 0);
2387 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2391 guestfs_chunk chunk;
2394 size_t msg_out_size;
2396 if (g->state != BUSY) {
2397 error (g, _("send_file_chunk: state %d != READY"), g->state);
2401 /* Allocate the chunk buffer. Don't use the stack to avoid
2402 * excessive stack usage and unnecessary copies.
2404 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2405 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2407 /* Serialize the chunk. */
2408 chunk.cancel = cancel;
2409 chunk.data.data_len = buflen;
2410 chunk.data.data_val = (char *) buf;
2412 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2413 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2419 len = xdr_getpos (&xdr);
2422 /* Reduce the size of the outgoing message buffer to the real length. */
2423 msg_out = safe_realloc (g, msg_out, len + 4);
2424 msg_out_size = len + 4;
2426 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2427 xdr_uint32_t (&xdr, &len);
2429 r = send_to_daemon (g, msg_out, msg_out_size);
2431 /* Did the daemon send a cancellation message? */
2434 fprintf (stderr, "got daemon cancellation\n");
2450 /* Receive a reply. */
2452 guestfs___recv (guestfs_h *g, const char *fn,
2453 guestfs_message_header *hdr,
2454 guestfs_message_error *err,
2455 xdrproc_t xdrp, char *ret)
2463 r = recv_from_daemon (g, &size, &buf);
2467 /* This can happen if a cancellation happens right at the end
2468 * of us sending a FileIn parameter to the daemon. Discard. The
2469 * daemon should send us an error message next.
2471 if (size == GUESTFS_CANCEL_FLAG)
2474 if (size == GUESTFS_LAUNCH_FLAG) {
2475 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2479 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2481 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2482 error (g, "%s: failed to parse reply header", fn);
2487 if (hdr->status == GUESTFS_STATUS_ERROR) {
2488 if (!xdr_guestfs_message_error (&xdr, err)) {
2489 error (g, "%s: failed to parse reply error", fn);
2495 if (xdrp && ret && !xdrp (&xdr, ret)) {
2496 error (g, "%s: failed to parse reply", fn);
2508 /* Receive a file. */
2510 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2511 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2514 guestfs___recv_file (guestfs_h *g, const char *filename)
2520 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2522 perrorf (g, "open: %s", filename);
2526 /* Receive the file in chunked encoding. */
2527 while ((r = receive_file_data (g, &buf)) > 0) {
2528 if (xwrite (fd, buf, r) == -1) {
2529 perrorf (g, "%s: write", filename);
2537 error (g, _("%s: error in chunked encoding"), filename);
2541 if (close (fd) == -1) {
2542 perrorf (g, "close: %s", filename);
2549 /* Send cancellation message to daemon, then wait until it
2550 * cancels (just throwing away data).
2554 uint32_t flag = GUESTFS_CANCEL_FLAG;
2557 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2560 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2561 xdr_uint32_t (&xdr, &flag);
2564 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2565 perrorf (g, _("write to daemon socket"));
2569 while (receive_file_data (g, NULL) > 0)
2570 ; /* just discard it */
2575 /* Receive a chunk of file data. */
2576 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2578 receive_file_data (guestfs_h *g, void **buf_r)
2584 guestfs_chunk chunk;
2586 r = recv_from_daemon (g, &len, &buf);
2588 error (g, _("receive_file_data: parse error in reply callback"));
2592 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2593 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2597 memset (&chunk, 0, sizeof chunk);
2599 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2600 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2601 error (g, _("failed to parse file chunk"));
2606 /* After decoding, the original buffer is no longer used. */
2610 error (g, _("file receive cancelled by daemon"));
2611 free (chunk.data.data_val);
2615 if (chunk.data.data_len == 0) { /* end of transfer */
2616 free (chunk.data.data_val);
2620 if (buf_r) *buf_r = chunk.data.data_val;
2621 else free (chunk.data.data_val); /* else caller frees */
2623 return chunk.data.data_len;