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 "printk.time=1 " /* display timestamp before kernel messages */ \
1161 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1163 /* Linux kernel command line. */
1164 snprintf (buf, sizeof buf,
1166 "%s " /* (selinux) */
1167 "%s " /* (vmchannel) */
1168 "%s " /* (verbose) */
1169 "%s", /* (append) */
1170 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1171 vmchannel ? vmchannel : "",
1172 g->verbose ? "guestfs_verbose=1" : "",
1173 g->append ? g->append : "");
1175 add_cmdline (g, "-kernel");
1176 add_cmdline (g, (char *) kernel);
1177 add_cmdline (g, "-initrd");
1178 add_cmdline (g, (char *) initrd);
1179 add_cmdline (g, "-append");
1180 add_cmdline (g, buf);
1182 /* Finish off the command line. */
1183 incr_cmdline_size (g);
1184 g->cmdline[g->cmdline_size-1] = NULL;
1190 /* Set up stdin, stdout. */
1196 if (dup (wfd[0]) == -1) {
1198 perror ("dup failed");
1201 if (dup (rfd[1]) == -1)
1209 /* Set up a new process group, so we can signal this process
1210 * and all subprocesses (eg. if qemu is really a shell script).
1215 setenv ("LC_ALL", "C", 1);
1217 execv (g->qemu, g->cmdline); /* Run qemu. */
1222 /* Parent (library). */
1230 /* Fork the recovery process off which will kill qemu if the parent
1231 * process fails to do so (eg. if the parent segfaults).
1233 g->recoverypid = -1;
1234 if (g->recovery_proc) {
1237 pid_t qemu_pid = g->pid;
1238 pid_t parent_pid = getppid ();
1240 /* Writing to argv is hideously complicated and error prone. See:
1241 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1244 /* Loop around waiting for one or both of the other processes to
1245 * disappear. It's fair to say this is very hairy. The PIDs that
1246 * we are looking at might be reused by another process. We are
1247 * effectively polling. Is the cure worse than the disease?
1250 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1252 if (kill (parent_pid, 0) == -1) {
1253 /* Parent's gone away, qemu still around, so kill qemu. */
1261 /* Don't worry, if the fork failed, this will be -1. The recovery
1262 * process isn't essential.
1267 /* Start the clock ... */
1271 /* Close the other ends of the pipe. */
1275 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1276 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1277 perrorf (g, "fcntl");
1281 g->fd[0] = wfd[1]; /* stdin of child */
1282 g->fd[1] = rfd[0]; /* stdout of child */
1284 g->fd[0] = open ("/dev/null", O_RDWR);
1285 if (g->fd[0] == -1) {
1286 perrorf (g, "open /dev/null");
1289 g->fd[1] = dup (g->fd[0]);
1290 if (g->fd[1] == -1) {
1297 if (null_vmchannel_sock) {
1301 /* Null vmchannel implementation: We listen on g->sock for a
1302 * connection. The connection could come from any local process
1303 * so we must check it comes from the appliance (or at least
1304 * from our UID) for security reasons.
1306 while (sock == -1) {
1307 sock = accept_from_daemon (g);
1311 if (check_peer_euid (g, sock, &uid) == -1)
1313 if (uid != geteuid ()) {
1315 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1316 uid, null_vmchannel_sock);
1322 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1323 perrorf (g, "fcntl");
1330 /* Other vmchannel. Open the Unix socket.
1332 * The vmchannel implementation that got merged with qemu sucks in
1333 * a number of ways. Both ends do connect(2), which means that no
1334 * one knows what, if anything, is connected to the other end, or
1335 * if it becomes disconnected. Even worse, we have to wait some
1336 * indeterminate time for qemu to create the socket and connect to
1337 * it (which happens very early in qemu's start-up), so any code
1338 * that uses vmchannel is inherently racy. Hence this silly loop.
1340 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1341 if (g->sock == -1) {
1342 perrorf (g, "socket");
1346 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1347 perrorf (g, "fcntl");
1351 addr.sun_family = AF_UNIX;
1352 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1353 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1356 /* Always sleep at least once to give qemu a small chance to start up. */
1359 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1360 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1363 if (errno != ENOENT)
1364 perrorf (g, "connect");
1369 error (g, _("failed to connect to vmchannel socket"));
1375 g->state = LAUNCHING;
1377 /* Wait for qemu to start and to connect back to us via vmchannel and
1378 * send the GUESTFS_LAUNCH_FLAG message.
1382 r = recv_from_daemon (g, &size, &buf);
1385 if (r == -1) return -1;
1387 if (size != GUESTFS_LAUNCH_FLAG) {
1388 error (g, _("guestfs_launch failed, see earlier error messages"));
1392 /* This is possible in some really strange situations, such as
1393 * guestfsd starts up OK but then qemu immediately exits. Check for
1394 * it because the caller is probably expecting to be able to send
1395 * commands after this function returns.
1397 if (g->state != READY) {
1398 error (g, _("qemu launched and contacted daemon, but state != READY"));
1410 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1411 waitpid (g->pid, NULL, 0);
1412 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1430 /* This function is used to print the qemu command line before it gets
1431 * executed, when in verbose mode.
1434 print_cmdline (guestfs_h *g)
1439 while (g->cmdline[i]) {
1440 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1441 fprintf (stderr, " \\\n ");
1443 if (i > 0) fputc (' ', stderr);
1445 /* Does it need shell quoting? This only deals with simple cases. */
1446 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1448 if (needs_quote) fputc ('\'', stderr);
1449 fprintf (stderr, "%s", g->cmdline[i]);
1450 if (needs_quote) fputc ('\'', stderr);
1454 fputc ('\n', stderr);
1457 /* This function does the hard work of building the supermin appliance
1458 * on the fly. 'path' is the directory containing the control files.
1459 * 'kernel' and 'initrd' are where we will return the names of the
1460 * kernel and initrd (only initrd is built). The work is done by
1461 * an external script. We just tell it where to put the result.
1464 build_supermin_appliance (guestfs_h *g, const char *path,
1465 char **kernel, char **initrd)
1470 len = strlen (g->tmpdir);
1471 *kernel = safe_malloc (g, len + 8);
1472 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1473 *initrd = safe_malloc (g, len + 8);
1474 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1476 snprintf (cmd, sizeof cmd,
1478 "libguestfs-supermin-helper '%s' %s %s",
1480 path, *kernel, *initrd);
1483 if (r == -1 || WEXITSTATUS(r) != 0) {
1484 error (g, _("external command failed: %s"), cmd);
1487 *kernel = *initrd = NULL;
1494 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1496 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1497 * 'qemu -version' so we know what options this qemu supports and
1501 test_qemu (guestfs_h *g)
1506 free (g->qemu_help);
1507 free (g->qemu_version);
1508 g->qemu_help = NULL;
1509 g->qemu_version = NULL;
1511 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1513 fp = popen (cmd, "r");
1514 /* qemu -help should always work (qemu -version OTOH wasn't
1515 * supported by qemu 0.9). If this command doesn't work then it
1516 * probably indicates that the qemu binary is missing.
1519 /* XXX This error is never printed, even if the qemu binary
1520 * doesn't exist. Why?
1523 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1527 if (read_all (g, fp, &g->qemu_help) == -1)
1530 if (pclose (fp) == -1)
1533 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1535 fp = popen (cmd, "r");
1537 /* Intentionally ignore errors. */
1538 read_all (g, fp, &g->qemu_version);
1546 read_all (guestfs_h *g, FILE *fp, char **ret)
1553 *ret = safe_realloc (g, *ret, n + 1);
1558 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1560 r = fread (p, 1, BUFSIZ, fp);
1562 perrorf (g, "read");
1569 /* Test if option is supported by qemu command line (just by grepping
1573 qemu_supports (guestfs_h *g, const char *option)
1575 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1578 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1579 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1580 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1583 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1585 struct sockaddr_in peer;
1586 socklen_t addrlen = sizeof peer;
1588 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1589 perrorf (g, "getpeername");
1593 if (peer.sin_family != AF_INET ||
1594 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1595 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1596 peer.sin_family, inet_ntoa (peer.sin_addr));
1600 struct sockaddr_in our;
1601 addrlen = sizeof our;
1602 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1603 perrorf (g, "getsockname");
1607 FILE *fp = fopen ("/proc/net/tcp", "r");
1609 perrorf (g, "/proc/net/tcp");
1614 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1615 error (g, "unexpected end of file in /proc/net/tcp");
1620 while (fgets (line, sizeof line, fp) != NULL) {
1621 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1622 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1625 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1627 &line_our_addr, &line_our_port,
1628 &line_peer_addr, &line_peer_port,
1629 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1631 /* Note about /proc/net/tcp: local_address and rem_address are
1632 * always in network byte order. However the port part is
1633 * always in host byte order.
1635 * The sockname and peername that we got above are in network
1636 * byte order. So we have to byte swap the port but not the
1639 if (line_our_addr == our.sin_addr.s_addr &&
1640 line_our_port == ntohs (our.sin_port) &&
1641 line_peer_addr == peer.sin_addr.s_addr &&
1642 line_peer_port == ntohs (peer.sin_port)) {
1650 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1655 /* You had to call this function after launch in versions <= 1.0.70,
1656 * but it is now a no-op.
1659 guestfs__wait_ready (guestfs_h *g)
1661 if (g->state != READY) {
1662 error (g, _("qemu has not been launched yet"));
1670 guestfs__kill_subprocess (guestfs_h *g)
1672 if (g->state == CONFIG) {
1673 error (g, _("no subprocess to kill"));
1678 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1680 kill (g->pid, SIGTERM);
1681 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1686 /* Access current state. */
1688 guestfs__is_config (guestfs_h *g)
1690 return g->state == CONFIG;
1694 guestfs__is_launching (guestfs_h *g)
1696 return g->state == LAUNCHING;
1700 guestfs__is_ready (guestfs_h *g)
1702 return g->state == READY;
1706 guestfs__is_busy (guestfs_h *g)
1708 return g->state == BUSY;
1712 guestfs__get_state (guestfs_h *g)
1718 guestfs_set_log_message_callback (guestfs_h *g,
1719 guestfs_log_message_cb cb, void *opaque)
1721 g->log_message_cb = cb;
1722 g->log_message_cb_data = opaque;
1726 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1727 guestfs_subprocess_quit_cb cb, void *opaque)
1729 g->subprocess_quit_cb = cb;
1730 g->subprocess_quit_cb_data = opaque;
1734 guestfs_set_launch_done_callback (guestfs_h *g,
1735 guestfs_launch_done_cb cb, void *opaque)
1737 g->launch_done_cb = cb;
1738 g->launch_done_cb_data = opaque;
1741 /*----------------------------------------------------------------------*/
1743 /* This is the code used to send and receive RPC messages and (for
1744 * certain types of message) to perform file transfers. This code is
1745 * driven from the generated actions (src/guestfs-actions.c). There
1746 * are five different cases to consider:
1748 * (1) A non-daemon function. There is no RPC involved at all, it's
1749 * all handled inside the library.
1751 * (2) A simple RPC (eg. "mount"). We write the request, then read
1752 * the reply. The sequence of calls is:
1754 * guestfs___set_busy
1757 * guestfs___end_busy
1759 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1760 * request, then write the file(s), then read the reply. The sequence
1763 * guestfs___set_busy
1765 * guestfs___send_file (possibly multiple times)
1767 * guestfs___end_busy
1769 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1770 * request, then read the reply, then read the file(s). The sequence
1773 * guestfs___set_busy
1776 * guestfs___recv_file (possibly multiple times)
1777 * guestfs___end_busy
1779 * (5) Both FileOut and FileIn parameters. There are no calls like
1780 * this in the current API, but they would be implemented as a
1781 * combination of cases (3) and (4).
1783 * During all writes and reads, we also select(2) on qemu stdout
1784 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1785 * anything received is passed up through the log_message_cb. This is
1786 * also the reason why all the sockets are non-blocking. We also have
1787 * to check for EOF (qemu died). All of this is handled by the
1788 * functions send_to_daemon and recv_from_daemon.
1792 guestfs___set_busy (guestfs_h *g)
1794 if (g->state != READY) {
1795 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1804 guestfs___end_busy (guestfs_h *g)
1818 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1824 /* This is called if we detect EOF, ie. qemu died. */
1826 child_cleanup (guestfs_h *g)
1829 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1831 /*kill (g->pid, SIGTERM);*/
1832 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1833 waitpid (g->pid, NULL, 0);
1834 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1845 if (g->subprocess_quit_cb)
1846 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1850 read_log_message_or_eof (guestfs_h *g, int fd)
1858 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1862 /* QEMU's console emulates a 16550A serial port. The real 16550A
1863 * device has a small FIFO buffer (16 bytes) which means here we see
1864 * lots of small reads of 1-16 bytes in length, usually single
1867 n = read (fd, buf, sizeof buf);
1869 /* Hopefully this indicates the qemu child process has died. */
1875 if (errno == EINTR || errno == EAGAIN)
1878 perrorf (g, "read");
1882 /* In verbose mode, copy all log messages to stderr. */
1884 ignore_value (write (STDERR_FILENO, buf, n));
1886 /* It's an actual log message, send it upwards if anyone is listening. */
1887 if (g->log_message_cb)
1888 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1894 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1903 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1906 n = read (fd, buf, 4);
1908 /* Hopefully this indicates the qemu child process has died. */
1914 if (errno == EINTR || errno == EAGAIN)
1917 perrorf (g, "read");
1921 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1922 xdr_uint32_t (&xdr, &flag);
1925 if (flag != GUESTFS_CANCEL_FLAG) {
1926 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1927 flag, GUESTFS_CANCEL_FLAG);
1934 /* This writes the whole N bytes of BUF to the daemon socket.
1936 * If the whole write is successful, it returns 0.
1937 * If there was an error, it returns -1.
1938 * If the daemon sent a cancellation message, it returns -2.
1940 * It also checks qemu stdout for log messages and passes those up
1941 * through log_message_cb.
1943 * It also checks for EOF (qemu died) and passes that up through the
1944 * child_cleanup function above.
1947 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1949 const char *buf = v_buf;
1955 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1960 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1961 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1962 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1964 int max_fd = MAX (g->sock, g->fd[1]);
1969 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1971 if (errno == EINTR || errno == EAGAIN)
1973 perrorf (g, "select");
1977 if (FD_ISSET (g->fd[1], &rset2)) {
1978 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1981 if (FD_ISSET (g->sock, &rset2)) {
1982 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1986 if (FD_ISSET (g->sock, &wset2)) {
1987 r = write (g->sock, buf, n);
1989 if (errno == EINTR || errno == EAGAIN)
1991 perrorf (g, "write");
1992 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2004 /* This reads a single message, file chunk, launch flag or
2005 * cancellation flag from the daemon. If something was read, it
2006 * returns 0, otherwise -1.
2008 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2010 * *size_rtn returns the size of the returned message or it may be
2011 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2013 * *buf_rtn is returned containing the message (if any) or will be set
2014 * to NULL. *buf_rtn must be freed by the caller.
2016 * It also checks qemu stdout for log messages and passes those up
2017 * through log_message_cb.
2019 * It also checks for EOF (qemu died) and passes that up through the
2020 * child_cleanup function above.
2023 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2029 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2030 g, g->state, size_rtn, buf_rtn);
2034 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2035 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2037 int max_fd = MAX (g->sock, g->fd[1]);
2043 /* nr is the size of the message, but we prime it as -4 because we
2044 * have to read the message length word first.
2048 while (nr < (ssize_t) *size_rtn) {
2050 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2052 if (errno == EINTR || errno == EAGAIN)
2054 perrorf (g, "select");
2060 if (FD_ISSET (g->fd[1], &rset2)) {
2061 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2067 if (FD_ISSET (g->sock, &rset2)) {
2068 if (nr < 0) { /* Have we read the message length word yet? */
2069 r = read (g->sock, lenbuf+nr+4, -nr);
2071 if (errno == EINTR || errno == EAGAIN)
2074 perrorf (g, "read");
2075 /* Under some circumstances we see "Connection reset by peer"
2076 * here when the child dies suddenly. Catch this and call
2077 * the cleanup function, same as for EOF.
2079 if (err == ECONNRESET)
2084 error (g, _("unexpected end of file when reading from daemon"));
2090 if (nr < 0) /* Still not got the whole length word. */
2094 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2095 xdr_uint32_t (&xdr, size_rtn);
2098 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2099 if (g->state != LAUNCHING)
2100 error (g, _("received magic signature from guestfsd, but in state %d"),
2104 if (g->launch_done_cb)
2105 g->launch_done_cb (g, g->launch_done_cb_data);
2109 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2111 /* If this happens, it's pretty bad and we've probably lost
2114 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2115 error (g, _("message length (%u) > maximum possible size (%d)"),
2116 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2120 /* Allocate the complete buffer, size now known. */
2121 *buf_rtn = safe_malloc (g, *size_rtn);
2125 size_t sizetoread = *size_rtn - nr;
2126 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2128 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2130 if (errno == EINTR || errno == EAGAIN)
2132 perrorf (g, "read");
2138 error (g, _("unexpected end of file when reading from daemon"));
2148 /* Got the full message, caller can start processing it. */
2149 #ifdef ENABLE_PACKET_DUMP
2153 for (i = 0; i < nr; i += 16) {
2154 printf ("%04zx: ", i);
2155 for (j = i; j < MIN (i+16, nr); ++j)
2156 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2157 for (; j < i+16; ++j)
2160 for (j = i; j < MIN (i+16, nr); ++j)
2161 if (c_isprint ((*(char **)buf_rtn)[j]))
2162 printf ("%c", (*(char **)buf_rtn)[j]);
2165 for (; j < i+16; ++j)
2175 /* This is very much like recv_from_daemon above, but g->sock is
2176 * a listening socket and we are accepting a new connection on
2177 * that socket instead of reading anything. Returns the newly
2181 accept_from_daemon (guestfs_h *g)
2187 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2191 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2192 FD_SET (g->sock, &rset); /* Read socket for accept. */
2194 int max_fd = MAX (g->sock, g->fd[1]);
2197 while (sock == -1) {
2199 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2201 if (errno == EINTR || errno == EAGAIN)
2203 perrorf (g, "select");
2207 if (FD_ISSET (g->fd[1], &rset2)) {
2208 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2211 if (FD_ISSET (g->sock, &rset2)) {
2212 sock = accept (g->sock, NULL, NULL);
2214 if (errno == EINTR || errno == EAGAIN)
2216 perrorf (g, "accept");
2226 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2228 struct guestfs_message_header hdr;
2231 int serial = g->msg_next_serial++;
2234 size_t msg_out_size;
2236 if (g->state != BUSY) {
2237 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2241 /* We have to allocate this message buffer on the heap because
2242 * it is quite large (although will be mostly unused). We
2243 * can't allocate it on the stack because in some environments
2244 * we have quite limited stack space available, notably when
2245 * running in the JVM.
2247 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2248 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2250 /* Serialize the header. */
2251 hdr.prog = GUESTFS_PROGRAM;
2252 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2254 hdr.direction = GUESTFS_DIRECTION_CALL;
2255 hdr.serial = serial;
2256 hdr.status = GUESTFS_STATUS_OK;
2258 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2259 error (g, _("xdr_guestfs_message_header failed"));
2263 /* Serialize the args. If any, because some message types
2264 * have no parameters.
2267 if (!(*xdrp) (&xdr, args)) {
2268 error (g, _("dispatch failed to marshal args"));
2273 /* Get the actual length of the message, resize the buffer to match
2274 * the actual length, and write the length word at the beginning.
2276 len = xdr_getpos (&xdr);
2279 msg_out = safe_realloc (g, msg_out, len + 4);
2280 msg_out_size = len + 4;
2282 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2283 xdr_uint32_t (&xdr, &len);
2286 r = send_to_daemon (g, msg_out, msg_out_size);
2287 if (r == -2) /* Ignore stray daemon cancellations. */
2300 static int cancel = 0; /* XXX Implement file cancellation. */
2301 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2302 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2303 static int send_file_cancellation (guestfs_h *g);
2304 static int send_file_complete (guestfs_h *g);
2310 * -2 daemon cancelled (we must read the error message)
2313 guestfs___send_file (guestfs_h *g, const char *filename)
2315 char buf[GUESTFS_MAX_CHUNK_SIZE];
2318 fd = open (filename, O_RDONLY);
2320 perrorf (g, "open: %s", filename);
2321 send_file_cancellation (g);
2322 /* Daemon sees cancellation and won't reply, so caller can
2328 /* Send file in chunked encoding. */
2330 r = read (fd, buf, sizeof buf);
2331 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2334 err = send_file_data (g, buf, r);
2336 if (err == -2) /* daemon sent cancellation */
2337 send_file_cancellation (g);
2342 if (cancel) { /* cancel from either end */
2343 send_file_cancellation (g);
2348 perrorf (g, "read: %s", filename);
2349 send_file_cancellation (g);
2353 /* End of file, but before we send that, we need to close
2354 * the file and check for errors.
2356 if (close (fd) == -1) {
2357 perrorf (g, "close: %s", filename);
2358 send_file_cancellation (g);
2362 return send_file_complete (g);
2365 /* Send a chunk of file data. */
2367 send_file_data (guestfs_h *g, const char *buf, size_t len)
2369 return send_file_chunk (g, 0, buf, len);
2372 /* Send a cancellation message. */
2374 send_file_cancellation (guestfs_h *g)
2376 return send_file_chunk (g, 1, NULL, 0);
2379 /* Send a file complete chunk. */
2381 send_file_complete (guestfs_h *g)
2384 return send_file_chunk (g, 0, buf, 0);
2388 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2392 guestfs_chunk chunk;
2395 size_t msg_out_size;
2397 if (g->state != BUSY) {
2398 error (g, _("send_file_chunk: state %d != READY"), g->state);
2402 /* Allocate the chunk buffer. Don't use the stack to avoid
2403 * excessive stack usage and unnecessary copies.
2405 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2406 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2408 /* Serialize the chunk. */
2409 chunk.cancel = cancel;
2410 chunk.data.data_len = buflen;
2411 chunk.data.data_val = (char *) buf;
2413 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2414 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2420 len = xdr_getpos (&xdr);
2423 /* Reduce the size of the outgoing message buffer to the real length. */
2424 msg_out = safe_realloc (g, msg_out, len + 4);
2425 msg_out_size = len + 4;
2427 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2428 xdr_uint32_t (&xdr, &len);
2430 r = send_to_daemon (g, msg_out, msg_out_size);
2432 /* Did the daemon send a cancellation message? */
2435 fprintf (stderr, "got daemon cancellation\n");
2451 /* Receive a reply. */
2453 guestfs___recv (guestfs_h *g, const char *fn,
2454 guestfs_message_header *hdr,
2455 guestfs_message_error *err,
2456 xdrproc_t xdrp, char *ret)
2464 r = recv_from_daemon (g, &size, &buf);
2468 /* This can happen if a cancellation happens right at the end
2469 * of us sending a FileIn parameter to the daemon. Discard. The
2470 * daemon should send us an error message next.
2472 if (size == GUESTFS_CANCEL_FLAG)
2475 if (size == GUESTFS_LAUNCH_FLAG) {
2476 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2480 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2482 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2483 error (g, "%s: failed to parse reply header", fn);
2488 if (hdr->status == GUESTFS_STATUS_ERROR) {
2489 if (!xdr_guestfs_message_error (&xdr, err)) {
2490 error (g, "%s: failed to parse reply error", fn);
2496 if (xdrp && ret && !xdrp (&xdr, ret)) {
2497 error (g, "%s: failed to parse reply", fn);
2509 /* Receive a file. */
2511 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2512 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2515 guestfs___recv_file (guestfs_h *g, const char *filename)
2521 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2523 perrorf (g, "open: %s", filename);
2527 /* Receive the file in chunked encoding. */
2528 while ((r = receive_file_data (g, &buf)) > 0) {
2529 if (xwrite (fd, buf, r) == -1) {
2530 perrorf (g, "%s: write", filename);
2538 error (g, _("%s: error in chunked encoding"), filename);
2542 if (close (fd) == -1) {
2543 perrorf (g, "close: %s", filename);
2550 /* Send cancellation message to daemon, then wait until it
2551 * cancels (just throwing away data).
2555 uint32_t flag = GUESTFS_CANCEL_FLAG;
2558 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2561 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2562 xdr_uint32_t (&xdr, &flag);
2565 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2566 perrorf (g, _("write to daemon socket"));
2570 while (receive_file_data (g, NULL) > 0)
2571 ; /* just discard it */
2576 /* Receive a chunk of file data. */
2577 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2579 receive_file_data (guestfs_h *g, void **buf_r)
2585 guestfs_chunk chunk;
2587 r = recv_from_daemon (g, &len, &buf);
2589 error (g, _("receive_file_data: parse error in reply callback"));
2593 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2594 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2598 memset (&chunk, 0, sizeof chunk);
2600 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2601 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2602 error (g, _("failed to parse file chunk"));
2607 /* After decoding, the original buffer is no longer used. */
2611 error (g, _("file receive cancelled by daemon"));
2612 free (chunk.data.data_val);
2616 if (chunk.data.data_len == 0) { /* end of transfer */
2617 free (chunk.data.data_val);
2621 if (buf_r) *buf_r = chunk.data.data_val;
2622 else free (chunk.data.data_val); /* else caller frees */
2624 return chunk.data.data_len;