2 * Copyright (C) 2009 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
33 #include <sys/select.h>
36 #include <rpc/types.h>
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
47 #ifdef HAVE_SYS_WAIT_H
51 #ifdef HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
60 #include "guestfs-internal-actions.h"
61 #include "guestfs_protocol.h"
62 #include "ignore-value.h"
66 #define _(str) dgettext(PACKAGE, (str))
67 //#define N_(str) dgettext(PACKAGE, (str))
73 #define error guestfs_error
74 #define perrorf guestfs_perrorf
75 #define safe_malloc guestfs_safe_malloc
76 #define safe_realloc guestfs_safe_realloc
77 #define safe_strdup guestfs_safe_strdup
78 //#define safe_memdup guestfs_safe_memdup
80 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
81 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
82 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
83 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
85 static void close_handles (void);
87 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
88 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
89 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
90 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
91 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
92 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
94 /* Default select-based main loop. */
95 struct select_handle_cb_data {
96 guestfs_handle_event_cb cb;
101 struct select_main_loop {
102 /* NB. These fields must be the same as in struct guestfs_main_loop: */
103 guestfs_add_handle_cb add_handle;
104 guestfs_remove_handle_cb remove_handle;
105 guestfs_add_timeout_cb add_timeout;
106 guestfs_remove_timeout_cb remove_timeout;
107 guestfs_main_loop_run_cb main_loop_run;
108 guestfs_main_loop_quit_cb main_loop_quit;
110 /* Additional private data: */
119 struct select_handle_cb_data *handle_cb_data;
122 /* Default main loop. */
123 static struct select_main_loop default_main_loop = {
124 .add_handle = select_add_handle,
125 .remove_handle = select_remove_handle,
126 .add_timeout = select_add_timeout,
127 .remove_timeout = select_remove_timeout,
128 .main_loop_run = select_main_loop_run,
129 .main_loop_quit = select_main_loop_quit,
131 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
132 * set by the normal action of everything being initialized to zero.
137 .handle_cb_data = NULL,
140 #define UNIX_PATH_MAX 108
142 /* Also in guestfsd.c */
143 #define VMCHANNEL_PORT 6666
144 #define VMCHANNEL_ADDR "10.0.2.4"
146 /* GuestFS handle and connection. */
147 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
151 struct guestfs_h *next; /* Linked list of open handles. */
153 /* State: see the state machine diagram in the man page guestfs(3). */
156 int fd[2]; /* Stdin/stdout of qemu. */
157 int sock; /* Daemon communications socket. */
158 pid_t pid; /* Qemu PID. */
159 pid_t recoverypid; /* Recovery process PID. */
160 time_t start_t; /* The time when we started qemu. */
162 int stdout_watch; /* Watches qemu stdout for log messages. */
163 int sock_watch; /* Watches daemon comm socket. */
165 char *tmpdir; /* Temporary directory containing socket. */
167 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
169 char **cmdline; /* Qemu command line. */
176 char *path; /* Path to kernel, initrd. */
177 char *qemu; /* Qemu binary. */
178 char *append; /* Append to kernel command line. */
180 int memsize; /* Size of RAM (megabytes). */
182 int selinux; /* selinux enabled? */
187 guestfs_abort_cb abort_cb;
188 guestfs_error_handler_cb error_cb;
189 void * error_cb_data;
190 guestfs_send_cb send_cb;
192 guestfs_reply_cb reply_cb;
193 void * reply_cb_data;
194 guestfs_log_message_cb log_message_cb;
195 void * log_message_cb_data;
196 guestfs_subprocess_quit_cb subprocess_quit_cb;
197 void * subprocess_quit_cb_data;
198 guestfs_launch_done_cb launch_done_cb;
199 void * launch_done_cb_data;
201 /* Main loop used by this handle. */
202 guestfs_main_loop *main_loop;
204 /* Messages sent and received from the daemon. */
206 unsigned int msg_in_size, msg_in_allocated;
208 unsigned int msg_out_size, msg_out_pos;
213 static guestfs_h *handles = NULL;
214 static int atexit_handler_set = 0;
217 guestfs_create (void)
222 g = malloc (sizeof (*g));
225 memset (g, 0, sizeof (*g));
232 g->stdout_watch = -1;
236 g->error_cb = default_error_cb;
237 g->error_cb_data = NULL;
239 str = getenv ("LIBGUESTFS_DEBUG");
240 g->verbose = str != NULL && strcmp (str, "1") == 0;
242 str = getenv ("LIBGUESTFS_TRACE");
243 g->trace = str != NULL && strcmp (str, "1") == 0;
245 str = getenv ("LIBGUESTFS_PATH");
246 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
247 if (!g->path) goto error;
249 str = getenv ("LIBGUESTFS_QEMU");
250 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
251 if (!g->qemu) goto error;
253 str = getenv ("LIBGUESTFS_APPEND");
255 g->append = strdup (str);
256 if (!g->append) goto error;
259 /* Choose a suitable memory size. Previously we tried to choose
260 * a minimal memory size, but this isn't really necessary since
261 * recent QEMU and KVM don't do anything nasty like locking
262 * memory into core any more. Thus we can safely choose a
263 * large, generous amount of memory, and it'll just get swapped
264 * on smaller systems.
266 str = getenv ("LIBGUESTFS_MEMSIZE");
268 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
269 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
275 g->main_loop = guestfs_get_default_main_loop ();
277 /* Start with large serial numbers so they are easy to spot
278 * inside the protocol.
280 g->msg_next_serial = 0x00123400;
282 /* Link the handles onto a global list. This is the one area
283 * where the library needs to be made thread-safe. (XXX)
285 /* acquire mutex (XXX) */
288 if (!atexit_handler_set) {
289 atexit (close_handles);
290 atexit_handler_set = 1;
292 /* release mutex (XXX) */
295 fprintf (stderr, "new guestfs handle %p\n", g);
308 guestfs_close (guestfs_h *g)
314 if (g->state == NO_HANDLE) {
315 /* Not safe to call 'error' here, so ... */
316 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
321 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
323 /* Try to sync if autosync flag is set. */
324 if (g->autosync && g->state == READY) {
325 guestfs_umount_all (g);
329 /* Remove any handlers that might be called back before we kill the
332 g->log_message_cb = NULL;
334 if (g->state != CONFIG)
335 guestfs_kill_subprocess (g);
337 /* Close any sockets and deregister any handlers. */
338 if (g->stdout_watch >= 0)
339 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
340 if (g->sock_watch >= 0)
341 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
342 g->stdout_watch = -1;
355 /* Wait for subprocess(es) to exit. */
356 waitpid (g->pid, NULL, 0);
357 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
359 /* Remove tmpfiles. */
361 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
364 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
367 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
376 for (i = 0; i < g->cmdline_size; ++i)
377 free (g->cmdline[i]);
381 /* Mark the handle as dead before freeing it. */
382 g->state = NO_HANDLE;
384 /* acquire mutex (XXX) */
388 for (gg = handles; gg->next != g; gg = gg->next)
392 /* release mutex (XXX) */
396 free (g->last_error);
401 free (g->qemu_version);
405 /* Close all open handles (called from atexit(3)). */
409 while (handles) guestfs_close (handles);
413 guestfs_last_error (guestfs_h *g)
415 return g->last_error;
419 set_last_error (guestfs_h *g, const char *msg)
421 free (g->last_error);
422 g->last_error = strdup (msg);
426 default_error_cb (guestfs_h *g, void *data, const char *msg)
428 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
432 guestfs_error (guestfs_h *g, const char *fs, ...)
438 int err = vasprintf (&msg, fs, args);
443 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
444 set_last_error (g, msg);
450 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
457 int err = vasprintf (&msg, fs, args);
464 strerror_r (errnum, buf, sizeof buf);
468 buf = strerror_r (errnum, _buf, sizeof _buf);
471 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
475 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
476 set_last_error (g, msg);
482 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
484 void *ptr = malloc (nbytes);
485 if (nbytes > 0 && !ptr) g->abort_cb ();
489 /* Return 1 if an array of N objects, each of size S, cannot exist due
490 to size arithmetic overflow. S must be positive and N must be
491 nonnegative. This is a macro, not an inline function, so that it
492 works correctly even when SIZE_MAX < N.
494 By gnulib convention, SIZE_MAX represents overflow in size
495 calculations, so the conservative dividend to use here is
496 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
497 However, malloc (SIZE_MAX) fails on all known hosts where
498 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
499 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
500 branch when S is known to be 1. */
501 # define xalloc_oversized(n, s) \
502 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
504 /* Technically we should add an autoconf test for this, testing for the desired
505 functionality, like what's done in gnulib, but for now, this is fine. */
506 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
508 /* Allocate zeroed memory for N elements of S bytes, with error
509 checking. S must be nonzero. */
511 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
513 /* From gnulib's calloc function in xmalloc.c. */
515 /* Test for overflow, since some calloc implementations don't have
516 proper overflow checks. But omit overflow and size-zero tests if
517 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
518 returns NULL if successful. */
519 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
520 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
526 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
528 void *p = realloc (ptr, nbytes);
529 if (nbytes > 0 && !p) g->abort_cb ();
534 guestfs_safe_strdup (guestfs_h *g, const char *str)
536 char *s = strdup (str);
537 if (!s) g->abort_cb ();
542 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
544 void *p = malloc (size);
545 if (!p) g->abort_cb ();
546 memcpy (p, ptr, size);
551 xwrite (int fd, const void *v_buf, size_t len)
553 const char *buf = v_buf;
557 r = write (fd, buf, len);
569 xread (int fd, void *v_buf, size_t len)
575 r = read (fd, buf, len);
577 if (errno == EINTR || errno == EAGAIN)
590 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
596 guestfs_get_out_of_memory_handler (guestfs_h *g)
602 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
605 g->error_cb_data = data;
608 guestfs_error_handler_cb
609 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
611 if (data_rtn) *data_rtn = g->error_cb_data;
616 guestfs__set_verbose (guestfs_h *g, int v)
623 guestfs__get_verbose (guestfs_h *g)
629 guestfs__set_autosync (guestfs_h *g, int a)
636 guestfs__get_autosync (guestfs_h *g)
642 guestfs__set_path (guestfs_h *g, const char *path)
649 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
654 guestfs__get_path (guestfs_h *g)
660 guestfs__set_qemu (guestfs_h *g, const char *qemu)
665 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
670 guestfs__get_qemu (guestfs_h *g)
676 guestfs__set_append (guestfs_h *g, const char *append)
681 g->append = append ? safe_strdup (g, append) : NULL;
686 guestfs__get_append (guestfs_h *g)
692 guestfs__set_memsize (guestfs_h *g, int memsize)
694 g->memsize = memsize;
699 guestfs__get_memsize (guestfs_h *g)
705 guestfs__set_selinux (guestfs_h *g, int selinux)
707 g->selinux = selinux;
712 guestfs__get_selinux (guestfs_h *g)
718 guestfs__get_pid (guestfs_h *g)
723 error (g, "get_pid: no qemu subprocess");
728 struct guestfs_version *
729 guestfs__version (guestfs_h *g)
731 struct guestfs_version *r;
733 r = safe_malloc (g, sizeof *r);
734 r->major = PACKAGE_VERSION_MAJOR;
735 r->minor = PACKAGE_VERSION_MINOR;
736 r->release = PACKAGE_VERSION_RELEASE;
737 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
742 guestfs__set_trace (guestfs_h *g, int t)
749 guestfs__get_trace (guestfs_h *g)
754 /* Add a string to the current command line. */
756 incr_cmdline_size (guestfs_h *g)
758 if (g->cmdline == NULL) {
759 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
761 g->cmdline = safe_malloc (g, sizeof (char *));
762 g->cmdline[0] = NULL;
766 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
770 add_cmdline (guestfs_h *g, const char *str)
772 if (g->state != CONFIG) {
774 _("command line cannot be altered after qemu subprocess launched"));
778 incr_cmdline_size (g);
779 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
784 guestfs__config (guestfs_h *g,
785 const char *qemu_param, const char *qemu_value)
787 if (qemu_param[0] != '-') {
788 error (g, _("guestfs_config: parameter must begin with '-' character"));
792 /* A bit fascist, but the user will probably break the extra
793 * parameters that we add if they try to set any of these.
795 if (strcmp (qemu_param, "-kernel") == 0 ||
796 strcmp (qemu_param, "-initrd") == 0 ||
797 strcmp (qemu_param, "-nographic") == 0 ||
798 strcmp (qemu_param, "-serial") == 0 ||
799 strcmp (qemu_param, "-full-screen") == 0 ||
800 strcmp (qemu_param, "-std-vga") == 0 ||
801 strcmp (qemu_param, "-vnc") == 0) {
802 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
806 if (add_cmdline (g, qemu_param) != 0) return -1;
808 if (qemu_value != NULL) {
809 if (add_cmdline (g, qemu_value) != 0) return -1;
816 guestfs__add_drive (guestfs_h *g, const char *filename)
818 size_t len = strlen (filename) + 64;
821 if (strchr (filename, ',') != NULL) {
822 error (g, _("filename cannot contain ',' (comma) character"));
826 /* cache=off improves reliability in the event of a host crash.
828 * However this option causes qemu to try to open the file with
829 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
830 * So we check if we can open the file with or without O_DIRECT,
831 * and use cache=off (or not) accordingly.
833 * This test also checks for the presence of the file, which
834 * is a documented semantic of this interface.
836 int fd = open (filename, O_RDONLY|O_DIRECT);
839 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
841 fd = open (filename, O_RDONLY);
844 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
846 perrorf (g, "%s", filename);
851 return guestfs_config (g, "-drive", buf);
855 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
857 size_t len = strlen (filename) + 64;
860 if (strchr (filename, ',') != NULL) {
861 error (g, _("filename cannot contain ',' (comma) character"));
865 if (access (filename, F_OK) == -1) {
866 perrorf (g, "%s", filename);
870 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
872 return guestfs_config (g, "-drive", buf);
876 guestfs__add_cdrom (guestfs_h *g, const char *filename)
878 if (strchr (filename, ',') != NULL) {
879 error (g, _("filename cannot contain ',' (comma) character"));
883 if (access (filename, F_OK) == -1) {
884 perrorf (g, "%s", filename);
888 return guestfs_config (g, "-cdrom", filename);
891 /* Returns true iff file is contained in dir. */
893 dir_contains_file (const char *dir, const char *file)
895 int dirlen = strlen (dir);
896 int filelen = strlen (file);
897 int len = dirlen+filelen+2;
900 snprintf (path, len, "%s/%s", dir, file);
901 return access (path, F_OK) == 0;
904 /* Returns true iff every listed file is contained in 'dir'. */
906 dir_contains_files (const char *dir, ...)
911 va_start (args, dir);
912 while ((file = va_arg (args, const char *)) != NULL) {
913 if (!dir_contains_file (dir, file)) {
922 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
923 static int test_qemu (guestfs_h *g);
924 static int qemu_supports (guestfs_h *g, const char *option);
925 static void print_cmdline (guestfs_h *g);
927 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
928 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
929 static const char *supermin_name =
930 "initramfs." REPO "." host_cpu ".supermin.img";
931 static const char *supermin_hostfiles_name =
932 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
935 guestfs__launch (guestfs_h *g)
938 char dir_template[PATH_MAX];
943 char *path, *pelem, *pend;
944 char *kernel = NULL, *initrd = NULL;
946 struct sockaddr_un addr;
954 tmpdir = getenv ("TMPDIR") ? : tmpdir;
955 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
959 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
963 if (g->state != CONFIG) {
964 error (g, _("qemu has already been launched"));
968 /* Make the temporary directory. */
970 g->tmpdir = safe_strdup (g, dir_template);
971 if (mkdtemp (g->tmpdir) == NULL) {
972 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
977 /* First search g->path for the supermin appliance, and try to
978 * synthesize a kernel and initrd from that. If it fails, we
979 * try the path search again looking for a backup ordinary
982 pelem = path = safe_strdup (g, g->path);
984 pend = strchrnul (pelem, ':');
985 pmore = *pend == ':';
989 /* Empty element of "." means cwd. */
990 if (len == 0 || (len == 1 && *pelem == '.')) {
993 "looking for supermin appliance in current directory\n");
994 if (dir_contains_files (".",
995 supermin_name, supermin_hostfiles_name,
996 "kmod.whitelist", NULL)) {
997 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
1002 /* Look at <path>/supermin* etc. */
1005 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
1007 if (dir_contains_files (pelem,
1008 supermin_name, supermin_hostfiles_name,
1009 "kmod.whitelist", NULL)) {
1010 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1021 if (kernel == NULL || initrd == NULL) {
1022 /* Search g->path for the kernel and initrd. */
1023 pelem = path = safe_strdup (g, g->path);
1025 pend = strchrnul (pelem, ':');
1026 pmore = *pend == ':';
1030 /* Empty element or "." means cwd. */
1031 if (len == 0 || (len == 1 && *pelem == '.')) {
1034 "looking for appliance in current directory\n");
1035 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1036 kernel = safe_strdup (g, kernel_name);
1037 initrd = safe_strdup (g, initrd_name);
1041 /* Look at <path>/kernel etc. */
1044 fprintf (stderr, "looking for appliance in %s\n", pelem);
1046 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1047 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1048 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1049 sprintf (kernel, "%s/%s", pelem, kernel_name);
1050 sprintf (initrd, "%s/%s", pelem, initrd_name);
1061 if (kernel == NULL || initrd == NULL) {
1062 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1063 kernel_name, initrd_name, g->path);
1067 /* Get qemu help text and version. */
1068 if (test_qemu (g) == -1)
1071 /* Make the vmchannel socket. */
1072 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1075 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1076 perrorf (g, "pipe");
1082 perrorf (g, "fork");
1090 if (r == 0) { /* Child (qemu). */
1091 char vmchannel[256];
1093 char memsize_str[256];
1095 /* Set up the full command line. Do this in the subprocess so we
1096 * don't need to worry about cleaning up.
1098 g->cmdline[0] = g->qemu;
1100 #define LINUX_CMDLINE \
1101 "panic=1 " /* force kernel to panic if daemon exits */ \
1102 "console=ttyS0 " /* serial console */ \
1103 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1104 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1105 "acpi=off " /* we don't need ACPI, turn it off */ \
1106 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1108 /* Linux kernel command line. */
1109 snprintf (append, sizeof append,
1112 "%s" /* (selinux) */
1113 "%s" /* (verbose) */
1114 "%s", /* (append) */
1115 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1116 g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1117 g->verbose ? "guestfs_verbose=1 " : " ",
1118 g->append ? g->append : "");
1120 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1122 add_cmdline (g, "-m");
1123 add_cmdline (g, memsize_str);
1124 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1125 add_cmdline (g, "-kernel");
1126 add_cmdline (g, (char *) kernel);
1127 add_cmdline (g, "-initrd");
1128 add_cmdline (g, (char *) initrd);
1129 add_cmdline (g, "-append");
1130 add_cmdline (g, append);
1131 add_cmdline (g, "-nographic");
1132 add_cmdline (g, "-serial");
1133 add_cmdline (g, "stdio");
1136 /* Doesn't work. See:
1137 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1138 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1140 if (qemu_supports (g, "guestfwd")) {
1141 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1142 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1144 snprintf (vmchannel, sizeof vmchannel,
1145 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1146 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1148 add_cmdline (g, "-net");
1149 add_cmdline (g, vmchannel);
1152 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1153 * syntax, or if not then we'll get a quick failure.
1155 snprintf (vmchannel, sizeof vmchannel,
1156 "channel,%d:unix:%s,server,nowait",
1157 VMCHANNEL_PORT, unixsock);
1159 add_cmdline (g, "-net");
1160 add_cmdline (g, vmchannel);
1161 add_cmdline (g, "-net");
1162 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1166 add_cmdline (g, "-net");
1167 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1169 /* These options recommended by KVM developers to improve reliability. */
1170 if (qemu_supports (g, "-no-hpet"))
1171 add_cmdline (g, "-no-hpet");
1173 if (qemu_supports (g, "-rtc-td-hack"))
1174 add_cmdline (g, "-rtc-td-hack");
1176 /* Finish off the command line. */
1177 incr_cmdline_size (g);
1178 g->cmdline[g->cmdline_size-1] = NULL;
1183 /* Set up stdin, stdout. */
1189 if (dup (wfd[0]) == -1) {
1191 perror ("dup failed");
1194 if (dup (rfd[1]) == -1)
1201 /* Set up a new process group, so we can signal this process
1202 * and all subprocesses (eg. if qemu is really a shell script).
1207 execv (g->qemu, g->cmdline); /* Run qemu. */
1212 /* Parent (library). */
1220 /* Fork the recovery process off which will kill qemu if the parent
1221 * process fails to do so (eg. if the parent segfaults).
1225 pid_t qemu_pid = g->pid;
1226 pid_t parent_pid = getppid ();
1228 /* Writing to argv is hideously complicated and error prone. See:
1229 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1232 /* Loop around waiting for one or both of the other processes to
1233 * disappear. It's fair to say this is very hairy. The PIDs that
1234 * we are looking at might be reused by another process. We are
1235 * effectively polling. Is the cure worse than the disease?
1238 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1240 if (kill (parent_pid, 0) == -1) {
1241 /* Parent's gone away, qemu still around, so kill qemu. */
1249 /* Don't worry, if the fork failed, this will be -1. The recovery
1250 * process isn't essential.
1254 /* Start the clock ... */
1257 /* Close the other ends of the pipe. */
1261 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1262 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1263 perrorf (g, "fcntl");
1267 g->fd[0] = wfd[1]; /* stdin of child */
1268 g->fd[1] = rfd[0]; /* stdout of child */
1270 /* Open the Unix socket. The vmchannel implementation that got
1271 * merged with qemu sucks in a number of ways. Both ends do
1272 * connect(2), which means that no one knows what, if anything, is
1273 * connected to the other end, or if it becomes disconnected. Even
1274 * worse, we have to wait some indeterminate time for qemu to create
1275 * the socket and connect to it (which happens very early in qemu's
1276 * start-up), so any code that uses vmchannel is inherently racy.
1277 * Hence this silly loop.
1279 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1280 if (g->sock == -1) {
1281 perrorf (g, "socket");
1285 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1286 perrorf (g, "fcntl");
1290 addr.sun_family = AF_UNIX;
1291 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1292 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1295 /* Always sleep at least once to give qemu a small chance to start up. */
1298 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1299 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1302 if (errno != ENOENT)
1303 perrorf (g, "connect");
1308 error (g, _("failed to connect to vmchannel socket"));
1312 /* Watch the file descriptors. */
1315 g->msg_in_size = g->msg_in_allocated = 0;
1319 g->msg_out_size = 0;
1323 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1324 GUESTFS_HANDLE_READABLE,
1325 stdout_event, NULL);
1326 if (g->stdout_watch == -1) {
1327 error (g, _("could not watch qemu stdout"));
1331 if (guestfs__switch_to_receiving (g) == -1)
1334 g->state = LAUNCHING;
1338 if (g->stdout_watch >= 0)
1339 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1340 if (g->sock_watch >= 0)
1341 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1350 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1351 waitpid (g->pid, NULL, 0);
1352 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1359 g->stdout_watch = -1;
1368 /* This function is used to print the qemu command line before it gets
1369 * executed, when in verbose mode.
1372 print_cmdline (guestfs_h *g)
1377 while (g->cmdline[i]) {
1378 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1379 fprintf (stderr, " \\\n ");
1381 if (i > 0) fputc (' ', stderr);
1383 /* Does it need shell quoting? This only deals with simple cases. */
1384 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1386 if (needs_quote) fputc ('\'', stderr);
1387 fprintf (stderr, "%s", g->cmdline[i]);
1388 if (needs_quote) fputc ('\'', stderr);
1392 fputc ('\n', stderr);
1395 /* This function does the hard work of building the supermin appliance
1396 * on the fly. 'path' is the directory containing the control files.
1397 * 'kernel' and 'initrd' are where we will return the names of the
1398 * kernel and initrd (only initrd is built). The work is done by
1399 * an external script. We just tell it where to put the result.
1402 build_supermin_appliance (guestfs_h *g, const char *path,
1403 char **kernel, char **initrd)
1408 len = strlen (g->tmpdir);
1409 *kernel = safe_malloc (g, len + 8);
1410 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1411 *initrd = safe_malloc (g, len + 8);
1412 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1414 snprintf (cmd, sizeof cmd,
1416 "libguestfs-supermin-helper '%s' %s %s",
1418 path, *kernel, *initrd);
1421 if (r == -1 || WEXITSTATUS(r) != 0) {
1422 error (g, _("external command failed: %s"), cmd);
1425 *kernel = *initrd = NULL;
1432 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1434 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1435 * 'qemu -version' so we know what options this qemu supports and
1439 test_qemu (guestfs_h *g)
1444 free (g->qemu_help);
1445 free (g->qemu_version);
1446 g->qemu_help = NULL;
1447 g->qemu_version = NULL;
1449 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1451 fp = popen (cmd, "r");
1452 /* qemu -help should always work (qemu -version OTOH wasn't
1453 * supported by qemu 0.9). If this command doesn't work then it
1454 * probably indicates that the qemu binary is missing.
1457 /* XXX This error is never printed, even if the qemu binary
1458 * doesn't exist. Why?
1461 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1465 if (read_all (g, fp, &g->qemu_help) == -1)
1468 if (pclose (fp) == -1)
1471 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1473 fp = popen (cmd, "r");
1475 /* Intentionally ignore errors. */
1476 read_all (g, fp, &g->qemu_version);
1484 read_all (guestfs_h *g, FILE *fp, char **ret)
1491 *ret = safe_realloc (g, *ret, n + 1);
1496 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1498 r = fread (p, 1, BUFSIZ, fp);
1500 perrorf (g, "read");
1507 /* Test if option is supported by qemu command line (just by grepping
1511 qemu_supports (guestfs_h *g, const char *option)
1513 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1517 finish_wait_ready (guestfs_h *g, void *vp)
1520 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1523 g->main_loop->main_loop_quit (g->main_loop, g);
1527 guestfs__wait_ready (guestfs_h *g)
1529 int finished = 0, r;
1531 if (g->state == READY) return 0;
1533 if (g->state == BUSY) {
1534 error (g, _("qemu has finished launching already"));
1538 if (g->state != LAUNCHING) {
1539 error (g, _("qemu has not been launched yet"));
1543 g->launch_done_cb = finish_wait_ready;
1544 g->launch_done_cb_data = &finished;
1545 r = g->main_loop->main_loop_run (g->main_loop, g);
1546 g->launch_done_cb = NULL;
1547 g->launch_done_cb_data = NULL;
1549 if (r == -1) return -1;
1551 if (finished != 1) {
1552 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1556 /* This is possible in some really strange situations, such as
1557 * guestfsd starts up OK but then qemu immediately exits. Check for
1558 * it because the caller is probably expecting to be able to send
1559 * commands after this function returns.
1561 if (g->state != READY) {
1562 error (g, _("qemu launched and contacted daemon, but state != READY"));
1570 guestfs__kill_subprocess (guestfs_h *g)
1572 if (g->state == CONFIG) {
1573 error (g, _("no subprocess to kill"));
1578 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1580 kill (g->pid, SIGTERM);
1581 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1586 /* Access current state. */
1588 guestfs__is_config (guestfs_h *g)
1590 return g->state == CONFIG;
1594 guestfs__is_launching (guestfs_h *g)
1596 return g->state == LAUNCHING;
1600 guestfs__is_ready (guestfs_h *g)
1602 return g->state == READY;
1606 guestfs__is_busy (guestfs_h *g)
1608 return g->state == BUSY;
1612 guestfs__get_state (guestfs_h *g)
1618 guestfs__set_ready (guestfs_h *g)
1620 if (g->state != BUSY) {
1621 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1630 guestfs__set_busy (guestfs_h *g)
1632 if (g->state != READY) {
1633 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1642 guestfs__end_busy (guestfs_h *g)
1656 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1662 /* We don't know if stdout_event or sock_read_event will be the
1663 * first to receive EOF if the qemu process dies. This function
1664 * has the common cleanup code for both.
1667 child_cleanup (guestfs_h *g)
1670 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1671 /*kill (g->pid, SIGTERM);*/
1672 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1673 waitpid (g->pid, NULL, 0);
1674 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1675 if (g->stdout_watch >= 0)
1676 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1677 if (g->sock_watch >= 0)
1678 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1688 g->stdout_watch = -1;
1691 if (g->subprocess_quit_cb)
1692 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1695 /* This function is called whenever qemu prints something on stdout.
1696 * Qemu's stdout is also connected to the guest's serial console, so
1697 * we see kernel messages here too.
1700 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1701 int watch, int fd, int events)
1709 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1710 g, g->state, fd, events);
1713 if (g->fd[1] != fd) {
1714 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1718 n = read (fd, buf, sizeof buf);
1720 /* Hopefully this indicates the qemu child process has died. */
1726 if (errno != EINTR && errno != EAGAIN)
1727 perrorf (g, "read");
1731 /* In verbose mode, copy all log messages to stderr. */
1733 ignore_value (write (STDERR_FILENO, buf, n));
1735 /* It's an actual log message, send it upwards if anyone is listening. */
1736 if (g->log_message_cb)
1737 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1740 /* The function is called whenever we can read something on the
1741 * guestfsd (daemon inside the guest) communication socket.
1744 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1745 int watch, int fd, int events)
1753 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1754 g, g->state, fd, events);
1756 if (g->sock != fd) {
1757 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1761 if (g->msg_in_size <= g->msg_in_allocated) {
1762 g->msg_in_allocated += 4096;
1763 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1765 n = read (g->sock, g->msg_in + g->msg_in_size,
1766 g->msg_in_allocated - g->msg_in_size);
1774 if (errno != EINTR && errno != EAGAIN)
1775 perrorf (g, "read");
1779 g->msg_in_size += n;
1781 /* Have we got enough of a message to be able to process it yet? */
1783 if (g->msg_in_size < 4) return;
1785 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1786 if (!xdr_uint32_t (&xdr, &len)) {
1787 error (g, _("can't decode length word"));
1791 /* Length is normally the length of the message, but when guestfsd
1792 * starts up it sends a "magic" value (longer than any possible
1793 * message). Check for this.
1795 if (len == GUESTFS_LAUNCH_FLAG) {
1796 if (g->state != LAUNCHING)
1797 error (g, _("received magic signature from guestfsd, but in state %d"),
1799 else if (g->msg_in_size != 4)
1800 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1804 if (g->launch_done_cb)
1805 g->launch_done_cb (g, g->launch_done_cb_data);
1811 /* This can happen if a cancellation happens right at the end
1812 * of us sending a FileIn parameter to the daemon. Discard. The
1813 * daemon should send us an error message next.
1815 if (len == GUESTFS_CANCEL_FLAG) {
1816 g->msg_in_size -= 4;
1817 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1821 /* If this happens, it's pretty bad and we've probably lost
1824 if (len > GUESTFS_MESSAGE_MAX) {
1825 error (g, _("message length (%u) > maximum possible size (%d)"),
1826 len, GUESTFS_MESSAGE_MAX);
1830 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1832 /* Got the full message, begin processing it. */
1837 for (i = 0; i < g->msg_in_size; i += 16) {
1838 printf ("%04x: ", i);
1839 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1840 printf ("%02x ", (unsigned char) g->msg_in[j]);
1841 for (; j < i+16; ++j)
1844 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1845 if (isprint (g->msg_in[j]))
1846 printf ("%c", g->msg_in[j]);
1849 for (; j < i+16; ++j)
1856 /* Not in the expected state. */
1857 if (g->state != BUSY)
1858 error (g, _("state %d != BUSY"), g->state);
1860 /* Push the message up to the higher layer. */
1862 g->reply_cb (g, g->reply_cb_data, &xdr);
1864 /* This message (probably) should never be printed. */
1865 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1867 g->msg_in_size -= len + 4;
1868 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1869 if (g->msg_in_size > 0) goto again;
1872 /* Free the message buffer if it's grown excessively large. */
1873 if (g->msg_in_allocated > 65536) {
1876 g->msg_in_size = g->msg_in_allocated = 0;
1883 /* The function is called whenever we can write something on the
1884 * guestfsd (daemon inside the guest) communication socket.
1887 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1888 int watch, int fd, int events)
1894 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1895 g, g->state, fd, events);
1897 if (g->sock != fd) {
1898 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1902 if (g->state != BUSY) {
1903 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1908 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1909 g->msg_out_size - g->msg_out_pos);
1911 n = write (g->sock, g->msg_out + g->msg_out_pos,
1912 g->msg_out_size - g->msg_out_pos);
1916 perrorf (g, "write");
1917 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1923 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1925 g->msg_out_pos += n;
1927 /* More to write? */
1928 if (g->msg_out_pos < g->msg_out_size)
1932 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1936 g->msg_out_pos = g->msg_out_size = 0;
1938 /* Done writing, call the higher layer. */
1940 g->send_cb (g, g->send_cb_data);
1944 guestfs_set_send_callback (guestfs_h *g,
1945 guestfs_send_cb cb, void *opaque)
1948 g->send_cb_data = opaque;
1952 guestfs_set_reply_callback (guestfs_h *g,
1953 guestfs_reply_cb cb, void *opaque)
1956 g->reply_cb_data = opaque;
1960 guestfs_set_log_message_callback (guestfs_h *g,
1961 guestfs_log_message_cb cb, void *opaque)
1963 g->log_message_cb = cb;
1964 g->log_message_cb_data = opaque;
1968 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1969 guestfs_subprocess_quit_cb cb, void *opaque)
1971 g->subprocess_quit_cb = cb;
1972 g->subprocess_quit_cb_data = opaque;
1976 guestfs_set_launch_done_callback (guestfs_h *g,
1977 guestfs_launch_done_cb cb, void *opaque)
1979 g->launch_done_cb = cb;
1980 g->launch_done_cb_data = opaque;
1983 /* Access to the handle's main loop and the default main loop. */
1985 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1987 g->main_loop = main_loop;
1991 guestfs_get_main_loop (guestfs_h *g)
1993 return g->main_loop;
1997 guestfs_get_default_main_loop (void)
1999 return (guestfs_main_loop *) &default_main_loop;
2002 /* Change the daemon socket handler so that we are now writing.
2003 * This sets the handle to sock_write_event.
2006 guestfs__switch_to_sending (guestfs_h *g)
2008 if (g->sock_watch >= 0) {
2009 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
2010 error (g, _("remove_handle failed"));
2017 g->main_loop->add_handle (g->main_loop, g, g->sock,
2018 GUESTFS_HANDLE_WRITABLE,
2019 sock_write_event, NULL);
2020 if (g->sock_watch == -1) {
2021 error (g, _("add_handle failed"));
2029 guestfs__switch_to_receiving (guestfs_h *g)
2031 if (g->sock_watch >= 0) {
2032 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
2033 error (g, _("remove_handle failed"));
2040 g->main_loop->add_handle (g->main_loop, g, g->sock,
2041 GUESTFS_HANDLE_READABLE,
2042 sock_read_event, NULL);
2043 if (g->sock_watch == -1) {
2044 error (g, _("add_handle failed"));
2051 /* Dispatch a call (len + header + args) to the remote daemon,
2052 * synchronously (ie. using the guest's main loop to wait until
2053 * it has been sent). Returns -1 for error, or the serial
2054 * number of the message.
2057 send_cb (guestfs_h *g, void *data)
2059 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2062 ml->main_loop_quit (ml, g);
2066 guestfs__send_sync (guestfs_h *g, int proc_nr,
2067 xdrproc_t xdrp, char *args)
2069 struct guestfs_message_header hdr;
2072 int serial = g->msg_next_serial++;
2074 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2076 if (g->state != BUSY) {
2077 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2081 /* This is probably an internal error. Or perhaps we should just
2082 * free the buffer anyway?
2084 if (g->msg_out != NULL) {
2085 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2089 /* We have to allocate this message buffer on the heap because
2090 * it is quite large (although will be mostly unused). We
2091 * can't allocate it on the stack because in some environments
2092 * we have quite limited stack space available, notably when
2093 * running in the JVM.
2095 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2096 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2098 /* Serialize the header. */
2099 hdr.prog = GUESTFS_PROGRAM;
2100 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2102 hdr.direction = GUESTFS_DIRECTION_CALL;
2103 hdr.serial = serial;
2104 hdr.status = GUESTFS_STATUS_OK;
2106 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2107 error (g, _("xdr_guestfs_message_header failed"));
2111 /* Serialize the args. If any, because some message types
2112 * have no parameters.
2115 if (!(*xdrp) (&xdr, args)) {
2116 error (g, _("dispatch failed to marshal args"));
2121 /* Get the actual length of the message, resize the buffer to match
2122 * the actual length, and write the length word at the beginning.
2124 len = xdr_getpos (&xdr);
2127 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2128 g->msg_out_size = len + 4;
2131 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2132 xdr_uint32_t (&xdr, &len);
2134 if (guestfs__switch_to_sending (g) == -1)
2138 guestfs_set_send_callback (g, send_cb, &sent);
2139 if (ml->main_loop_run (ml, g) == -1)
2142 error (g, _("send failed, see earlier error messages"));
2151 g->msg_out_size = 0;
2155 static int cancel = 0; /* XXX Implement file cancellation. */
2156 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2157 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2158 static int send_file_cancellation_sync (guestfs_h *g);
2159 static int send_file_complete_sync (guestfs_h *g);
2161 /* Synchronously send a file.
2165 * -2 daemon cancelled (we must read the error message)
2168 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2170 char buf[GUESTFS_MAX_CHUNK_SIZE];
2173 fd = open (filename, O_RDONLY);
2175 perrorf (g, "open: %s", filename);
2176 send_file_cancellation_sync (g);
2177 /* Daemon sees cancellation and won't reply, so caller can
2183 /* Send file in chunked encoding. */
2185 r = read (fd, buf, sizeof buf);
2186 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2189 err = send_file_data_sync (g, buf, r);
2191 if (err == -2) /* daemon sent cancellation */
2192 send_file_cancellation_sync (g);
2197 if (cancel) { /* cancel from either end */
2198 send_file_cancellation_sync (g);
2203 perrorf (g, "read: %s", filename);
2204 send_file_cancellation_sync (g);
2208 /* End of file, but before we send that, we need to close
2209 * the file and check for errors.
2211 if (close (fd) == -1) {
2212 perrorf (g, "close: %s", filename);
2213 send_file_cancellation_sync (g);
2217 return send_file_complete_sync (g);
2220 /* Send a chunk of file data. */
2222 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2224 return send_file_chunk_sync (g, 0, buf, len);
2227 /* Send a cancellation message. */
2229 send_file_cancellation_sync (guestfs_h *g)
2231 return send_file_chunk_sync (g, 1, NULL, 0);
2234 /* Send a file complete chunk. */
2236 send_file_complete_sync (guestfs_h *g)
2239 return send_file_chunk_sync (g, 0, buf, 0);
2242 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2245 static int check_for_daemon_cancellation (guestfs_h *g);
2248 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2252 guestfs_chunk chunk;
2254 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2256 if (g->state != BUSY) {
2257 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2261 /* This is probably an internal error. Or perhaps we should just
2262 * free the buffer anyway?
2264 if (g->msg_out != NULL) {
2265 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2269 /* Did the daemon send a cancellation message? */
2270 if (check_for_daemon_cancellation (g)) {
2272 fprintf (stderr, "got daemon cancellation\n");
2276 /* Allocate the chunk buffer. Don't use the stack to avoid
2277 * excessive stack usage and unnecessary copies.
2279 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2280 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2282 /* Serialize the chunk. */
2283 chunk.cancel = cancel;
2284 chunk.data.data_len = buflen;
2285 chunk.data.data_val = (char *) buf;
2287 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2288 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2294 len = xdr_getpos (&xdr);
2297 /* Reduce the size of the outgoing message buffer to the real length. */
2298 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2299 g->msg_out_size = len + 4;
2302 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2303 xdr_uint32_t (&xdr, &len);
2305 if (guestfs__switch_to_sending (g) == -1)
2309 guestfs_set_send_callback (g, send_cb, &sent);
2310 if (ml->main_loop_run (ml, g) == -1)
2313 error (g, _("send file chunk failed, see earlier error messages"));
2322 g->msg_out_size = 0;
2326 /* At this point we are sending FileIn file(s) to the guest, and not
2327 * expecting to read anything, so if we do read anything, it must be
2328 * a cancellation message. This checks for this case without blocking.
2331 check_for_daemon_cancellation (guestfs_h *g)
2341 FD_SET (g->sock, &rset);
2344 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2346 perrorf (g, "select");
2352 /* Read the message from the daemon. */
2353 r = xread (g->sock, buf, sizeof buf);
2355 perrorf (g, "read");
2359 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2360 xdr_uint32_t (&xdr, &flag);
2363 if (flag != GUESTFS_CANCEL_FLAG) {
2364 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2365 flag, GUESTFS_CANCEL_FLAG);
2372 /* Synchronously receive a file. */
2374 /* Returns -1 = error, 0 = EOF, 1 = more data */
2375 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2378 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2384 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2386 perrorf (g, "open: %s", filename);
2390 /* Receive the file in chunked encoding. */
2391 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2392 if (xwrite (fd, buf, len) == -1) {
2393 perrorf (g, "%s: write", filename);
2398 if (r == 0) break; /* End of file. */
2402 error (g, _("%s: error in chunked encoding"), filename);
2406 if (close (fd) == -1) {
2407 perrorf (g, "close: %s", filename);
2414 /* Send cancellation message to daemon, then wait until it
2415 * cancels (just throwing away data).
2419 uint32_t flag = GUESTFS_CANCEL_FLAG;
2422 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2425 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2426 xdr_uint32_t (&xdr, &flag);
2429 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2430 perrorf (g, _("write to daemon socket"));
2434 while (receive_file_data_sync (g, NULL, NULL) > 0)
2435 ; /* just discard it */
2440 /* Note that the reply callback can be called multiple times before
2441 * the main loop quits and we get back to the synchronous code. So
2442 * we have to be prepared to save multiple chunks on a list here.
2444 struct receive_file_ctx {
2445 int count; /* 0 if receive_file_cb not called, or
2446 * else count number of chunks.
2448 guestfs_chunk *chunks; /* Array of chunks. */
2452 free_chunks (struct receive_file_ctx *ctx)
2456 for (i = 0; i < ctx->count; ++i)
2457 free (ctx->chunks[i].data.data_val);
2463 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2465 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2466 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2467 guestfs_chunk chunk;
2469 if (ctx->count == -1) /* Parse error occurred previously. */
2472 ml->main_loop_quit (ml, g);
2474 memset (&chunk, 0, sizeof chunk);
2476 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2477 error (g, _("failed to parse file chunk"));
2484 /* Copy the chunk to the list. */
2485 ctx->chunks = safe_realloc (g, ctx->chunks,
2486 sizeof (guestfs_chunk) * (ctx->count+1));
2487 ctx->chunks[ctx->count] = chunk;
2491 /* Receive a chunk of file data. */
2492 /* Returns -1 = error, 0 = EOF, 1 = more data */
2494 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2496 struct receive_file_ctx ctx;
2497 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2504 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2505 (void) ml->main_loop_run (ml, g);
2506 guestfs_set_reply_callback (g, NULL, NULL);
2508 if (ctx.count == 0) {
2509 error (g, _("receive_file_data_sync: reply callback not called\n"));
2513 if (ctx.count == -1) {
2514 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2515 /* callback already freed the chunks */
2520 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2522 /* Process each chunk in the list. */
2523 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2526 for (i = 0; i < ctx.count; ++i) {
2527 if (ctx.chunks[i].cancel) {
2528 error (g, _("file receive cancelled by daemon"));
2530 if (buf) free (*buf);
2531 if (len_r) *len_r = 0;
2535 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2537 if (len_r) *len_r = len;
2542 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2543 memcpy (((char *)*buf)+len, ctx.chunks[i].data.data_val,
2544 ctx.chunks[i].data.data_len);
2546 len += ctx.chunks[i].data.data_len;
2549 if (len_r) *len_r = len;
2554 /* This is the default main loop implementation, using select(2). */
2557 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2558 guestfs_handle_event_cb cb, void *data)
2560 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2562 if (fd < 0 || fd >= FD_SETSIZE) {
2563 error (g, _("fd %d is out of range"), fd);
2567 if ((events & ~(GUESTFS_HANDLE_READABLE |
2568 GUESTFS_HANDLE_WRITABLE |
2569 GUESTFS_HANDLE_HANGUP |
2570 GUESTFS_HANDLE_ERROR)) != 0) {
2571 error (g, _("set of events (0x%x) contains unknown events"), events);
2576 error (g, _("set of events is empty"));
2580 if (FD_ISSET (fd, &ml->rset) ||
2581 FD_ISSET (fd, &ml->wset) ||
2582 FD_ISSET (fd, &ml->xset)) {
2583 error (g, _("fd %d is already registered"), fd);
2588 error (g, _("callback is NULL"));
2592 if ((events & GUESTFS_HANDLE_READABLE))
2593 FD_SET (fd, &ml->rset);
2594 if ((events & GUESTFS_HANDLE_WRITABLE))
2595 FD_SET (fd, &ml->wset);
2596 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2597 FD_SET (fd, &ml->xset);
2599 if (fd > ml->max_fd) {
2601 ml->handle_cb_data =
2602 safe_realloc (g, ml->handle_cb_data,
2603 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2605 ml->handle_cb_data[fd].cb = cb;
2606 ml->handle_cb_data[fd].g = g;
2607 ml->handle_cb_data[fd].data = data;
2611 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2616 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2618 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2620 if (fd < 0 || fd >= FD_SETSIZE) {
2621 error (g, _("fd %d is out of range"), fd);
2625 if (!FD_ISSET (fd, &ml->rset) &&
2626 !FD_ISSET (fd, &ml->wset) &&
2627 !FD_ISSET (fd, &ml->xset)) {
2628 error (g, _("fd %d was not registered"), fd);
2632 FD_CLR (fd, &ml->rset);
2633 FD_CLR (fd, &ml->wset);
2634 FD_CLR (fd, &ml->xset);
2636 if (fd == ml->max_fd) {
2638 ml->handle_cb_data =
2639 safe_realloc (g, ml->handle_cb_data,
2640 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2649 __attribute__((noreturn))
2650 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2651 guestfs_handle_timeout_cb cb, void *data)
2653 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2655 abort (); /* XXX not implemented yet */
2659 __attribute__((noreturn))
2660 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2662 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2664 abort (); /* XXX not implemented yet */
2667 /* The 'g' parameter is just used for error reporting. Events
2668 * for multiple handles can be dispatched by running the main
2672 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2674 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2676 fd_set rset2, wset2, xset2;
2678 if (ml->is_running) {
2679 error (g, _("select_main_loop_run: this cannot be called recursively"));
2685 while (ml->is_running) {
2686 if (ml->nr_fds == 0)
2692 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2694 if (errno == EINTR || errno == EAGAIN)
2696 perrorf (g, "select");
2701 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2703 if (FD_ISSET (fd, &rset2))
2704 events |= GUESTFS_HANDLE_READABLE;
2705 if (FD_ISSET (fd, &wset2))
2706 events |= GUESTFS_HANDLE_WRITABLE;
2707 if (FD_ISSET (fd, &xset2))
2708 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2711 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2712 ml->handle_cb_data[fd].g,
2713 ml->handle_cb_data[fd].data,
2724 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2726 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2728 /* Note that legitimately ml->is_running can be zero when
2729 * this function is called.