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 */
33 #include <sys/select.h>
36 #include <rpc/types.h>
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
47 #ifdef HAVE_SYS_WAIT_H
51 #ifdef HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
60 #include "guestfs-internal-actions.h"
61 #include "guestfs_protocol.h"
62 #include "ignore-value.h"
66 #define _(str) dgettext(PACKAGE, (str))
67 //#define N_(str) dgettext(PACKAGE, (str))
73 #define error guestfs_error
74 #define perrorf guestfs_perrorf
75 #define safe_malloc guestfs_safe_malloc
76 #define safe_realloc guestfs_safe_realloc
77 #define safe_strdup guestfs_safe_strdup
78 //#define safe_memdup guestfs_safe_memdup
80 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
81 static int send_to_daemon (guestfs_h *g, const void *v_buf, size_t n);
82 static int recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn);
83 static void close_handles (void);
85 #define UNIX_PATH_MAX 108
87 /* Also in guestfsd.c */
88 #define VMCHANNEL_PORT 6666
89 #define VMCHANNEL_ADDR "10.0.2.4"
91 /* GuestFS handle and connection. */
92 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
96 struct guestfs_h *next; /* Linked list of open handles. */
98 /* State: see the state machine diagram in the man page guestfs(3). */
101 int fd[2]; /* Stdin/stdout of qemu. */
102 int sock; /* Daemon communications socket. */
103 pid_t pid; /* Qemu PID. */
104 pid_t recoverypid; /* Recovery process PID. */
105 time_t start_t; /* The time when we started qemu. */
107 char *tmpdir; /* Temporary directory containing socket. */
109 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
111 char **cmdline; /* Qemu command line. */
118 char *path; /* Path to kernel, initrd. */
119 char *qemu; /* Qemu binary. */
120 char *append; /* Append to kernel command line. */
122 int memsize; /* Size of RAM (megabytes). */
124 int selinux; /* selinux enabled? */
129 guestfs_abort_cb abort_cb;
130 guestfs_error_handler_cb error_cb;
131 void * error_cb_data;
132 guestfs_log_message_cb log_message_cb;
133 void * log_message_cb_data;
134 guestfs_subprocess_quit_cb subprocess_quit_cb;
135 void * subprocess_quit_cb_data;
136 guestfs_launch_done_cb launch_done_cb;
137 void * launch_done_cb_data;
142 static guestfs_h *handles = NULL;
143 static int atexit_handler_set = 0;
146 guestfs_create (void)
151 g = malloc (sizeof (*g));
154 memset (g, 0, sizeof (*g));
163 g->error_cb = default_error_cb;
164 g->error_cb_data = NULL;
166 str = getenv ("LIBGUESTFS_DEBUG");
167 g->verbose = str != NULL && strcmp (str, "1") == 0;
169 str = getenv ("LIBGUESTFS_TRACE");
170 g->trace = str != NULL && strcmp (str, "1") == 0;
172 str = getenv ("LIBGUESTFS_PATH");
173 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
174 if (!g->path) goto error;
176 str = getenv ("LIBGUESTFS_QEMU");
177 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
178 if (!g->qemu) goto error;
180 str = getenv ("LIBGUESTFS_APPEND");
182 g->append = strdup (str);
183 if (!g->append) goto error;
186 /* Choose a suitable memory size. Previously we tried to choose
187 * a minimal memory size, but this isn't really necessary since
188 * recent QEMU and KVM don't do anything nasty like locking
189 * memory into core any more. Thus we can safely choose a
190 * large, generous amount of memory, and it'll just get swapped
191 * on smaller systems.
193 str = getenv ("LIBGUESTFS_MEMSIZE");
195 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
196 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
202 /* Start with large serial numbers so they are easy to spot
203 * inside the protocol.
205 g->msg_next_serial = 0x00123400;
207 /* Link the handles onto a global list. This is the one area
208 * where the library needs to be made thread-safe. (XXX)
210 /* acquire mutex (XXX) */
213 if (!atexit_handler_set) {
214 atexit (close_handles);
215 atexit_handler_set = 1;
217 /* release mutex (XXX) */
220 fprintf (stderr, "new guestfs handle %p\n", g);
233 guestfs_close (guestfs_h *g)
239 if (g->state == NO_HANDLE) {
240 /* Not safe to call 'error' here, so ... */
241 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
246 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
248 /* Try to sync if autosync flag is set. */
249 if (g->autosync && g->state == READY) {
250 guestfs_umount_all (g);
254 /* Remove any handlers that might be called back before we kill the
257 g->log_message_cb = NULL;
259 if (g->state != CONFIG)
260 guestfs_kill_subprocess (g);
273 /* Wait for subprocess(es) to exit. */
274 waitpid (g->pid, NULL, 0);
275 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
277 /* Remove tmpfiles. */
279 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
282 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
285 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
294 for (i = 0; i < g->cmdline_size; ++i)
295 free (g->cmdline[i]);
299 /* Mark the handle as dead before freeing it. */
300 g->state = NO_HANDLE;
302 /* acquire mutex (XXX) */
306 for (gg = handles; gg->next != g; gg = gg->next)
310 /* release mutex (XXX) */
312 free (g->last_error);
317 free (g->qemu_version);
321 /* Close all open handles (called from atexit(3)). */
325 while (handles) guestfs_close (handles);
329 guestfs_last_error (guestfs_h *g)
331 return g->last_error;
335 set_last_error (guestfs_h *g, const char *msg)
337 free (g->last_error);
338 g->last_error = strdup (msg);
342 default_error_cb (guestfs_h *g, void *data, const char *msg)
344 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
348 guestfs_error (guestfs_h *g, const char *fs, ...)
354 int err = vasprintf (&msg, fs, args);
359 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
360 set_last_error (g, msg);
366 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
373 int err = vasprintf (&msg, fs, args);
380 strerror_r (errnum, buf, sizeof buf);
384 buf = strerror_r (errnum, _buf, sizeof _buf);
387 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
391 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
392 set_last_error (g, msg);
398 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
400 void *ptr = malloc (nbytes);
401 if (nbytes > 0 && !ptr) g->abort_cb ();
405 /* Return 1 if an array of N objects, each of size S, cannot exist due
406 to size arithmetic overflow. S must be positive and N must be
407 nonnegative. This is a macro, not an inline function, so that it
408 works correctly even when SIZE_MAX < N.
410 By gnulib convention, SIZE_MAX represents overflow in size
411 calculations, so the conservative dividend to use here is
412 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
413 However, malloc (SIZE_MAX) fails on all known hosts where
414 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
415 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
416 branch when S is known to be 1. */
417 # define xalloc_oversized(n, s) \
418 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
420 /* Technically we should add an autoconf test for this, testing for the desired
421 functionality, like what's done in gnulib, but for now, this is fine. */
422 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
424 /* Allocate zeroed memory for N elements of S bytes, with error
425 checking. S must be nonzero. */
427 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
429 /* From gnulib's calloc function in xmalloc.c. */
431 /* Test for overflow, since some calloc implementations don't have
432 proper overflow checks. But omit overflow and size-zero tests if
433 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
434 returns NULL if successful. */
435 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
436 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
442 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
444 void *p = realloc (ptr, nbytes);
445 if (nbytes > 0 && !p) g->abort_cb ();
450 guestfs_safe_strdup (guestfs_h *g, const char *str)
452 char *s = strdup (str);
453 if (!s) g->abort_cb ();
458 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
460 void *p = malloc (size);
461 if (!p) g->abort_cb ();
462 memcpy (p, ptr, size);
467 xwrite (int fd, const void *v_buf, size_t len)
469 const char *buf = v_buf;
473 r = write (fd, buf, len);
485 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
491 guestfs_get_out_of_memory_handler (guestfs_h *g)
497 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
500 g->error_cb_data = data;
503 guestfs_error_handler_cb
504 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
506 if (data_rtn) *data_rtn = g->error_cb_data;
511 guestfs__set_verbose (guestfs_h *g, int v)
518 guestfs__get_verbose (guestfs_h *g)
524 guestfs__set_autosync (guestfs_h *g, int a)
531 guestfs__get_autosync (guestfs_h *g)
537 guestfs__set_path (guestfs_h *g, const char *path)
544 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
549 guestfs__get_path (guestfs_h *g)
555 guestfs__set_qemu (guestfs_h *g, const char *qemu)
560 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
565 guestfs__get_qemu (guestfs_h *g)
571 guestfs__set_append (guestfs_h *g, const char *append)
576 g->append = append ? safe_strdup (g, append) : NULL;
581 guestfs__get_append (guestfs_h *g)
587 guestfs__set_memsize (guestfs_h *g, int memsize)
589 g->memsize = memsize;
594 guestfs__get_memsize (guestfs_h *g)
600 guestfs__set_selinux (guestfs_h *g, int selinux)
602 g->selinux = selinux;
607 guestfs__get_selinux (guestfs_h *g)
613 guestfs__get_pid (guestfs_h *g)
618 error (g, "get_pid: no qemu subprocess");
623 struct guestfs_version *
624 guestfs__version (guestfs_h *g)
626 struct guestfs_version *r;
628 r = safe_malloc (g, sizeof *r);
629 r->major = PACKAGE_VERSION_MAJOR;
630 r->minor = PACKAGE_VERSION_MINOR;
631 r->release = PACKAGE_VERSION_RELEASE;
632 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
637 guestfs__set_trace (guestfs_h *g, int t)
644 guestfs__get_trace (guestfs_h *g)
649 /* Add a string to the current command line. */
651 incr_cmdline_size (guestfs_h *g)
653 if (g->cmdline == NULL) {
654 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
656 g->cmdline = safe_malloc (g, sizeof (char *));
657 g->cmdline[0] = NULL;
661 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
665 add_cmdline (guestfs_h *g, const char *str)
667 if (g->state != CONFIG) {
669 _("command line cannot be altered after qemu subprocess launched"));
673 incr_cmdline_size (g);
674 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
679 guestfs__config (guestfs_h *g,
680 const char *qemu_param, const char *qemu_value)
682 if (qemu_param[0] != '-') {
683 error (g, _("guestfs_config: parameter must begin with '-' character"));
687 /* A bit fascist, but the user will probably break the extra
688 * parameters that we add if they try to set any of these.
690 if (strcmp (qemu_param, "-kernel") == 0 ||
691 strcmp (qemu_param, "-initrd") == 0 ||
692 strcmp (qemu_param, "-nographic") == 0 ||
693 strcmp (qemu_param, "-serial") == 0 ||
694 strcmp (qemu_param, "-full-screen") == 0 ||
695 strcmp (qemu_param, "-std-vga") == 0 ||
696 strcmp (qemu_param, "-vnc") == 0) {
697 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
701 if (add_cmdline (g, qemu_param) != 0) return -1;
703 if (qemu_value != NULL) {
704 if (add_cmdline (g, qemu_value) != 0) return -1;
711 guestfs__add_drive (guestfs_h *g, const char *filename)
713 size_t len = strlen (filename) + 64;
716 if (strchr (filename, ',') != NULL) {
717 error (g, _("filename cannot contain ',' (comma) character"));
721 /* cache=off improves reliability in the event of a host crash.
723 * However this option causes qemu to try to open the file with
724 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
725 * So we check if we can open the file with or without O_DIRECT,
726 * and use cache=off (or not) accordingly.
728 * This test also checks for the presence of the file, which
729 * is a documented semantic of this interface.
731 int fd = open (filename, O_RDONLY|O_DIRECT);
734 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
736 fd = open (filename, O_RDONLY);
739 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
741 perrorf (g, "%s", filename);
746 return guestfs__config (g, "-drive", buf);
750 guestfs__add_drive_ro (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 if (access (filename, F_OK) == -1) {
761 perrorf (g, "%s", filename);
765 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
767 return guestfs__config (g, "-drive", buf);
771 guestfs__add_cdrom (guestfs_h *g, const char *filename)
773 if (strchr (filename, ',') != NULL) {
774 error (g, _("filename cannot contain ',' (comma) character"));
778 if (access (filename, F_OK) == -1) {
779 perrorf (g, "%s", filename);
783 return guestfs__config (g, "-cdrom", filename);
786 /* Returns true iff file is contained in dir. */
788 dir_contains_file (const char *dir, const char *file)
790 int dirlen = strlen (dir);
791 int filelen = strlen (file);
792 int len = dirlen+filelen+2;
795 snprintf (path, len, "%s/%s", dir, file);
796 return access (path, F_OK) == 0;
799 /* Returns true iff every listed file is contained in 'dir'. */
801 dir_contains_files (const char *dir, ...)
806 va_start (args, dir);
807 while ((file = va_arg (args, const char *)) != NULL) {
808 if (!dir_contains_file (dir, file)) {
817 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
818 static int test_qemu (guestfs_h *g);
819 static int qemu_supports (guestfs_h *g, const char *option);
820 static void print_cmdline (guestfs_h *g);
822 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
823 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
824 static const char *supermin_name =
825 "initramfs." REPO "." host_cpu ".supermin.img";
826 static const char *supermin_hostfiles_name =
827 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
830 guestfs__launch (guestfs_h *g)
833 char dir_template[PATH_MAX];
838 char *path, *pelem, *pend;
839 char *kernel = NULL, *initrd = NULL;
841 struct sockaddr_un addr;
849 tmpdir = getenv ("TMPDIR") ? : tmpdir;
850 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
854 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
858 if (g->state != CONFIG) {
859 error (g, _("qemu has already been launched"));
863 /* Make the temporary directory. */
865 g->tmpdir = safe_strdup (g, dir_template);
866 if (mkdtemp (g->tmpdir) == NULL) {
867 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
872 /* First search g->path for the supermin appliance, and try to
873 * synthesize a kernel and initrd from that. If it fails, we
874 * try the path search again looking for a backup ordinary
877 pelem = path = safe_strdup (g, g->path);
879 pend = strchrnul (pelem, ':');
880 pmore = *pend == ':';
884 /* Empty element of "." means cwd. */
885 if (len == 0 || (len == 1 && *pelem == '.')) {
888 "looking for supermin appliance in current directory\n");
889 if (dir_contains_files (".",
890 supermin_name, supermin_hostfiles_name,
891 "kmod.whitelist", NULL)) {
892 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
897 /* Look at <path>/supermin* etc. */
900 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
902 if (dir_contains_files (pelem,
903 supermin_name, supermin_hostfiles_name,
904 "kmod.whitelist", NULL)) {
905 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
916 if (kernel == NULL || initrd == NULL) {
917 /* Search g->path for the kernel and initrd. */
918 pelem = path = safe_strdup (g, g->path);
920 pend = strchrnul (pelem, ':');
921 pmore = *pend == ':';
925 /* Empty element or "." means cwd. */
926 if (len == 0 || (len == 1 && *pelem == '.')) {
929 "looking for appliance in current directory\n");
930 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
931 kernel = safe_strdup (g, kernel_name);
932 initrd = safe_strdup (g, initrd_name);
936 /* Look at <path>/kernel etc. */
939 fprintf (stderr, "looking for appliance in %s\n", pelem);
941 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
942 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
943 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
944 sprintf (kernel, "%s/%s", pelem, kernel_name);
945 sprintf (initrd, "%s/%s", pelem, initrd_name);
956 if (kernel == NULL || initrd == NULL) {
957 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
958 kernel_name, initrd_name, g->path);
962 /* Get qemu help text and version. */
963 if (test_qemu (g) == -1)
966 /* Make the vmchannel socket. */
967 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
970 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
985 if (r == 0) { /* Child (qemu). */
988 char memsize_str[256];
990 /* Set up the full command line. Do this in the subprocess so we
991 * don't need to worry about cleaning up.
993 g->cmdline[0] = g->qemu;
995 #define LINUX_CMDLINE \
996 "panic=1 " /* force kernel to panic if daemon exits */ \
997 "console=ttyS0 " /* serial console */ \
998 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
999 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1000 "acpi=off " /* we don't need ACPI, turn it off */ \
1001 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1003 /* Linux kernel command line. */
1004 snprintf (append, sizeof append,
1007 "%s" /* (selinux) */
1008 "%s" /* (verbose) */
1009 "%s", /* (append) */
1010 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1011 g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1012 g->verbose ? "guestfs_verbose=1 " : " ",
1013 g->append ? g->append : "");
1015 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1017 add_cmdline (g, "-m");
1018 add_cmdline (g, memsize_str);
1019 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1020 add_cmdline (g, "-kernel");
1021 add_cmdline (g, (char *) kernel);
1022 add_cmdline (g, "-initrd");
1023 add_cmdline (g, (char *) initrd);
1024 add_cmdline (g, "-append");
1025 add_cmdline (g, append);
1026 add_cmdline (g, "-nographic");
1027 add_cmdline (g, "-serial");
1028 add_cmdline (g, "stdio");
1031 /* Doesn't work. See:
1032 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1033 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1035 if (qemu_supports (g, "guestfwd")) {
1036 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1037 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1039 snprintf (vmchannel, sizeof vmchannel,
1040 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1041 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1043 add_cmdline (g, "-net");
1044 add_cmdline (g, vmchannel);
1047 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1048 * syntax, or if not then we'll get a quick failure.
1050 snprintf (vmchannel, sizeof vmchannel,
1051 "channel,%d:unix:%s,server,nowait",
1052 VMCHANNEL_PORT, unixsock);
1054 add_cmdline (g, "-net");
1055 add_cmdline (g, vmchannel);
1056 add_cmdline (g, "-net");
1057 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1061 add_cmdline (g, "-net");
1062 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1064 /* These options recommended by KVM developers to improve reliability. */
1065 if (qemu_supports (g, "-no-hpet"))
1066 add_cmdline (g, "-no-hpet");
1068 if (qemu_supports (g, "-rtc-td-hack"))
1069 add_cmdline (g, "-rtc-td-hack");
1071 /* Finish off the command line. */
1072 incr_cmdline_size (g);
1073 g->cmdline[g->cmdline_size-1] = NULL;
1078 /* Set up stdin, stdout. */
1084 if (dup (wfd[0]) == -1) {
1086 perror ("dup failed");
1089 if (dup (rfd[1]) == -1)
1096 /* Set up a new process group, so we can signal this process
1097 * and all subprocesses (eg. if qemu is really a shell script).
1102 execv (g->qemu, g->cmdline); /* Run qemu. */
1107 /* Parent (library). */
1115 /* Fork the recovery process off which will kill qemu if the parent
1116 * process fails to do so (eg. if the parent segfaults).
1120 pid_t qemu_pid = g->pid;
1121 pid_t parent_pid = getppid ();
1123 /* Writing to argv is hideously complicated and error prone. See:
1124 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1127 /* Loop around waiting for one or both of the other processes to
1128 * disappear. It's fair to say this is very hairy. The PIDs that
1129 * we are looking at might be reused by another process. We are
1130 * effectively polling. Is the cure worse than the disease?
1133 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1135 if (kill (parent_pid, 0) == -1) {
1136 /* Parent's gone away, qemu still around, so kill qemu. */
1144 /* Don't worry, if the fork failed, this will be -1. The recovery
1145 * process isn't essential.
1149 /* Start the clock ... */
1152 /* Close the other ends of the pipe. */
1156 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1157 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1158 perrorf (g, "fcntl");
1162 g->fd[0] = wfd[1]; /* stdin of child */
1163 g->fd[1] = rfd[0]; /* stdout of child */
1165 /* Open the Unix socket. The vmchannel implementation that got
1166 * merged with qemu sucks in a number of ways. Both ends do
1167 * connect(2), which means that no one knows what, if anything, is
1168 * connected to the other end, or if it becomes disconnected. Even
1169 * worse, we have to wait some indeterminate time for qemu to create
1170 * the socket and connect to it (which happens very early in qemu's
1171 * start-up), so any code that uses vmchannel is inherently racy.
1172 * Hence this silly loop.
1174 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1175 if (g->sock == -1) {
1176 perrorf (g, "socket");
1180 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1181 perrorf (g, "fcntl");
1185 addr.sun_family = AF_UNIX;
1186 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1187 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1190 /* Always sleep at least once to give qemu a small chance to start up. */
1193 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1194 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1197 if (errno != ENOENT)
1198 perrorf (g, "connect");
1203 error (g, _("failed to connect to vmchannel socket"));
1207 g->state = LAUNCHING;
1217 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1218 waitpid (g->pid, NULL, 0);
1219 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1233 /* This function is used to print the qemu command line before it gets
1234 * executed, when in verbose mode.
1237 print_cmdline (guestfs_h *g)
1242 while (g->cmdline[i]) {
1243 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1244 fprintf (stderr, " \\\n ");
1246 if (i > 0) fputc (' ', stderr);
1248 /* Does it need shell quoting? This only deals with simple cases. */
1249 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1251 if (needs_quote) fputc ('\'', stderr);
1252 fprintf (stderr, "%s", g->cmdline[i]);
1253 if (needs_quote) fputc ('\'', stderr);
1257 fputc ('\n', stderr);
1260 /* This function does the hard work of building the supermin appliance
1261 * on the fly. 'path' is the directory containing the control files.
1262 * 'kernel' and 'initrd' are where we will return the names of the
1263 * kernel and initrd (only initrd is built). The work is done by
1264 * an external script. We just tell it where to put the result.
1267 build_supermin_appliance (guestfs_h *g, const char *path,
1268 char **kernel, char **initrd)
1273 len = strlen (g->tmpdir);
1274 *kernel = safe_malloc (g, len + 8);
1275 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1276 *initrd = safe_malloc (g, len + 8);
1277 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1279 snprintf (cmd, sizeof cmd,
1281 "libguestfs-supermin-helper '%s' %s %s",
1283 path, *kernel, *initrd);
1286 if (r == -1 || WEXITSTATUS(r) != 0) {
1287 error (g, _("external command failed: %s"), cmd);
1290 *kernel = *initrd = NULL;
1297 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1299 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1300 * 'qemu -version' so we know what options this qemu supports and
1304 test_qemu (guestfs_h *g)
1309 free (g->qemu_help);
1310 free (g->qemu_version);
1311 g->qemu_help = NULL;
1312 g->qemu_version = NULL;
1314 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1316 fp = popen (cmd, "r");
1317 /* qemu -help should always work (qemu -version OTOH wasn't
1318 * supported by qemu 0.9). If this command doesn't work then it
1319 * probably indicates that the qemu binary is missing.
1322 /* XXX This error is never printed, even if the qemu binary
1323 * doesn't exist. Why?
1326 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1330 if (read_all (g, fp, &g->qemu_help) == -1)
1333 if (pclose (fp) == -1)
1336 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1338 fp = popen (cmd, "r");
1340 /* Intentionally ignore errors. */
1341 read_all (g, fp, &g->qemu_version);
1349 read_all (guestfs_h *g, FILE *fp, char **ret)
1356 *ret = safe_realloc (g, *ret, n + 1);
1361 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1363 r = fread (p, 1, BUFSIZ, fp);
1365 perrorf (g, "read");
1372 /* Test if option is supported by qemu command line (just by grepping
1376 qemu_supports (guestfs_h *g, const char *option)
1378 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1382 guestfs__wait_ready (guestfs_h *g)
1388 if (g->state == READY) return 0;
1390 if (g->state == BUSY) {
1391 error (g, _("qemu has finished launching already"));
1395 if (g->state != LAUNCHING) {
1396 error (g, _("qemu has not been launched yet"));
1400 r = recv_from_daemon (g, &size, &buf);
1403 if (r == -1) return -1;
1405 if (size != GUESTFS_LAUNCH_FLAG) {
1406 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1410 /* This is possible in some really strange situations, such as
1411 * guestfsd starts up OK but then qemu immediately exits. Check for
1412 * it because the caller is probably expecting to be able to send
1413 * commands after this function returns.
1415 if (g->state != READY) {
1416 error (g, _("qemu launched and contacted daemon, but state != READY"));
1424 guestfs__kill_subprocess (guestfs_h *g)
1426 if (g->state == CONFIG) {
1427 error (g, _("no subprocess to kill"));
1432 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1434 kill (g->pid, SIGTERM);
1435 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1440 /* Access current state. */
1442 guestfs__is_config (guestfs_h *g)
1444 return g->state == CONFIG;
1448 guestfs__is_launching (guestfs_h *g)
1450 return g->state == LAUNCHING;
1454 guestfs__is_ready (guestfs_h *g)
1456 return g->state == READY;
1460 guestfs__is_busy (guestfs_h *g)
1462 return g->state == BUSY;
1466 guestfs__get_state (guestfs_h *g)
1472 guestfs_set_log_message_callback (guestfs_h *g,
1473 guestfs_log_message_cb cb, void *opaque)
1475 g->log_message_cb = cb;
1476 g->log_message_cb_data = opaque;
1480 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1481 guestfs_subprocess_quit_cb cb, void *opaque)
1483 g->subprocess_quit_cb = cb;
1484 g->subprocess_quit_cb_data = opaque;
1488 guestfs_set_launch_done_callback (guestfs_h *g,
1489 guestfs_launch_done_cb cb, void *opaque)
1491 g->launch_done_cb = cb;
1492 g->launch_done_cb_data = opaque;
1495 /*----------------------------------------------------------------------*/
1497 /* This is the code used to send and receive RPC messages and (for
1498 * certain types of message) to perform file transfers. This code is
1499 * driven from the generated actions (src/guestfs-actions.c). There
1500 * are five different cases to consider:
1502 * (1) A non-daemon function. There is no RPC involved at all, it's
1503 * all handled inside the library.
1505 * (2) A simple RPC (eg. "mount"). We write the request, then read
1506 * the reply. The sequence of calls is:
1508 * guestfs___set_busy
1511 * guestfs___end_busy
1513 * (3) An RPC with FileOut parameters (eg. "upload"). We write the
1514 * request, then write the file(s), then read the reply. The sequence
1517 * guestfs___set_busy
1519 * guestfs___send_file (possibly multiple times)
1521 * guestfs___end_busy
1523 * (4) An RPC with FileIn parameters (eg. "download"). We write the
1524 * request, then read the reply, then read the file(s). The sequence
1527 * guestfs___set_busy
1530 * guestfs___recv_file (possibly multiple times)
1531 * guestfs___end_busy
1533 * (5) Both FileOut and FileIn parameters. There are no calls like
1534 * this in the current API, but they would be implemented as a
1535 * combination of cases (3) and (4).
1537 * During all writes and reads, we also select(2) on qemu stdout
1538 * looking for messages (guestfsd stderr and guest kernel dmesg), and
1539 * anything received is passed up through the log_message_cb. This is
1540 * also the reason why all the sockets are non-blocking. We also have
1541 * to check for EOF (qemu died). All of this is handled by the
1542 * functions send_to_daemon and recv_from_daemon.
1546 guestfs___set_busy (guestfs_h *g)
1548 if (g->state != READY) {
1549 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1558 guestfs___end_busy (guestfs_h *g)
1572 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1578 /* This is called if we detect EOF, ie. qemu died. */
1580 child_cleanup (guestfs_h *g)
1583 fprintf (stderr, "child_cleanup: %p: child process died\n", g);
1585 /*kill (g->pid, SIGTERM);*/
1586 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1587 waitpid (g->pid, NULL, 0);
1588 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1599 if (g->subprocess_quit_cb)
1600 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1604 read_log_message_or_eof (guestfs_h *g, int fd)
1612 "read_log_message_or_eof: %p g->state = %d, fd = %d\n",
1616 /* QEMU's console emulates a 16550A serial port. The real 16550A
1617 * device has a small FIFO buffer (16 bytes) which means here we see
1618 * lots of small reads of 1-16 bytes in length, usually single
1621 n = read (fd, buf, sizeof buf);
1623 /* Hopefully this indicates the qemu child process has died. */
1629 if (errno == EINTR || errno == EAGAIN)
1632 perrorf (g, "read");
1636 /* In verbose mode, copy all log messages to stderr. */
1638 ignore_value (write (STDERR_FILENO, buf, n));
1640 /* It's an actual log message, send it upwards if anyone is listening. */
1641 if (g->log_message_cb)
1642 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1648 check_for_daemon_cancellation_or_eof (guestfs_h *g, int fd)
1657 "check_for_daemon_cancellation_or_eof: %p g->state = %d, fd = %d\n",
1660 n = read (fd, buf, 4);
1662 /* Hopefully this indicates the qemu child process has died. */
1668 if (errno == EINTR || errno == EAGAIN)
1671 perrorf (g, "read");
1675 xdrmem_create (&xdr, buf, 4, XDR_DECODE);
1676 xdr_uint32_t (&xdr, &flag);
1679 if (flag != GUESTFS_CANCEL_FLAG) {
1680 error (g, _("check_for_daemon_cancellation_or_eof: read 0x%x from daemon, expected 0x%x\n"),
1681 flag, GUESTFS_CANCEL_FLAG);
1688 /* This writes the whole N bytes of BUF to the daemon socket.
1690 * If the whole write is successful, it returns 0.
1691 * If there was an error, it returns -1.
1692 * If the daemon sent a cancellation message, it returns -2.
1694 * It also checks qemu stdout for log messages and passes those up
1695 * through log_message_cb.
1697 * It also checks for EOF (qemu died) and passes that up through the
1698 * child_cleanup function above.
1701 send_to_daemon (guestfs_h *g, const void *v_buf, size_t n)
1703 const char *buf = v_buf;
1709 "send_to_daemon: %p g->state = %d, n = %zu\n", g, g->state, n);
1714 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1715 FD_SET (g->sock, &rset); /* Read socket for cancellation & EOF. */
1716 FD_SET (g->sock, &wset); /* Write to socket to send the data. */
1718 int max_fd = g->sock > g->fd[1] ? g->sock : g->fd[1];
1723 int r = select (max_fd+1, &rset2, &wset2, NULL, NULL);
1725 if (errno == EINTR || errno == EAGAIN)
1727 perrorf (g, "select");
1731 if (FD_ISSET (g->fd[1], &rset2)) {
1732 if (read_log_message_or_eof (g, g->fd[1]) == -1)
1735 if (FD_ISSET (g->sock, &rset2)) {
1736 r = check_for_daemon_cancellation_or_eof (g, g->sock);
1740 if (FD_ISSET (g->sock, &wset2)) {
1741 r = write (g->sock, buf, n);
1743 if (errno == EINTR || errno == EAGAIN)
1745 perrorf (g, "write");
1746 if (errno == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1758 /* This reads a single message, file chunk, launch flag or
1759 * cancellation flag from the daemon. If something was read, it
1760 * returns 0, otherwise -1.
1762 * Both size_rtn and buf_rtn must be passed by the caller as non-NULL.
1764 * *size_rtn returns the size of the returned message or it may be
1765 * GUESTFS_LAUNCH_FLAG or GUESTFS_CANCEL_FLAG.
1767 * *buf_rtn is returned containing the message (if any) or will be set
1768 * to NULL. *buf_rtn must be freed by the caller.
1770 * It also checks qemu stdout for log messages and passes those up
1771 * through log_message_cb.
1773 * It also checks for EOF (qemu died) and passes that up through the
1774 * child_cleanup function above.
1777 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
1783 "recv_from_daemon: %p g->state = %d, size_rtn = %p, buf_rtn = %p\n",
1784 g, g->state, size_rtn, buf_rtn);
1788 FD_SET (g->fd[1], &rset); /* Read qemu stdout for log messages & EOF. */
1789 FD_SET (g->sock, &rset); /* Read socket for data & EOF. */
1791 int max_fd = g->sock > g->fd[1] ? g->sock : g->fd[1];
1797 /* nr is the size of the message, but we prime it as -4 because we
1798 * have to read the message length word first.
1802 while (nr < (ssize_t) *size_rtn) {
1804 int r = select (max_fd+1, &rset2, NULL, NULL, NULL);
1806 if (errno == EINTR || errno == EAGAIN)
1808 perrorf (g, "select");
1814 if (FD_ISSET (g->fd[1], &rset2)) {
1815 if (read_log_message_or_eof (g, g->fd[1]) == -1) {
1821 if (FD_ISSET (g->sock, &rset2)) {
1822 if (nr < 0) { /* Have we read the message length word yet? */
1823 r = read (g->sock, lenbuf+nr+4, -nr);
1825 if (errno == EINTR || errno == EAGAIN)
1828 perrorf (g, "read");
1829 /* Under some circumstances we see "Connection reset by peer"
1830 * here when the child dies suddenly. Catch this and call
1831 * the cleanup function, same as for EOF.
1833 if (err == ECONNRESET)
1838 error (g, _("unexpected end of file when reading from daemon"));
1844 if (nr < 0) /* Still not got the whole length word. */
1848 xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
1849 xdr_uint32_t (&xdr, size_rtn);
1852 if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
1853 if (g->state != LAUNCHING)
1854 error (g, _("received magic signature from guestfsd, but in state %d"),
1858 if (g->launch_done_cb)
1859 g->launch_done_cb (g, g->launch_done_cb_data);
1863 else if (*size_rtn == GUESTFS_CANCEL_FLAG)
1865 /* If this happens, it's pretty bad and we've probably lost
1868 else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
1869 error (g, _("message length (%u) > maximum possible size (%d)"),
1870 (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
1874 /* Allocate the complete buffer, size now known. */
1875 *buf_rtn = safe_malloc (g, *size_rtn);
1879 size_t sizetoread = *size_rtn - nr;
1880 if (sizetoread > BUFSIZ) sizetoread = BUFSIZ;
1882 r = read (g->sock, (char *) (*buf_rtn) + nr, sizetoread);
1884 if (errno == EINTR || errno == EAGAIN)
1886 perrorf (g, "read");
1892 error (g, _("unexpected end of file when reading from daemon"));
1902 /* Got the full message, caller can start processing it. */
1907 for (i = 0; i < nr; i += 16) {
1908 printf ("%04x: ", i);
1909 for (j = i; j < MIN (i+16, nr); ++j)
1910 printf ("%02x ", (unsigned char) (*buf_rtn)[j]);
1911 for (; j < i+16; ++j)
1914 for (j = i; j < MIN (i+16, g->nr); ++j)
1915 if (isprint ((*buf_rtn)[j]))
1916 printf ("%c", (*buf_rtn)[j]);
1919 for (; j < i+16; ++j)
1930 guestfs___send (guestfs_h *g, int proc_nr, xdrproc_t xdrp, char *args)
1932 struct guestfs_message_header hdr;
1935 int serial = g->msg_next_serial++;
1938 size_t msg_out_size;
1940 if (g->state != BUSY) {
1941 error (g, _("guestfs___send: state %d != BUSY"), g->state);
1945 /* We have to allocate this message buffer on the heap because
1946 * it is quite large (although will be mostly unused). We
1947 * can't allocate it on the stack because in some environments
1948 * we have quite limited stack space available, notably when
1949 * running in the JVM.
1951 msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
1952 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
1954 /* Serialize the header. */
1955 hdr.prog = GUESTFS_PROGRAM;
1956 hdr.vers = GUESTFS_PROTOCOL_VERSION;
1958 hdr.direction = GUESTFS_DIRECTION_CALL;
1959 hdr.serial = serial;
1960 hdr.status = GUESTFS_STATUS_OK;
1962 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
1963 error (g, _("xdr_guestfs_message_header failed"));
1967 /* Serialize the args. If any, because some message types
1968 * have no parameters.
1971 if (!(*xdrp) (&xdr, args)) {
1972 error (g, _("dispatch failed to marshal args"));
1977 /* Get the actual length of the message, resize the buffer to match
1978 * the actual length, and write the length word at the beginning.
1980 len = xdr_getpos (&xdr);
1983 msg_out = safe_realloc (g, msg_out, len + 4);
1984 msg_out_size = len + 4;
1986 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
1987 xdr_uint32_t (&xdr, &len);
1990 r = send_to_daemon (g, msg_out, msg_out_size);
1991 if (r == -2) /* Ignore stray daemon cancellations. */
2004 static int cancel = 0; /* XXX Implement file cancellation. */
2005 static int send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t len);
2006 static int send_file_data (guestfs_h *g, const char *buf, size_t len);
2007 static int send_file_cancellation (guestfs_h *g);
2008 static int send_file_complete (guestfs_h *g);
2014 * -2 daemon cancelled (we must read the error message)
2017 guestfs___send_file (guestfs_h *g, const char *filename)
2019 char buf[GUESTFS_MAX_CHUNK_SIZE];
2022 fd = open (filename, O_RDONLY);
2024 perrorf (g, "open: %s", filename);
2025 send_file_cancellation (g);
2026 /* Daemon sees cancellation and won't reply, so caller can
2032 /* Send file in chunked encoding. */
2034 r = read (fd, buf, sizeof buf);
2035 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2038 err = send_file_data (g, buf, r);
2040 if (err == -2) /* daemon sent cancellation */
2041 send_file_cancellation (g);
2046 if (cancel) { /* cancel from either end */
2047 send_file_cancellation (g);
2052 perrorf (g, "read: %s", filename);
2053 send_file_cancellation (g);
2057 /* End of file, but before we send that, we need to close
2058 * the file and check for errors.
2060 if (close (fd) == -1) {
2061 perrorf (g, "close: %s", filename);
2062 send_file_cancellation (g);
2066 return send_file_complete (g);
2069 /* Send a chunk of file data. */
2071 send_file_data (guestfs_h *g, const char *buf, size_t len)
2073 return send_file_chunk (g, 0, buf, len);
2076 /* Send a cancellation message. */
2078 send_file_cancellation (guestfs_h *g)
2080 return send_file_chunk (g, 1, NULL, 0);
2083 /* Send a file complete chunk. */
2085 send_file_complete (guestfs_h *g)
2088 return send_file_chunk (g, 0, buf, 0);
2092 send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2096 guestfs_chunk chunk;
2099 size_t msg_out_size;
2101 if (g->state != BUSY) {
2102 error (g, _("send_file_chunk: state %d != READY"), g->state);
2106 /* Allocate the chunk buffer. Don't use the stack to avoid
2107 * excessive stack usage and unnecessary copies.
2109 msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2110 xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2112 /* Serialize the chunk. */
2113 chunk.cancel = cancel;
2114 chunk.data.data_len = buflen;
2115 chunk.data.data_val = (char *) buf;
2117 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2118 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2124 len = xdr_getpos (&xdr);
2127 /* Reduce the size of the outgoing message buffer to the real length. */
2128 msg_out = safe_realloc (g, msg_out, len + 4);
2129 msg_out_size = len + 4;
2131 xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
2132 xdr_uint32_t (&xdr, &len);
2134 r = send_to_daemon (g, msg_out, msg_out_size);
2136 /* Did the daemon send a cancellation message? */
2139 fprintf (stderr, "got daemon cancellation\n");
2155 /* Receive a reply. */
2157 guestfs___recv (guestfs_h *g, const char *fn,
2158 guestfs_message_header *hdr,
2159 guestfs_message_error *err,
2160 xdrproc_t xdrp, char *ret)
2168 r = recv_from_daemon (g, &size, &buf);
2172 /* This can happen if a cancellation happens right at the end
2173 * of us sending a FileIn parameter to the daemon. Discard. The
2174 * daemon should send us an error message next.
2176 if (size == GUESTFS_CANCEL_FLAG)
2179 if (size == GUESTFS_LAUNCH_FLAG) {
2180 error (g, "%s: received unexpected launch flag from daemon when expecting reply", fn);
2184 xdrmem_create (&xdr, buf, size, XDR_DECODE);
2186 if (!xdr_guestfs_message_header (&xdr, hdr)) {
2187 error (g, "%s: failed to parse reply header", fn);
2192 if (hdr->status == GUESTFS_STATUS_ERROR) {
2193 if (!xdr_guestfs_message_error (&xdr, err)) {
2194 error (g, "%s: failed to parse reply error", fn);
2200 if (xdrp && ret && !xdrp (&xdr, ret)) {
2201 error (g, "%s: failed to parse reply", fn);
2213 /* Receive a file. */
2215 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2216 static ssize_t receive_file_data (guestfs_h *g, void **buf);
2219 guestfs___recv_file (guestfs_h *g, const char *filename)
2225 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2227 perrorf (g, "open: %s", filename);
2231 /* Receive the file in chunked encoding. */
2232 while ((r = receive_file_data (g, &buf)) > 0) {
2233 if (xwrite (fd, buf, r) == -1) {
2234 perrorf (g, "%s: write", filename);
2242 error (g, _("%s: error in chunked encoding"), filename);
2246 if (close (fd) == -1) {
2247 perrorf (g, "close: %s", filename);
2254 /* Send cancellation message to daemon, then wait until it
2255 * cancels (just throwing away data).
2259 uint32_t flag = GUESTFS_CANCEL_FLAG;
2262 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2265 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2266 xdr_uint32_t (&xdr, &flag);
2269 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2270 perrorf (g, _("write to daemon socket"));
2274 while (receive_file_data (g, NULL) > 0)
2275 ; /* just discard it */
2280 /* Receive a chunk of file data. */
2281 /* Returns -1 = error, 0 = EOF, > 0 = more data */
2283 receive_file_data (guestfs_h *g, void **buf_r)
2289 guestfs_chunk chunk;
2291 r = recv_from_daemon (g, &len, &buf);
2293 error (g, _("receive_file_data: parse error in reply callback"));
2297 if (len == GUESTFS_LAUNCH_FLAG || len == GUESTFS_CANCEL_FLAG) {
2298 error (g, _("receive_file_data: unexpected flag received when reading file chunks"));
2302 memset (&chunk, 0, sizeof chunk);
2304 xdrmem_create (&xdr, buf, len, XDR_DECODE);
2305 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2306 error (g, _("failed to parse file chunk"));
2311 /* After decoding, the original buffer is no longer used. */
2315 error (g, _("file receive cancelled by daemon"));
2316 free (chunk.data.data_val);
2320 if (chunk.data.data_len == 0) { /* end of transfer */
2321 free (chunk.data.data_val);
2325 if (buf_r) *buf_r = chunk.data.data_val;
2326 else free (chunk.data.data_val); /* else caller frees */
2328 return chunk.data.data_len;