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 if (access (filename, F_OK) == -1) {
803 perrorf (g, "%s", filename);
807 /* cache=off improves reliability in the event of a host crash. */
808 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, DRIVE_IF);
810 return guestfs_config (g, "-drive", buf);
814 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
816 size_t len = strlen (filename) + 64;
819 if (strchr (filename, ',') != NULL) {
820 error (g, _("filename cannot contain ',' (comma) character"));
824 if (access (filename, F_OK) == -1) {
825 perrorf (g, "%s", filename);
829 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
831 return guestfs_config (g, "-drive", buf);
835 guestfs_add_cdrom (guestfs_h *g, const char *filename)
837 if (strchr (filename, ',') != NULL) {
838 error (g, _("filename cannot contain ',' (comma) character"));
842 if (access (filename, F_OK) == -1) {
843 perrorf (g, "%s", filename);
847 return guestfs_config (g, "-cdrom", filename);
850 /* Returns true iff file is contained in dir. */
852 dir_contains_file (const char *dir, const char *file)
854 int dirlen = strlen (dir);
855 int filelen = strlen (file);
856 int len = dirlen+filelen+2;
859 snprintf (path, len, "%s/%s", dir, file);
860 return access (path, F_OK) == 0;
863 /* Returns true iff every listed file is contained in 'dir'. */
865 dir_contains_files (const char *dir, ...)
870 va_start (args, dir);
871 while ((file = va_arg (args, const char *)) != NULL) {
872 if (!dir_contains_file (dir, file)) {
881 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
882 static int test_qemu (guestfs_h *g);
883 static int qemu_supports (guestfs_h *g, const char *option);
884 static void print_cmdline (guestfs_h *g);
886 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
887 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
888 static const char *supermin_name =
889 "initramfs." REPO "." host_cpu ".supermin.img";
890 static const char *supermin_hostfiles_name =
891 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
894 guestfs_launch (guestfs_h *g)
897 char dir_template[PATH_MAX];
902 char *path, *pelem, *pend;
903 char *kernel = NULL, *initrd = NULL;
905 struct sockaddr_un addr;
913 tmpdir = getenv ("TMPDIR") ? : tmpdir;
914 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
918 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
922 if (g->state != CONFIG) {
923 error (g, _("qemu has already been launched"));
927 /* Make the temporary directory. */
929 g->tmpdir = safe_strdup (g, dir_template);
930 if (mkdtemp (g->tmpdir) == NULL) {
931 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
936 /* First search g->path for the supermin appliance, and try to
937 * synthesize a kernel and initrd from that. If it fails, we
938 * try the path search again looking for a backup ordinary
941 pelem = path = safe_strdup (g, g->path);
943 pend = strchrnul (pelem, ':');
944 pmore = *pend == ':';
948 /* Empty element of "." means cwd. */
949 if (len == 0 || (len == 1 && *pelem == '.')) {
952 "looking for supermin appliance in current directory\n");
953 if (dir_contains_files (".",
954 supermin_name, supermin_hostfiles_name,
955 "kmod.whitelist", NULL)) {
956 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
961 /* Look at <path>/supermin* etc. */
964 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
966 if (dir_contains_files (pelem,
967 supermin_name, supermin_hostfiles_name,
968 "kmod.whitelist", NULL)) {
969 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
980 if (kernel == NULL || initrd == NULL) {
981 /* Search g->path for the kernel and initrd. */
982 pelem = path = safe_strdup (g, g->path);
984 pend = strchrnul (pelem, ':');
985 pmore = *pend == ':';
989 /* Empty element or "." means cwd. */
990 if (len == 0 || (len == 1 && *pelem == '.')) {
993 "looking for appliance in current directory\n");
994 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
995 kernel = safe_strdup (g, kernel_name);
996 initrd = safe_strdup (g, initrd_name);
1000 /* Look at <path>/kernel etc. */
1003 fprintf (stderr, "looking for appliance in %s\n", pelem);
1005 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1006 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1007 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1008 sprintf (kernel, "%s/%s", pelem, kernel_name);
1009 sprintf (initrd, "%s/%s", pelem, initrd_name);
1020 if (kernel == NULL || initrd == NULL) {
1021 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1022 kernel_name, initrd_name, g->path);
1026 /* Get qemu help text and version. */
1027 if (test_qemu (g) == -1)
1030 /* Make the vmchannel socket. */
1031 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1034 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1035 perrorf (g, "pipe");
1041 perrorf (g, "fork");
1049 if (r == 0) { /* Child (qemu). */
1050 char vmchannel[256];
1052 char memsize_str[256];
1054 /* Set up the full command line. Do this in the subprocess so we
1055 * don't need to worry about cleaning up.
1057 g->cmdline[0] = g->qemu;
1059 #define LINUX_CMDLINE \
1060 "panic=1 " /* force kernel to panic if daemon exits */ \
1061 "console=ttyS0 " /* serial console */ \
1062 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1063 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1064 "acpi=off " /* we don't need ACPI, turn it off */ \
1065 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1067 /* Linux kernel command line. */
1068 snprintf (append, sizeof append,
1071 "%s" /* (selinux) */
1072 "%s" /* (verbose) */
1073 "%s", /* (append) */
1074 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1075 g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1076 g->verbose ? "guestfs_verbose=1 " : " ",
1077 g->append ? g->append : "");
1079 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1081 add_cmdline (g, "-m");
1082 add_cmdline (g, memsize_str);
1083 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1084 add_cmdline (g, "-kernel");
1085 add_cmdline (g, (char *) kernel);
1086 add_cmdline (g, "-initrd");
1087 add_cmdline (g, (char *) initrd);
1088 add_cmdline (g, "-append");
1089 add_cmdline (g, append);
1090 add_cmdline (g, "-nographic");
1091 add_cmdline (g, "-serial");
1092 add_cmdline (g, "stdio");
1095 /* Doesn't work. See:
1096 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1097 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1099 if (qemu_supports (g, "guestfwd")) {
1100 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1101 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1103 snprintf (vmchannel, sizeof vmchannel,
1104 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1105 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1107 add_cmdline (g, "-net");
1108 add_cmdline (g, vmchannel);
1111 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1112 * syntax, or if not then we'll get a quick failure.
1114 snprintf (vmchannel, sizeof vmchannel,
1115 "channel,%d:unix:%s,server,nowait",
1116 VMCHANNEL_PORT, unixsock);
1118 add_cmdline (g, "-net");
1119 add_cmdline (g, vmchannel);
1120 add_cmdline (g, "-net");
1121 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1125 add_cmdline (g, "-net");
1126 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1128 /* These options recommended by KVM developers to improve reliability. */
1129 if (qemu_supports (g, "-no-hpet"))
1130 add_cmdline (g, "-no-hpet");
1132 if (qemu_supports (g, "-rtc-td-hack"))
1133 add_cmdline (g, "-rtc-td-hack");
1135 /* Finish off the command line. */
1136 incr_cmdline_size (g);
1137 g->cmdline[g->cmdline_size-1] = NULL;
1142 /* Set up stdin, stdout. */
1153 /* Set up a new process group, so we can signal this process
1154 * and all subprocesses (eg. if qemu is really a shell script).
1159 execv (g->qemu, g->cmdline); /* Run qemu. */
1164 /* Parent (library). */
1172 /* Fork the recovery process off which will kill qemu if the parent
1173 * process fails to do so (eg. if the parent segfaults).
1177 pid_t qemu_pid = g->pid;
1178 pid_t parent_pid = getppid ();
1180 /* Writing to argv is hideously complicated and error prone. See:
1181 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1184 /* Loop around waiting for one or both of the other processes to
1185 * disappear. It's fair to say this is very hairy. The PIDs that
1186 * we are looking at might be reused by another process. We are
1187 * effectively polling. Is the cure worse than the disease?
1190 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1192 if (kill (parent_pid, 0) == -1) {
1193 /* Parent's gone away, qemu still around, so kill qemu. */
1201 /* Don't worry, if the fork failed, this will be -1. The recovery
1202 * process isn't essential.
1206 /* Start the clock ... */
1209 /* Close the other ends of the pipe. */
1213 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1214 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1215 perrorf (g, "fcntl");
1219 g->fd[0] = wfd[1]; /* stdin of child */
1220 g->fd[1] = rfd[0]; /* stdout of child */
1222 /* Open the Unix socket. The vmchannel implementation that got
1223 * merged with qemu sucks in a number of ways. Both ends do
1224 * connect(2), which means that no one knows what, if anything, is
1225 * connected to the other end, or if it becomes disconnected. Even
1226 * worse, we have to wait some indeterminate time for qemu to create
1227 * the socket and connect to it (which happens very early in qemu's
1228 * start-up), so any code that uses vmchannel is inherently racy.
1229 * Hence this silly loop.
1231 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1232 if (g->sock == -1) {
1233 perrorf (g, "socket");
1237 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1238 perrorf (g, "fcntl");
1242 addr.sun_family = AF_UNIX;
1243 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1244 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1247 /* Always sleep at least once to give qemu a small chance to start up. */
1250 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1251 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1254 if (errno != ENOENT)
1255 perrorf (g, "connect");
1260 error (g, _("failed to connect to vmchannel socket"));
1264 /* Watch the file descriptors. */
1267 g->msg_in_size = g->msg_in_allocated = 0;
1271 g->msg_out_size = 0;
1275 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1276 GUESTFS_HANDLE_READABLE,
1277 stdout_event, NULL);
1278 if (g->stdout_watch == -1) {
1279 error (g, _("could not watch qemu stdout"));
1283 if (guestfs__switch_to_receiving (g) == -1)
1286 g->state = LAUNCHING;
1290 if (g->stdout_watch >= 0)
1291 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1292 if (g->sock_watch >= 0)
1293 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1302 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1303 waitpid (g->pid, NULL, 0);
1304 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1311 g->stdout_watch = -1;
1320 /* This function is used to print the qemu command line before it gets
1321 * executed, when in verbose mode.
1324 print_cmdline (guestfs_h *g)
1329 while (g->cmdline[i]) {
1330 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1331 fprintf (stderr, " \\\n ");
1333 if (i > 0) fputc (' ', stderr);
1335 /* Does it need shell quoting? This only deals with simple cases. */
1336 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1338 if (needs_quote) fputc ('\'', stderr);
1339 fprintf (stderr, "%s", g->cmdline[i]);
1340 if (needs_quote) fputc ('\'', stderr);
1344 fputc ('\n', stderr);
1347 /* This function does the hard work of building the supermin appliance
1348 * on the fly. 'path' is the directory containing the control files.
1349 * 'kernel' and 'initrd' are where we will return the names of the
1350 * kernel and initrd (only initrd is built). The work is done by
1351 * an external script. We just tell it where to put the result.
1354 build_supermin_appliance (guestfs_h *g, const char *path,
1355 char **kernel, char **initrd)
1360 len = strlen (g->tmpdir);
1361 *kernel = safe_malloc (g, len + 8);
1362 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1363 *initrd = safe_malloc (g, len + 8);
1364 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1366 snprintf (cmd, sizeof cmd,
1368 "libguestfs-supermin-helper '%s' %s %s",
1370 path, *kernel, *initrd);
1373 if (r == -1 || WEXITSTATUS(r) != 0) {
1374 error (g, _("external command failed: %s"), cmd);
1377 *kernel = *initrd = NULL;
1384 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1386 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1387 * 'qemu -version' so we know what options this qemu supports and
1391 test_qemu (guestfs_h *g)
1396 free (g->qemu_help);
1397 free (g->qemu_version);
1398 g->qemu_help = NULL;
1399 g->qemu_version = NULL;
1401 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1403 fp = popen (cmd, "r");
1404 /* qemu -help should always work (qemu -version OTOH wasn't
1405 * supported by qemu 0.9). If this command doesn't work then it
1406 * probably indicates that the qemu binary is missing.
1409 /* XXX This error is never printed, even if the qemu binary
1410 * doesn't exist. Why?
1413 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1417 if (read_all (g, fp, &g->qemu_help) == -1)
1420 if (pclose (fp) == -1)
1423 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1425 fp = popen (cmd, "r");
1427 /* Intentionally ignore errors. */
1428 read_all (g, fp, &g->qemu_version);
1436 read_all (guestfs_h *g, FILE *fp, char **ret)
1443 *ret = safe_realloc (g, *ret, n + 1);
1448 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1450 r = fread (p, 1, BUFSIZ, fp);
1452 perrorf (g, "read");
1459 /* Test if option is supported by qemu command line (just by grepping
1463 qemu_supports (guestfs_h *g, const char *option)
1465 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1469 finish_wait_ready (guestfs_h *g, void *vp)
1472 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1475 g->main_loop->main_loop_quit (g->main_loop, g);
1479 guestfs_wait_ready (guestfs_h *g)
1481 int finished = 0, r;
1483 if (g->state == READY) return 0;
1485 if (g->state == BUSY) {
1486 error (g, _("qemu has finished launching already"));
1490 if (g->state != LAUNCHING) {
1491 error (g, _("qemu has not been launched yet"));
1495 g->launch_done_cb = finish_wait_ready;
1496 g->launch_done_cb_data = &finished;
1497 r = g->main_loop->main_loop_run (g->main_loop, g);
1498 g->launch_done_cb = NULL;
1499 g->launch_done_cb_data = NULL;
1501 if (r == -1) return -1;
1503 if (finished != 1) {
1504 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1508 /* This is possible in some really strange situations, such as
1509 * guestfsd starts up OK but then qemu immediately exits. Check for
1510 * it because the caller is probably expecting to be able to send
1511 * commands after this function returns.
1513 if (g->state != READY) {
1514 error (g, _("qemu launched and contacted daemon, but state != READY"));
1522 guestfs_kill_subprocess (guestfs_h *g)
1524 if (g->state == CONFIG) {
1525 error (g, _("no subprocess to kill"));
1530 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1532 kill (g->pid, SIGTERM);
1533 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1538 /* Access current state. */
1540 guestfs_is_config (guestfs_h *g)
1542 return g->state == CONFIG;
1546 guestfs_is_launching (guestfs_h *g)
1548 return g->state == LAUNCHING;
1552 guestfs_is_ready (guestfs_h *g)
1554 return g->state == READY;
1558 guestfs_is_busy (guestfs_h *g)
1560 return g->state == BUSY;
1564 guestfs_get_state (guestfs_h *g)
1570 guestfs_set_ready (guestfs_h *g)
1572 if (g->state != BUSY) {
1573 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1582 guestfs_set_busy (guestfs_h *g)
1584 if (g->state != READY) {
1585 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1594 guestfs_end_busy (guestfs_h *g)
1606 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1612 /* We don't know if stdout_event or sock_read_event will be the
1613 * first to receive EOF if the qemu process dies. This function
1614 * has the common cleanup code for both.
1617 child_cleanup (guestfs_h *g)
1620 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1621 /*kill (g->pid, SIGTERM);*/
1622 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1623 waitpid (g->pid, NULL, 0);
1624 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1625 if (g->stdout_watch >= 0)
1626 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1627 if (g->sock_watch >= 0)
1628 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1638 g->stdout_watch = -1;
1641 if (g->subprocess_quit_cb)
1642 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1645 /* This function is called whenever qemu prints something on stdout.
1646 * Qemu's stdout is also connected to the guest's serial console, so
1647 * we see kernel messages here too.
1650 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1651 int watch, int fd, int events)
1659 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1660 g, g->state, fd, events);
1663 if (g->fd[1] != fd) {
1664 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1668 n = read (fd, buf, sizeof buf);
1670 /* Hopefully this indicates the qemu child process has died. */
1676 if (errno != EINTR && errno != EAGAIN)
1677 perrorf (g, "read");
1681 /* In verbose mode, copy all log messages to stderr. */
1685 /* It's an actual log message, send it upwards if anyone is listening. */
1686 if (g->log_message_cb)
1687 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1690 /* The function is called whenever we can read something on the
1691 * guestfsd (daemon inside the guest) communication socket.
1694 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1695 int watch, int fd, int events)
1703 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1704 g, g->state, fd, events);
1706 if (g->sock != fd) {
1707 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1711 if (g->msg_in_size <= g->msg_in_allocated) {
1712 g->msg_in_allocated += 4096;
1713 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1715 n = read (g->sock, g->msg_in + g->msg_in_size,
1716 g->msg_in_allocated - g->msg_in_size);
1724 if (errno != EINTR && errno != EAGAIN)
1725 perrorf (g, "read");
1729 g->msg_in_size += n;
1731 /* Have we got enough of a message to be able to process it yet? */
1733 if (g->msg_in_size < 4) return;
1735 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1736 if (!xdr_uint32_t (&xdr, &len)) {
1737 error (g, _("can't decode length word"));
1741 /* Length is normally the length of the message, but when guestfsd
1742 * starts up it sends a "magic" value (longer than any possible
1743 * message). Check for this.
1745 if (len == GUESTFS_LAUNCH_FLAG) {
1746 if (g->state != LAUNCHING)
1747 error (g, _("received magic signature from guestfsd, but in state %d"),
1749 else if (g->msg_in_size != 4)
1750 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1754 if (g->launch_done_cb)
1755 g->launch_done_cb (g, g->launch_done_cb_data);
1761 /* This can happen if a cancellation happens right at the end
1762 * of us sending a FileIn parameter to the daemon. Discard. The
1763 * daemon should send us an error message next.
1765 if (len == GUESTFS_CANCEL_FLAG) {
1766 g->msg_in_size -= 4;
1767 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1771 /* If this happens, it's pretty bad and we've probably lost
1774 if (len > GUESTFS_MESSAGE_MAX) {
1775 error (g, _("message length (%u) > maximum possible size (%d)"),
1776 len, GUESTFS_MESSAGE_MAX);
1780 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1782 /* Got the full message, begin processing it. */
1787 for (i = 0; i < g->msg_in_size; i += 16) {
1788 printf ("%04x: ", i);
1789 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1790 printf ("%02x ", (unsigned char) g->msg_in[j]);
1791 for (; j < i+16; ++j)
1794 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1795 if (isprint (g->msg_in[j]))
1796 printf ("%c", g->msg_in[j]);
1799 for (; j < i+16; ++j)
1806 /* Not in the expected state. */
1807 if (g->state != BUSY)
1808 error (g, _("state %d != BUSY"), g->state);
1810 /* Push the message up to the higher layer. */
1812 g->reply_cb (g, g->reply_cb_data, &xdr);
1814 /* This message (probably) should never be printed. */
1815 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1817 g->msg_in_size -= len + 4;
1818 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1819 if (g->msg_in_size > 0) goto again;
1822 /* Free the message buffer if it's grown excessively large. */
1823 if (g->msg_in_allocated > 65536) {
1826 g->msg_in_size = g->msg_in_allocated = 0;
1833 /* The function is called whenever we can write something on the
1834 * guestfsd (daemon inside the guest) communication socket.
1837 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1838 int watch, int fd, int events)
1844 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1845 g, g->state, fd, events);
1847 if (g->sock != fd) {
1848 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1852 if (g->state != BUSY) {
1853 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1858 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1859 g->msg_out_size - g->msg_out_pos);
1861 n = write (g->sock, g->msg_out + g->msg_out_pos,
1862 g->msg_out_size - g->msg_out_pos);
1866 perrorf (g, "write");
1867 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1873 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1875 g->msg_out_pos += n;
1877 /* More to write? */
1878 if (g->msg_out_pos < g->msg_out_size)
1882 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1886 g->msg_out_pos = g->msg_out_size = 0;
1888 /* Done writing, call the higher layer. */
1890 g->send_cb (g, g->send_cb_data);
1894 guestfs_set_send_callback (guestfs_h *g,
1895 guestfs_send_cb cb, void *opaque)
1898 g->send_cb_data = opaque;
1902 guestfs_set_reply_callback (guestfs_h *g,
1903 guestfs_reply_cb cb, void *opaque)
1906 g->reply_cb_data = opaque;
1910 guestfs_set_log_message_callback (guestfs_h *g,
1911 guestfs_log_message_cb cb, void *opaque)
1913 g->log_message_cb = cb;
1914 g->log_message_cb_data = opaque;
1918 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1919 guestfs_subprocess_quit_cb cb, void *opaque)
1921 g->subprocess_quit_cb = cb;
1922 g->subprocess_quit_cb_data = opaque;
1926 guestfs_set_launch_done_callback (guestfs_h *g,
1927 guestfs_launch_done_cb cb, void *opaque)
1929 g->launch_done_cb = cb;
1930 g->launch_done_cb_data = opaque;
1933 /* Access to the handle's main loop and the default main loop. */
1935 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1937 g->main_loop = main_loop;
1941 guestfs_get_main_loop (guestfs_h *g)
1943 return g->main_loop;
1947 guestfs_get_default_main_loop (void)
1949 return (guestfs_main_loop *) &default_main_loop;
1952 /* Change the daemon socket handler so that we are now writing.
1953 * This sets the handle to sock_write_event.
1956 guestfs__switch_to_sending (guestfs_h *g)
1958 if (g->sock_watch >= 0) {
1959 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1960 error (g, _("remove_handle failed"));
1967 g->main_loop->add_handle (g->main_loop, g, g->sock,
1968 GUESTFS_HANDLE_WRITABLE,
1969 sock_write_event, NULL);
1970 if (g->sock_watch == -1) {
1971 error (g, _("add_handle failed"));
1979 guestfs__switch_to_receiving (guestfs_h *g)
1981 if (g->sock_watch >= 0) {
1982 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1983 error (g, _("remove_handle failed"));
1990 g->main_loop->add_handle (g->main_loop, g, g->sock,
1991 GUESTFS_HANDLE_READABLE,
1992 sock_read_event, NULL);
1993 if (g->sock_watch == -1) {
1994 error (g, _("add_handle failed"));
2001 /* Dispatch a call (len + header + args) to the remote daemon,
2002 * synchronously (ie. using the guest's main loop to wait until
2003 * it has been sent). Returns -1 for error, or the serial
2004 * number of the message.
2007 send_cb (guestfs_h *g, void *data)
2009 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2012 ml->main_loop_quit (ml, g);
2016 guestfs__send_sync (guestfs_h *g, int proc_nr,
2017 xdrproc_t xdrp, char *args)
2019 struct guestfs_message_header hdr;
2022 int serial = g->msg_next_serial++;
2024 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2026 if (g->state != BUSY) {
2027 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2031 /* This is probably an internal error. Or perhaps we should just
2032 * free the buffer anyway?
2034 if (g->msg_out != NULL) {
2035 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2039 /* We have to allocate this message buffer on the heap because
2040 * it is quite large (although will be mostly unused). We
2041 * can't allocate it on the stack because in some environments
2042 * we have quite limited stack space available, notably when
2043 * running in the JVM.
2045 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2046 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2048 /* Serialize the header. */
2049 hdr.prog = GUESTFS_PROGRAM;
2050 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2052 hdr.direction = GUESTFS_DIRECTION_CALL;
2053 hdr.serial = serial;
2054 hdr.status = GUESTFS_STATUS_OK;
2056 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2057 error (g, _("xdr_guestfs_message_header failed"));
2061 /* Serialize the args. If any, because some message types
2062 * have no parameters.
2065 if (!(*xdrp) (&xdr, args)) {
2066 error (g, _("dispatch failed to marshal args"));
2071 /* Get the actual length of the message, resize the buffer to match
2072 * the actual length, and write the length word at the beginning.
2074 len = xdr_getpos (&xdr);
2077 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2078 g->msg_out_size = len + 4;
2081 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2082 xdr_uint32_t (&xdr, &len);
2084 if (guestfs__switch_to_sending (g) == -1)
2088 guestfs_set_send_callback (g, send_cb, &sent);
2089 if (ml->main_loop_run (ml, g) == -1)
2092 error (g, _("send failed, see earlier error messages"));
2101 g->msg_out_size = 0;
2105 static int cancel = 0; /* XXX Implement file cancellation. */
2106 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2107 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2108 static int send_file_cancellation_sync (guestfs_h *g);
2109 static int send_file_complete_sync (guestfs_h *g);
2111 /* Synchronously send a file.
2115 * -2 daemon cancelled (we must read the error message)
2118 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2120 char buf[GUESTFS_MAX_CHUNK_SIZE];
2123 fd = open (filename, O_RDONLY);
2125 perrorf (g, "open: %s", filename);
2126 send_file_cancellation_sync (g);
2127 /* Daemon sees cancellation and won't reply, so caller can
2133 /* Send file in chunked encoding. */
2135 r = read (fd, buf, sizeof buf);
2136 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2139 err = send_file_data_sync (g, buf, r);
2141 if (err == -2) /* daemon sent cancellation */
2142 send_file_cancellation_sync (g);
2147 if (cancel) { /* cancel from either end */
2148 send_file_cancellation_sync (g);
2153 perrorf (g, "read: %s", filename);
2154 send_file_cancellation_sync (g);
2158 /* End of file, but before we send that, we need to close
2159 * the file and check for errors.
2161 if (close (fd) == -1) {
2162 perrorf (g, "close: %s", filename);
2163 send_file_cancellation_sync (g);
2167 return send_file_complete_sync (g);
2170 /* Send a chunk of file data. */
2172 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2174 return send_file_chunk_sync (g, 0, buf, len);
2177 /* Send a cancellation message. */
2179 send_file_cancellation_sync (guestfs_h *g)
2181 return send_file_chunk_sync (g, 1, NULL, 0);
2184 /* Send a file complete chunk. */
2186 send_file_complete_sync (guestfs_h *g)
2189 return send_file_chunk_sync (g, 0, buf, 0);
2192 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2195 static int check_for_daemon_cancellation (guestfs_h *g);
2198 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2202 guestfs_chunk chunk;
2204 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2206 if (g->state != BUSY) {
2207 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2211 /* This is probably an internal error. Or perhaps we should just
2212 * free the buffer anyway?
2214 if (g->msg_out != NULL) {
2215 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2219 /* Did the daemon send a cancellation message? */
2220 if (check_for_daemon_cancellation (g)) {
2222 fprintf (stderr, "got daemon cancellation\n");
2226 /* Allocate the chunk buffer. Don't use the stack to avoid
2227 * excessive stack usage and unnecessary copies.
2229 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2230 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2232 /* Serialize the chunk. */
2233 chunk.cancel = cancel;
2234 chunk.data.data_len = buflen;
2235 chunk.data.data_val = (char *) buf;
2237 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2238 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2244 len = xdr_getpos (&xdr);
2247 /* Reduce the size of the outgoing message buffer to the real length. */
2248 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2249 g->msg_out_size = len + 4;
2252 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2253 xdr_uint32_t (&xdr, &len);
2255 if (guestfs__switch_to_sending (g) == -1)
2259 guestfs_set_send_callback (g, send_cb, &sent);
2260 if (ml->main_loop_run (ml, g) == -1)
2263 error (g, _("send file chunk failed, see earlier error messages"));
2272 g->msg_out_size = 0;
2276 /* At this point we are sending FileIn file(s) to the guest, and not
2277 * expecting to read anything, so if we do read anything, it must be
2278 * a cancellation message. This checks for this case without blocking.
2281 check_for_daemon_cancellation (guestfs_h *g)
2291 FD_SET (g->sock, &rset);
2294 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2296 perrorf (g, "select");
2302 /* Read the message from the daemon. */
2303 r = xread (g->sock, buf, sizeof buf);
2305 perrorf (g, "read");
2309 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2310 xdr_uint32_t (&xdr, &flag);
2313 if (flag != GUESTFS_CANCEL_FLAG) {
2314 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2315 flag, GUESTFS_CANCEL_FLAG);
2322 /* Synchronously receive a file. */
2324 /* Returns -1 = error, 0 = EOF, 1 = more data */
2325 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2328 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2334 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2336 perrorf (g, "open: %s", filename);
2340 /* Receive the file in chunked encoding. */
2341 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2342 if (xwrite (fd, buf, len) == -1) {
2343 perrorf (g, "%s: write", filename);
2348 if (r == 0) break; /* End of file. */
2352 error (g, _("%s: error in chunked encoding"), filename);
2356 if (close (fd) == -1) {
2357 perrorf (g, "close: %s", filename);
2364 /* Send cancellation message to daemon, then wait until it
2365 * cancels (just throwing away data).
2369 uint32_t flag = GUESTFS_CANCEL_FLAG;
2372 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2375 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2376 xdr_uint32_t (&xdr, &flag);
2379 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2380 perrorf (g, _("write to daemon socket"));
2384 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2385 ; /* just discard it */
2390 /* Note that the reply callback can be called multiple times before
2391 * the main loop quits and we get back to the synchronous code. So
2392 * we have to be prepared to save multiple chunks on a list here.
2394 struct receive_file_ctx {
2395 int count; /* 0 if receive_file_cb not called, or
2396 * else count number of chunks.
2398 guestfs_chunk *chunks; /* Array of chunks. */
2402 free_chunks (struct receive_file_ctx *ctx)
2406 for (i = 0; i < ctx->count; ++i)
2407 free (ctx->chunks[i].data.data_val);
2413 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2415 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2416 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2417 guestfs_chunk chunk;
2419 if (ctx->count == -1) /* Parse error occurred previously. */
2422 ml->main_loop_quit (ml, g);
2424 memset (&chunk, 0, sizeof chunk);
2426 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2427 error (g, _("failed to parse file chunk"));
2434 /* Copy the chunk to the list. */
2435 ctx->chunks = safe_realloc (g, ctx->chunks,
2436 sizeof (guestfs_chunk) * (ctx->count+1));
2437 ctx->chunks[ctx->count] = chunk;
2441 /* Receive a chunk of file data. */
2442 /* Returns -1 = error, 0 = EOF, 1 = more data */
2444 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2446 struct receive_file_ctx ctx;
2447 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2454 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2455 (void) ml->main_loop_run (ml, g);
2456 guestfs_set_reply_callback (g, NULL, NULL);
2458 if (ctx.count == 0) {
2459 error (g, _("receive_file_data_sync: reply callback not called\n"));
2463 if (ctx.count == -1) {
2464 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2465 /* callback already freed the chunks */
2470 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2472 /* Process each chunk in the list. */
2473 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2476 for (i = 0; i < ctx.count; ++i) {
2477 if (ctx.chunks[i].cancel) {
2478 error (g, _("file receive cancelled by daemon"));
2480 if (buf) free (*buf);
2481 if (len_r) *len_r = 0;
2485 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2487 if (len_r) *len_r = len;
2492 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2493 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2494 ctx.chunks[i].data.data_len);
2496 len += ctx.chunks[i].data.data_len;
2499 if (len_r) *len_r = len;
2504 /* This is the default main loop implementation, using select(2). */
2507 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2508 guestfs_handle_event_cb cb, void *data)
2510 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2512 if (fd < 0 || fd >= FD_SETSIZE) {
2513 error (g, _("fd %d is out of range"), fd);
2517 if ((events & ~(GUESTFS_HANDLE_READABLE |
2518 GUESTFS_HANDLE_WRITABLE |
2519 GUESTFS_HANDLE_HANGUP |
2520 GUESTFS_HANDLE_ERROR)) != 0) {
2521 error (g, _("set of events (0x%x) contains unknown events"), events);
2526 error (g, _("set of events is empty"));
2530 if (FD_ISSET (fd, &ml->rset) ||
2531 FD_ISSET (fd, &ml->wset) ||
2532 FD_ISSET (fd, &ml->xset)) {
2533 error (g, _("fd %d is already registered"), fd);
2538 error (g, _("callback is NULL"));
2542 if ((events & GUESTFS_HANDLE_READABLE))
2543 FD_SET (fd, &ml->rset);
2544 if ((events & GUESTFS_HANDLE_WRITABLE))
2545 FD_SET (fd, &ml->wset);
2546 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2547 FD_SET (fd, &ml->xset);
2549 if (fd > ml->max_fd) {
2551 ml->handle_cb_data =
2552 safe_realloc (g, ml->handle_cb_data,
2553 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2555 ml->handle_cb_data[fd].cb = cb;
2556 ml->handle_cb_data[fd].g = g;
2557 ml->handle_cb_data[fd].data = data;
2561 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2566 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2568 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2570 if (fd < 0 || fd >= FD_SETSIZE) {
2571 error (g, _("fd %d is out of range"), fd);
2575 if (!FD_ISSET (fd, &ml->rset) &&
2576 !FD_ISSET (fd, &ml->wset) &&
2577 !FD_ISSET (fd, &ml->xset)) {
2578 error (g, _("fd %d was not registered"), fd);
2582 FD_CLR (fd, &ml->rset);
2583 FD_CLR (fd, &ml->wset);
2584 FD_CLR (fd, &ml->xset);
2586 if (fd == ml->max_fd) {
2588 ml->handle_cb_data =
2589 safe_realloc (g, ml->handle_cb_data,
2590 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2599 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2600 guestfs_handle_timeout_cb cb, void *data)
2602 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2604 abort (); /* XXX not implemented yet */
2608 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2610 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2612 abort (); /* XXX not implemented yet */
2615 /* The 'g' parameter is just used for error reporting. Events
2616 * for multiple handles can be dispatched by running the main
2620 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2622 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2624 fd_set rset2, wset2, xset2;
2626 if (ml->is_running) {
2627 error (g, _("select_main_loop_run: this cannot be called recursively"));
2633 while (ml->is_running) {
2634 if (ml->nr_fds == 0)
2640 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2642 if (errno == EINTR || errno == EAGAIN)
2644 perrorf (g, "select");
2649 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2651 if (FD_ISSET (fd, &rset2))
2652 events |= GUESTFS_HANDLE_READABLE;
2653 if (FD_ISSET (fd, &wset2))
2654 events |= GUESTFS_HANDLE_WRITABLE;
2655 if (FD_ISSET (fd, &xset2))
2656 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2659 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2660 ml->handle_cb_data[fd].g,
2661 ml->handle_cb_data[fd].data,
2672 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2674 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2676 /* Note that legitimately ml->is_running can be zero when
2677 * this function is called.