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 */
22 #define _GNU_SOURCE /* for vasprintf, GNU strerror_r, strchrnul */
34 #include <sys/select.h>
37 #include <rpc/types.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
48 #ifdef HAVE_SYS_WAIT_H
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
61 #include "guestfs_protocol.h"
65 #define _(str) dgettext(PACKAGE, (str))
66 #define N_(str) dgettext(PACKAGE, (str))
72 #define error guestfs_error
73 #define perrorf guestfs_perrorf
74 #define safe_malloc guestfs_safe_malloc
75 #define safe_realloc guestfs_safe_realloc
76 #define safe_strdup guestfs_safe_strdup
77 #define safe_memdup guestfs_safe_memdup
79 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
80 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
81 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
82 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
84 static void close_handles (void);
86 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
87 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
88 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
89 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
90 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
91 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
93 /* Default select-based main loop. */
94 struct select_handle_cb_data {
95 guestfs_handle_event_cb cb;
100 struct select_main_loop {
101 /* NB. These fields must be the same as in struct guestfs_main_loop: */
102 guestfs_add_handle_cb add_handle;
103 guestfs_remove_handle_cb remove_handle;
104 guestfs_add_timeout_cb add_timeout;
105 guestfs_remove_timeout_cb remove_timeout;
106 guestfs_main_loop_run_cb main_loop_run;
107 guestfs_main_loop_quit_cb main_loop_quit;
109 /* Additional private data: */
118 struct select_handle_cb_data *handle_cb_data;
121 /* Default main loop. */
122 static struct select_main_loop default_main_loop = {
123 .add_handle = select_add_handle,
124 .remove_handle = select_remove_handle,
125 .add_timeout = select_add_timeout,
126 .remove_timeout = select_remove_timeout,
127 .main_loop_run = select_main_loop_run,
128 .main_loop_quit = select_main_loop_quit,
130 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
131 * set by the normal action of everything being initialized to zero.
136 .handle_cb_data = NULL,
139 #define UNIX_PATH_MAX 108
141 /* Also in guestfsd.c */
142 #define VMCHANNEL_PORT 6666
143 #define VMCHANNEL_ADDR "10.0.2.4"
145 /* GuestFS handle and connection. */
146 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
150 struct guestfs_h *next; /* Linked list of open handles. */
152 /* State: see the state machine diagram in the man page guestfs(3). */
155 int fd[2]; /* Stdin/stdout of qemu. */
156 int sock; /* Daemon communications socket. */
157 pid_t pid; /* Qemu PID. */
158 pid_t recoverypid; /* Recovery process PID. */
159 time_t start_t; /* The time when we started qemu. */
161 int stdout_watch; /* Watches qemu stdout for log messages. */
162 int sock_watch; /* Watches daemon comm socket. */
164 char *tmpdir; /* Temporary directory containing socket. */
166 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
168 char **cmdline; /* Qemu command line. */
174 char *path; /* Path to kernel, initrd. */
175 char *qemu; /* Qemu binary. */
176 char *append; /* Append to kernel command line. */
178 int memsize; /* Size of RAM (megabytes). */
180 int selinux; /* selinux enabled? */
185 guestfs_abort_cb abort_cb;
186 guestfs_error_handler_cb error_cb;
187 void * error_cb_data;
188 guestfs_send_cb send_cb;
190 guestfs_reply_cb reply_cb;
191 void * reply_cb_data;
192 guestfs_log_message_cb log_message_cb;
193 void * log_message_cb_data;
194 guestfs_subprocess_quit_cb subprocess_quit_cb;
195 void * subprocess_quit_cb_data;
196 guestfs_launch_done_cb launch_done_cb;
197 void * launch_done_cb_data;
199 /* Main loop used by this handle. */
200 guestfs_main_loop *main_loop;
202 /* Messages sent and received from the daemon. */
204 int msg_in_size, msg_in_allocated;
206 int msg_out_size, msg_out_pos;
211 static guestfs_h *handles = NULL;
212 static int atexit_handler_set = 0;
215 guestfs_create (void)
220 g = malloc (sizeof (*g));
223 memset (g, 0, sizeof (*g));
230 g->stdout_watch = -1;
234 g->error_cb = default_error_cb;
235 g->error_cb_data = NULL;
237 str = getenv ("LIBGUESTFS_DEBUG");
238 g->verbose = str != NULL && strcmp (str, "1") == 0;
240 str = getenv ("LIBGUESTFS_PATH");
241 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
242 if (!g->path) goto error;
244 str = getenv ("LIBGUESTFS_QEMU");
245 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
246 if (!g->qemu) goto error;
248 str = getenv ("LIBGUESTFS_APPEND");
250 g->append = strdup (str);
251 if (!g->append) goto error;
254 /* Choose a suitable memory size. Previously we tried to choose
255 * a minimal memory size, but this isn't really necessary since
256 * recent QEMU and KVM don't do anything nasty like locking
257 * memory into core any more. Thus we can safely choose a
258 * large, generous amount of memory, and it'll just get swapped
259 * on smaller systems.
261 str = getenv ("LIBGUESTFS_MEMSIZE");
263 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
264 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
270 g->main_loop = guestfs_get_default_main_loop ();
272 /* Start with large serial numbers so they are easy to spot
273 * inside the protocol.
275 g->msg_next_serial = 0x00123400;
277 /* Link the handles onto a global list. This is the one area
278 * where the library needs to be made thread-safe. (XXX)
280 /* acquire mutex (XXX) */
283 if (!atexit_handler_set) {
284 atexit (close_handles);
285 atexit_handler_set = 1;
287 /* release mutex (XXX) */
290 fprintf (stderr, "new guestfs handle %p\n", g);
303 guestfs_close (guestfs_h *g)
309 if (g->state == NO_HANDLE) {
310 /* Not safe to call 'error' here, so ... */
311 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
316 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
318 /* Try to sync if autosync flag is set. */
319 if (g->autosync && g->state == READY) {
320 guestfs_umount_all (g);
324 /* Remove any handlers that might be called back before we kill the
327 g->log_message_cb = NULL;
329 if (g->state != CONFIG)
330 guestfs_kill_subprocess (g);
332 /* Close any sockets and deregister any handlers. */
333 if (g->stdout_watch >= 0)
334 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
335 if (g->sock_watch >= 0)
336 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
337 g->stdout_watch = -1;
350 /* Remove tmpfiles. */
352 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
355 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
358 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
367 for (i = 0; i < g->cmdline_size; ++i)
368 free (g->cmdline[i]);
372 /* Mark the handle as dead before freeing it. */
373 g->state = NO_HANDLE;
375 /* acquire mutex (XXX) */
379 for (gg = handles; gg->next != g; gg = gg->next)
383 /* release mutex (XXX) */
387 free (g->last_error);
392 free (g->qemu_version);
396 /* Close all open handles (called from atexit(3)). */
400 while (handles) guestfs_close (handles);
404 guestfs_last_error (guestfs_h *g)
406 return g->last_error;
410 set_last_error (guestfs_h *g, const char *msg)
412 free (g->last_error);
413 g->last_error = strdup (msg);
417 default_error_cb (guestfs_h *g, void *data, const char *msg)
419 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
423 guestfs_error (guestfs_h *g, const char *fs, ...)
429 int err = vasprintf (&msg, fs, args);
434 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
435 set_last_error (g, msg);
441 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
448 int err = vasprintf (&msg, fs, args);
455 strerror_r (errnum, buf, sizeof buf);
459 buf = strerror_r (errnum, _buf, sizeof _buf);
462 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
466 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
467 set_last_error (g, msg);
473 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
475 void *ptr = malloc (nbytes);
476 if (nbytes > 0 && !ptr) g->abort_cb ();
480 /* Return 1 if an array of N objects, each of size S, cannot exist due
481 to size arithmetic overflow. S must be positive and N must be
482 nonnegative. This is a macro, not an inline function, so that it
483 works correctly even when SIZE_MAX < N.
485 By gnulib convention, SIZE_MAX represents overflow in size
486 calculations, so the conservative dividend to use here is
487 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
488 However, malloc (SIZE_MAX) fails on all known hosts where
489 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
490 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
491 branch when S is known to be 1. */
492 # define xalloc_oversized(n, s) \
493 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
495 /* Technically we should add an autoconf test for this, testing for the desired
496 functionality, like what's done in gnulib, but for now, this is fine. */
497 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
499 /* Allocate zeroed memory for N elements of S bytes, with error
500 checking. S must be nonzero. */
502 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
504 /* From gnulib's calloc function in xmalloc.c. */
506 /* Test for overflow, since some calloc implementations don't have
507 proper overflow checks. But omit overflow and size-zero tests if
508 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
509 returns NULL if successful. */
510 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
511 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
517 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
519 void *p = realloc (ptr, nbytes);
520 if (nbytes > 0 && !p) g->abort_cb ();
525 guestfs_safe_strdup (guestfs_h *g, const char *str)
527 char *s = strdup (str);
528 if (!s) g->abort_cb ();
533 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
535 void *p = malloc (size);
536 if (!p) g->abort_cb ();
537 memcpy (p, ptr, size);
542 xwrite (int fd, const void *buf, size_t len)
547 r = write (fd, buf, len);
559 xread (int fd, void *buf, size_t len)
564 r = read (fd, buf, len);
566 if (errno == EINTR || errno == EAGAIN)
579 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
585 guestfs_get_out_of_memory_handler (guestfs_h *g)
591 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
594 g->error_cb_data = data;
597 guestfs_error_handler_cb
598 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
600 if (data_rtn) *data_rtn = g->error_cb_data;
605 guestfs_set_verbose (guestfs_h *g, int v)
612 guestfs_get_verbose (guestfs_h *g)
618 guestfs_set_autosync (guestfs_h *g, int a)
625 guestfs_get_autosync (guestfs_h *g)
631 guestfs_set_path (guestfs_h *g, const char *path)
638 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
643 guestfs_get_path (guestfs_h *g)
649 guestfs_set_qemu (guestfs_h *g, const char *qemu)
654 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
659 guestfs_get_qemu (guestfs_h *g)
665 guestfs_set_append (guestfs_h *g, const char *append)
670 g->append = append ? safe_strdup (g, append) : NULL;
675 guestfs_get_append (guestfs_h *g)
681 guestfs_set_memsize (guestfs_h *g, int memsize)
683 g->memsize = memsize;
688 guestfs_get_memsize (guestfs_h *g)
694 guestfs_set_selinux (guestfs_h *g, int selinux)
696 g->selinux = selinux;
701 guestfs_get_selinux (guestfs_h *g)
707 guestfs_get_pid (guestfs_h *g)
712 error (g, "get_pid: no qemu subprocess");
717 struct guestfs_version *
718 guestfs_version (guestfs_h *g)
720 struct guestfs_version *r;
722 r = safe_malloc (g, sizeof *r);
723 r->major = PACKAGE_VERSION_MAJOR;
724 r->minor = PACKAGE_VERSION_MINOR;
725 r->release = PACKAGE_VERSION_RELEASE;
726 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
730 /* Add a string to the current command line. */
732 incr_cmdline_size (guestfs_h *g)
734 if (g->cmdline == NULL) {
735 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
737 g->cmdline = safe_malloc (g, sizeof (char *));
738 g->cmdline[0] = NULL;
742 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
746 add_cmdline (guestfs_h *g, const char *str)
748 if (g->state != CONFIG) {
750 _("command line cannot be altered after qemu subprocess launched"));
754 incr_cmdline_size (g);
755 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
760 guestfs_config (guestfs_h *g,
761 const char *qemu_param, const char *qemu_value)
763 if (qemu_param[0] != '-') {
764 error (g, _("guestfs_config: parameter must begin with '-' character"));
768 /* A bit fascist, but the user will probably break the extra
769 * parameters that we add if they try to set any of these.
771 if (strcmp (qemu_param, "-kernel") == 0 ||
772 strcmp (qemu_param, "-initrd") == 0 ||
773 strcmp (qemu_param, "-nographic") == 0 ||
774 strcmp (qemu_param, "-serial") == 0 ||
775 strcmp (qemu_param, "-full-screen") == 0 ||
776 strcmp (qemu_param, "-std-vga") == 0 ||
777 strcmp (qemu_param, "-vnc") == 0) {
778 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
782 if (add_cmdline (g, qemu_param) != 0) return -1;
784 if (qemu_value != NULL) {
785 if (add_cmdline (g, qemu_value) != 0) return -1;
792 guestfs_add_drive (guestfs_h *g, const char *filename)
794 size_t len = strlen (filename) + 64;
797 if (strchr (filename, ',') != NULL) {
798 error (g, _("filename cannot contain ',' (comma) character"));
802 /* cache=off improves reliability in the event of a host crash.
804 * However this option causes qemu to try to open the file with
805 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
806 * So we check if we can open the file with or without O_DIRECT,
807 * and use cache=off (or not) accordingly.
809 * This test also checks for the presence of the file, which
810 * is a documented semantic of this interface.
812 int fd = open (filename, O_RDONLY|O_DIRECT);
815 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
817 fd = open (filename, O_RDONLY);
820 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
822 perrorf (g, "%s", filename);
827 return guestfs_config (g, "-drive", buf);
831 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
833 size_t len = strlen (filename) + 64;
836 if (strchr (filename, ',') != NULL) {
837 error (g, _("filename cannot contain ',' (comma) character"));
841 if (access (filename, F_OK) == -1) {
842 perrorf (g, "%s", filename);
846 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
848 return guestfs_config (g, "-drive", buf);
852 guestfs_add_cdrom (guestfs_h *g, const char *filename)
854 if (strchr (filename, ',') != NULL) {
855 error (g, _("filename cannot contain ',' (comma) character"));
859 if (access (filename, F_OK) == -1) {
860 perrorf (g, "%s", filename);
864 return guestfs_config (g, "-cdrom", filename);
867 /* Returns true iff file is contained in dir. */
869 dir_contains_file (const char *dir, const char *file)
871 int dirlen = strlen (dir);
872 int filelen = strlen (file);
873 int len = dirlen+filelen+2;
876 snprintf (path, len, "%s/%s", dir, file);
877 return access (path, F_OK) == 0;
880 /* Returns true iff every listed file is contained in 'dir'. */
882 dir_contains_files (const char *dir, ...)
887 va_start (args, dir);
888 while ((file = va_arg (args, const char *)) != NULL) {
889 if (!dir_contains_file (dir, file)) {
898 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
899 static int test_qemu (guestfs_h *g);
900 static int qemu_supports (guestfs_h *g, const char *option);
901 static void print_cmdline (guestfs_h *g);
903 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
904 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
905 static const char *supermin_name =
906 "initramfs." REPO "." host_cpu ".supermin.img";
907 static const char *supermin_hostfiles_name =
908 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
911 guestfs_launch (guestfs_h *g)
914 char dir_template[PATH_MAX];
919 char *path, *pelem, *pend;
920 char *kernel = NULL, *initrd = NULL;
922 struct sockaddr_un addr;
930 tmpdir = getenv ("TMPDIR") ? : tmpdir;
931 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
935 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
939 if (g->state != CONFIG) {
940 error (g, _("qemu has already been launched"));
944 /* Make the temporary directory. */
946 g->tmpdir = safe_strdup (g, dir_template);
947 if (mkdtemp (g->tmpdir) == NULL) {
948 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
953 /* First search g->path for the supermin appliance, and try to
954 * synthesize a kernel and initrd from that. If it fails, we
955 * try the path search again looking for a backup ordinary
958 pelem = path = safe_strdup (g, g->path);
960 pend = strchrnul (pelem, ':');
961 pmore = *pend == ':';
965 /* Empty element of "." means cwd. */
966 if (len == 0 || (len == 1 && *pelem == '.')) {
969 "looking for supermin appliance in current directory\n");
970 if (dir_contains_files (".",
971 supermin_name, supermin_hostfiles_name,
972 "kmod.whitelist", NULL)) {
973 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
978 /* Look at <path>/supermin* etc. */
981 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
983 if (dir_contains_files (pelem,
984 supermin_name, supermin_hostfiles_name,
985 "kmod.whitelist", NULL)) {
986 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
997 if (kernel == NULL || initrd == NULL) {
998 /* Search g->path for the kernel and initrd. */
999 pelem = path = safe_strdup (g, g->path);
1001 pend = strchrnul (pelem, ':');
1002 pmore = *pend == ':';
1006 /* Empty element or "." means cwd. */
1007 if (len == 0 || (len == 1 && *pelem == '.')) {
1010 "looking for appliance in current directory\n");
1011 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1012 kernel = safe_strdup (g, kernel_name);
1013 initrd = safe_strdup (g, initrd_name);
1017 /* Look at <path>/kernel etc. */
1020 fprintf (stderr, "looking for appliance in %s\n", pelem);
1022 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1023 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1024 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1025 sprintf (kernel, "%s/%s", pelem, kernel_name);
1026 sprintf (initrd, "%s/%s", pelem, initrd_name);
1037 if (kernel == NULL || initrd == NULL) {
1038 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1039 kernel_name, initrd_name, g->path);
1043 /* Get qemu help text and version. */
1044 if (test_qemu (g) == -1)
1047 /* Make the vmchannel socket. */
1048 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1051 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1052 perrorf (g, "pipe");
1058 perrorf (g, "fork");
1066 if (r == 0) { /* Child (qemu). */
1067 char vmchannel[256];
1069 char memsize_str[256];
1071 /* Set up the full command line. Do this in the subprocess so we
1072 * don't need to worry about cleaning up.
1074 g->cmdline[0] = g->qemu;
1076 #define LINUX_CMDLINE \
1077 "panic=1 " /* force kernel to panic if daemon exits */ \
1078 "console=ttyS0 " /* serial console */ \
1079 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1080 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1081 "acpi=off " /* we don't need ACPI, turn it off */ \
1082 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1084 /* Linux kernel command line. */
1085 snprintf (append, sizeof append,
1088 "%s" /* (selinux) */
1089 "%s" /* (verbose) */
1090 "%s", /* (append) */
1091 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1092 g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1093 g->verbose ? "guestfs_verbose=1 " : " ",
1094 g->append ? g->append : "");
1096 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1098 add_cmdline (g, "-m");
1099 add_cmdline (g, memsize_str);
1100 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1101 add_cmdline (g, "-kernel");
1102 add_cmdline (g, (char *) kernel);
1103 add_cmdline (g, "-initrd");
1104 add_cmdline (g, (char *) initrd);
1105 add_cmdline (g, "-append");
1106 add_cmdline (g, append);
1107 add_cmdline (g, "-nographic");
1108 add_cmdline (g, "-serial");
1109 add_cmdline (g, "stdio");
1112 /* Doesn't work. See:
1113 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1114 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1116 if (qemu_supports (g, "guestfwd")) {
1117 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1118 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1120 snprintf (vmchannel, sizeof vmchannel,
1121 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1122 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1124 add_cmdline (g, "-net");
1125 add_cmdline (g, vmchannel);
1128 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1129 * syntax, or if not then we'll get a quick failure.
1131 snprintf (vmchannel, sizeof vmchannel,
1132 "channel,%d:unix:%s,server,nowait",
1133 VMCHANNEL_PORT, unixsock);
1135 add_cmdline (g, "-net");
1136 add_cmdline (g, vmchannel);
1137 add_cmdline (g, "-net");
1138 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1142 add_cmdline (g, "-net");
1143 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1145 /* These options recommended by KVM developers to improve reliability. */
1146 if (qemu_supports (g, "-no-hpet"))
1147 add_cmdline (g, "-no-hpet");
1149 if (qemu_supports (g, "-rtc-td-hack"))
1150 add_cmdline (g, "-rtc-td-hack");
1152 /* Finish off the command line. */
1153 incr_cmdline_size (g);
1154 g->cmdline[g->cmdline_size-1] = NULL;
1159 /* Set up stdin, stdout. */
1170 /* Set up a new process group, so we can signal this process
1171 * and all subprocesses (eg. if qemu is really a shell script).
1176 execv (g->qemu, g->cmdline); /* Run qemu. */
1181 /* Parent (library). */
1189 /* Fork the recovery process off which will kill qemu if the parent
1190 * process fails to do so (eg. if the parent segfaults).
1194 pid_t qemu_pid = g->pid;
1195 pid_t parent_pid = getppid ();
1197 /* Writing to argv is hideously complicated and error prone. See:
1198 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1201 /* Loop around waiting for one or both of the other processes to
1202 * disappear. It's fair to say this is very hairy. The PIDs that
1203 * we are looking at might be reused by another process. We are
1204 * effectively polling. Is the cure worse than the disease?
1207 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1209 if (kill (parent_pid, 0) == -1) {
1210 /* Parent's gone away, qemu still around, so kill qemu. */
1218 /* Don't worry, if the fork failed, this will be -1. The recovery
1219 * process isn't essential.
1223 /* Start the clock ... */
1226 /* Close the other ends of the pipe. */
1230 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1231 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1232 perrorf (g, "fcntl");
1236 g->fd[0] = wfd[1]; /* stdin of child */
1237 g->fd[1] = rfd[0]; /* stdout of child */
1239 /* Open the Unix socket. The vmchannel implementation that got
1240 * merged with qemu sucks in a number of ways. Both ends do
1241 * connect(2), which means that no one knows what, if anything, is
1242 * connected to the other end, or if it becomes disconnected. Even
1243 * worse, we have to wait some indeterminate time for qemu to create
1244 * the socket and connect to it (which happens very early in qemu's
1245 * start-up), so any code that uses vmchannel is inherently racy.
1246 * Hence this silly loop.
1248 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1249 if (g->sock == -1) {
1250 perrorf (g, "socket");
1254 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1255 perrorf (g, "fcntl");
1259 addr.sun_family = AF_UNIX;
1260 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1261 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1264 /* Always sleep at least once to give qemu a small chance to start up. */
1267 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1268 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1271 if (errno != ENOENT)
1272 perrorf (g, "connect");
1277 error (g, _("failed to connect to vmchannel socket"));
1281 /* Watch the file descriptors. */
1284 g->msg_in_size = g->msg_in_allocated = 0;
1288 g->msg_out_size = 0;
1292 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1293 GUESTFS_HANDLE_READABLE,
1294 stdout_event, NULL);
1295 if (g->stdout_watch == -1) {
1296 error (g, _("could not watch qemu stdout"));
1300 if (guestfs__switch_to_receiving (g) == -1)
1303 g->state = LAUNCHING;
1307 if (g->stdout_watch >= 0)
1308 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1309 if (g->sock_watch >= 0)
1310 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1319 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1320 waitpid (g->pid, NULL, 0);
1321 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1328 g->stdout_watch = -1;
1337 /* This function is used to print the qemu command line before it gets
1338 * executed, when in verbose mode.
1341 print_cmdline (guestfs_h *g)
1346 while (g->cmdline[i]) {
1347 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1348 fprintf (stderr, " \\\n ");
1350 if (i > 0) fputc (' ', stderr);
1352 /* Does it need shell quoting? This only deals with simple cases. */
1353 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1355 if (needs_quote) fputc ('\'', stderr);
1356 fprintf (stderr, "%s", g->cmdline[i]);
1357 if (needs_quote) fputc ('\'', stderr);
1361 fputc ('\n', stderr);
1364 /* This function does the hard work of building the supermin appliance
1365 * on the fly. 'path' is the directory containing the control files.
1366 * 'kernel' and 'initrd' are where we will return the names of the
1367 * kernel and initrd (only initrd is built). The work is done by
1368 * an external script. We just tell it where to put the result.
1371 build_supermin_appliance (guestfs_h *g, const char *path,
1372 char **kernel, char **initrd)
1377 len = strlen (g->tmpdir);
1378 *kernel = safe_malloc (g, len + 8);
1379 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1380 *initrd = safe_malloc (g, len + 8);
1381 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1383 snprintf (cmd, sizeof cmd,
1385 "libguestfs-supermin-helper '%s' %s %s",
1387 path, *kernel, *initrd);
1390 if (r == -1 || WEXITSTATUS(r) != 0) {
1391 error (g, _("external command failed: %s"), cmd);
1394 *kernel = *initrd = NULL;
1401 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1403 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1404 * 'qemu -version' so we know what options this qemu supports and
1408 test_qemu (guestfs_h *g)
1413 free (g->qemu_help);
1414 free (g->qemu_version);
1415 g->qemu_help = NULL;
1416 g->qemu_version = NULL;
1418 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1420 fp = popen (cmd, "r");
1421 /* qemu -help should always work (qemu -version OTOH wasn't
1422 * supported by qemu 0.9). If this command doesn't work then it
1423 * probably indicates that the qemu binary is missing.
1426 /* XXX This error is never printed, even if the qemu binary
1427 * doesn't exist. Why?
1430 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1434 if (read_all (g, fp, &g->qemu_help) == -1)
1437 if (pclose (fp) == -1)
1440 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1442 fp = popen (cmd, "r");
1444 /* Intentionally ignore errors. */
1445 read_all (g, fp, &g->qemu_version);
1453 read_all (guestfs_h *g, FILE *fp, char **ret)
1460 *ret = safe_realloc (g, *ret, n + 1);
1465 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1467 r = fread (p, 1, BUFSIZ, fp);
1469 perrorf (g, "read");
1476 /* Test if option is supported by qemu command line (just by grepping
1480 qemu_supports (guestfs_h *g, const char *option)
1482 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1486 finish_wait_ready (guestfs_h *g, void *vp)
1489 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1492 g->main_loop->main_loop_quit (g->main_loop, g);
1496 guestfs_wait_ready (guestfs_h *g)
1498 int finished = 0, r;
1500 if (g->state == READY) return 0;
1502 if (g->state == BUSY) {
1503 error (g, _("qemu has finished launching already"));
1507 if (g->state != LAUNCHING) {
1508 error (g, _("qemu has not been launched yet"));
1512 g->launch_done_cb = finish_wait_ready;
1513 g->launch_done_cb_data = &finished;
1514 r = g->main_loop->main_loop_run (g->main_loop, g);
1515 g->launch_done_cb = NULL;
1516 g->launch_done_cb_data = NULL;
1518 if (r == -1) return -1;
1520 if (finished != 1) {
1521 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1525 /* This is possible in some really strange situations, such as
1526 * guestfsd starts up OK but then qemu immediately exits. Check for
1527 * it because the caller is probably expecting to be able to send
1528 * commands after this function returns.
1530 if (g->state != READY) {
1531 error (g, _("qemu launched and contacted daemon, but state != READY"));
1539 guestfs_kill_subprocess (guestfs_h *g)
1541 if (g->state == CONFIG) {
1542 error (g, _("no subprocess to kill"));
1547 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1549 kill (g->pid, SIGTERM);
1550 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1555 /* Access current state. */
1557 guestfs_is_config (guestfs_h *g)
1559 return g->state == CONFIG;
1563 guestfs_is_launching (guestfs_h *g)
1565 return g->state == LAUNCHING;
1569 guestfs_is_ready (guestfs_h *g)
1571 return g->state == READY;
1575 guestfs_is_busy (guestfs_h *g)
1577 return g->state == BUSY;
1581 guestfs_get_state (guestfs_h *g)
1587 guestfs_set_ready (guestfs_h *g)
1589 if (g->state != BUSY) {
1590 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1599 guestfs_set_busy (guestfs_h *g)
1601 if (g->state != READY) {
1602 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1611 guestfs_end_busy (guestfs_h *g)
1623 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1629 /* We don't know if stdout_event or sock_read_event will be the
1630 * first to receive EOF if the qemu process dies. This function
1631 * has the common cleanup code for both.
1634 child_cleanup (guestfs_h *g)
1637 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1638 /*kill (g->pid, SIGTERM);*/
1639 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1640 waitpid (g->pid, NULL, 0);
1641 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1642 if (g->stdout_watch >= 0)
1643 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1644 if (g->sock_watch >= 0)
1645 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1655 g->stdout_watch = -1;
1658 if (g->subprocess_quit_cb)
1659 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1662 /* This function is called whenever qemu prints something on stdout.
1663 * Qemu's stdout is also connected to the guest's serial console, so
1664 * we see kernel messages here too.
1667 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1668 int watch, int fd, int events)
1676 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1677 g, g->state, fd, events);
1680 if (g->fd[1] != fd) {
1681 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1685 n = read (fd, buf, sizeof buf);
1687 /* Hopefully this indicates the qemu child process has died. */
1693 if (errno != EINTR && errno != EAGAIN)
1694 perrorf (g, "read");
1698 /* In verbose mode, copy all log messages to stderr. */
1702 /* It's an actual log message, send it upwards if anyone is listening. */
1703 if (g->log_message_cb)
1704 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1707 /* The function is called whenever we can read something on the
1708 * guestfsd (daemon inside the guest) communication socket.
1711 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1712 int watch, int fd, int events)
1720 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1721 g, g->state, fd, events);
1723 if (g->sock != fd) {
1724 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1728 if (g->msg_in_size <= g->msg_in_allocated) {
1729 g->msg_in_allocated += 4096;
1730 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1732 n = read (g->sock, g->msg_in + g->msg_in_size,
1733 g->msg_in_allocated - g->msg_in_size);
1741 if (errno != EINTR && errno != EAGAIN)
1742 perrorf (g, "read");
1746 g->msg_in_size += n;
1748 /* Have we got enough of a message to be able to process it yet? */
1750 if (g->msg_in_size < 4) return;
1752 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1753 if (!xdr_uint32_t (&xdr, &len)) {
1754 error (g, _("can't decode length word"));
1758 /* Length is normally the length of the message, but when guestfsd
1759 * starts up it sends a "magic" value (longer than any possible
1760 * message). Check for this.
1762 if (len == GUESTFS_LAUNCH_FLAG) {
1763 if (g->state != LAUNCHING)
1764 error (g, _("received magic signature from guestfsd, but in state %d"),
1766 else if (g->msg_in_size != 4)
1767 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1771 if (g->launch_done_cb)
1772 g->launch_done_cb (g, g->launch_done_cb_data);
1778 /* This can happen if a cancellation happens right at the end
1779 * of us sending a FileIn parameter to the daemon. Discard. The
1780 * daemon should send us an error message next.
1782 if (len == GUESTFS_CANCEL_FLAG) {
1783 g->msg_in_size -= 4;
1784 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1788 /* If this happens, it's pretty bad and we've probably lost
1791 if (len > GUESTFS_MESSAGE_MAX) {
1792 error (g, _("message length (%u) > maximum possible size (%d)"),
1793 len, GUESTFS_MESSAGE_MAX);
1797 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1799 /* Got the full message, begin processing it. */
1804 for (i = 0; i < g->msg_in_size; i += 16) {
1805 printf ("%04x: ", i);
1806 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1807 printf ("%02x ", (unsigned char) g->msg_in[j]);
1808 for (; j < i+16; ++j)
1811 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1812 if (isprint (g->msg_in[j]))
1813 printf ("%c", g->msg_in[j]);
1816 for (; j < i+16; ++j)
1823 /* Not in the expected state. */
1824 if (g->state != BUSY)
1825 error (g, _("state %d != BUSY"), g->state);
1827 /* Push the message up to the higher layer. */
1829 g->reply_cb (g, g->reply_cb_data, &xdr);
1831 /* This message (probably) should never be printed. */
1832 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1834 g->msg_in_size -= len + 4;
1835 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1836 if (g->msg_in_size > 0) goto again;
1839 /* Free the message buffer if it's grown excessively large. */
1840 if (g->msg_in_allocated > 65536) {
1843 g->msg_in_size = g->msg_in_allocated = 0;
1850 /* The function is called whenever we can write something on the
1851 * guestfsd (daemon inside the guest) communication socket.
1854 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1855 int watch, int fd, int events)
1861 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1862 g, g->state, fd, events);
1864 if (g->sock != fd) {
1865 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1869 if (g->state != BUSY) {
1870 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1875 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1876 g->msg_out_size - g->msg_out_pos);
1878 n = write (g->sock, g->msg_out + g->msg_out_pos,
1879 g->msg_out_size - g->msg_out_pos);
1883 perrorf (g, "write");
1884 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1890 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1892 g->msg_out_pos += n;
1894 /* More to write? */
1895 if (g->msg_out_pos < g->msg_out_size)
1899 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1903 g->msg_out_pos = g->msg_out_size = 0;
1905 /* Done writing, call the higher layer. */
1907 g->send_cb (g, g->send_cb_data);
1911 guestfs_set_send_callback (guestfs_h *g,
1912 guestfs_send_cb cb, void *opaque)
1915 g->send_cb_data = opaque;
1919 guestfs_set_reply_callback (guestfs_h *g,
1920 guestfs_reply_cb cb, void *opaque)
1923 g->reply_cb_data = opaque;
1927 guestfs_set_log_message_callback (guestfs_h *g,
1928 guestfs_log_message_cb cb, void *opaque)
1930 g->log_message_cb = cb;
1931 g->log_message_cb_data = opaque;
1935 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1936 guestfs_subprocess_quit_cb cb, void *opaque)
1938 g->subprocess_quit_cb = cb;
1939 g->subprocess_quit_cb_data = opaque;
1943 guestfs_set_launch_done_callback (guestfs_h *g,
1944 guestfs_launch_done_cb cb, void *opaque)
1946 g->launch_done_cb = cb;
1947 g->launch_done_cb_data = opaque;
1950 /* Access to the handle's main loop and the default main loop. */
1952 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1954 g->main_loop = main_loop;
1958 guestfs_get_main_loop (guestfs_h *g)
1960 return g->main_loop;
1964 guestfs_get_default_main_loop (void)
1966 return (guestfs_main_loop *) &default_main_loop;
1969 /* Change the daemon socket handler so that we are now writing.
1970 * This sets the handle to sock_write_event.
1973 guestfs__switch_to_sending (guestfs_h *g)
1975 if (g->sock_watch >= 0) {
1976 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1977 error (g, _("remove_handle failed"));
1984 g->main_loop->add_handle (g->main_loop, g, g->sock,
1985 GUESTFS_HANDLE_WRITABLE,
1986 sock_write_event, NULL);
1987 if (g->sock_watch == -1) {
1988 error (g, _("add_handle failed"));
1996 guestfs__switch_to_receiving (guestfs_h *g)
1998 if (g->sock_watch >= 0) {
1999 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
2000 error (g, _("remove_handle failed"));
2007 g->main_loop->add_handle (g->main_loop, g, g->sock,
2008 GUESTFS_HANDLE_READABLE,
2009 sock_read_event, NULL);
2010 if (g->sock_watch == -1) {
2011 error (g, _("add_handle failed"));
2018 /* Dispatch a call (len + header + args) to the remote daemon,
2019 * synchronously (ie. using the guest's main loop to wait until
2020 * it has been sent). Returns -1 for error, or the serial
2021 * number of the message.
2024 send_cb (guestfs_h *g, void *data)
2026 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2029 ml->main_loop_quit (ml, g);
2033 guestfs__send_sync (guestfs_h *g, int proc_nr,
2034 xdrproc_t xdrp, char *args)
2036 struct guestfs_message_header hdr;
2039 int serial = g->msg_next_serial++;
2041 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2043 if (g->state != BUSY) {
2044 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2048 /* This is probably an internal error. Or perhaps we should just
2049 * free the buffer anyway?
2051 if (g->msg_out != NULL) {
2052 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2056 /* We have to allocate this message buffer on the heap because
2057 * it is quite large (although will be mostly unused). We
2058 * can't allocate it on the stack because in some environments
2059 * we have quite limited stack space available, notably when
2060 * running in the JVM.
2062 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2063 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2065 /* Serialize the header. */
2066 hdr.prog = GUESTFS_PROGRAM;
2067 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2069 hdr.direction = GUESTFS_DIRECTION_CALL;
2070 hdr.serial = serial;
2071 hdr.status = GUESTFS_STATUS_OK;
2073 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2074 error (g, _("xdr_guestfs_message_header failed"));
2078 /* Serialize the args. If any, because some message types
2079 * have no parameters.
2082 if (!(*xdrp) (&xdr, args)) {
2083 error (g, _("dispatch failed to marshal args"));
2088 /* Get the actual length of the message, resize the buffer to match
2089 * the actual length, and write the length word at the beginning.
2091 len = xdr_getpos (&xdr);
2094 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2095 g->msg_out_size = len + 4;
2098 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2099 xdr_uint32_t (&xdr, &len);
2101 if (guestfs__switch_to_sending (g) == -1)
2105 guestfs_set_send_callback (g, send_cb, &sent);
2106 if (ml->main_loop_run (ml, g) == -1)
2109 error (g, _("send failed, see earlier error messages"));
2118 g->msg_out_size = 0;
2122 static int cancel = 0; /* XXX Implement file cancellation. */
2123 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2124 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2125 static int send_file_cancellation_sync (guestfs_h *g);
2126 static int send_file_complete_sync (guestfs_h *g);
2128 /* Synchronously send a file.
2132 * -2 daemon cancelled (we must read the error message)
2135 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2137 char buf[GUESTFS_MAX_CHUNK_SIZE];
2140 fd = open (filename, O_RDONLY);
2142 perrorf (g, "open: %s", filename);
2143 send_file_cancellation_sync (g);
2144 /* Daemon sees cancellation and won't reply, so caller can
2150 /* Send file in chunked encoding. */
2152 r = read (fd, buf, sizeof buf);
2153 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2156 err = send_file_data_sync (g, buf, r);
2158 if (err == -2) /* daemon sent cancellation */
2159 send_file_cancellation_sync (g);
2164 if (cancel) { /* cancel from either end */
2165 send_file_cancellation_sync (g);
2170 perrorf (g, "read: %s", filename);
2171 send_file_cancellation_sync (g);
2175 /* End of file, but before we send that, we need to close
2176 * the file and check for errors.
2178 if (close (fd) == -1) {
2179 perrorf (g, "close: %s", filename);
2180 send_file_cancellation_sync (g);
2184 return send_file_complete_sync (g);
2187 /* Send a chunk of file data. */
2189 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2191 return send_file_chunk_sync (g, 0, buf, len);
2194 /* Send a cancellation message. */
2196 send_file_cancellation_sync (guestfs_h *g)
2198 return send_file_chunk_sync (g, 1, NULL, 0);
2201 /* Send a file complete chunk. */
2203 send_file_complete_sync (guestfs_h *g)
2206 return send_file_chunk_sync (g, 0, buf, 0);
2209 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2212 static int check_for_daemon_cancellation (guestfs_h *g);
2215 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2219 guestfs_chunk chunk;
2221 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2223 if (g->state != BUSY) {
2224 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2228 /* This is probably an internal error. Or perhaps we should just
2229 * free the buffer anyway?
2231 if (g->msg_out != NULL) {
2232 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2236 /* Did the daemon send a cancellation message? */
2237 if (check_for_daemon_cancellation (g)) {
2239 fprintf (stderr, "got daemon cancellation\n");
2243 /* Allocate the chunk buffer. Don't use the stack to avoid
2244 * excessive stack usage and unnecessary copies.
2246 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2247 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2249 /* Serialize the chunk. */
2250 chunk.cancel = cancel;
2251 chunk.data.data_len = buflen;
2252 chunk.data.data_val = (char *) buf;
2254 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2255 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2261 len = xdr_getpos (&xdr);
2264 /* Reduce the size of the outgoing message buffer to the real length. */
2265 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2266 g->msg_out_size = len + 4;
2269 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2270 xdr_uint32_t (&xdr, &len);
2272 if (guestfs__switch_to_sending (g) == -1)
2276 guestfs_set_send_callback (g, send_cb, &sent);
2277 if (ml->main_loop_run (ml, g) == -1)
2280 error (g, _("send file chunk failed, see earlier error messages"));
2289 g->msg_out_size = 0;
2293 /* At this point we are sending FileIn file(s) to the guest, and not
2294 * expecting to read anything, so if we do read anything, it must be
2295 * a cancellation message. This checks for this case without blocking.
2298 check_for_daemon_cancellation (guestfs_h *g)
2308 FD_SET (g->sock, &rset);
2311 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2313 perrorf (g, "select");
2319 /* Read the message from the daemon. */
2320 r = xread (g->sock, buf, sizeof buf);
2322 perrorf (g, "read");
2326 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2327 xdr_uint32_t (&xdr, &flag);
2330 if (flag != GUESTFS_CANCEL_FLAG) {
2331 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2332 flag, GUESTFS_CANCEL_FLAG);
2339 /* Synchronously receive a file. */
2341 /* Returns -1 = error, 0 = EOF, 1 = more data */
2342 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2345 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2351 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2353 perrorf (g, "open: %s", filename);
2357 /* Receive the file in chunked encoding. */
2358 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2359 if (xwrite (fd, buf, len) == -1) {
2360 perrorf (g, "%s: write", filename);
2365 if (r == 0) break; /* End of file. */
2369 error (g, _("%s: error in chunked encoding"), filename);
2373 if (close (fd) == -1) {
2374 perrorf (g, "close: %s", filename);
2381 /* Send cancellation message to daemon, then wait until it
2382 * cancels (just throwing away data).
2386 uint32_t flag = GUESTFS_CANCEL_FLAG;
2389 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2392 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2393 xdr_uint32_t (&xdr, &flag);
2396 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2397 perrorf (g, _("write to daemon socket"));
2401 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2402 ; /* just discard it */
2407 /* Note that the reply callback can be called multiple times before
2408 * the main loop quits and we get back to the synchronous code. So
2409 * we have to be prepared to save multiple chunks on a list here.
2411 struct receive_file_ctx {
2412 int count; /* 0 if receive_file_cb not called, or
2413 * else count number of chunks.
2415 guestfs_chunk *chunks; /* Array of chunks. */
2419 free_chunks (struct receive_file_ctx *ctx)
2423 for (i = 0; i < ctx->count; ++i)
2424 free (ctx->chunks[i].data.data_val);
2430 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2432 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2433 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2434 guestfs_chunk chunk;
2436 if (ctx->count == -1) /* Parse error occurred previously. */
2439 ml->main_loop_quit (ml, g);
2441 memset (&chunk, 0, sizeof chunk);
2443 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2444 error (g, _("failed to parse file chunk"));
2451 /* Copy the chunk to the list. */
2452 ctx->chunks = safe_realloc (g, ctx->chunks,
2453 sizeof (guestfs_chunk) * (ctx->count+1));
2454 ctx->chunks[ctx->count] = chunk;
2458 /* Receive a chunk of file data. */
2459 /* Returns -1 = error, 0 = EOF, 1 = more data */
2461 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2463 struct receive_file_ctx ctx;
2464 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2471 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2472 (void) ml->main_loop_run (ml, g);
2473 guestfs_set_reply_callback (g, NULL, NULL);
2475 if (ctx.count == 0) {
2476 error (g, _("receive_file_data_sync: reply callback not called\n"));
2480 if (ctx.count == -1) {
2481 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2482 /* callback already freed the chunks */
2487 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2489 /* Process each chunk in the list. */
2490 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2493 for (i = 0; i < ctx.count; ++i) {
2494 if (ctx.chunks[i].cancel) {
2495 error (g, _("file receive cancelled by daemon"));
2497 if (buf) free (*buf);
2498 if (len_r) *len_r = 0;
2502 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2504 if (len_r) *len_r = len;
2509 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2510 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2511 ctx.chunks[i].data.data_len);
2513 len += ctx.chunks[i].data.data_len;
2516 if (len_r) *len_r = len;
2521 /* This is the default main loop implementation, using select(2). */
2524 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2525 guestfs_handle_event_cb cb, void *data)
2527 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2529 if (fd < 0 || fd >= FD_SETSIZE) {
2530 error (g, _("fd %d is out of range"), fd);
2534 if ((events & ~(GUESTFS_HANDLE_READABLE |
2535 GUESTFS_HANDLE_WRITABLE |
2536 GUESTFS_HANDLE_HANGUP |
2537 GUESTFS_HANDLE_ERROR)) != 0) {
2538 error (g, _("set of events (0x%x) contains unknown events"), events);
2543 error (g, _("set of events is empty"));
2547 if (FD_ISSET (fd, &ml->rset) ||
2548 FD_ISSET (fd, &ml->wset) ||
2549 FD_ISSET (fd, &ml->xset)) {
2550 error (g, _("fd %d is already registered"), fd);
2555 error (g, _("callback is NULL"));
2559 if ((events & GUESTFS_HANDLE_READABLE))
2560 FD_SET (fd, &ml->rset);
2561 if ((events & GUESTFS_HANDLE_WRITABLE))
2562 FD_SET (fd, &ml->wset);
2563 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2564 FD_SET (fd, &ml->xset);
2566 if (fd > ml->max_fd) {
2568 ml->handle_cb_data =
2569 safe_realloc (g, ml->handle_cb_data,
2570 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2572 ml->handle_cb_data[fd].cb = cb;
2573 ml->handle_cb_data[fd].g = g;
2574 ml->handle_cb_data[fd].data = data;
2578 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2583 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2585 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2587 if (fd < 0 || fd >= FD_SETSIZE) {
2588 error (g, _("fd %d is out of range"), fd);
2592 if (!FD_ISSET (fd, &ml->rset) &&
2593 !FD_ISSET (fd, &ml->wset) &&
2594 !FD_ISSET (fd, &ml->xset)) {
2595 error (g, _("fd %d was not registered"), fd);
2599 FD_CLR (fd, &ml->rset);
2600 FD_CLR (fd, &ml->wset);
2601 FD_CLR (fd, &ml->xset);
2603 if (fd == ml->max_fd) {
2605 ml->handle_cb_data =
2606 safe_realloc (g, ml->handle_cb_data,
2607 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2616 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2617 guestfs_handle_timeout_cb cb, void *data)
2619 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2621 abort (); /* XXX not implemented yet */
2625 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2627 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2629 abort (); /* XXX not implemented yet */
2632 /* The 'g' parameter is just used for error reporting. Events
2633 * for multiple handles can be dispatched by running the main
2637 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2639 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2641 fd_set rset2, wset2, xset2;
2643 if (ml->is_running) {
2644 error (g, _("select_main_loop_run: this cannot be called recursively"));
2650 while (ml->is_running) {
2651 if (ml->nr_fds == 0)
2657 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2659 if (errno == EINTR || errno == EAGAIN)
2661 perrorf (g, "select");
2666 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2668 if (FD_ISSET (fd, &rset2))
2669 events |= GUESTFS_HANDLE_READABLE;
2670 if (FD_ISSET (fd, &wset2))
2671 events |= GUESTFS_HANDLE_WRITABLE;
2672 if (FD_ISSET (fd, &xset2))
2673 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2676 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2677 ml->handle_cb_data[fd].g,
2678 ml->handle_cb_data[fd].data,
2689 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2691 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2693 /* Note that legitimately ml->is_running can be zero when
2694 * this function is called.