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 */
34 #include <sys/select.h>
37 #include <rpc/types.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
48 #ifdef HAVE_SYS_WAIT_H
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
60 #include <arpa/inet.h>
61 #include <netinet/in.h>
64 #include "guestfs-internal.h"
65 #include "guestfs-internal-actions.h"
66 #include "guestfs_protocol.h"
68 #include "ignore-value.h"
72 #define _(str) dgettext(PACKAGE, (str))
73 //#define N_(str) dgettext(PACKAGE, (str))
79 #define error guestfs_error
80 #define perrorf guestfs_perrorf
81 #define safe_malloc guestfs_safe_malloc
82 #define safe_realloc guestfs_safe_realloc
83 #define safe_strdup guestfs_safe_strdup
84 //#define safe_memdup guestfs_safe_memdup
86 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
87 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
88 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
89 static int accept_from_daemon (guestfs_h *g);
90 static int check_peer_euid (guestfs_h *g, int sock, uid_t *rtn);
91 static void close_handles (void);
93 #define UNIX_PATH_MAX 108
95 /* Also in guestfsd.c */
96 #define GUESTFWD_ADDR "10.0.2.4"
97 #define GUESTFWD_PORT "6666"
99 /* GuestFS handle and connection. */
100 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
104 struct guestfs_h *next; /* Linked list of open handles. */
106 /* State: see the state machine diagram in the man page guestfs(3). */
109 int fd[2]; /* Stdin/stdout of qemu. */
110 int sock; /* Daemon communications socket. */
111 pid_t pid; /* Qemu PID. */
112 pid_t recoverypid; /* Recovery process PID. */
114 struct timeval launch_t; /* The time that we called guestfs_launch. */
116 char *tmpdir; /* Temporary directory containing socket. */
118 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
120 char **cmdline; /* Qemu command line. */
129 char *path; /* Path to kernel, initrd. */
130 char *qemu; /* Qemu binary. */
131 char *append; /* Append to kernel command line. */
133 int memsize; /* Size of RAM (megabytes). */
135 int selinux; /* selinux enabled? */
140 guestfs_abort_cb abort_cb;
141 guestfs_error_handler_cb error_cb;
142 void * error_cb_data;
143 guestfs_log_message_cb log_message_cb;
144 void * log_message_cb_data;
145 guestfs_subprocess_quit_cb subprocess_quit_cb;
146 void * subprocess_quit_cb_data;
147 guestfs_launch_done_cb launch_done_cb;
148 void * launch_done_cb_data;
153 static guestfs_h *handles = NULL;
154 static int atexit_handler_set = 0;
157 guestfs_create (void)
162 g = malloc (sizeof (*g));
165 memset (g, 0, sizeof (*g));
174 g->error_cb = default_error_cb;
175 g->error_cb_data = NULL;
177 g->recovery_proc = 1;
179 str = getenv ("LIBGUESTFS_DEBUG");
180 g->verbose = str != NULL && STREQ (str, "1");
182 str = getenv ("LIBGUESTFS_TRACE");
183 g->trace = str != NULL && STREQ (str, "1");
185 str = getenv ("LIBGUESTFS_PATH");
186 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
187 if (!g->path) goto error;
189 str = getenv ("LIBGUESTFS_QEMU");
190 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
191 if (!g->qemu) goto error;
193 str = getenv ("LIBGUESTFS_APPEND");
195 g->append = strdup (str);
196 if (!g->append) goto error;
199 /* Choose a suitable memory size. Previously we tried to choose
200 * a minimal memory size, but this isn't really necessary since
201 * recent QEMU and KVM don't do anything nasty like locking
202 * memory into core any more. Thus we can safely choose a
203 * large, generous amount of memory, and it'll just get swapped
204 * on smaller systems.
206 str = getenv ("LIBGUESTFS_MEMSIZE");
208 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
209 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
215 /* Start with large serial numbers so they are easy to spot
216 * inside the protocol.
218 g->msg_next_serial = 0x00123400;
220 /* Link the handles onto a global list. This is the one area
221 * where the library needs to be made thread-safe. (XXX)
223 /* acquire mutex (XXX) */
226 if (!atexit_handler_set) {
227 atexit (close_handles);
228 atexit_handler_set = 1;
230 /* release mutex (XXX) */
233 fprintf (stderr, "new guestfs handle %p\n", g);
246 guestfs_close (guestfs_h *g)
252 if (g->state == NO_HANDLE) {
253 /* Not safe to call 'error' here, so ... */
254 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
259 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
261 /* Try to sync if autosync flag is set. */
262 if (g->autosync && g->state == READY) {
263 guestfs_umount_all (g);
267 /* Remove any handlers that might be called back before we kill the
270 g->log_message_cb = NULL;
272 if (g->state != CONFIG)
273 guestfs_kill_subprocess (g);
286 /* Wait for subprocess(es) to exit. */
287 waitpid (g->pid, NULL, 0);
288 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
290 /* Remove tmpfiles. */
292 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
295 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
298 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
307 for (i = 0; i < g->cmdline_size; ++i)
308 free (g->cmdline[i]);
312 /* Mark the handle as dead before freeing it. */
313 g->state = NO_HANDLE;
315 /* acquire mutex (XXX) */
319 for (gg = handles; gg->next != g; gg = gg->next)
323 /* release mutex (XXX) */
325 free (g->last_error);
330 free (g->qemu_version);
334 /* Close all open handles (called from atexit(3)). */
338 while (handles) guestfs_close (handles);
342 guestfs_last_error (guestfs_h *g)
344 return g->last_error;
348 set_last_error (guestfs_h *g, const char *msg)
350 free (g->last_error);
351 g->last_error = strdup (msg);
355 default_error_cb (guestfs_h *g, void *data, const char *msg)
357 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
361 guestfs_error (guestfs_h *g, const char *fs, ...)
367 int err = vasprintf (&msg, fs, args);
372 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
373 set_last_error (g, msg);
379 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
386 int err = vasprintf (&msg, fs, args);
393 strerror_r (errnum, buf, sizeof buf);
397 buf = strerror_r (errnum, _buf, sizeof _buf);
400 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
404 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
405 set_last_error (g, msg);
411 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
413 void *ptr = malloc (nbytes);
414 if (nbytes > 0 && !ptr) g->abort_cb ();
418 /* Return 1 if an array of N objects, each of size S, cannot exist due
419 to size arithmetic overflow. S must be positive and N must be
420 nonnegative. This is a macro, not an inline function, so that it
421 works correctly even when SIZE_MAX < N.
423 By gnulib convention, SIZE_MAX represents overflow in size
424 calculations, so the conservative dividend to use here is
425 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
426 However, malloc (SIZE_MAX) fails on all known hosts where
427 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
428 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
429 branch when S is known to be 1. */
430 # define xalloc_oversized(n, s) \
431 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
433 /* Technically we should add an autoconf test for this, testing for the desired
434 functionality, like what's done in gnulib, but for now, this is fine. */
435 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
437 /* Allocate zeroed memory for N elements of S bytes, with error
438 checking. S must be nonzero. */
440 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
442 /* From gnulib's calloc function in xmalloc.c. */
444 /* Test for overflow, since some calloc implementations don't have
445 proper overflow checks. But omit overflow and size-zero tests if
446 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
447 returns NULL if successful. */
448 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
449 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
455 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
457 void *p = realloc (ptr, nbytes);
458 if (nbytes > 0 && !p) g->abort_cb ();
463 guestfs_safe_strdup (guestfs_h *g, const char *str)
465 char *s = strdup (str);
466 if (!s) g->abort_cb ();
471 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
473 void *p = malloc (size);
474 if (!p) g->abort_cb ();
475 memcpy (p, ptr, size);
480 xwrite (int fd, const void *v_buf, size_t len)
482 const char *buf = v_buf;
486 r = write (fd, buf, len);
498 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
504 guestfs_get_out_of_memory_handler (guestfs_h *g)
510 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
513 g->error_cb_data = data;
516 guestfs_error_handler_cb
517 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
519 if (data_rtn) *data_rtn = g->error_cb_data;
524 guestfs__set_verbose (guestfs_h *g, int v)
531 guestfs__get_verbose (guestfs_h *g)
537 guestfs__set_autosync (guestfs_h *g, int a)
544 guestfs__get_autosync (guestfs_h *g)
550 guestfs__set_path (guestfs_h *g, const char *path)
557 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
562 guestfs__get_path (guestfs_h *g)
568 guestfs__set_qemu (guestfs_h *g, const char *qemu)
573 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
578 guestfs__get_qemu (guestfs_h *g)
584 guestfs__set_append (guestfs_h *g, const char *append)
589 g->append = append ? safe_strdup (g, append) : NULL;
594 guestfs__get_append (guestfs_h *g)
600 guestfs__set_memsize (guestfs_h *g, int memsize)
602 g->memsize = memsize;
607 guestfs__get_memsize (guestfs_h *g)
613 guestfs__set_selinux (guestfs_h *g, int selinux)
615 g->selinux = selinux;
620 guestfs__get_selinux (guestfs_h *g)
626 guestfs__get_pid (guestfs_h *g)
631 error (g, "get_pid: no qemu subprocess");
636 struct guestfs_version *
637 guestfs__version (guestfs_h *g)
639 struct guestfs_version *r;
641 r = safe_malloc (g, sizeof *r);
642 r->major = PACKAGE_VERSION_MAJOR;
643 r->minor = PACKAGE_VERSION_MINOR;
644 r->release = PACKAGE_VERSION_RELEASE;
645 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
650 guestfs__set_trace (guestfs_h *g, int t)
657 guestfs__get_trace (guestfs_h *g)
663 guestfs__set_direct (guestfs_h *g, int d)
670 guestfs__get_direct (guestfs_h *g)
676 guestfs__set_recovery_proc (guestfs_h *g, int f)
678 g->recovery_proc = !!f;
683 guestfs__get_recovery_proc (guestfs_h *g)
685 return g->recovery_proc;
688 /* Add a string to the current command line. */
690 incr_cmdline_size (guestfs_h *g)
692 if (g->cmdline == NULL) {
693 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
695 g->cmdline = safe_malloc (g, sizeof (char *));
696 g->cmdline[0] = NULL;
700 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
704 add_cmdline (guestfs_h *g, const char *str)
706 if (g->state != CONFIG) {
708 _("command line cannot be altered after qemu subprocess launched"));
712 incr_cmdline_size (g);
713 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
718 guestfs__config (guestfs_h *g,
719 const char *qemu_param, const char *qemu_value)
721 if (qemu_param[0] != '-') {
722 error (g, _("guestfs_config: parameter must begin with '-' character"));
726 /* A bit fascist, but the user will probably break the extra
727 * parameters that we add if they try to set any of these.
729 if (STREQ (qemu_param, "-kernel") ||
730 STREQ (qemu_param, "-initrd") ||
731 STREQ (qemu_param, "-nographic") ||
732 STREQ (qemu_param, "-serial") ||
733 STREQ (qemu_param, "-full-screen") ||
734 STREQ (qemu_param, "-std-vga") ||
735 STREQ (qemu_param, "-vnc")) {
736 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
740 if (add_cmdline (g, qemu_param) != 0) return -1;
742 if (qemu_value != NULL) {
743 if (add_cmdline (g, qemu_value) != 0) return -1;
750 guestfs__add_drive (guestfs_h *g, const char *filename)
752 size_t len = strlen (filename) + 64;
755 if (strchr (filename, ',') != NULL) {
756 error (g, _("filename cannot contain ',' (comma) character"));
760 /* cache=off improves reliability in the event of a host crash.
762 * However this option causes qemu to try to open the file with
763 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
764 * So we check if we can open the file with or without O_DIRECT,
765 * and use cache=off (or not) accordingly.
767 * This test also checks for the presence of the file, which
768 * is a documented semantic of this interface.
770 int fd = open (filename, O_RDONLY|O_DIRECT);
773 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
775 fd = open (filename, O_RDONLY);
778 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
780 perrorf (g, "%s", filename);
785 return guestfs__config (g, "-drive", buf);
789 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
791 size_t len = strlen (filename) + 64;
794 if (strchr (filename, ',') != NULL) {
795 error (g, _("filename cannot contain ',' (comma) character"));
799 if (access (filename, F_OK) == -1) {
800 perrorf (g, "%s", filename);
804 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
806 return guestfs__config (g, "-drive", buf);
810 guestfs__add_cdrom (guestfs_h *g, const char *filename)
812 if (strchr (filename, ',') != NULL) {
813 error (g, _("filename cannot contain ',' (comma) character"));
817 if (access (filename, F_OK) == -1) {
818 perrorf (g, "%s", filename);
822 return guestfs__config (g, "-cdrom", filename);
825 /* Returns true iff file is contained in dir. */
827 dir_contains_file (const char *dir, const char *file)
829 int dirlen = strlen (dir);
830 int filelen = strlen (file);
831 int len = dirlen+filelen+2;
834 snprintf (path, len, "%s/%s", dir, file);
835 return access (path, F_OK) == 0;
838 /* Returns true iff every listed file is contained in 'dir'. */
840 dir_contains_files (const char *dir, ...)
845 va_start (args, dir);
846 while ((file = va_arg (args, const char *)) != NULL) {
847 if (!dir_contains_file (dir, file)) {
856 static void print_timestamped_message (guestfs_h *g, const char *fs, ...);
857 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
858 static int test_qemu (guestfs_h *g);
859 static int qemu_supports (guestfs_h *g, const char *option);
860 static void print_cmdline (guestfs_h *g);
862 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
863 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
864 static const char *supermin_name =
865 "initramfs." REPO "." host_cpu ".supermin.img";
866 static const char *supermin_hostfiles_name =
867 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
870 guestfs__launch (guestfs_h *g)
873 char dir_template[PATH_MAX];
878 char *path, *pelem, *pend;
879 char *kernel = NULL, *initrd = NULL;
880 int null_vmchannel_sock;
882 struct sockaddr_un addr;
884 /* Start the clock ... */
885 gettimeofday (&g->launch_t, NULL);
893 tmpdir = getenv ("TMPDIR") ? : tmpdir;
894 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
898 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
902 if (g->state != CONFIG) {
903 error (g, _("qemu has already been launched"));
907 /* Make the temporary directory. */
909 g->tmpdir = safe_strdup (g, dir_template);
910 if (mkdtemp (g->tmpdir) == NULL) {
911 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
916 /* First search g->path for the supermin appliance, and try to
917 * synthesize a kernel and initrd from that. If it fails, we
918 * try the path search again looking for a backup ordinary
921 pelem = path = safe_strdup (g, g->path);
923 pend = strchrnul (pelem, ':');
924 pmore = *pend == ':';
928 /* Empty element of "." means cwd. */
929 if (len == 0 || (len == 1 && *pelem == '.')) {
932 "looking for supermin appliance in current directory\n");
933 if (dir_contains_files (".",
934 supermin_name, supermin_hostfiles_name,
935 "kmod.whitelist", NULL)) {
936 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
941 /* Look at <path>/supermin* etc. */
944 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
946 if (dir_contains_files (pelem,
947 supermin_name, supermin_hostfiles_name,
948 "kmod.whitelist", NULL)) {
949 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
960 if (kernel == NULL || initrd == NULL) {
961 /* Search g->path for the kernel and initrd. */
962 pelem = path = safe_strdup (g, g->path);
964 pend = strchrnul (pelem, ':');
965 pmore = *pend == ':';
969 /* Empty element or "." means cwd. */
970 if (len == 0 || (len == 1 && *pelem == '.')) {
973 "looking for appliance in current directory\n");
974 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
975 kernel = safe_strdup (g, kernel_name);
976 initrd = safe_strdup (g, initrd_name);
980 /* Look at <path>/kernel etc. */
983 fprintf (stderr, "looking for appliance in %s\n", pelem);
985 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
986 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
987 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
988 sprintf (kernel, "%s/%s", pelem, kernel_name);
989 sprintf (initrd, "%s/%s", pelem, initrd_name);
1000 if (kernel == NULL || initrd == NULL) {
1001 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1002 kernel_name, initrd_name, g->path);
1007 print_timestamped_message (g, "begin testing qemu features");
1009 /* Get qemu help text and version. */
1010 if (test_qemu (g) == -1)
1013 /* Choose which vmchannel implementation to use. */
1014 if (qemu_supports (g, "-net user")) {
1015 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1016 * networking in qemu) but no other vmchannel support. The daemon
1017 * will connect back to a random port number on localhost.
1019 struct sockaddr_in addr;
1020 socklen_t addrlen = sizeof addr;
1022 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1023 if (g->sock == -1) {
1024 perrorf (g, "socket");
1027 addr.sin_family = AF_INET;
1028 addr.sin_port = htons (0);
1029 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1030 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1031 perrorf (g, "bind");
1035 if (listen (g->sock, 256) == -1) {
1036 perrorf (g, "listen");
1040 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1041 perrorf (g, "getsockname");
1045 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1046 perrorf (g, "fcntl");
1050 null_vmchannel_sock = ntohs (addr.sin_port);
1052 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1054 /* Using some vmchannel impl. We need to create a local Unix
1055 * domain socket for qemu to use.
1057 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1059 null_vmchannel_sock = 0;
1063 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1064 perrorf (g, "pipe");
1070 print_timestamped_message (g, "finished testing qemu features");
1074 perrorf (g, "fork");
1084 if (r == 0) { /* Child (qemu). */
1086 const char *vmchannel = NULL;
1088 /* Set up the full command line. Do this in the subprocess so we
1089 * don't need to worry about cleaning up.
1091 g->cmdline[0] = g->qemu;
1093 snprintf (buf, sizeof buf, "%d", g->memsize);
1094 add_cmdline (g, "-m");
1095 add_cmdline (g, buf);
1097 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1098 add_cmdline (g, "-nographic");
1099 add_cmdline (g, "-serial");
1100 add_cmdline (g, "stdio");
1102 /* These options recommended by KVM developers to improve reliability. */
1103 if (qemu_supports (g, "-no-hpet"))
1104 add_cmdline (g, "-no-hpet");
1106 if (qemu_supports (g, "-rtc-td-hack"))
1107 add_cmdline (g, "-rtc-td-hack");
1109 /* If qemu has SLIRP (user mode network) enabled then we can get
1110 * away with "no vmchannel", where we just connect back to a random
1113 if (null_vmchannel_sock) {
1114 add_cmdline (g, "-net");
1115 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1117 snprintf (buf, sizeof buf,
1118 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1119 vmchannel = strdup (buf);
1122 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1124 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1126 * The original suggested format doesn't work, see:
1128 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1130 * However Gerd Hoffman privately suggested to me using -chardev
1131 * instead, which does work.
1133 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1134 snprintf (buf, sizeof buf,
1135 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1137 add_cmdline (g, "-chardev");
1138 add_cmdline (g, buf);
1140 snprintf (buf, sizeof buf,
1141 "user,vlan=0,net=10.0.2.0/8,"
1142 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1143 "-chardev:guestfsvmc");
1145 add_cmdline (g, "-net");
1146 add_cmdline (g, buf);
1148 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1151 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1152 * syntax, or if not then we'll get a quick failure.
1155 snprintf (buf, sizeof buf,
1156 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1158 add_cmdline (g, "-net");
1159 add_cmdline (g, buf);
1160 add_cmdline (g, "-net");
1161 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1163 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1165 add_cmdline (g, "-net");
1166 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1168 #define LINUX_CMDLINE \
1169 "panic=1 " /* force kernel to panic if daemon exits */ \
1170 "console=ttyS0 " /* serial console */ \
1171 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1172 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1173 "acpi=off " /* we don't need ACPI, turn it off */ \
1174 "printk.time=1 " /* display timestamp before kernel messages */ \
1175 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1177 /* Linux kernel command line. */
1178 snprintf (buf, sizeof buf,
1180 "%s " /* (selinux) */
1181 "%s " /* (vmchannel) */
1182 "%s " /* (verbose) */
1183 "%s", /* (append) */
1184 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1185 vmchannel ? vmchannel : "",
1186 g->verbose ? "guestfs_verbose=1" : "",
1187 g->append ? g->append : "");
1189 add_cmdline (g, "-kernel");
1190 add_cmdline (g, (char *) kernel);
1191 add_cmdline (g, "-initrd");
1192 add_cmdline (g, (char *) initrd);
1193 add_cmdline (g, "-append");
1194 add_cmdline (g, buf);
1196 /* Finish off the command line. */
1197 incr_cmdline_size (g);
1198 g->cmdline[g->cmdline_size-1] = NULL;
1204 /* Set up stdin, stdout. */
1210 if (dup (wfd[0]) == -1) {
1212 perror ("dup failed");
1215 if (dup (rfd[1]) == -1)
1223 /* Set up a new process group, so we can signal this process
1224 * and all subprocesses (eg. if qemu is really a shell script).
1229 setenv ("LC_ALL", "C", 1);
1231 execv (g->qemu, g->cmdline); /* Run qemu. */
1236 /* Parent (library). */
1244 /* Fork the recovery process off which will kill qemu if the parent
1245 * process fails to do so (eg. if the parent segfaults).
1247 g->recoverypid = -1;
1248 if (g->recovery_proc) {
1251 pid_t qemu_pid = g->pid;
1252 pid_t parent_pid = getppid ();
1254 /* Writing to argv is hideously complicated and error prone. See:
1255 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1258 /* Loop around waiting for one or both of the other processes to
1259 * disappear. It's fair to say this is very hairy. The PIDs that
1260 * we are looking at might be reused by another process. We are
1261 * effectively polling. Is the cure worse than the disease?
1264 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1266 if (kill (parent_pid, 0) == -1) {
1267 /* Parent's gone away, qemu still around, so kill qemu. */
1275 /* Don't worry, if the fork failed, this will be -1. The recovery
1276 * process isn't essential.
1282 /* Close the other ends of the pipe. */
1286 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1287 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1288 perrorf (g, "fcntl");
1292 g->fd[0] = wfd[1]; /* stdin of child */
1293 g->fd[1] = rfd[0]; /* stdout of child */
1295 g->fd[0] = open ("/dev/null", O_RDWR);
1296 if (g->fd[0] == -1) {
1297 perrorf (g, "open /dev/null");
1300 g->fd[1] = dup (g->fd[0]);
1301 if (g->fd[1] == -1) {
1308 if (null_vmchannel_sock) {
1312 /* Null vmchannel implementation: We listen on g->sock for a
1313 * connection. The connection could come from any local process
1314 * so we must check it comes from the appliance (or at least
1315 * from our UID) for security reasons.
1317 while (sock == -1) {
1318 sock = accept_from_daemon (g);
1322 if (check_peer_euid (g, sock, &uid) == -1)
1324 if (uid != geteuid ()) {
1326 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1327 uid, null_vmchannel_sock);
1333 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1334 perrorf (g, "fcntl");
1341 /* Other vmchannel. Open the Unix socket.
1343 * The vmchannel implementation that got merged with qemu sucks in
1344 * a number of ways. Both ends do connect(2), which means that no
1345 * one knows what, if anything, is connected to the other end, or
1346 * if it becomes disconnected. Even worse, we have to wait some
1347 * indeterminate time for qemu to create the socket and connect to
1348 * it (which happens very early in qemu's start-up), so any code
1349 * that uses vmchannel is inherently racy. Hence this silly loop.
1351 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1352 if (g->sock == -1) {
1353 perrorf (g, "socket");
1357 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1358 perrorf (g, "fcntl");
1362 addr.sun_family = AF_UNIX;
1363 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1364 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1367 /* Always sleep at least once to give qemu a small chance to start up. */
1370 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1371 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1374 if (errno != ENOENT)
1375 perrorf (g, "connect");
1380 error (g, _("failed to connect to vmchannel socket"));
1386 g->state = LAUNCHING;
1388 /* Wait for qemu to start and to connect back to us via vmchannel and
1389 * send the GUESTFS_LAUNCH_FLAG message.
1393 r = recv_from_daemon (g, &size, &buf);
1396 if (r == -1) return -1;
1398 if (size != GUESTFS_LAUNCH_FLAG) {
1399 error (g, _("guestfs_launch failed, see earlier error messages"));
1404 print_timestamped_message (g, "appliance is up");
1406 /* This is possible in some really strange situations, such as
1407 * guestfsd starts up OK but then qemu immediately exits. Check for
1408 * it because the caller is probably expecting to be able to send
1409 * commands after this function returns.
1411 if (g->state != READY) {
1412 error (g, _("qemu launched and contacted daemon, but state != READY"));
1424 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1425 waitpid (g->pid, NULL, 0);
1426 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1431 memset (&g->launch_t, 0, sizeof g->launch_t);
1444 /* This function is used to print the qemu command line before it gets
1445 * executed, when in verbose mode.
1448 print_cmdline (guestfs_h *g)
1453 while (g->cmdline[i]) {
1454 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1455 fprintf (stderr, " \\\n ");
1457 if (i > 0) fputc (' ', stderr);
1459 /* Does it need shell quoting? This only deals with simple cases. */
1460 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1462 if (needs_quote) fputc ('\'', stderr);
1463 fprintf (stderr, "%s", g->cmdline[i]);
1464 if (needs_quote) fputc ('\'', stderr);
1468 fputc ('\n', stderr);
1471 /* This function does the hard work of building the supermin appliance
1472 * on the fly. 'path' is the directory containing the control files.
1473 * 'kernel' and 'initrd' are where we will return the names of the
1474 * kernel and initrd (only initrd is built). The work is done by
1475 * an external script. We just tell it where to put the result.
1478 build_supermin_appliance (guestfs_h *g, const char *path,
1479 char **kernel, char **initrd)
1485 print_timestamped_message (g, "begin building supermin appliance");
1487 len = strlen (g->tmpdir);
1488 *kernel = safe_malloc (g, len + 8);
1489 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1490 *initrd = safe_malloc (g, len + 8);
1491 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1493 snprintf (cmd, sizeof cmd,
1495 "libguestfs-supermin-helper '%s' %s %s",
1497 path, *kernel, *initrd);
1500 if (r == -1 || WEXITSTATUS(r) != 0) {
1501 error (g, _("external command failed: %s"), cmd);
1504 *kernel = *initrd = NULL;
1509 print_timestamped_message (g, "finished building supermin appliance");
1514 /* Compute Y - X and return the result in milliseconds.
1515 * Approximately the same as this code:
1516 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1519 timeval_diff (const struct timeval *x, const struct timeval *y)
1523 msec = (y->tv_sec - x->tv_sec) * 1000;
1524 msec += (y->tv_usec - x->tv_usec) / 1000;
1529 print_timestamped_message (guestfs_h *g, const char *fs, ...)
1534 struct timeval tv, diff;
1536 va_start (args, fs);
1537 err = vasprintf (&msg, fs, args);
1540 if (err < 0) return;
1542 gettimeofday (&tv, NULL);
1544 fprintf (stderr, "[%05" PRIi64 "ms] %s\n",
1545 timeval_diff (&g->launch_t, &tv), msg);
1550 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1552 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1553 * 'qemu -version' so we know what options this qemu supports and
1557 test_qemu (guestfs_h *g)
1562 free (g->qemu_help);
1563 free (g->qemu_version);
1564 g->qemu_help = NULL;
1565 g->qemu_version = NULL;
1567 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1569 fp = popen (cmd, "r");
1570 /* qemu -help should always work (qemu -version OTOH wasn't
1571 * supported by qemu 0.9). If this command doesn't work then it
1572 * probably indicates that the qemu binary is missing.
1575 /* XXX This error is never printed, even if the qemu binary
1576 * doesn't exist. Why?
1579 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1583 if (read_all (g, fp, &g->qemu_help) == -1)
1586 if (pclose (fp) == -1)
1589 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1591 fp = popen (cmd, "r");
1593 /* Intentionally ignore errors. */
1594 read_all (g, fp, &g->qemu_version);
1602 read_all (guestfs_h *g, FILE *fp, char **ret)
1609 *ret = safe_realloc (g, *ret, n + 1);
1614 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1616 r = fread (p, 1, BUFSIZ, fp);
1618 perrorf (g, "read");
1625 /* Test if option is supported by qemu command line (just by grepping
1629 qemu_supports (guestfs_h *g, const char *option)
1631 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1634 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1635 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1636 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1639 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1641 struct sockaddr_in peer;
1642 socklen_t addrlen = sizeof peer;
1644 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1645 perrorf (g, "getpeername");
1649 if (peer.sin_family != AF_INET ||
1650 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1651 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1652 peer.sin_family, inet_ntoa (peer.sin_addr));
1656 struct sockaddr_in our;
1657 addrlen = sizeof our;
1658 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1659 perrorf (g, "getsockname");
1663 FILE *fp = fopen ("/proc/net/tcp", "r");
1665 perrorf (g, "/proc/net/tcp");
1670 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1671 error (g, "unexpected end of file in /proc/net/tcp");
1676 while (fgets (line, sizeof line, fp) != NULL) {
1677 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1678 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1681 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1683 &line_our_addr, &line_our_port,
1684 &line_peer_addr, &line_peer_port,
1685 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1687 /* Note about /proc/net/tcp: local_address and rem_address are
1688 * always in network byte order. However the port part is
1689 * always in host byte order.
1691 * The sockname and peername that we got above are in network
1692 * byte order. So we have to byte swap the port but not the
1695 if (line_our_addr == our.sin_addr.s_addr &&
1696 line_our_port == ntohs (our.sin_port) &&
1697 line_peer_addr == peer.sin_addr.s_addr &&
1698 line_peer_port == ntohs (peer.sin_port)) {
1706 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1711 /* You had to call this function after launch in versions <= 1.0.70,
1712 * but it is now a no-op.
1715 guestfs__wait_ready (guestfs_h *g)
1717 if (g->state != READY) {
1718 error (g, _("qemu has not been launched yet"));
1726 guestfs__kill_subprocess (guestfs_h *g)
1728 if (g->state == CONFIG) {
1729 error (g, _("no subprocess to kill"));
1734 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1736 kill (g->pid, SIGTERM);
1737 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1742 /* Access current state. */
1744 guestfs__is_config (guestfs_h *g)
1746 return g->state == CONFIG;
1750 guestfs__is_launching (guestfs_h *g)
1752 return g->state == LAUNCHING;
1756 guestfs__is_ready (guestfs_h *g)
1758 return g->state == READY;
1762 guestfs__is_busy (guestfs_h *g)
1764 return g->state == BUSY;
1768 guestfs__get_state (guestfs_h *g)
1774 guestfs_set_log_message_callback (guestfs_h *g,
1775 guestfs_log_message_cb cb, void *opaque)
1777 g->log_message_cb = cb;
1778 g->log_message_cb_data = opaque;
1782 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1783 guestfs_subprocess_quit_cb cb, void *opaque)
1785 g->subprocess_quit_cb = cb;
1786 g->subprocess_quit_cb_data = opaque;
1790 guestfs_set_launch_done_callback (guestfs_h *g,
1791 guestfs_launch_done_cb cb, void *opaque)
1793 g->launch_done_cb = cb;
1794 g->launch_done_cb_data = opaque;
1797 /*----------------------------------------------------------------------*/
1799 /* This is the code used to send and receive RPC messages and (for
1800 * certain types of message) to perform file transfers. This code is
1801 * driven from the generated actions (src/guestfs-actions.c). There
1802 * are five different cases to consider:
1804 * (1) A non-daemon function. There is no RPC involved at all, it's
1805 * all handled inside the library.
1807 * (2) A simple RPC (eg. "mount"). We write the request, then read
1808 * the reply. The sequence of calls is:
1810 * guestfs___set_busy
1813 * guestfs___end_busy
1815 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1816 * request, then write the file(s), then read the reply. The sequence
1819 * guestfs___set_busy
1821 * guestfs___send_file (possibly multiple times)
1823 * guestfs___end_busy
1825 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1826 * request, then read the reply, then read the file(s). The sequence
1829 * guestfs___set_busy
1832 * guestfs___recv_file (possibly multiple times)
1833 * guestfs___end_busy
1835 * (5) Both FileOut and FileIn parameters. There are no calls like
1836 * this in the current API, but they would be implemented as a
1837 * combination of cases (3) and (4).
1839 * During all writes and reads, we also select(2) on qemu stdout
1840 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1841 * anything received is passed up through the log_message_cb. This is
1842 * also the reason why all the sockets are non-blocking. We also have
1843 * to check for EOF (qemu died). All of this is handled by the
1844 * functions send_to_daemon and recv_from_daemon.
1848 guestfs___set_busy (guestfs_h *g)
1850 if (g->state != READY) {
1851 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1860 guestfs___end_busy (guestfs_h *g)
1874 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1880 /* This is called if we detect EOF, ie. qemu died. */
1882 child_cleanup (guestfs_h *g)
1885 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1887 /*kill (g->pid, SIGTERM);*/
1888 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1889 waitpid (g->pid, NULL, 0);
1890 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1899 memset (&g->launch_t, 0, sizeof g->launch_t);
1901 if (g->subprocess_quit_cb)
1902 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1906 read_log_message_or_eof (guestfs_h *g, int fd)
1914 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1918 /* QEMU's console emulates a 16550A serial port. The real 16550A
1919 * device has a small FIFO buffer (16 bytes) which means here we see
1920 * lots of small reads of 1-16 bytes in length, usually single
1923 n = read (fd, buf, sizeof buf);
1925 /* Hopefully this indicates the qemu child process has died. */
1931 if (errno == EINTR || errno == EAGAIN)
1934 perrorf (g, "read");
1938 /* In verbose mode, copy all log messages to stderr. */
1940 ignore_value (write (STDERR_FILENO, buf, n));
1942 /* It's an actual log message, send it upwards if anyone is listening. */
1943 if (g->log_message_cb)
1944 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1950 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1959 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1962 n = read (fd, buf, 4);
1964 /* Hopefully this indicates the qemu child process has died. */
1970 if (errno == EINTR || errno == EAGAIN)
1973 perrorf (g, "read");
1977 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1978 xdr_uint32_t (&xdr, &flag);
1981 if (flag != GUESTFS_CANCEL_FLAG) {
1982 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1983 flag, GUESTFS_CANCEL_FLAG);
1990 /* This writes the whole N bytes of BUF to the daemon socket.
1992 * If the whole write is successful, it returns 0.
1993 * If there was an error, it returns -1.
1994 * If the daemon sent a cancellation message, it returns -2.
1996 * It also checks qemu stdout for log messages and passes those up
1997 * through log_message_cb.
1999 * It also checks for EOF (qemu died) and passes that up through the
2000 * child_cleanup function above.
2003 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
2005 const char *buf = v_buf;
2011 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
2016 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2017 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
2018 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
2020 int max_fd = MAX (g->sock, g->fd[1]);
2025 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
2027 if (errno == EINTR || errno == EAGAIN)
2029 perrorf (g, "select");
2033 if (FD_ISSET (g->fd[1], &rset2)) {
2034 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2037 if (FD_ISSET (g->sock, &rset2)) {
2038 r = check_for_daemon_cancellation_or_eof (g, g->sock);
2042 if (FD_ISSET (g->sock, &wset2)) {
2043 r = write (g->sock, buf, n);
2045 if (errno == EINTR || errno == EAGAIN)
2047 perrorf (g, "write");
2048 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2060 /* This reads a single message, file chunk, launch flag or
2061 * cancellation flag from the daemon. If something was read, it
2062 * returns 0, otherwise -1.
2064 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2066 * *size_rtn returns the size of the returned message or it may be
2067 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2069 * *buf_rtn is returned containing the message (if any) or will be set
2070 * to NULL. *buf_rtn must be freed by the caller.
2072 * It also checks qemu stdout for log messages and passes those up
2073 * through log_message_cb.
2075 * It also checks for EOF (qemu died) and passes that up through the
2076 * child_cleanup function above.
2079 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2085 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2086 g, g->state, size_rtn, buf_rtn);
2090 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2091 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2093 int max_fd = MAX (g->sock, g->fd[1]);
2099 /* nr is the size of the message, but we prime it as -4 because we
2100 * have to read the message length word first.
2104 while (nr < (ssize_t) *size_rtn) {
2106 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2108 if (errno == EINTR || errno == EAGAIN)
2110 perrorf (g, "select");
2116 if (FD_ISSET (g->fd[1], &rset2)) {
2117 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2123 if (FD_ISSET (g->sock, &rset2)) {
2124 if (nr < 0) { /* Have we read the message length word yet? */
2125 r = read (g->sock, lenbuf+nr+4, -nr);
2127 if (errno == EINTR || errno == EAGAIN)
2130 perrorf (g, "read");
2131 /* Under some circumstances we see "Connection reset by peer"
2132 * here when the child dies suddenly. Catch this and call
2133 * the cleanup function, same as for EOF.
2135 if (err == ECONNRESET)
2140 error (g, _("unexpected end of file when reading from daemon"));
2146 if (nr < 0) /* Still not got the whole length word. */
2150 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2151 xdr_uint32_t (&xdr, size_rtn);
2154 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2155 if (g->state != LAUNCHING)
2156 error (g, _("received magic signature from guestfsd, but in state %d"),
2160 if (g->launch_done_cb)
2161 g->launch_done_cb (g, g->launch_done_cb_data);
2165 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2167 /* If this happens, it's pretty bad and we've probably lost
2170 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2171 error (g, _("message length (%u) > maximum possible size (%d)"),
2172 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2176 /* Allocate the complete buffer, size now known. */
2177 *buf_rtn = safe_malloc (g, *size_rtn);
2181 size_t sizetoread = *size_rtn - nr;
2182 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2184 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2186 if (errno == EINTR || errno == EAGAIN)
2188 perrorf (g, "read");
2194 error (g, _("unexpected end of file when reading from daemon"));
2204 /* Got the full message, caller can start processing it. */
2205 #ifdef ENABLE_PACKET_DUMP
2209 for (i = 0; i < nr; i += 16) {
2210 printf ("%04zx: ", i);
2211 for (j = i; j < MIN (i+16, nr); ++j)
2212 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2213 for (; j < i+16; ++j)
2216 for (j = i; j < MIN (i+16, nr); ++j)
2217 if (c_isprint ((*(char **)buf_rtn)[j]))
2218 printf ("%c", (*(char **)buf_rtn)[j]);
2221 for (; j < i+16; ++j)
2231 /* This is very much like recv_from_daemon above, but g->sock is
2232 * a listening socket and we are accepting a new connection on
2233 * that socket instead of reading anything. Returns the newly
2237 accept_from_daemon (guestfs_h *g)
2243 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2247 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2248 FD_SET (g->sock, &rset); /* Read socket for accept. */
2250 int max_fd = MAX (g->sock, g->fd[1]);
2253 while (sock == -1) {
2255 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2257 if (errno == EINTR || errno == EAGAIN)
2259 perrorf (g, "select");
2263 if (FD_ISSET (g->fd[1], &rset2)) {
2264 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2267 if (FD_ISSET (g->sock, &rset2)) {
2268 sock = accept (g->sock, NULL, NULL);
2270 if (errno == EINTR || errno == EAGAIN)
2272 perrorf (g, "accept");
2282 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2284 struct guestfs_message_header hdr;
2287 int serial = g->msg_next_serial++;
2290 size_t msg_out_size;
2292 if (g->state != BUSY) {
2293 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2297 /* We have to allocate this message buffer on the heap because
2298 * it is quite large (although will be mostly unused). We
2299 * can't allocate it on the stack because in some environments
2300 * we have quite limited stack space available, notably when
2301 * running in the JVM.
2303 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2304 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2306 /* Serialize the header. */
2307 hdr.prog = GUESTFS_PROGRAM;
2308 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2310 hdr.direction = GUESTFS_DIRECTION_CALL;
2311 hdr.serial = serial;
2312 hdr.status = GUESTFS_STATUS_OK;
2314 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2315 error (g, _("xdr_guestfs_message_header failed"));
2319 /* Serialize the args. If any, because some message types
2320 * have no parameters.
2323 if (!(*xdrp) (&xdr, args)) {
2324 error (g, _("dispatch failed to marshal args"));
2329 /* Get the actual length of the message, resize the buffer to match
2330 * the actual length, and write the length word at the beginning.
2332 len = xdr_getpos (&xdr);
2335 msg_out = safe_realloc (g, msg_out, len + 4);
2336 msg_out_size = len + 4;
2338 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2339 xdr_uint32_t (&xdr, &len);
2342 r = send_to_daemon (g, msg_out, msg_out_size);
2343 if (r == -2) /* Ignore stray daemon cancellations. */
2356 static int cancel = 0; /* XXX Implement file cancellation. */
2357 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2358 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2359 static int send_file_cancellation (guestfs_h *g);
2360 static int send_file_complete (guestfs_h *g);
2366 * -2 daemon cancelled (we must read the error message)
2369 guestfs___send_file (guestfs_h *g, const char *filename)
2371 char buf[GUESTFS_MAX_CHUNK_SIZE];
2374 fd = open (filename, O_RDONLY);
2376 perrorf (g, "open: %s", filename);
2377 send_file_cancellation (g);
2378 /* Daemon sees cancellation and won't reply, so caller can
2384 /* Send file in chunked encoding. */
2386 r = read (fd, buf, sizeof buf);
2387 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2390 err = send_file_data (g, buf, r);
2392 if (err == -2) /* daemon sent cancellation */
2393 send_file_cancellation (g);
2398 if (cancel) { /* cancel from either end */
2399 send_file_cancellation (g);
2404 perrorf (g, "read: %s", filename);
2405 send_file_cancellation (g);
2409 /* End of file, but before we send that, we need to close
2410 * the file and check for errors.
2412 if (close (fd) == -1) {
2413 perrorf (g, "close: %s", filename);
2414 send_file_cancellation (g);
2418 return send_file_complete (g);
2421 /* Send a chunk of file data. */
2423 send_file_data (guestfs_h *g, const char *buf, size_t len)
2425 return send_file_chunk (g, 0, buf, len);
2428 /* Send a cancellation message. */
2430 send_file_cancellation (guestfs_h *g)
2432 return send_file_chunk (g, 1, NULL, 0);
2435 /* Send a file complete chunk. */
2437 send_file_complete (guestfs_h *g)
2440 return send_file_chunk (g, 0, buf, 0);
2444 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2448 guestfs_chunk chunk;
2451 size_t msg_out_size;
2453 if (g->state != BUSY) {
2454 error (g, _("send_file_chunk: state %d != READY"), g->state);
2458 /* Allocate the chunk buffer. Don't use the stack to avoid
2459 * excessive stack usage and unnecessary copies.
2461 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2462 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2464 /* Serialize the chunk. */
2465 chunk.cancel = cancel;
2466 chunk.data.data_len = buflen;
2467 chunk.data.data_val = (char *) buf;
2469 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2470 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2476 len = xdr_getpos (&xdr);
2479 /* Reduce the size of the outgoing message buffer to the real length. */
2480 msg_out = safe_realloc (g, msg_out, len + 4);
2481 msg_out_size = len + 4;
2483 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2484 xdr_uint32_t (&xdr, &len);
2486 r = send_to_daemon (g, msg_out, msg_out_size);
2488 /* Did the daemon send a cancellation message? */
2491 fprintf (stderr, "got daemon cancellation\n");
2507 /* Receive a reply. */
2509 guestfs___recv (guestfs_h *g, const char *fn,
2510 guestfs_message_header *hdr,
2511 guestfs_message_error *err,
2512 xdrproc_t xdrp, char *ret)
2520 r = recv_from_daemon (g, &size, &buf);
2524 /* This can happen if a cancellation happens right at the end
2525 * of us sending a FileIn parameter to the daemon. Discard. The
2526 * daemon should send us an error message next.
2528 if (size == GUESTFS_CANCEL_FLAG)
2531 if (size == GUESTFS_LAUNCH_FLAG) {
2532 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2536 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2538 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2539 error (g, "%s: failed to parse reply header", fn);
2544 if (hdr->status == GUESTFS_STATUS_ERROR) {
2545 if (!xdr_guestfs_message_error (&xdr, err)) {
2546 error (g, "%s: failed to parse reply error", fn);
2552 if (xdrp && ret && !xdrp (&xdr, ret)) {
2553 error (g, "%s: failed to parse reply", fn);
2565 /* Receive a file. */
2567 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2568 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2571 guestfs___recv_file (guestfs_h *g, const char *filename)
2577 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2579 perrorf (g, "open: %s", filename);
2583 /* Receive the file in chunked encoding. */
2584 while ((r = receive_file_data (g, &buf)) > 0) {
2585 if (xwrite (fd, buf, r) == -1) {
2586 perrorf (g, "%s: write", filename);
2594 error (g, _("%s: error in chunked encoding"), filename);
2598 if (close (fd) == -1) {
2599 perrorf (g, "close: %s", filename);
2606 /* Send cancellation message to daemon, then wait until it
2607 * cancels (just throwing away data).
2611 uint32_t flag = GUESTFS_CANCEL_FLAG;
2614 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2617 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2618 xdr_uint32_t (&xdr, &flag);
2621 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2622 perrorf (g, _("write to daemon socket"));
2626 while (receive_file_data (g, NULL) > 0)
2627 ; /* just discard it */
2632 /* Receive a chunk of file data. */
2633 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2635 receive_file_data (guestfs_h *g, void **buf_r)
2641 guestfs_chunk chunk;
2643 r = recv_from_daemon (g, &len, &buf);
2645 error (g, _("receive_file_data: parse error in reply callback"));
2649 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2650 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2654 memset (&chunk, 0, sizeof chunk);
2656 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2657 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2658 error (g, _("failed to parse file chunk"));
2663 /* After decoding, the original buffer is no longer used. */
2667 error (g, _("file receive cancelled by daemon"));
2668 free (chunk.data.data_val);
2672 if (chunk.data.data_len == 0) { /* end of transfer */
2673 free (chunk.data.data_val);
2677 if (buf_r) *buf_r = chunk.data.data_val;
2678 else free (chunk.data.data_val); /* else caller frees */
2680 return chunk.data.data_len;