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"
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. */
175 char *path; /* Path to kernel, initrd. */
176 char *qemu; /* Qemu binary. */
177 char *append; /* Append to kernel command line. */
179 int memsize; /* Size of RAM (megabytes). */
181 int selinux; /* selinux enabled? */
186 guestfs_abort_cb abort_cb;
187 guestfs_error_handler_cb error_cb;
188 void * error_cb_data;
189 guestfs_send_cb send_cb;
191 guestfs_reply_cb reply_cb;
192 void * reply_cb_data;
193 guestfs_log_message_cb log_message_cb;
194 void * log_message_cb_data;
195 guestfs_subprocess_quit_cb subprocess_quit_cb;
196 void * subprocess_quit_cb_data;
197 guestfs_launch_done_cb launch_done_cb;
198 void * launch_done_cb_data;
200 /* Main loop used by this handle. */
201 guestfs_main_loop *main_loop;
203 /* Messages sent and received from the daemon. */
205 unsigned int msg_in_size, msg_in_allocated;
207 unsigned int msg_out_size, msg_out_pos;
212 static guestfs_h *handles = NULL;
213 static int atexit_handler_set = 0;
216 guestfs_create (void)
221 g = malloc (sizeof (*g));
224 memset (g, 0, sizeof (*g));
231 g->stdout_watch = -1;
235 g->error_cb = default_error_cb;
236 g->error_cb_data = NULL;
238 str = getenv ("LIBGUESTFS_DEBUG");
239 g->verbose = str != NULL && strcmp (str, "1") == 0;
241 str = getenv ("LIBGUESTFS_PATH");
242 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
243 if (!g->path) goto error;
245 str = getenv ("LIBGUESTFS_QEMU");
246 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
247 if (!g->qemu) goto error;
249 str = getenv ("LIBGUESTFS_APPEND");
251 g->append = strdup (str);
252 if (!g->append) goto error;
255 /* Choose a suitable memory size. Previously we tried to choose
256 * a minimal memory size, but this isn't really necessary since
257 * recent QEMU and KVM don't do anything nasty like locking
258 * memory into core any more. Thus we can safely choose a
259 * large, generous amount of memory, and it'll just get swapped
260 * on smaller systems.
262 str = getenv ("LIBGUESTFS_MEMSIZE");
264 if (sscanf (str, "%d", &g->memsize) != 1 || g->memsize <= 256) {
265 fprintf (stderr, "libguestfs: non-numeric or too small value for LIBGUESTFS_MEMSIZE\n");
271 g->main_loop = guestfs_get_default_main_loop ();
273 /* Start with large serial numbers so they are easy to spot
274 * inside the protocol.
276 g->msg_next_serial = 0x00123400;
278 /* Link the handles onto a global list. This is the one area
279 * where the library needs to be made thread-safe. (XXX)
281 /* acquire mutex (XXX) */
284 if (!atexit_handler_set) {
285 atexit (close_handles);
286 atexit_handler_set = 1;
288 /* release mutex (XXX) */
291 fprintf (stderr, "new guestfs handle %p\n", g);
304 guestfs_close (guestfs_h *g)
310 if (g->state == NO_HANDLE) {
311 /* Not safe to call 'error' here, so ... */
312 fprintf (stderr, _("guestfs_close: called twice on the same handle\n"));
317 fprintf (stderr, "closing guestfs handle %p (state %d)\n", g, g->state);
319 /* Try to sync if autosync flag is set. */
320 if (g->autosync && g->state == READY) {
321 guestfs_umount_all (g);
325 /* Remove any handlers that might be called back before we kill the
328 g->log_message_cb = NULL;
330 if (g->state != CONFIG)
331 guestfs_kill_subprocess (g);
333 /* Close any sockets and deregister any handlers. */
334 if (g->stdout_watch >= 0)
335 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
336 if (g->sock_watch >= 0)
337 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
338 g->stdout_watch = -1;
351 /* Wait for subprocess(es) to exit. */
352 waitpid (g->pid, NULL, 0);
353 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
355 /* Remove tmpfiles. */
357 snprintf (filename, sizeof filename, "%s/sock", g->tmpdir);
360 snprintf (filename, sizeof filename, "%s/initrd", g->tmpdir);
363 snprintf (filename, sizeof filename, "%s/kernel", g->tmpdir);
372 for (i = 0; i < g->cmdline_size; ++i)
373 free (g->cmdline[i]);
377 /* Mark the handle as dead before freeing it. */
378 g->state = NO_HANDLE;
380 /* acquire mutex (XXX) */
384 for (gg = handles; gg->next != g; gg = gg->next)
388 /* release mutex (XXX) */
392 free (g->last_error);
397 free (g->qemu_version);
401 /* Close all open handles (called from atexit(3)). */
405 while (handles) guestfs_close (handles);
409 guestfs_last_error (guestfs_h *g)
411 return g->last_error;
415 set_last_error (guestfs_h *g, const char *msg)
417 free (g->last_error);
418 g->last_error = strdup (msg);
422 default_error_cb (guestfs_h *g, void *data, const char *msg)
424 fprintf (stderr, _("libguestfs: error: %s\n"), msg);
428 guestfs_error (guestfs_h *g, const char *fs, ...)
434 int err = vasprintf (&msg, fs, args);
439 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
440 set_last_error (g, msg);
446 guestfs_perrorf (guestfs_h *g, const char *fs, ...)
453 int err = vasprintf (&msg, fs, args);
460 strerror_r (errnum, buf, sizeof buf);
464 buf = strerror_r (errnum, _buf, sizeof _buf);
467 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
471 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
472 set_last_error (g, msg);
478 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
480 void *ptr = malloc (nbytes);
481 if (nbytes > 0 && !ptr) g->abort_cb ();
485 /* Return 1 if an array of N objects, each of size S, cannot exist due
486 to size arithmetic overflow. S must be positive and N must be
487 nonnegative. This is a macro, not an inline function, so that it
488 works correctly even when SIZE_MAX < N.
490 By gnulib convention, SIZE_MAX represents overflow in size
491 calculations, so the conservative dividend to use here is
492 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
493 However, malloc (SIZE_MAX) fails on all known hosts where
494 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
495 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
496 branch when S is known to be 1. */
497 # define xalloc_oversized(n, s) \
498 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
500 /* Technically we should add an autoconf test for this, testing for the desired
501 functionality, like what's done in gnulib, but for now, this is fine. */
502 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
504 /* Allocate zeroed memory for N elements of S bytes, with error
505 checking. S must be nonzero. */
507 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
509 /* From gnulib's calloc function in xmalloc.c. */
511 /* Test for overflow, since some calloc implementations don't have
512 proper overflow checks. But omit overflow and size-zero tests if
513 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
514 returns NULL if successful. */
515 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
516 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
522 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
524 void *p = realloc (ptr, nbytes);
525 if (nbytes > 0 && !p) g->abort_cb ();
530 guestfs_safe_strdup (guestfs_h *g, const char *str)
532 char *s = strdup (str);
533 if (!s) g->abort_cb ();
538 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
540 void *p = malloc (size);
541 if (!p) g->abort_cb ();
542 memcpy (p, ptr, size);
547 xwrite (int fd, const void *v_buf, size_t len)
549 const char *buf = v_buf;
553 r = write (fd, buf, len);
565 xread (int fd, void *v_buf, size_t len)
571 r = read (fd, buf, len);
573 if (errno == EINTR || errno == EAGAIN)
586 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
592 guestfs_get_out_of_memory_handler (guestfs_h *g)
598 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
601 g->error_cb_data = data;
604 guestfs_error_handler_cb
605 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
607 if (data_rtn) *data_rtn = g->error_cb_data;
612 guestfs_set_verbose (guestfs_h *g, int v)
619 guestfs_get_verbose (guestfs_h *g)
625 guestfs_set_autosync (guestfs_h *g, int a)
632 guestfs_get_autosync (guestfs_h *g)
638 guestfs_set_path (guestfs_h *g, const char *path)
645 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
650 guestfs_get_path (guestfs_h *g)
656 guestfs_set_qemu (guestfs_h *g, const char *qemu)
661 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
666 guestfs_get_qemu (guestfs_h *g)
672 guestfs_set_append (guestfs_h *g, const char *append)
677 g->append = append ? safe_strdup (g, append) : NULL;
682 guestfs_get_append (guestfs_h *g)
688 guestfs_set_memsize (guestfs_h *g, int memsize)
690 g->memsize = memsize;
695 guestfs_get_memsize (guestfs_h *g)
701 guestfs_set_selinux (guestfs_h *g, int selinux)
703 g->selinux = selinux;
708 guestfs_get_selinux (guestfs_h *g)
714 guestfs_get_pid (guestfs_h *g)
719 error (g, "get_pid: no qemu subprocess");
724 struct guestfs_version *
725 guestfs_version (guestfs_h *g)
727 struct guestfs_version *r;
729 r = safe_malloc (g, sizeof *r);
730 r->major = PACKAGE_VERSION_MAJOR;
731 r->minor = PACKAGE_VERSION_MINOR;
732 r->release = PACKAGE_VERSION_RELEASE;
733 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
737 /* Add a string to the current command line. */
739 incr_cmdline_size (guestfs_h *g)
741 if (g->cmdline == NULL) {
742 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
744 g->cmdline = safe_malloc (g, sizeof (char *));
745 g->cmdline[0] = NULL;
749 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
753 add_cmdline (guestfs_h *g, const char *str)
755 if (g->state != CONFIG) {
757 _("command line cannot be altered after qemu subprocess launched"));
761 incr_cmdline_size (g);
762 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
767 guestfs_config (guestfs_h *g,
768 const char *qemu_param, const char *qemu_value)
770 if (qemu_param[0] != '-') {
771 error (g, _("guestfs_config: parameter must begin with '-' character"));
775 /* A bit fascist, but the user will probably break the extra
776 * parameters that we add if they try to set any of these.
778 if (strcmp (qemu_param, "-kernel") == 0 ||
779 strcmp (qemu_param, "-initrd") == 0 ||
780 strcmp (qemu_param, "-nographic") == 0 ||
781 strcmp (qemu_param, "-serial") == 0 ||
782 strcmp (qemu_param, "-full-screen") == 0 ||
783 strcmp (qemu_param, "-std-vga") == 0 ||
784 strcmp (qemu_param, "-vnc") == 0) {
785 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
789 if (add_cmdline (g, qemu_param) != 0) return -1;
791 if (qemu_value != NULL) {
792 if (add_cmdline (g, qemu_value) != 0) return -1;
799 guestfs_add_drive (guestfs_h *g, const char *filename)
801 size_t len = strlen (filename) + 64;
804 if (strchr (filename, ',') != NULL) {
805 error (g, _("filename cannot contain ',' (comma) character"));
809 /* cache=off improves reliability in the event of a host crash.
811 * However this option causes qemu to try to open the file with
812 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
813 * So we check if we can open the file with or without O_DIRECT,
814 * and use cache=off (or not) accordingly.
816 * This test also checks for the presence of the file, which
817 * is a documented semantic of this interface.
819 int fd = open (filename, O_RDONLY|O_DIRECT);
822 snprintf (buf, len, "file=%s,cache=off,if=" DRIVE_IF, filename);
824 fd = open (filename, O_RDONLY);
827 snprintf (buf, len, "file=%s,if=" DRIVE_IF, filename);
829 perrorf (g, "%s", filename);
834 return guestfs_config (g, "-drive", buf);
838 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
840 size_t len = strlen (filename) + 64;
843 if (strchr (filename, ',') != NULL) {
844 error (g, _("filename cannot contain ',' (comma) character"));
848 if (access (filename, F_OK) == -1) {
849 perrorf (g, "%s", filename);
853 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
855 return guestfs_config (g, "-drive", buf);
859 guestfs_add_cdrom (guestfs_h *g, const char *filename)
861 if (strchr (filename, ',') != NULL) {
862 error (g, _("filename cannot contain ',' (comma) character"));
866 if (access (filename, F_OK) == -1) {
867 perrorf (g, "%s", filename);
871 return guestfs_config (g, "-cdrom", filename);
874 /* Returns true iff file is contained in dir. */
876 dir_contains_file (const char *dir, const char *file)
878 int dirlen = strlen (dir);
879 int filelen = strlen (file);
880 int len = dirlen+filelen+2;
883 snprintf (path, len, "%s/%s", dir, file);
884 return access (path, F_OK) == 0;
887 /* Returns true iff every listed file is contained in 'dir'. */
889 dir_contains_files (const char *dir, ...)
894 va_start (args, dir);
895 while ((file = va_arg (args, const char *)) != NULL) {
896 if (!dir_contains_file (dir, file)) {
905 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
906 static int test_qemu (guestfs_h *g);
907 static int qemu_supports (guestfs_h *g, const char *option);
908 static void print_cmdline (guestfs_h *g);
910 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
911 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
912 static const char *supermin_name =
913 "initramfs." REPO "." host_cpu ".supermin.img";
914 static const char *supermin_hostfiles_name =
915 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
918 guestfs_launch (guestfs_h *g)
921 char dir_template[PATH_MAX];
926 char *path, *pelem, *pend;
927 char *kernel = NULL, *initrd = NULL;
929 struct sockaddr_un addr;
937 tmpdir = getenv ("TMPDIR") ? : tmpdir;
938 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
942 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
946 if (g->state != CONFIG) {
947 error (g, _("qemu has already been launched"));
951 /* Make the temporary directory. */
953 g->tmpdir = safe_strdup (g, dir_template);
954 if (mkdtemp (g->tmpdir) == NULL) {
955 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
960 /* First search g->path for the supermin appliance, and try to
961 * synthesize a kernel and initrd from that. If it fails, we
962 * try the path search again looking for a backup ordinary
965 pelem = path = safe_strdup (g, g->path);
967 pend = strchrnul (pelem, ':');
968 pmore = *pend == ':';
972 /* Empty element of "." means cwd. */
973 if (len == 0 || (len == 1 && *pelem == '.')) {
976 "looking for supermin appliance in current directory\n");
977 if (dir_contains_files (".",
978 supermin_name, supermin_hostfiles_name,
979 "kmod.whitelist", NULL)) {
980 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
985 /* Look at <path>/supermin* etc. */
988 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
990 if (dir_contains_files (pelem,
991 supermin_name, supermin_hostfiles_name,
992 "kmod.whitelist", NULL)) {
993 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
1004 if (kernel == NULL || initrd == NULL) {
1005 /* Search g->path for the kernel and initrd. */
1006 pelem = path = safe_strdup (g, g->path);
1008 pend = strchrnul (pelem, ':');
1009 pmore = *pend == ':';
1013 /* Empty element or "." means cwd. */
1014 if (len == 0 || (len == 1 && *pelem == '.')) {
1017 "looking for appliance in current directory\n");
1018 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1019 kernel = safe_strdup (g, kernel_name);
1020 initrd = safe_strdup (g, initrd_name);
1024 /* Look at <path>/kernel etc. */
1027 fprintf (stderr, "looking for appliance in %s\n", pelem);
1029 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1030 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1031 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1032 sprintf (kernel, "%s/%s", pelem, kernel_name);
1033 sprintf (initrd, "%s/%s", pelem, initrd_name);
1044 if (kernel == NULL || initrd == NULL) {
1045 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1046 kernel_name, initrd_name, g->path);
1050 /* Get qemu help text and version. */
1051 if (test_qemu (g) == -1)
1054 /* Make the vmchannel socket. */
1055 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1058 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1059 perrorf (g, "pipe");
1065 perrorf (g, "fork");
1073 if (r == 0) { /* Child (qemu). */
1074 char vmchannel[256];
1076 char memsize_str[256];
1078 /* Set up the full command line. Do this in the subprocess so we
1079 * don't need to worry about cleaning up.
1081 g->cmdline[0] = g->qemu;
1083 #define LINUX_CMDLINE \
1084 "panic=1 " /* force kernel to panic if daemon exits */ \
1085 "console=ttyS0 " /* serial console */ \
1086 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1087 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1088 "acpi=off " /* we don't need ACPI, turn it off */ \
1089 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
1091 /* Linux kernel command line. */
1092 snprintf (append, sizeof append,
1095 "%s" /* (selinux) */
1096 "%s" /* (verbose) */
1097 "%s", /* (append) */
1098 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1099 g->selinux ? "selinux=1 enforcing=0 " : "selinux=0 ",
1100 g->verbose ? "guestfs_verbose=1 " : " ",
1101 g->append ? g->append : "");
1103 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1105 add_cmdline (g, "-m");
1106 add_cmdline (g, memsize_str);
1107 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1108 add_cmdline (g, "-kernel");
1109 add_cmdline (g, (char *) kernel);
1110 add_cmdline (g, "-initrd");
1111 add_cmdline (g, (char *) initrd);
1112 add_cmdline (g, "-append");
1113 add_cmdline (g, append);
1114 add_cmdline (g, "-nographic");
1115 add_cmdline (g, "-serial");
1116 add_cmdline (g, "stdio");
1119 /* Doesn't work. See:
1120 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1121 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1123 if (qemu_supports (g, "guestfwd")) {
1124 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1125 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1127 snprintf (vmchannel, sizeof vmchannel,
1128 "user,vlan=0,net=10.0.2.0/8,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1129 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1131 add_cmdline (g, "-net");
1132 add_cmdline (g, vmchannel);
1135 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1136 * syntax, or if not then we'll get a quick failure.
1138 snprintf (vmchannel, sizeof vmchannel,
1139 "channel,%d:unix:%s,server,nowait",
1140 VMCHANNEL_PORT, unixsock);
1142 add_cmdline (g, "-net");
1143 add_cmdline (g, vmchannel);
1144 add_cmdline (g, "-net");
1145 add_cmdline (g, "user,vlan=0,net=10.0.2.0/8");
1149 add_cmdline (g, "-net");
1150 add_cmdline (g, "nic,model=" NET_IF ",vlan=0");
1152 /* These options recommended by KVM developers to improve reliability. */
1153 if (qemu_supports (g, "-no-hpet"))
1154 add_cmdline (g, "-no-hpet");
1156 if (qemu_supports (g, "-rtc-td-hack"))
1157 add_cmdline (g, "-rtc-td-hack");
1159 /* Finish off the command line. */
1160 incr_cmdline_size (g);
1161 g->cmdline[g->cmdline_size-1] = NULL;
1166 /* Set up stdin, stdout. */
1172 if (dup (wfd[0]) == -1) {
1174 perror ("dup failed");
1177 if (dup (rfd[1]) == -1)
1184 /* Set up a new process group, so we can signal this process
1185 * and all subprocesses (eg. if qemu is really a shell script).
1190 execv (g->qemu, g->cmdline); /* Run qemu. */
1195 /* Parent (library). */
1203 /* Fork the recovery process off which will kill qemu if the parent
1204 * process fails to do so (eg. if the parent segfaults).
1208 pid_t qemu_pid = g->pid;
1209 pid_t parent_pid = getppid ();
1211 /* Writing to argv is hideously complicated and error prone. See:
1212 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1215 /* Loop around waiting for one or both of the other processes to
1216 * disappear. It's fair to say this is very hairy. The PIDs that
1217 * we are looking at might be reused by another process. We are
1218 * effectively polling. Is the cure worse than the disease?
1221 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1223 if (kill (parent_pid, 0) == -1) {
1224 /* Parent's gone away, qemu still around, so kill qemu. */
1232 /* Don't worry, if the fork failed, this will be -1. The recovery
1233 * process isn't essential.
1237 /* Start the clock ... */
1240 /* Close the other ends of the pipe. */
1244 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1245 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1246 perrorf (g, "fcntl");
1250 g->fd[0] = wfd[1]; /* stdin of child */
1251 g->fd[1] = rfd[0]; /* stdout of child */
1253 /* Open the Unix socket. The vmchannel implementation that got
1254 * merged with qemu sucks in a number of ways. Both ends do
1255 * connect(2), which means that no one knows what, if anything, is
1256 * connected to the other end, or if it becomes disconnected. Even
1257 * worse, we have to wait some indeterminate time for qemu to create
1258 * the socket and connect to it (which happens very early in qemu's
1259 * start-up), so any code that uses vmchannel is inherently racy.
1260 * Hence this silly loop.
1262 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1263 if (g->sock == -1) {
1264 perrorf (g, "socket");
1268 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1269 perrorf (g, "fcntl");
1273 addr.sun_family = AF_UNIX;
1274 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1275 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1278 /* Always sleep at least once to give qemu a small chance to start up. */
1281 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1282 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1285 if (errno != ENOENT)
1286 perrorf (g, "connect");
1291 error (g, _("failed to connect to vmchannel socket"));
1295 /* Watch the file descriptors. */
1298 g->msg_in_size = g->msg_in_allocated = 0;
1302 g->msg_out_size = 0;
1306 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1307 GUESTFS_HANDLE_READABLE,
1308 stdout_event, NULL);
1309 if (g->stdout_watch == -1) {
1310 error (g, _("could not watch qemu stdout"));
1314 if (guestfs__switch_to_receiving (g) == -1)
1317 g->state = LAUNCHING;
1321 if (g->stdout_watch >= 0)
1322 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1323 if (g->sock_watch >= 0)
1324 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1333 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1334 waitpid (g->pid, NULL, 0);
1335 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1342 g->stdout_watch = -1;
1351 /* This function is used to print the qemu command line before it gets
1352 * executed, when in verbose mode.
1355 print_cmdline (guestfs_h *g)
1360 while (g->cmdline[i]) {
1361 if (g->cmdline[i][0] == '-') /* -option starts a new line */
1362 fprintf (stderr, " \\\n ");
1364 if (i > 0) fputc (' ', stderr);
1366 /* Does it need shell quoting? This only deals with simple cases. */
1367 needs_quote = strcspn (g->cmdline[i], " ") != strlen (g->cmdline[i]);
1369 if (needs_quote) fputc ('\'', stderr);
1370 fprintf (stderr, "%s", g->cmdline[i]);
1371 if (needs_quote) fputc ('\'', stderr);
1375 fputc ('\n', stderr);
1378 /* This function does the hard work of building the supermin appliance
1379 * on the fly. 'path' is the directory containing the control files.
1380 * 'kernel' and 'initrd' are where we will return the names of the
1381 * kernel and initrd (only initrd is built). The work is done by
1382 * an external script. We just tell it where to put the result.
1385 build_supermin_appliance (guestfs_h *g, const char *path,
1386 char **kernel, char **initrd)
1391 len = strlen (g->tmpdir);
1392 *kernel = safe_malloc (g, len + 8);
1393 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1394 *initrd = safe_malloc (g, len + 8);
1395 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1397 snprintf (cmd, sizeof cmd,
1399 "libguestfs-supermin-helper '%s' %s %s",
1401 path, *kernel, *initrd);
1404 if (r == -1 || WEXITSTATUS(r) != 0) {
1405 error (g, _("external command failed: %s"), cmd);
1408 *kernel = *initrd = NULL;
1415 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1417 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1418 * 'qemu -version' so we know what options this qemu supports and
1422 test_qemu (guestfs_h *g)
1427 free (g->qemu_help);
1428 free (g->qemu_version);
1429 g->qemu_help = NULL;
1430 g->qemu_version = NULL;
1432 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1434 fp = popen (cmd, "r");
1435 /* qemu -help should always work (qemu -version OTOH wasn't
1436 * supported by qemu 0.9). If this command doesn't work then it
1437 * probably indicates that the qemu binary is missing.
1440 /* XXX This error is never printed, even if the qemu binary
1441 * doesn't exist. Why?
1444 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1448 if (read_all (g, fp, &g->qemu_help) == -1)
1451 if (pclose (fp) == -1)
1454 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1456 fp = popen (cmd, "r");
1458 /* Intentionally ignore errors. */
1459 read_all (g, fp, &g->qemu_version);
1467 read_all (guestfs_h *g, FILE *fp, char **ret)
1474 *ret = safe_realloc (g, *ret, n + 1);
1479 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1481 r = fread (p, 1, BUFSIZ, fp);
1483 perrorf (g, "read");
1490 /* Test if option is supported by qemu command line (just by grepping
1494 qemu_supports (guestfs_h *g, const char *option)
1496 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1500 finish_wait_ready (guestfs_h *g, void *vp)
1503 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1506 g->main_loop->main_loop_quit (g->main_loop, g);
1510 guestfs_wait_ready (guestfs_h *g)
1512 int finished = 0, r;
1514 if (g->state == READY) return 0;
1516 if (g->state == BUSY) {
1517 error (g, _("qemu has finished launching already"));
1521 if (g->state != LAUNCHING) {
1522 error (g, _("qemu has not been launched yet"));
1526 g->launch_done_cb = finish_wait_ready;
1527 g->launch_done_cb_data = &finished;
1528 r = g->main_loop->main_loop_run (g->main_loop, g);
1529 g->launch_done_cb = NULL;
1530 g->launch_done_cb_data = NULL;
1532 if (r == -1) return -1;
1534 if (finished != 1) {
1535 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1539 /* This is possible in some really strange situations, such as
1540 * guestfsd starts up OK but then qemu immediately exits. Check for
1541 * it because the caller is probably expecting to be able to send
1542 * commands after this function returns.
1544 if (g->state != READY) {
1545 error (g, _("qemu launched and contacted daemon, but state != READY"));
1553 guestfs_kill_subprocess (guestfs_h *g)
1555 if (g->state == CONFIG) {
1556 error (g, _("no subprocess to kill"));
1561 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1563 kill (g->pid, SIGTERM);
1564 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1569 /* Access current state. */
1571 guestfs_is_config (guestfs_h *g)
1573 return g->state == CONFIG;
1577 guestfs_is_launching (guestfs_h *g)
1579 return g->state == LAUNCHING;
1583 guestfs_is_ready (guestfs_h *g)
1585 return g->state == READY;
1589 guestfs_is_busy (guestfs_h *g)
1591 return g->state == BUSY;
1595 guestfs_get_state (guestfs_h *g)
1601 guestfs_set_ready (guestfs_h *g)
1603 if (g->state != BUSY) {
1604 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1613 guestfs_set_busy (guestfs_h *g)
1615 if (g->state != READY) {
1616 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1625 guestfs_end_busy (guestfs_h *g)
1639 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1645 /* We don't know if stdout_event or sock_read_event will be the
1646 * first to receive EOF if the qemu process dies. This function
1647 * has the common cleanup code for both.
1650 child_cleanup (guestfs_h *g)
1653 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1654 /*kill (g->pid, SIGTERM);*/
1655 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1656 waitpid (g->pid, NULL, 0);
1657 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1658 if (g->stdout_watch >= 0)
1659 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1660 if (g->sock_watch >= 0)
1661 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1671 g->stdout_watch = -1;
1674 if (g->subprocess_quit_cb)
1675 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1678 /* This function is called whenever qemu prints something on stdout.
1679 * Qemu's stdout is also connected to the guest's serial console, so
1680 * we see kernel messages here too.
1683 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1684 int watch, int fd, int events)
1692 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1693 g, g->state, fd, events);
1696 if (g->fd[1] != fd) {
1697 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1701 n = read (fd, buf, sizeof buf);
1703 /* Hopefully this indicates the qemu child process has died. */
1709 if (errno != EINTR && errno != EAGAIN)
1710 perrorf (g, "read");
1714 /* In verbose mode, copy all log messages to stderr. */
1716 ignore_value (write (STDERR_FILENO, buf, n));
1718 /* It's an actual log message, send it upwards if anyone is listening. */
1719 if (g->log_message_cb)
1720 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1723 /* The function is called whenever we can read something on the
1724 * guestfsd (daemon inside the guest) communication socket.
1727 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1728 int watch, int fd, int events)
1736 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1737 g, g->state, fd, events);
1739 if (g->sock != fd) {
1740 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1744 if (g->msg_in_size <= g->msg_in_allocated) {
1745 g->msg_in_allocated += 4096;
1746 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1748 n = read (g->sock, g->msg_in + g->msg_in_size,
1749 g->msg_in_allocated - g->msg_in_size);
1757 if (errno != EINTR && errno != EAGAIN)
1758 perrorf (g, "read");
1762 g->msg_in_size += n;
1764 /* Have we got enough of a message to be able to process it yet? */
1766 if (g->msg_in_size < 4) return;
1768 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1769 if (!xdr_uint32_t (&xdr, &len)) {
1770 error (g, _("can't decode length word"));
1774 /* Length is normally the length of the message, but when guestfsd
1775 * starts up it sends a "magic" value (longer than any possible
1776 * message). Check for this.
1778 if (len == GUESTFS_LAUNCH_FLAG) {
1779 if (g->state != LAUNCHING)
1780 error (g, _("received magic signature from guestfsd, but in state %d"),
1782 else if (g->msg_in_size != 4)
1783 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1787 if (g->launch_done_cb)
1788 g->launch_done_cb (g, g->launch_done_cb_data);
1794 /* This can happen if a cancellation happens right at the end
1795 * of us sending a FileIn parameter to the daemon. Discard. The
1796 * daemon should send us an error message next.
1798 if (len == GUESTFS_CANCEL_FLAG) {
1799 g->msg_in_size -= 4;
1800 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1804 /* If this happens, it's pretty bad and we've probably lost
1807 if (len > GUESTFS_MESSAGE_MAX) {
1808 error (g, _("message length (%u) > maximum possible size (%d)"),
1809 len, GUESTFS_MESSAGE_MAX);
1813 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1815 /* Got the full message, begin processing it. */
1820 for (i = 0; i < g->msg_in_size; i += 16) {
1821 printf ("%04x: ", i);
1822 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1823 printf ("%02x ", (unsigned char) g->msg_in[j]);
1824 for (; j < i+16; ++j)
1827 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1828 if (isprint (g->msg_in[j]))
1829 printf ("%c", g->msg_in[j]);
1832 for (; j < i+16; ++j)
1839 /* Not in the expected state. */
1840 if (g->state != BUSY)
1841 error (g, _("state %d != BUSY"), g->state);
1843 /* Push the message up to the higher layer. */
1845 g->reply_cb (g, g->reply_cb_data, &xdr);
1847 /* This message (probably) should never be printed. */
1848 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1850 g->msg_in_size -= len + 4;
1851 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1852 if (g->msg_in_size > 0) goto again;
1855 /* Free the message buffer if it's grown excessively large. */
1856 if (g->msg_in_allocated > 65536) {
1859 g->msg_in_size = g->msg_in_allocated = 0;
1866 /* The function is called whenever we can write something on the
1867 * guestfsd (daemon inside the guest) communication socket.
1870 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1871 int watch, int fd, int events)
1877 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1878 g, g->state, fd, events);
1880 if (g->sock != fd) {
1881 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1885 if (g->state != BUSY) {
1886 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1891 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1892 g->msg_out_size - g->msg_out_pos);
1894 n = write (g->sock, g->msg_out + g->msg_out_pos,
1895 g->msg_out_size - g->msg_out_pos);
1899 perrorf (g, "write");
1900 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1906 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1908 g->msg_out_pos += n;
1910 /* More to write? */
1911 if (g->msg_out_pos < g->msg_out_size)
1915 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1919 g->msg_out_pos = g->msg_out_size = 0;
1921 /* Done writing, call the higher layer. */
1923 g->send_cb (g, g->send_cb_data);
1927 guestfs_set_send_callback (guestfs_h *g,
1928 guestfs_send_cb cb, void *opaque)
1931 g->send_cb_data = opaque;
1935 guestfs_set_reply_callback (guestfs_h *g,
1936 guestfs_reply_cb cb, void *opaque)
1939 g->reply_cb_data = opaque;
1943 guestfs_set_log_message_callback (guestfs_h *g,
1944 guestfs_log_message_cb cb, void *opaque)
1946 g->log_message_cb = cb;
1947 g->log_message_cb_data = opaque;
1951 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1952 guestfs_subprocess_quit_cb cb, void *opaque)
1954 g->subprocess_quit_cb = cb;
1955 g->subprocess_quit_cb_data = opaque;
1959 guestfs_set_launch_done_callback (guestfs_h *g,
1960 guestfs_launch_done_cb cb, void *opaque)
1962 g->launch_done_cb = cb;
1963 g->launch_done_cb_data = opaque;
1966 /* Access to the handle's main loop and the default main loop. */
1968 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1970 g->main_loop = main_loop;
1974 guestfs_get_main_loop (guestfs_h *g)
1976 return g->main_loop;
1980 guestfs_get_default_main_loop (void)
1982 return (guestfs_main_loop *) &default_main_loop;
1985 /* Change the daemon socket handler so that we are now writing.
1986 * This sets the handle to sock_write_event.
1989 guestfs__switch_to_sending (guestfs_h *g)
1991 if (g->sock_watch >= 0) {
1992 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1993 error (g, _("remove_handle failed"));
2000 g->main_loop->add_handle (g->main_loop, g, g->sock,
2001 GUESTFS_HANDLE_WRITABLE,
2002 sock_write_event, NULL);
2003 if (g->sock_watch == -1) {
2004 error (g, _("add_handle failed"));
2012 guestfs__switch_to_receiving (guestfs_h *g)
2014 if (g->sock_watch >= 0) {
2015 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
2016 error (g, _("remove_handle failed"));
2023 g->main_loop->add_handle (g->main_loop, g, g->sock,
2024 GUESTFS_HANDLE_READABLE,
2025 sock_read_event, NULL);
2026 if (g->sock_watch == -1) {
2027 error (g, _("add_handle failed"));
2034 /* Dispatch a call (len + header + args) to the remote daemon,
2035 * synchronously (ie. using the guest's main loop to wait until
2036 * it has been sent). Returns -1 for error, or the serial
2037 * number of the message.
2040 send_cb (guestfs_h *g, void *data)
2042 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2045 ml->main_loop_quit (ml, g);
2049 guestfs__send_sync (guestfs_h *g, int proc_nr,
2050 xdrproc_t xdrp, char *args)
2052 struct guestfs_message_header hdr;
2055 int serial = g->msg_next_serial++;
2057 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2059 if (g->state != BUSY) {
2060 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2064 /* This is probably an internal error. Or perhaps we should just
2065 * free the buffer anyway?
2067 if (g->msg_out != NULL) {
2068 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2072 /* We have to allocate this message buffer on the heap because
2073 * it is quite large (although will be mostly unused). We
2074 * can't allocate it on the stack because in some environments
2075 * we have quite limited stack space available, notably when
2076 * running in the JVM.
2078 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2079 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2081 /* Serialize the header. */
2082 hdr.prog = GUESTFS_PROGRAM;
2083 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2085 hdr.direction = GUESTFS_DIRECTION_CALL;
2086 hdr.serial = serial;
2087 hdr.status = GUESTFS_STATUS_OK;
2089 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2090 error (g, _("xdr_guestfs_message_header failed"));
2094 /* Serialize the args. If any, because some message types
2095 * have no parameters.
2098 if (!(*xdrp) (&xdr, args)) {
2099 error (g, _("dispatch failed to marshal args"));
2104 /* Get the actual length of the message, resize the buffer to match
2105 * the actual length, and write the length word at the beginning.
2107 len = xdr_getpos (&xdr);
2110 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2111 g->msg_out_size = len + 4;
2114 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2115 xdr_uint32_t (&xdr, &len);
2117 if (guestfs__switch_to_sending (g) == -1)
2121 guestfs_set_send_callback (g, send_cb, &sent);
2122 if (ml->main_loop_run (ml, g) == -1)
2125 error (g, _("send failed, see earlier error messages"));
2134 g->msg_out_size = 0;
2138 static int cancel = 0; /* XXX Implement file cancellation. */
2139 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2140 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2141 static int send_file_cancellation_sync (guestfs_h *g);
2142 static int send_file_complete_sync (guestfs_h *g);
2144 /* Synchronously send a file.
2148 * -2 daemon cancelled (we must read the error message)
2151 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2153 char buf[GUESTFS_MAX_CHUNK_SIZE];
2156 fd = open (filename, O_RDONLY);
2158 perrorf (g, "open: %s", filename);
2159 send_file_cancellation_sync (g);
2160 /* Daemon sees cancellation and won't reply, so caller can
2166 /* Send file in chunked encoding. */
2168 r = read (fd, buf, sizeof buf);
2169 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2172 err = send_file_data_sync (g, buf, r);
2174 if (err == -2) /* daemon sent cancellation */
2175 send_file_cancellation_sync (g);
2180 if (cancel) { /* cancel from either end */
2181 send_file_cancellation_sync (g);
2186 perrorf (g, "read: %s", filename);
2187 send_file_cancellation_sync (g);
2191 /* End of file, but before we send that, we need to close
2192 * the file and check for errors.
2194 if (close (fd) == -1) {
2195 perrorf (g, "close: %s", filename);
2196 send_file_cancellation_sync (g);
2200 return send_file_complete_sync (g);
2203 /* Send a chunk of file data. */
2205 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2207 return send_file_chunk_sync (g, 0, buf, len);
2210 /* Send a cancellation message. */
2212 send_file_cancellation_sync (guestfs_h *g)
2214 return send_file_chunk_sync (g, 1, NULL, 0);
2217 /* Send a file complete chunk. */
2219 send_file_complete_sync (guestfs_h *g)
2222 return send_file_chunk_sync (g, 0, buf, 0);
2225 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2228 static int check_for_daemon_cancellation (guestfs_h *g);
2231 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2235 guestfs_chunk chunk;
2237 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2239 if (g->state != BUSY) {
2240 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2244 /* This is probably an internal error. Or perhaps we should just
2245 * free the buffer anyway?
2247 if (g->msg_out != NULL) {
2248 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2252 /* Did the daemon send a cancellation message? */
2253 if (check_for_daemon_cancellation (g)) {
2255 fprintf (stderr, "got daemon cancellation\n");
2259 /* Allocate the chunk buffer. Don't use the stack to avoid
2260 * excessive stack usage and unnecessary copies.
2262 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2263 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2265 /* Serialize the chunk. */
2266 chunk.cancel = cancel;
2267 chunk.data.data_len = buflen;
2268 chunk.data.data_val = (char *) buf;
2270 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2271 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2277 len = xdr_getpos (&xdr);
2280 /* Reduce the size of the outgoing message buffer to the real length. */
2281 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2282 g->msg_out_size = len + 4;
2285 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2286 xdr_uint32_t (&xdr, &len);
2288 if (guestfs__switch_to_sending (g) == -1)
2292 guestfs_set_send_callback (g, send_cb, &sent);
2293 if (ml->main_loop_run (ml, g) == -1)
2296 error (g, _("send file chunk failed, see earlier error messages"));
2305 g->msg_out_size = 0;
2309 /* At this point we are sending FileIn file(s) to the guest, and not
2310 * expecting to read anything, so if we do read anything, it must be
2311 * a cancellation message. This checks for this case without blocking.
2314 check_for_daemon_cancellation (guestfs_h *g)
2324 FD_SET (g->sock, &rset);
2327 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2329 perrorf (g, "select");
2335 /* Read the message from the daemon. */
2336 r = xread (g->sock, buf, sizeof buf);
2338 perrorf (g, "read");
2342 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2343 xdr_uint32_t (&xdr, &flag);
2346 if (flag != GUESTFS_CANCEL_FLAG) {
2347 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2348 flag, GUESTFS_CANCEL_FLAG);
2355 /* Synchronously receive a file. */
2357 /* Returns -1 = error, 0 = EOF, 1 = more data */
2358 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2361 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2367 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2369 perrorf (g, "open: %s", filename);
2373 /* Receive the file in chunked encoding. */
2374 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2375 if (xwrite (fd, buf, len) == -1) {
2376 perrorf (g, "%s: write", filename);
2381 if (r == 0) break; /* End of file. */
2385 error (g, _("%s: error in chunked encoding"), filename);
2389 if (close (fd) == -1) {
2390 perrorf (g, "close: %s", filename);
2397 /* Send cancellation message to daemon, then wait until it
2398 * cancels (just throwing away data).
2402 uint32_t flag = GUESTFS_CANCEL_FLAG;
2405 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2408 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2409 xdr_uint32_t (&xdr, &flag);
2412 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2413 perrorf (g, _("write to daemon socket"));
2417 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2418 ; /* just discard it */
2423 /* Note that the reply callback can be called multiple times before
2424 * the main loop quits and we get back to the synchronous code. So
2425 * we have to be prepared to save multiple chunks on a list here.
2427 struct receive_file_ctx {
2428 int count; /* 0 if receive_file_cb not called, or
2429 * else count number of chunks.
2431 guestfs_chunk *chunks; /* Array of chunks. */
2435 free_chunks (struct receive_file_ctx *ctx)
2439 for (i = 0; i < ctx->count; ++i)
2440 free (ctx->chunks[i].data.data_val);
2446 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2448 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2449 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2450 guestfs_chunk chunk;
2452 if (ctx->count == -1) /* Parse error occurred previously. */
2455 ml->main_loop_quit (ml, g);
2457 memset (&chunk, 0, sizeof chunk);
2459 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2460 error (g, _("failed to parse file chunk"));
2467 /* Copy the chunk to the list. */
2468 ctx->chunks = safe_realloc (g, ctx->chunks,
2469 sizeof (guestfs_chunk) * (ctx->count+1));
2470 ctx->chunks[ctx->count] = chunk;
2474 /* Receive a chunk of file data. */
2475 /* Returns -1 = error, 0 = EOF, 1 = more data */
2477 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2479 struct receive_file_ctx ctx;
2480 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2487 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2488 (void) ml->main_loop_run (ml, g);
2489 guestfs_set_reply_callback (g, NULL, NULL);
2491 if (ctx.count == 0) {
2492 error (g, _("receive_file_data_sync: reply callback not called\n"));
2496 if (ctx.count == -1) {
2497 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2498 /* callback already freed the chunks */
2503 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2505 /* Process each chunk in the list. */
2506 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2509 for (i = 0; i < ctx.count; ++i) {
2510 if (ctx.chunks[i].cancel) {
2511 error (g, _("file receive cancelled by daemon"));
2513 if (buf) free (*buf);
2514 if (len_r) *len_r = 0;
2518 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2520 if (len_r) *len_r = len;
2525 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2526 memcpy (((char *)*buf)+len, ctx.chunks[i].data.data_val,
2527 ctx.chunks[i].data.data_len);
2529 len += ctx.chunks[i].data.data_len;
2532 if (len_r) *len_r = len;
2537 /* This is the default main loop implementation, using select(2). */
2540 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2541 guestfs_handle_event_cb cb, void *data)
2543 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2545 if (fd < 0 || fd >= FD_SETSIZE) {
2546 error (g, _("fd %d is out of range"), fd);
2550 if ((events & ~(GUESTFS_HANDLE_READABLE |
2551 GUESTFS_HANDLE_WRITABLE |
2552 GUESTFS_HANDLE_HANGUP |
2553 GUESTFS_HANDLE_ERROR)) != 0) {
2554 error (g, _("set of events (0x%x) contains unknown events"), events);
2559 error (g, _("set of events is empty"));
2563 if (FD_ISSET (fd, &ml->rset) ||
2564 FD_ISSET (fd, &ml->wset) ||
2565 FD_ISSET (fd, &ml->xset)) {
2566 error (g, _("fd %d is already registered"), fd);
2571 error (g, _("callback is NULL"));
2575 if ((events & GUESTFS_HANDLE_READABLE))
2576 FD_SET (fd, &ml->rset);
2577 if ((events & GUESTFS_HANDLE_WRITABLE))
2578 FD_SET (fd, &ml->wset);
2579 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2580 FD_SET (fd, &ml->xset);
2582 if (fd > ml->max_fd) {
2584 ml->handle_cb_data =
2585 safe_realloc (g, ml->handle_cb_data,
2586 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2588 ml->handle_cb_data[fd].cb = cb;
2589 ml->handle_cb_data[fd].g = g;
2590 ml->handle_cb_data[fd].data = data;
2594 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2599 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2601 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2603 if (fd < 0 || fd >= FD_SETSIZE) {
2604 error (g, _("fd %d is out of range"), fd);
2608 if (!FD_ISSET (fd, &ml->rset) &&
2609 !FD_ISSET (fd, &ml->wset) &&
2610 !FD_ISSET (fd, &ml->xset)) {
2611 error (g, _("fd %d was not registered"), fd);
2615 FD_CLR (fd, &ml->rset);
2616 FD_CLR (fd, &ml->wset);
2617 FD_CLR (fd, &ml->xset);
2619 if (fd == ml->max_fd) {
2621 ml->handle_cb_data =
2622 safe_realloc (g, ml->handle_cb_data,
2623 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2632 __attribute__((noreturn))
2633 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2634 guestfs_handle_timeout_cb cb, void *data)
2636 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2638 abort (); /* XXX not implemented yet */
2642 __attribute__((noreturn))
2643 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2645 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2647 abort (); /* XXX not implemented yet */
2650 /* The 'g' parameter is just used for error reporting. Events
2651 * for multiple handles can be dispatched by running the main
2655 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2657 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2659 fd_set rset2, wset2, xset2;
2661 if (ml->is_running) {
2662 error (g, _("select_main_loop_run: this cannot be called recursively"));
2668 while (ml->is_running) {
2669 if (ml->nr_fds == 0)
2675 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2677 if (errno == EINTR || errno == EAGAIN)
2679 perrorf (g, "select");
2684 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2686 if (FD_ISSET (fd, &rset2))
2687 events |= GUESTFS_HANDLE_READABLE;
2688 if (FD_ISSET (fd, &wset2))
2689 events |= GUESTFS_HANDLE_WRITABLE;
2690 if (FD_ISSET (fd, &xset2))
2691 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2694 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2695 ml->handle_cb_data[fd].g,
2696 ml->handle_cb_data[fd].data,
2707 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2709 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2711 /* Note that legitimately ml->is_running can be zero when
2712 * this function is called.