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. */
111 struct timeval launch_t; /* The time that we called guestfs_launch. */
113 char *tmpdir; /* Temporary directory containing socket. */
115 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
117 char **cmdline; /* Qemu command line. */
126 char *path; /* Path to kernel, initrd. */
127 char *qemu; /* Qemu binary. */
128 char *append; /* Append to kernel command line. */
130 int memsize; /* Size of RAM (megabytes). */
132 int selinux; /* selinux enabled? */
137 guestfs_abort_cb abort_cb;
138 guestfs_error_handler_cb error_cb;
139 void * error_cb_data;
140 guestfs_log_message_cb log_message_cb;
141 void * log_message_cb_data;
142 guestfs_subprocess_quit_cb subprocess_quit_cb;
143 void * subprocess_quit_cb_data;
144 guestfs_launch_done_cb launch_done_cb;
145 void * launch_done_cb_data;
150 static guestfs_h *handles = NULL;
151 static int atexit_handler_set = 0;
154 guestfs_create (void)
159 g = malloc (sizeof (*g));
162 memset (g, 0, sizeof (*g));
171 g->error_cb = default_error_cb;
172 g->error_cb_data = NULL;
174 g->recovery_proc = 1;
176 str = getenv ("LIBGUESTFS_DEBUG");
177 g->verbose = str != NULL && STREQ (str, "1");
179 str = getenv ("LIBGUESTFS_TRACE");
180 g->trace = str != NULL && STREQ (str, "1");
182 str = getenv ("LIBGUESTFS_PATH");
183 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
184 if (!g->path) goto error;
186 str = getenv ("LIBGUESTFS_QEMU");
187 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
188 if (!g->qemu) goto error;
190 str = getenv ("LIBGUESTFS_APPEND");
192 g->append = strdup (str);
193 if (!g->append) goto error;
196 /* Choose a suitable memory size. Previously we tried to choose
197 * a minimal memory size, but this isn't really necessary since
198 * recent QEMU and KVM don't do anything nasty like locking
199 * memory into core any more. Thus we can safely choose a
200 * large, generous amount of memory, and it'll just get swapped
201 * on smaller systems.
203 str = getenv ("LIBGUESTFS_MEMSIZE");
205 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
206 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
212 /* Start with large serial numbers so they are easy to spot
213 * inside the protocol.
215 g->msg_next_serial = 0x00123400;
217 /* Link the handles onto a global list. This is the one area
218 * where the library needs to be made thread-safe. (XXX)
220 /* acquire mutex (XXX) */
223 if (!atexit_handler_set) {
224 atexit (close_handles);
225 atexit_handler_set = 1;
227 /* release mutex (XXX) */
230 fprintf (stderr, "new guestfs handle %p\n", g);
243 guestfs_close (guestfs_h *g)
249 if (g->state == NO_HANDLE) {
250 /* Not safe to call 'error' here, so ... */
251 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
256 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
258 /* Try to sync if autosync flag is set. */
259 if (g->autosync && g->state == READY) {
260 guestfs_umount_all (g);
264 /* Remove any handlers that might be called back before we kill the
267 g->log_message_cb = NULL;
269 if (g->state != CONFIG)
270 guestfs_kill_subprocess (g);
283 /* Wait for subprocess(es) to exit. */
284 waitpid (g->pid, NULL, 0);
285 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
287 /* Remove tmpfiles. */
289 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
292 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
295 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
304 for (i = 0; i < g->cmdline_size; ++i)
305 free (g->cmdline[i]);
309 /* Mark the handle as dead before freeing it. */
310 g->state = NO_HANDLE;
312 /* acquire mutex (XXX) */
316 for (gg = handles; gg->next != g; gg = gg->next)
320 /* release mutex (XXX) */
322 free (g->last_error);
327 free (g->qemu_version);
331 /* Close all open handles (called from atexit(3)). */
335 while (handles) guestfs_close (handles);
339 guestfs_last_error (guestfs_h *g)
341 return g->last_error;
345 set_last_error (guestfs_h *g, const char *msg)
347 free (g->last_error);
348 g->last_error = strdup (msg);
352 default_error_cb (guestfs_h *g, void *data, const char *msg)
354 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
358 guestfs_error (guestfs_h *g, const char *fs, ...)
364 int err = vasprintf (&msg, fs, args);
369 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
370 set_last_error (g, msg);
376 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
383 int err = vasprintf (&msg, fs, args);
390 strerror_r (errnum, buf, sizeof buf);
394 buf = strerror_r (errnum, _buf, sizeof _buf);
397 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
401 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
402 set_last_error (g, msg);
408 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
410 void *ptr = malloc (nbytes);
411 if (nbytes > 0 && !ptr) g->abort_cb ();
415 /* Return 1 if an array of N objects, each of size S, cannot exist due
416 to size arithmetic overflow. S must be positive and N must be
417 nonnegative. This is a macro, not an inline function, so that it
418 works correctly even when SIZE_MAX < N.
420 By gnulib convention, SIZE_MAX represents overflow in size
421 calculations, so the conservative dividend to use here is
422 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
423 However, malloc (SIZE_MAX) fails on all known hosts where
424 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
425 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
426 branch when S is known to be 1. */
427 # define xalloc_oversized(n, s) \
428 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
430 /* Technically we should add an autoconf test for this, testing for the desired
431 functionality, like what's done in gnulib, but for now, this is fine. */
432 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
434 /* Allocate zeroed memory for N elements of S bytes, with error
435 checking. S must be nonzero. */
437 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
439 /* From gnulib's calloc function in xmalloc.c. */
441 /* Test for overflow, since some calloc implementations don't have
442 proper overflow checks. But omit overflow and size-zero tests if
443 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
444 returns NULL if successful. */
445 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
446 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
452 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
454 void *p = realloc (ptr, nbytes);
455 if (nbytes > 0 && !p) g->abort_cb ();
460 guestfs_safe_strdup (guestfs_h *g, const char *str)
462 char *s = strdup (str);
463 if (!s) g->abort_cb ();
468 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
470 void *p = malloc (size);
471 if (!p) g->abort_cb ();
472 memcpy (p, ptr, size);
477 xwrite (int fd, const void *v_buf, size_t len)
479 const char *buf = v_buf;
483 r = write (fd, buf, len);
495 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
501 guestfs_get_out_of_memory_handler (guestfs_h *g)
507 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
510 g->error_cb_data = data;
513 guestfs_error_handler_cb
514 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
516 if (data_rtn) *data_rtn = g->error_cb_data;
521 guestfs__set_verbose (guestfs_h *g, int v)
528 guestfs__get_verbose (guestfs_h *g)
534 guestfs__set_autosync (guestfs_h *g, int a)
541 guestfs__get_autosync (guestfs_h *g)
547 guestfs__set_path (guestfs_h *g, const char *path)
554 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
559 guestfs__get_path (guestfs_h *g)
565 guestfs__set_qemu (guestfs_h *g, const char *qemu)
570 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
575 guestfs__get_qemu (guestfs_h *g)
581 guestfs__set_append (guestfs_h *g, const char *append)
586 g->append = append ? safe_strdup (g, append) : NULL;
591 guestfs__get_append (guestfs_h *g)
597 guestfs__set_memsize (guestfs_h *g, int memsize)
599 g->memsize = memsize;
604 guestfs__get_memsize (guestfs_h *g)
610 guestfs__set_selinux (guestfs_h *g, int selinux)
612 g->selinux = selinux;
617 guestfs__get_selinux (guestfs_h *g)
623 guestfs__get_pid (guestfs_h *g)
628 error (g, "get_pid: no qemu subprocess");
633 struct guestfs_version *
634 guestfs__version (guestfs_h *g)
636 struct guestfs_version *r;
638 r = safe_malloc (g, sizeof *r);
639 r->major = PACKAGE_VERSION_MAJOR;
640 r->minor = PACKAGE_VERSION_MINOR;
641 r->release = PACKAGE_VERSION_RELEASE;
642 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
647 guestfs__set_trace (guestfs_h *g, int t)
654 guestfs__get_trace (guestfs_h *g)
660 guestfs__set_direct (guestfs_h *g, int d)
667 guestfs__get_direct (guestfs_h *g)
673 guestfs__set_recovery_proc (guestfs_h *g, int f)
675 g->recovery_proc = !!f;
680 guestfs__get_recovery_proc (guestfs_h *g)
682 return g->recovery_proc;
685 /* Add a string to the current command line. */
687 incr_cmdline_size (guestfs_h *g)
689 if (g->cmdline == NULL) {
690 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
692 g->cmdline = safe_malloc (g, sizeof (char *));
693 g->cmdline[0] = NULL;
697 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
701 add_cmdline (guestfs_h *g, const char *str)
703 if (g->state != CONFIG) {
705 _("command line cannot be altered after qemu subprocess launched"));
709 incr_cmdline_size (g);
710 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
715 guestfs__config (guestfs_h *g,
716 const char *qemu_param, const char *qemu_value)
718 if (qemu_param[0] != '-') {
719 error (g, _("guestfs_config: parameter must begin with '-' character"));
723 /* A bit fascist, but the user will probably break the extra
724 * parameters that we add if they try to set any of these.
726 if (STREQ (qemu_param, "-kernel") ||
727 STREQ (qemu_param, "-initrd") ||
728 STREQ (qemu_param, "-nographic") ||
729 STREQ (qemu_param, "-serial") ||
730 STREQ (qemu_param, "-full-screen") ||
731 STREQ (qemu_param, "-std-vga") ||
732 STREQ (qemu_param, "-vnc")) {
733 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
737 if (add_cmdline (g, qemu_param) != 0) return -1;
739 if (qemu_value != NULL) {
740 if (add_cmdline (g, qemu_value) != 0) return -1;
747 guestfs__add_drive (guestfs_h *g, const char *filename)
749 size_t len = strlen (filename) + 64;
752 if (strchr (filename, ',') != NULL) {
753 error (g, _("filename cannot contain ',' (comma) character"));
757 /* cache=off improves reliability in the event of a host crash.
759 * However this option causes qemu to try to open the file with
760 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
761 * So we check if we can open the file with or without O_DIRECT,
762 * and use cache=off (or not) accordingly.
764 * This test also checks for the presence of the file, which
765 * is a documented semantic of this interface.
767 int fd = open (filename, O_RDONLY|O_DIRECT);
770 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
772 fd = open (filename, O_RDONLY);
775 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
777 perrorf (g, "%s", filename);
782 return guestfs__config (g, "-drive", buf);
786 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
788 size_t len = strlen (filename) + 64;
791 if (strchr (filename, ',') != NULL) {
792 error (g, _("filename cannot contain ',' (comma) character"));
796 if (access (filename, F_OK) == -1) {
797 perrorf (g, "%s", filename);
801 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
803 return guestfs__config (g, "-drive", buf);
807 guestfs__add_cdrom (guestfs_h *g, const char *filename)
809 if (strchr (filename, ',') != NULL) {
810 error (g, _("filename cannot contain ',' (comma) character"));
814 if (access (filename, F_OK) == -1) {
815 perrorf (g, "%s", filename);
819 return guestfs__config (g, "-cdrom", filename);
822 /* Returns true iff file is contained in dir. */
824 dir_contains_file (const char *dir, const char *file)
826 int dirlen = strlen (dir);
827 int filelen = strlen (file);
828 int len = dirlen+filelen+2;
831 snprintf (path, len, "%s/%s", dir, file);
832 return access (path, F_OK) == 0;
835 /* Returns true iff every listed file is contained in 'dir'. */
837 dir_contains_files (const char *dir, ...)
842 va_start (args, dir);
843 while ((file = va_arg (args, const char *)) != NULL) {
844 if (!dir_contains_file (dir, file)) {
853 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
854 static int test_qemu (guestfs_h *g);
855 static int qemu_supports (guestfs_h *g, const char *option);
856 static void print_cmdline (guestfs_h *g);
858 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
859 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
860 static const char *supermin_name =
861 "initramfs." REPO "." host_cpu ".supermin.img";
862 static const char *supermin_hostfiles_name =
863 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
866 guestfs__launch (guestfs_h *g)
869 char dir_template[PATH_MAX];
874 char *path, *pelem, *pend;
875 char *kernel = NULL, *initrd = NULL;
876 int null_vmchannel_sock;
878 struct sockaddr_un addr;
880 /* Start the clock ... */
881 gettimeofday (&g->launch_t, NULL);
889 tmpdir = getenv ("TMPDIR") ? : tmpdir;
890 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
894 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
898 if (g->state != CONFIG) {
899 error (g, _("qemu has already been launched"));
903 /* Make the temporary directory. */
905 g->tmpdir = safe_strdup (g, dir_template);
906 if (mkdtemp (g->tmpdir) == NULL) {
907 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
912 /* First search g->path for the supermin appliance, and try to
913 * synthesize a kernel and initrd from that. If it fails, we
914 * try the path search again looking for a backup ordinary
917 pelem = path = safe_strdup (g, g->path);
919 pend = strchrnul (pelem, ':');
920 pmore = *pend == ':';
924 /* Empty element of "." means cwd. */
925 if (len == 0 || (len == 1 && *pelem == '.')) {
928 "looking for supermin appliance in current directory\n");
929 if (dir_contains_files (".",
930 supermin_name, supermin_hostfiles_name,
931 "kmod.whitelist", NULL)) {
932 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
937 /* Look at <path>/supermin* etc. */
940 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
942 if (dir_contains_files (pelem,
943 supermin_name, supermin_hostfiles_name,
944 "kmod.whitelist", NULL)) {
945 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
956 if (kernel == NULL || initrd == NULL) {
957 /* Search g->path for the kernel and initrd. */
958 pelem = path = safe_strdup (g, g->path);
960 pend = strchrnul (pelem, ':');
961 pmore = *pend == ':';
965 /* Empty element or "." means cwd. */
966 if (len == 0 || (len == 1 && *pelem == '.')) {
969 "looking for appliance in current directory\n");
970 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
971 kernel = safe_strdup (g, kernel_name);
972 initrd = safe_strdup (g, initrd_name);
976 /* Look at <path>/kernel etc. */
979 fprintf (stderr, "looking for appliance in %s\n", pelem);
981 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
982 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
983 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
984 sprintf (kernel, "%s/%s", pelem, kernel_name);
985 sprintf (initrd, "%s/%s", pelem, initrd_name);
996 if (kernel == NULL || initrd == NULL) {
997 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
998 kernel_name, initrd_name, g->path);
1002 /* Get qemu help text and version. */
1003 if (test_qemu (g) == -1)
1006 /* Choose which vmchannel implementation to use. */
1007 if (qemu_supports (g, "-net user")) {
1008 /* The "null vmchannel" implementation. Requires SLIRP (user mode
1009 * networking in qemu) but no other vmchannel support. The daemon
1010 * will connect back to a random port number on localhost.
1012 struct sockaddr_in addr;
1013 socklen_t addrlen = sizeof addr;
1015 g->sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1016 if (g->sock == -1) {
1017 perrorf (g, "socket");
1020 addr.sin_family = AF_INET;
1021 addr.sin_port = htons (0);
1022 addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1023 if (bind (g->sock, (struct sockaddr *) &addr, addrlen) == -1) {
1024 perrorf (g, "bind");
1028 if (listen (g->sock, 256) == -1) {
1029 perrorf (g, "listen");
1033 if (getsockname (g->sock, (struct sockaddr *) &addr, &addrlen) == -1) {
1034 perrorf (g, "getsockname");
1038 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1039 perrorf (g, "fcntl");
1043 null_vmchannel_sock = ntohs (addr.sin_port);
1045 fprintf (stderr, "null_vmchannel_sock = %d\n", null_vmchannel_sock);
1047 /* Using some vmchannel impl. We need to create a local Unix
1048 * domain socket for qemu to use.
1050 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1052 null_vmchannel_sock = 0;
1056 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1057 perrorf (g, "pipe");
1064 perrorf (g, "fork");
1074 if (r == 0) { /* Child (qemu). */
1076 const char *vmchannel = NULL;
1078 /* Set up the full command line. Do this in the subprocess so we
1079 * don't need to worry about cleaning up.
1081 g->cmdline[0] = g->qemu;
1083 snprintf (buf, sizeof buf, "%d", g->memsize);
1084 add_cmdline (g, "-m");
1085 add_cmdline (g, buf);
1087 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1088 add_cmdline (g, "-nographic");
1089 add_cmdline (g, "-serial");
1090 add_cmdline (g, "stdio");
1092 /* These options recommended by KVM developers to improve reliability. */
1093 if (qemu_supports (g, "-no-hpet"))
1094 add_cmdline (g, "-no-hpet");
1096 if (qemu_supports (g, "-rtc-td-hack"))
1097 add_cmdline (g, "-rtc-td-hack");
1099 /* If qemu has SLIRP (user mode network) enabled then we can get
1100 * away with "no vmchannel", where we just connect back to a random
1103 if (null_vmchannel_sock) {
1104 add_cmdline (g, "-net");
1105 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1107 snprintf (buf, sizeof buf,
1108 "guestfs_vmchannel=tcp:10.0.2.2:%d", null_vmchannel_sock);
1109 vmchannel = strdup (buf);
1112 /* New-style -net user,guestfwd=... syntax for guestfwd. See:
1114 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1116 * The original suggested format doesn't work, see:
1118 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01654.html
1120 * However Gerd Hoffman privately suggested to me using -chardev
1121 * instead, which does work.
1123 else if (qemu_supports (g, "-chardev") && qemu_supports (g, "guestfwd")) {
1124 snprintf (buf, sizeof buf,
1125 "socket,id=guestfsvmc,path=%s,server,nowait", unixsock);
1127 add_cmdline (g, "-chardev");
1128 add_cmdline (g, buf);
1130 snprintf (buf, sizeof buf,
1131 "user,vlan=0,net=10.0.2.0/8,"
1132 "guestfwd=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT
1133 "-chardev:guestfsvmc");
1135 add_cmdline (g, "-net");
1136 add_cmdline (g, buf);
1138 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1141 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1142 * syntax, or if not then we'll get a quick failure.
1145 snprintf (buf, sizeof buf,
1146 "channel," GUESTFWD_PORT ":unix:%s,server,nowait", unixsock);
1148 add_cmdline (g, "-net");
1149 add_cmdline (g, buf);
1150 add_cmdline (g, "-net");
1151 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1153 vmchannel = "guestfs_vmchannel=tcp:" GUESTFWD_ADDR ":" GUESTFWD_PORT;
1155 add_cmdline (g, "-net");
1156 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1158 #define LINUX_CMDLINE \
1159 "panic=1 " /* force kernel to panic if daemon exits */ \
1160 "console=ttyS0 " /* serial console */ \
1161 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1162 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1163 "acpi=off " /* we don't need ACPI, turn it off */ \
1164 "printk.time=1 " /* display timestamp before kernel messages */ \
1165 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1167 /* Linux kernel command line. */
1168 snprintf (buf, sizeof buf,
1170 "%s " /* (selinux) */
1171 "%s " /* (vmchannel) */
1172 "%s " /* (verbose) */
1173 "%s", /* (append) */
1174 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
1175 vmchannel ? vmchannel : "",
1176 g->verbose ? "guestfs_verbose=1" : "",
1177 g->append ? g->append : "");
1179 add_cmdline (g, "-kernel");
1180 add_cmdline (g, (char *) kernel);
1181 add_cmdline (g, "-initrd");
1182 add_cmdline (g, (char *) initrd);
1183 add_cmdline (g, "-append");
1184 add_cmdline (g, buf);
1186 /* Finish off the command line. */
1187 incr_cmdline_size (g);
1188 g->cmdline[g->cmdline_size-1] = NULL;
1194 /* Set up stdin, stdout. */
1200 if (dup (wfd[0]) == -1) {
1202 perror ("dup failed");
1205 if (dup (rfd[1]) == -1)
1213 /* Set up a new process group, so we can signal this process
1214 * and all subprocesses (eg. if qemu is really a shell script).
1219 setenv ("LC_ALL", "C", 1);
1221 execv (g->qemu, g->cmdline); /* Run qemu. */
1226 /* Parent (library). */
1234 /* Fork the recovery process off which will kill qemu if the parent
1235 * process fails to do so (eg. if the parent segfaults).
1237 g->recoverypid = -1;
1238 if (g->recovery_proc) {
1241 pid_t qemu_pid = g->pid;
1242 pid_t parent_pid = getppid ();
1244 /* Writing to argv is hideously complicated and error prone. See:
1245 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1248 /* Loop around waiting for one or both of the other processes to
1249 * disappear. It's fair to say this is very hairy. The PIDs that
1250 * we are looking at might be reused by another process. We are
1251 * effectively polling. Is the cure worse than the disease?
1254 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1256 if (kill (parent_pid, 0) == -1) {
1257 /* Parent's gone away, qemu still around, so kill qemu. */
1265 /* Don't worry, if the fork failed, this will be -1. The recovery
1266 * process isn't essential.
1272 /* Close the other ends of the pipe. */
1276 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1277 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1278 perrorf (g, "fcntl");
1282 g->fd[0] = wfd[1]; /* stdin of child */
1283 g->fd[1] = rfd[0]; /* stdout of child */
1285 g->fd[0] = open ("/dev/null", O_RDWR);
1286 if (g->fd[0] == -1) {
1287 perrorf (g, "open /dev/null");
1290 g->fd[1] = dup (g->fd[0]);
1291 if (g->fd[1] == -1) {
1298 if (null_vmchannel_sock) {
1302 /* Null vmchannel implementation: We listen on g->sock for a
1303 * connection. The connection could come from any local process
1304 * so we must check it comes from the appliance (or at least
1305 * from our UID) for security reasons.
1307 while (sock == -1) {
1308 sock = accept_from_daemon (g);
1312 if (check_peer_euid (g, sock, &uid) == -1)
1314 if (uid != geteuid ()) {
1316 "libguestfs: warning: unexpected connection from UID %d to port %d\n",
1317 uid, null_vmchannel_sock);
1323 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
1324 perrorf (g, "fcntl");
1331 /* Other vmchannel. Open the Unix socket.
1333 * The vmchannel implementation that got merged with qemu sucks in
1334 * a number of ways. Both ends do connect(2), which means that no
1335 * one knows what, if anything, is connected to the other end, or
1336 * if it becomes disconnected. Even worse, we have to wait some
1337 * indeterminate time for qemu to create the socket and connect to
1338 * it (which happens very early in qemu's start-up), so any code
1339 * that uses vmchannel is inherently racy. Hence this silly loop.
1341 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1342 if (g->sock == -1) {
1343 perrorf (g, "socket");
1347 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1348 perrorf (g, "fcntl");
1352 addr.sun_family = AF_UNIX;
1353 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1354 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1357 /* Always sleep at least once to give qemu a small chance to start up. */
1360 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1361 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1364 if (errno != ENOENT)
1365 perrorf (g, "connect");
1370 error (g, _("failed to connect to vmchannel socket"));
1376 g->state = LAUNCHING;
1378 /* Wait for qemu to start and to connect back to us via vmchannel and
1379 * send the GUESTFS_LAUNCH_FLAG message.
1383 r = recv_from_daemon (g, &size, &buf);
1386 if (r == -1) return -1;
1388 if (size != GUESTFS_LAUNCH_FLAG) {
1389 error (g, _("guestfs_launch failed, see earlier error messages"));
1393 /* This is possible in some really strange situations, such as
1394 * guestfsd starts up OK but then qemu immediately exits. Check for
1395 * it because the caller is probably expecting to be able to send
1396 * commands after this function returns.
1398 if (g->state != READY) {
1399 error (g, _("qemu launched and contacted daemon, but state != READY"));
1411 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1412 waitpid (g->pid, NULL, 0);
1413 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1418 memset (&g->launch_t, 0, sizeof g->launch_t);
1431 /* This function is used to print the qemu command line before it gets
1432 * executed, when in verbose mode.
1435 print_cmdline (guestfs_h *g)
1440 while (g->cmdline[i]) {
1441 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1442 fprintf (stderr, " \\\n ");
1444 if (i > 0) fputc (' ', stderr);
1446 /* Does it need shell quoting? This only deals with simple cases. */
1447 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1449 if (needs_quote) fputc ('\'', stderr);
1450 fprintf (stderr, "%s", g->cmdline[i]);
1451 if (needs_quote) fputc ('\'', stderr);
1455 fputc ('\n', stderr);
1458 /* This function does the hard work of building the supermin appliance
1459 * on the fly. 'path' is the directory containing the control files.
1460 * 'kernel' and 'initrd' are where we will return the names of the
1461 * kernel and initrd (only initrd is built). The work is done by
1462 * an external script. We just tell it where to put the result.
1465 build_supermin_appliance (guestfs_h *g, const char *path,
1466 char **kernel, char **initrd)
1471 len = strlen (g->tmpdir);
1472 *kernel = safe_malloc (g, len + 8);
1473 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1474 *initrd = safe_malloc (g, len + 8);
1475 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1477 snprintf (cmd, sizeof cmd,
1479 "libguestfs-supermin-helper '%s' %s %s",
1481 path, *kernel, *initrd);
1484 if (r == -1 || WEXITSTATUS(r) != 0) {
1485 error (g, _("external command failed: %s"), cmd);
1488 *kernel = *initrd = NULL;
1495 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1497 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1498 * 'qemu -version' so we know what options this qemu supports and
1502 test_qemu (guestfs_h *g)
1507 free (g->qemu_help);
1508 free (g->qemu_version);
1509 g->qemu_help = NULL;
1510 g->qemu_version = NULL;
1512 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -help", g->qemu);
1514 fp = popen (cmd, "r");
1515 /* qemu -help should always work (qemu -version OTOH wasn't
1516 * supported by qemu 0.9). If this command doesn't work then it
1517 * probably indicates that the qemu binary is missing.
1520 /* XXX This error is never printed, even if the qemu binary
1521 * doesn't exist. Why?
1524 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1528 if (read_all (g, fp, &g->qemu_help) == -1)
1531 if (pclose (fp) == -1)
1534 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -version 2>/dev/null", g->qemu);
1536 fp = popen (cmd, "r");
1538 /* Intentionally ignore errors. */
1539 read_all (g, fp, &g->qemu_version);
1547 read_all (guestfs_h *g, FILE *fp, char **ret)
1554 *ret = safe_realloc (g, *ret, n + 1);
1559 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1561 r = fread (p, 1, BUFSIZ, fp);
1563 perrorf (g, "read");
1570 /* Test if option is supported by qemu command line (just by grepping
1574 qemu_supports (guestfs_h *g, const char *option)
1576 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1579 /* Check the peer effective UID for a TCP socket. Ideally we'd like
1580 * SO_PEERCRED for a loopback TCP socket. This isn't possible on
1581 * Linux (but it is on Solaris!) so we read /proc/net/tcp instead.
1584 check_peer_euid (guestfs_h *g, int sock, uid_t *rtn)
1586 struct sockaddr_in peer;
1587 socklen_t addrlen = sizeof peer;
1589 if (getpeername (sock, (struct sockaddr *) &peer, &addrlen) == -1) {
1590 perrorf (g, "getpeername");
1594 if (peer.sin_family != AF_INET ||
1595 ntohl (peer.sin_addr.s_addr) != INADDR_LOOPBACK) {
1596 error (g, "check_peer_euid: unexpected connection from non-IPv4, non-loopback peer (family = %d, addr = %s)",
1597 peer.sin_family, inet_ntoa (peer.sin_addr));
1601 struct sockaddr_in our;
1602 addrlen = sizeof our;
1603 if (getsockname (sock, (struct sockaddr *) &our, &addrlen) == -1) {
1604 perrorf (g, "getsockname");
1608 FILE *fp = fopen ("/proc/net/tcp", "r");
1610 perrorf (g, "/proc/net/tcp");
1615 if (fgets (line, sizeof line, fp) == NULL) { /* Drop first line. */
1616 error (g, "unexpected end of file in /proc/net/tcp");
1621 while (fgets (line, sizeof line, fp) != NULL) {
1622 unsigned line_our_addr, line_our_port, line_peer_addr, line_peer_port;
1623 int dummy0, dummy1, dummy2, dummy3, dummy4, dummy5, dummy6;
1626 if (sscanf (line, "%d:%08X:%04X %08X:%04X %02X %08X:%08X %02X:%08X %08X %d",
1628 &line_our_addr, &line_our_port,
1629 &line_peer_addr, &line_peer_port,
1630 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, &dummy6,
1632 /* Note about /proc/net/tcp: local_address and rem_address are
1633 * always in network byte order. However the port part is
1634 * always in host byte order.
1636 * The sockname and peername that we got above are in network
1637 * byte order. So we have to byte swap the port but not the
1640 if (line_our_addr == our.sin_addr.s_addr &&
1641 line_our_port == ntohs (our.sin_port) &&
1642 line_peer_addr == peer.sin_addr.s_addr &&
1643 line_peer_port == ntohs (peer.sin_port)) {
1651 error (g, "check_peer_euid: no matching TCP connection found in /proc/net/tcp");
1656 /* You had to call this function after launch in versions <= 1.0.70,
1657 * but it is now a no-op.
1660 guestfs__wait_ready (guestfs_h *g)
1662 if (g->state != READY) {
1663 error (g, _("qemu has not been launched yet"));
1671 guestfs__kill_subprocess (guestfs_h *g)
1673 if (g->state == CONFIG) {
1674 error (g, _("no subprocess to kill"));
1679 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1681 kill (g->pid, SIGTERM);
1682 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1687 /* Access current state. */
1689 guestfs__is_config (guestfs_h *g)
1691 return g->state == CONFIG;
1695 guestfs__is_launching (guestfs_h *g)
1697 return g->state == LAUNCHING;
1701 guestfs__is_ready (guestfs_h *g)
1703 return g->state == READY;
1707 guestfs__is_busy (guestfs_h *g)
1709 return g->state == BUSY;
1713 guestfs__get_state (guestfs_h *g)
1719 guestfs_set_log_message_callback (guestfs_h *g,
1720 guestfs_log_message_cb cb, void *opaque)
1722 g->log_message_cb = cb;
1723 g->log_message_cb_data = opaque;
1727 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1728 guestfs_subprocess_quit_cb cb, void *opaque)
1730 g->subprocess_quit_cb = cb;
1731 g->subprocess_quit_cb_data = opaque;
1735 guestfs_set_launch_done_callback (guestfs_h *g,
1736 guestfs_launch_done_cb cb, void *opaque)
1738 g->launch_done_cb = cb;
1739 g->launch_done_cb_data = opaque;
1742 /*----------------------------------------------------------------------*/
1744 /* This is the code used to send and receive RPC messages and (for
1745 * certain types of message) to perform file transfers. This code is
1746 * driven from the generated actions (src/guestfs-actions.c). There
1747 * are five different cases to consider:
1749 * (1) A non-daemon function. There is no RPC involved at all, it's
1750 * all handled inside the library.
1752 * (2) A simple RPC (eg. "mount"). We write the request, then read
1753 * the reply. The sequence of calls is:
1755 * guestfs___set_busy
1758 * guestfs___end_busy
1760 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1761 * request, then write the file(s), then read the reply. The sequence
1764 * guestfs___set_busy
1766 * guestfs___send_file (possibly multiple times)
1768 * guestfs___end_busy
1770 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1771 * request, then read the reply, then read the file(s). The sequence
1774 * guestfs___set_busy
1777 * guestfs___recv_file (possibly multiple times)
1778 * guestfs___end_busy
1780 * (5) Both FileOut and FileIn parameters. There are no calls like
1781 * this in the current API, but they would be implemented as a
1782 * combination of cases (3) and (4).
1784 * During all writes and reads, we also select(2) on qemu stdout
1785 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1786 * anything received is passed up through the log_message_cb. This is
1787 * also the reason why all the sockets are non-blocking. We also have
1788 * to check for EOF (qemu died). All of this is handled by the
1789 * functions send_to_daemon and recv_from_daemon.
1793 guestfs___set_busy (guestfs_h *g)
1795 if (g->state != READY) {
1796 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1805 guestfs___end_busy (guestfs_h *g)
1819 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1825 /* This is called if we detect EOF, ie. qemu died. */
1827 child_cleanup (guestfs_h *g)
1830 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1832 /*kill (g->pid, SIGTERM);*/
1833 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1834 waitpid (g->pid, NULL, 0);
1835 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1844 memset (&g->launch_t, 0, sizeof g->launch_t);
1846 if (g->subprocess_quit_cb)
1847 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1851 read_log_message_or_eof (guestfs_h *g, int fd)
1859 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1863 /* QEMU's console emulates a 16550A serial port. The real 16550A
1864 * device has a small FIFO buffer (16 bytes) which means here we see
1865 * lots of small reads of 1-16 bytes in length, usually single
1868 n = read (fd, buf, sizeof buf);
1870 /* Hopefully this indicates the qemu child process has died. */
1876 if (errno == EINTR || errno == EAGAIN)
1879 perrorf (g, "read");
1883 /* In verbose mode, copy all log messages to stderr. */
1885 ignore_value (write (STDERR_FILENO, buf, n));
1887 /* It's an actual log message, send it upwards if anyone is listening. */
1888 if (g->log_message_cb)
1889 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1895 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1904 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1907 n = read (fd, buf, 4);
1909 /* Hopefully this indicates the qemu child process has died. */
1915 if (errno == EINTR || errno == EAGAIN)
1918 perrorf (g, "read");
1922 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1923 xdr_uint32_t (&xdr, &flag);
1926 if (flag != GUESTFS_CANCEL_FLAG) {
1927 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1928 flag, GUESTFS_CANCEL_FLAG);
1935 /* This writes the whole N bytes of BUF to the daemon socket.
1937 * If the whole write is successful, it returns 0.
1938 * If there was an error, it returns -1.
1939 * If the daemon sent a cancellation message, it returns -2.
1941 * It also checks qemu stdout for log messages and passes those up
1942 * through log_message_cb.
1944 * It also checks for EOF (qemu died) and passes that up through the
1945 * child_cleanup function above.
1948 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1950 const char *buf = v_buf;
1956 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1961 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1962 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1963 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1965 int max_fd = MAX (g->sock, g->fd[1]);
1970 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1972 if (errno == EINTR || errno == EAGAIN)
1974 perrorf (g, "select");
1978 if (FD_ISSET (g->fd[1], &rset2)) {
1979 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1982 if (FD_ISSET (g->sock, &rset2)) {
1983 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1987 if (FD_ISSET (g->sock, &wset2)) {
1988 r = write (g->sock, buf, n);
1990 if (errno == EINTR || errno == EAGAIN)
1992 perrorf (g, "write");
1993 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
2005 /* This reads a single message, file chunk, launch flag or
2006 * cancellation flag from the daemon. If something was read, it
2007 * returns 0, otherwise -1.
2009 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
2011 * *size_rtn returns the size of the returned message or it may be
2012 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
2014 * *buf_rtn is returned containing the message (if any) or will be set
2015 * to NULL. *buf_rtn must be freed by the caller.
2017 * It also checks qemu stdout for log messages and passes those up
2018 * through log_message_cb.
2020 * It also checks for EOF (qemu died) and passes that up through the
2021 * child_cleanup function above.
2024 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2030 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
2031 g, g->state, size_rtn, buf_rtn);
2035 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2036 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
2038 int max_fd = MAX (g->sock, g->fd[1]);
2044 /* nr is the size of the message, but we prime it as -4 because we
2045 * have to read the message length word first.
2049 while (nr < (ssize_t) *size_rtn) {
2051 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2053 if (errno == EINTR || errno == EAGAIN)
2055 perrorf (g, "select");
2061 if (FD_ISSET (g->fd[1], &rset2)) {
2062 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
2068 if (FD_ISSET (g->sock, &rset2)) {
2069 if (nr < 0) { /* Have we read the message length word yet? */
2070 r = read (g->sock, lenbuf+nr+4, -nr);
2072 if (errno == EINTR || errno == EAGAIN)
2075 perrorf (g, "read");
2076 /* Under some circumstances we see "Connection reset by peer"
2077 * here when the child dies suddenly. Catch this and call
2078 * the cleanup function, same as for EOF.
2080 if (err == ECONNRESET)
2085 error (g, _("unexpected end of file when reading from daemon"));
2091 if (nr < 0) /* Still not got the whole length word. */
2095 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
2096 xdr_uint32_t (&xdr, size_rtn);
2099 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
2100 if (g->state != LAUNCHING)
2101 error (g, _("received magic signature from guestfsd, but in state %d"),
2105 if (g->launch_done_cb)
2106 g->launch_done_cb (g, g->launch_done_cb_data);
2110 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
2112 /* If this happens, it's pretty bad and we've probably lost
2115 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
2116 error (g, _("message length (%u) > maximum possible size (%d)"),
2117 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
2121 /* Allocate the complete buffer, size now known. */
2122 *buf_rtn = safe_malloc (g, *size_rtn);
2126 size_t sizetoread = *size_rtn - nr;
2127 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
2129 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
2131 if (errno == EINTR || errno == EAGAIN)
2133 perrorf (g, "read");
2139 error (g, _("unexpected end of file when reading from daemon"));
2149 /* Got the full message, caller can start processing it. */
2150 #ifdef ENABLE_PACKET_DUMP
2154 for (i = 0; i < nr; i += 16) {
2155 printf ("%04zx: ", i);
2156 for (j = i; j < MIN (i+16, nr); ++j)
2157 printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
2158 for (; j < i+16; ++j)
2161 for (j = i; j < MIN (i+16, nr); ++j)
2162 if (c_isprint ((*(char **)buf_rtn)[j]))
2163 printf ("%c", (*(char **)buf_rtn)[j]);
2166 for (; j < i+16; ++j)
2176 /* This is very much like recv_from_daemon above, but g->sock is
2177 * a listening socket and we are accepting a new connection on
2178 * that socket instead of reading anything. Returns the newly
2182 accept_from_daemon (guestfs_h *g)
2188 "accept_from_daemon: %p g->state = %d\n", g, g->state);
2192 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
2193 FD_SET (g->sock, &rset); /* Read socket for accept. */
2195 int max_fd = MAX (g->sock, g->fd[1]);
2198 while (sock == -1) {
2200 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
2202 if (errno == EINTR || errno == EAGAIN)
2204 perrorf (g, "select");
2208 if (FD_ISSET (g->fd[1], &rset2)) {
2209 if (read_log_message_or_eof (g, g->fd[1]) == -1)
2212 if (FD_ISSET (g->sock, &rset2)) {
2213 sock = accept (g->sock, NULL, NULL);
2215 if (errno == EINTR || errno == EAGAIN)
2217 perrorf (g, "accept");
2227 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
2229 struct guestfs_message_header hdr;
2232 int serial = g->msg_next_serial++;
2235 size_t msg_out_size;
2237 if (g->state != BUSY) {
2238 error (g, _("guestfs___send: state %d != BUSY"), g->state);
2242 /* We have to allocate this message buffer on the heap because
2243 * it is quite large (although will be mostly unused). We
2244 * can't allocate it on the stack because in some environments
2245 * we have quite limited stack space available, notably when
2246 * running in the JVM.
2248 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2249 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2251 /* Serialize the header. */
2252 hdr.prog = GUESTFS_PROGRAM;
2253 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2255 hdr.direction = GUESTFS_DIRECTION_CALL;
2256 hdr.serial = serial;
2257 hdr.status = GUESTFS_STATUS_OK;
2259 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2260 error (g, _("xdr_guestfs_message_header failed"));
2264 /* Serialize the args. If any, because some message types
2265 * have no parameters.
2268 if (!(*xdrp) (&xdr, args)) {
2269 error (g, _("dispatch failed to marshal args"));
2274 /* Get the actual length of the message, resize the buffer to match
2275 * the actual length, and write the length word at the beginning.
2277 len = xdr_getpos (&xdr);
2280 msg_out = safe_realloc (g, msg_out, len + 4);
2281 msg_out_size = len + 4;
2283 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2284 xdr_uint32_t (&xdr, &len);
2287 r = send_to_daemon (g, msg_out, msg_out_size);
2288 if (r == -2) /* Ignore stray daemon cancellations. */
2301 static int cancel = 0; /* XXX Implement file cancellation. */
2302 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2303 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2304 static int send_file_cancellation (guestfs_h *g);
2305 static int send_file_complete (guestfs_h *g);
2311 * -2 daemon cancelled (we must read the error message)
2314 guestfs___send_file (guestfs_h *g, const char *filename)
2316 char buf[GUESTFS_MAX_CHUNK_SIZE];
2319 fd = open (filename, O_RDONLY);
2321 perrorf (g, "open: %s", filename);
2322 send_file_cancellation (g);
2323 /* Daemon sees cancellation and won't reply, so caller can
2329 /* Send file in chunked encoding. */
2331 r = read (fd, buf, sizeof buf);
2332 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2335 err = send_file_data (g, buf, r);
2337 if (err == -2) /* daemon sent cancellation */
2338 send_file_cancellation (g);
2343 if (cancel) { /* cancel from either end */
2344 send_file_cancellation (g);
2349 perrorf (g, "read: %s", filename);
2350 send_file_cancellation (g);
2354 /* End of file, but before we send that, we need to close
2355 * the file and check for errors.
2357 if (close (fd) == -1) {
2358 perrorf (g, "close: %s", filename);
2359 send_file_cancellation (g);
2363 return send_file_complete (g);
2366 /* Send a chunk of file data. */
2368 send_file_data (guestfs_h *g, const char *buf, size_t len)
2370 return send_file_chunk (g, 0, buf, len);
2373 /* Send a cancellation message. */
2375 send_file_cancellation (guestfs_h *g)
2377 return send_file_chunk (g, 1, NULL, 0);
2380 /* Send a file complete chunk. */
2382 send_file_complete (guestfs_h *g)
2385 return send_file_chunk (g, 0, buf, 0);
2389 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2393 guestfs_chunk chunk;
2396 size_t msg_out_size;
2398 if (g->state != BUSY) {
2399 error (g, _("send_file_chunk: state %d != READY"), g->state);
2403 /* Allocate the chunk buffer. Don't use the stack to avoid
2404 * excessive stack usage and unnecessary copies.
2406 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2407 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2409 /* Serialize the chunk. */
2410 chunk.cancel = cancel;
2411 chunk.data.data_len = buflen;
2412 chunk.data.data_val = (char *) buf;
2414 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2415 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2421 len = xdr_getpos (&xdr);
2424 /* Reduce the size of the outgoing message buffer to the real length. */
2425 msg_out = safe_realloc (g, msg_out, len + 4);
2426 msg_out_size = len + 4;
2428 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2429 xdr_uint32_t (&xdr, &len);
2431 r = send_to_daemon (g, msg_out, msg_out_size);
2433 /* Did the daemon send a cancellation message? */
2436 fprintf (stderr, "got daemon cancellation\n");
2452 /* Receive a reply. */
2454 guestfs___recv (guestfs_h *g, const char *fn,
2455 guestfs_message_header *hdr,
2456 guestfs_message_error *err,
2457 xdrproc_t xdrp, char *ret)
2465 r = recv_from_daemon (g, &size, &buf);
2469 /* This can happen if a cancellation happens right at the end
2470 * of us sending a FileIn parameter to the daemon. Discard. The
2471 * daemon should send us an error message next.
2473 if (size == GUESTFS_CANCEL_FLAG)
2476 if (size == GUESTFS_LAUNCH_FLAG) {
2477 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2481 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2483 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2484 error (g, "%s: failed to parse reply header", fn);
2489 if (hdr->status == GUESTFS_STATUS_ERROR) {
2490 if (!xdr_guestfs_message_error (&xdr, err)) {
2491 error (g, "%s: failed to parse reply error", fn);
2497 if (xdrp && ret && !xdrp (&xdr, ret)) {
2498 error (g, "%s: failed to parse reply", fn);
2510 /* Receive a file. */
2512 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2513 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2516 guestfs___recv_file (guestfs_h *g, const char *filename)
2522 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2524 perrorf (g, "open: %s", filename);
2528 /* Receive the file in chunked encoding. */
2529 while ((r = receive_file_data (g, &buf)) > 0) {
2530 if (xwrite (fd, buf, r) == -1) {
2531 perrorf (g, "%s: write", filename);
2539 error (g, _("%s: error in chunked encoding"), filename);
2543 if (close (fd) == -1) {
2544 perrorf (g, "close: %s", filename);
2551 /* Send cancellation message to daemon, then wait until it
2552 * cancels (just throwing away data).
2556 uint32_t flag = GUESTFS_CANCEL_FLAG;
2559 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2562 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2563 xdr_uint32_t (&xdr, &flag);
2566 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2567 perrorf (g, _("write to daemon socket"));
2571 while (receive_file_data (g, NULL) > 0)
2572 ; /* just discard it */
2577 /* Receive a chunk of file data. */
2578 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2580 receive_file_data (guestfs_h *g, void **buf_r)
2586 guestfs_chunk chunk;
2588 r = recv_from_daemon (g, &len, &buf);
2590 error (g, _("receive_file_data: parse error in reply callback"));
2594 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2595 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2599 memset (&chunk, 0, sizeof chunk);
2601 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2602 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2603 error (g, _("failed to parse file chunk"));
2608 /* After decoding, the original buffer is no longer used. */
2612 error (g, _("file receive cancelled by daemon"));
2613 free (chunk.data.data_val);
2617 if (chunk.data.data_len == 0) { /* end of transfer */
2618 free (chunk.data.data_val);
2622 if (buf_r) *buf_r = chunk.data.data_val;
2623 else free (chunk.data.data_val); /* else caller frees */
2625 return chunk.data.data_len;