2 * Copyright (C) 2009 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
22 #define _GNU_SOURCE /* for vasprintf, GNU strerror_r, strchrnul */
34 #include <sys/select.h>
37 #include <rpc/types.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
48 #ifdef HAVE_SYS_WAIT_H
52 #ifdef HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
61 #include "guestfs_protocol.h"
65 #define _(str) dgettext(PACKAGE, (str))
66 #define N_(str) dgettext(PACKAGE, (str))
72 #define error guestfs_error
73 #define perrorf guestfs_perrorf
74 #define safe_malloc guestfs_safe_malloc
75 #define safe_realloc guestfs_safe_realloc
76 #define safe_strdup guestfs_safe_strdup
77 #define safe_memdup guestfs_safe_memdup
79 static void default_error_cb (guestfs_h *g, void *data, const char *msg);
80 static void stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
81 static void sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
82 static void sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data, int watch, int fd, int events);
84 static void close_handles (void);
86 static int select_add_handle (guestfs_main_loop *ml, guestfs_h *g, int fd, int events, guestfs_handle_event_cb cb, void *data);
87 static int select_remove_handle (guestfs_main_loop *ml, guestfs_h *g, int watch);
88 static int select_add_timeout (guestfs_main_loop *ml, guestfs_h *g, int interval, guestfs_handle_timeout_cb cb, void *data);
89 static int select_remove_timeout (guestfs_main_loop *ml, guestfs_h *g, int timer);
90 static int select_main_loop_run (guestfs_main_loop *ml, guestfs_h *g);
91 static int select_main_loop_quit (guestfs_main_loop *ml, guestfs_h *g);
93 /* Default select-based main loop. */
94 struct select_handle_cb_data {
95 guestfs_handle_event_cb cb;
100 struct select_main_loop {
101 /* NB. These fields must be the same as in struct guestfs_main_loop: */
102 guestfs_add_handle_cb add_handle;
103 guestfs_remove_handle_cb remove_handle;
104 guestfs_add_timeout_cb add_timeout;
105 guestfs_remove_timeout_cb remove_timeout;
106 guestfs_main_loop_run_cb main_loop_run;
107 guestfs_main_loop_quit_cb main_loop_quit;
109 /* Additional private data: */
118 struct select_handle_cb_data *handle_cb_data;
121 /* Default main loop. */
122 static struct select_main_loop default_main_loop = {
123 .add_handle = select_add_handle,
124 .remove_handle = select_remove_handle,
125 .add_timeout = select_add_timeout,
126 .remove_timeout = select_remove_timeout,
127 .main_loop_run = select_main_loop_run,
128 .main_loop_quit = select_main_loop_quit,
130 /* XXX hopefully .rset, .wset, .xset are initialized to the empty
131 * set by the normal action of everything being initialized to zero.
136 .handle_cb_data = NULL,
139 #define UNIX_PATH_MAX 108
141 /* Also in guestfsd.c */
142 #define VMCHANNEL_PORT 6666
143 #define VMCHANNEL_ADDR "10.0.2.4"
145 /* GuestFS handle and connection. */
146 enum state { CONFIG, LAUNCHING, READY, BUSY, NO_HANDLE };
150 struct guestfs_h *next; /* Linked list of open handles. */
152 /* State: see the state machine diagram in the man page guestfs(3). */
155 int fd[2]; /* Stdin/stdout of qemu. */
156 int sock; /* Daemon communications socket. */
157 pid_t pid; /* Qemu PID. */
158 pid_t recoverypid; /* Recovery process PID. */
159 time_t start_t; /* The time when we started qemu. */
161 int stdout_watch; /* Watches qemu stdout for log messages. */
162 int sock_watch; /* Watches daemon comm socket. */
164 char *tmpdir; /* Temporary directory containing socket. */
166 char *qemu_help, *qemu_version; /* Output of qemu -help, qemu -version. */
168 char **cmdline; /* Qemu command line. */
174 char *path; /* Path to kernel, initrd. */
175 char *qemu; /* Qemu binary. */
176 char *append; /* Append to kernel command line. */
177 char *kernel; /* Override appliance kernel. */
179 int memsize; /* Size of RAM (megabytes). */
184 guestfs_abort_cb abort_cb;
185 guestfs_error_handler_cb error_cb;
186 void * error_cb_data;
187 guestfs_send_cb send_cb;
189 guestfs_reply_cb reply_cb;
190 void * reply_cb_data;
191 guestfs_log_message_cb log_message_cb;
192 void * log_message_cb_data;
193 guestfs_subprocess_quit_cb subprocess_quit_cb;
194 void * subprocess_quit_cb_data;
195 guestfs_launch_done_cb launch_done_cb;
196 void * launch_done_cb_data;
198 /* Main loop used by this handle. */
199 guestfs_main_loop *main_loop;
201 /* Messages sent and received from the daemon. */
203 int msg_in_size, msg_in_allocated;
205 int msg_out_size, msg_out_pos;
210 static guestfs_h *handles = NULL;
211 static int atexit_handler_set = 0;
214 guestfs_create (void)
219 g = malloc (sizeof (*g));
222 memset (g, 0, sizeof (*g));
229 g->stdout_watch = -1;
233 g->error_cb = default_error_cb;
234 g->error_cb_data = NULL;
236 str = getenv ("LIBGUESTFS_DEBUG");
237 g->verbose = str != NULL && strcmp (str, "1") == 0;
239 str = getenv ("LIBGUESTFS_PATH");
240 g->path = str != NULL ? strdup (str) : strdup (GUESTFS_DEFAULT_PATH);
241 if (!g->path) goto error;
243 str = getenv ("LIBGUESTFS_QEMU");
244 g->qemu = str != NULL ? strdup (str) : strdup (QEMU);
245 if (!g->qemu) goto error;
247 str = getenv ("LIBGUESTFS_APPEND");
249 g->append = strdup (str);
250 if (!g->append) goto error;
253 str = getenv ("LIBGUESTFS_KERNEL");
255 g->kernel = strdup (str);
256 if (!g->kernel) 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 /* 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 vasprintf (&msg, fs, args);
458 strerror_r (err, buf, sizeof buf);
462 buf = strerror_r (err, _buf, sizeof _buf);
465 msg = safe_realloc (g, msg, strlen (msg) + 2 + strlen (buf) + 1);
469 if (g->error_cb) g->error_cb (g, g->error_cb_data, msg);
470 set_last_error (g, msg);
476 guestfs_safe_malloc (guestfs_h *g, size_t nbytes)
478 void *ptr = malloc (nbytes);
479 if (nbytes > 0 && !ptr) g->abort_cb ();
483 /* Return 1 if an array of N objects, each of size S, cannot exist due
484 to size arithmetic overflow. S must be positive and N must be
485 nonnegative. This is a macro, not an inline function, so that it
486 works correctly even when SIZE_MAX < N.
488 By gnulib convention, SIZE_MAX represents overflow in size
489 calculations, so the conservative dividend to use here is
490 SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
491 However, malloc (SIZE_MAX) fails on all known hosts where
492 sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
493 exactly-SIZE_MAX allocations on such hosts; this avoids a test and
494 branch when S is known to be 1. */
495 # define xalloc_oversized(n, s) \
496 ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
498 /* Technically we should add an autoconf test for this, testing for the desired
499 functionality, like what's done in gnulib, but for now, this is fine. */
500 #define HAVE_GNU_CALLOC (__GLIBC__ >= 2)
502 /* Allocate zeroed memory for N elements of S bytes, with error
503 checking. S must be nonzero. */
505 guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s)
507 /* From gnulib's calloc function in xmalloc.c. */
509 /* Test for overflow, since some calloc implementations don't have
510 proper overflow checks. But omit overflow and size-zero tests if
511 HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
512 returns NULL if successful. */
513 if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
514 || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
520 guestfs_safe_realloc (guestfs_h *g, void *ptr, int nbytes)
522 void *p = realloc (ptr, nbytes);
523 if (nbytes > 0 && !p) g->abort_cb ();
528 guestfs_safe_strdup (guestfs_h *g, const char *str)
530 char *s = strdup (str);
531 if (!s) g->abort_cb ();
536 guestfs_safe_memdup (guestfs_h *g, void *ptr, size_t size)
538 void *p = malloc (size);
539 if (!p) g->abort_cb ();
540 memcpy (p, ptr, size);
545 xwrite (int fd, const void *buf, size_t len)
550 r = write (fd, buf, len);
562 xread (int fd, void *buf, size_t len)
567 r = read (fd, buf, len);
569 if (errno == EINTR || errno == EAGAIN)
582 guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb cb)
588 guestfs_get_out_of_memory_handler (guestfs_h *g)
594 guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *data)
597 g->error_cb_data = data;
600 guestfs_error_handler_cb
601 guestfs_get_error_handler (guestfs_h *g, void **data_rtn)
603 if (data_rtn) *data_rtn = g->error_cb_data;
608 guestfs_set_verbose (guestfs_h *g, int v)
615 guestfs_get_verbose (guestfs_h *g)
621 guestfs_set_autosync (guestfs_h *g, int a)
628 guestfs_get_autosync (guestfs_h *g)
634 guestfs_set_path (guestfs_h *g, const char *path)
641 safe_strdup (g, GUESTFS_DEFAULT_PATH) : safe_strdup (g, path);
646 guestfs_get_path (guestfs_h *g)
652 guestfs_set_qemu (guestfs_h *g, const char *qemu)
657 g->qemu = qemu == NULL ? safe_strdup (g, QEMU) : safe_strdup (g, qemu);
662 guestfs_get_qemu (guestfs_h *g)
668 guestfs_set_append (guestfs_h *g, const char *append)
673 g->append = append ? safe_strdup (g, append) : NULL;
678 guestfs_get_append (guestfs_h *g)
684 guestfs_set_kernel (guestfs_h *g, const char *kernel)
689 g->kernel = kernel ? safe_strdup (g, kernel) : NULL;
694 guestfs_get_kernel (guestfs_h *g)
700 guestfs_set_memsize (guestfs_h *g, int memsize)
702 g->memsize = memsize;
707 guestfs_get_memsize (guestfs_h *g)
713 guestfs_get_pid (guestfs_h *g)
718 error (g, "get_pid: no qemu subprocess");
723 struct guestfs_version *
724 guestfs_version (guestfs_h *g)
726 struct guestfs_version *r;
728 r = safe_malloc (g, sizeof *r);
729 r->major = PACKAGE_VERSION_MAJOR;
730 r->minor = PACKAGE_VERSION_MINOR;
731 r->release = PACKAGE_VERSION_RELEASE;
732 r->extra = safe_strdup (g, PACKAGE_VERSION_EXTRA);
736 /* Add a string to the current command line. */
738 incr_cmdline_size (guestfs_h *g)
740 if (g->cmdline == NULL) {
741 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
743 g->cmdline = safe_malloc (g, sizeof (char *));
744 g->cmdline[0] = NULL;
748 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
752 add_cmdline (guestfs_h *g, const char *str)
754 if (g->state != CONFIG) {
756 _("command line cannot be altered after qemu subprocess launched"));
760 incr_cmdline_size (g);
761 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
766 guestfs_config (guestfs_h *g,
767 const char *qemu_param, const char *qemu_value)
769 if (qemu_param[0] != '-') {
770 error (g, _("guestfs_config: parameter must begin with '-' character"));
774 /* A bit fascist, but the user will probably break the extra
775 * parameters that we add if they try to set any of these.
777 if (strcmp (qemu_param, "-kernel") == 0 ||
778 strcmp (qemu_param, "-initrd") == 0 ||
779 strcmp (qemu_param, "-nographic") == 0 ||
780 strcmp (qemu_param, "-serial") == 0 ||
781 strcmp (qemu_param, "-full-screen") == 0 ||
782 strcmp (qemu_param, "-std-vga") == 0 ||
783 strcmp (qemu_param, "-vnc") == 0) {
784 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
788 if (add_cmdline (g, qemu_param) != 0) return -1;
790 if (qemu_value != NULL) {
791 if (add_cmdline (g, qemu_value) != 0) return -1;
798 guestfs_add_drive (guestfs_h *g, const char *filename)
800 size_t len = strlen (filename) + 64;
803 if (strchr (filename, ',') != NULL) {
804 error (g, _("filename cannot contain ',' (comma) character"));
808 if (access (filename, F_OK) == -1) {
809 perrorf (g, "%s", filename);
813 /* cache=off improves reliability in the event of a host crash. */
814 snprintf (buf, len, "file=%s,cache=off,if=%s", filename, DRIVE_IF);
816 return guestfs_config (g, "-drive", buf);
820 guestfs_add_drive_ro (guestfs_h *g, const char *filename)
822 size_t len = strlen (filename) + 64;
825 if (strchr (filename, ',') != NULL) {
826 error (g, _("filename cannot contain ',' (comma) character"));
830 if (access (filename, F_OK) == -1) {
831 perrorf (g, "%s", filename);
835 snprintf (buf, len, "file=%s,snapshot=on,if=%s", filename, DRIVE_IF);
837 return guestfs_config (g, "-drive", buf);
841 guestfs_add_cdrom (guestfs_h *g, const char *filename)
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 return guestfs_config (g, "-cdrom", filename);
856 /* Returns true iff file is contained in dir. */
858 dir_contains_file (const char *dir, const char *file)
860 int dirlen = strlen (dir);
861 int filelen = strlen (file);
862 int len = dirlen+filelen+2;
865 snprintf (path, len, "%s/%s", dir, file);
866 return access (path, F_OK) == 0;
869 /* Returns true iff every listed file is contained in 'dir'. */
871 dir_contains_files (const char *dir, ...)
876 va_start (args, dir);
877 while ((file = va_arg (args, const char *)) != NULL) {
878 if (!dir_contains_file (dir, file)) {
887 static int build_supermin_appliance (guestfs_h *g, const char *path, char **kernel, char **initrd);
888 static int test_qemu (guestfs_h *g);
889 static int qemu_supports (guestfs_h *g, const char *option);
891 static const char *kernel_name = "vmlinuz." REPO "." host_cpu;
892 static const char *initrd_name = "initramfs." REPO "." host_cpu ".img";
893 static const char *supermin_name =
894 "initramfs." REPO "." host_cpu ".supermin.img";
895 static const char *supermin_hostfiles_name =
896 "initramfs." REPO "." host_cpu ".supermin.hostfiles";
899 guestfs_launch (guestfs_h *g)
902 char dir_template[PATH_MAX];
907 char *path, *pelem, *pend;
908 char *kernel = NULL, *initrd = NULL;
910 struct sockaddr_un addr;
918 tmpdir = getenv ("TMPDIR") ? : tmpdir;
919 snprintf (dir_template, sizeof dir_template, "%s/libguestfsXXXXXX", tmpdir);
923 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
927 if (g->state != CONFIG) {
928 error (g, _("qemu has already been launched"));
932 /* Make the temporary directory. */
934 g->tmpdir = safe_strdup (g, dir_template);
935 if (mkdtemp (g->tmpdir) == NULL) {
936 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
941 /* First search g->path for the supermin appliance, and try to
942 * synthesize a kernel and initrd from that. If it fails, we
943 * try the path search again looking for a backup ordinary
946 pelem = path = safe_strdup (g, g->path);
948 pend = strchrnul (pelem, ':');
949 pmore = *pend == ':';
953 /* Empty element of "." means cwd. */
954 if (len == 0 || (len == 1 && *pelem == '.')) {
957 "looking for supermin appliance in current directory\n");
958 if (dir_contains_files (".",
959 supermin_name, supermin_hostfiles_name,
960 "kmod.whitelist", NULL)) {
961 if (build_supermin_appliance (g, ".", &kernel, &initrd) == -1)
966 /* Look at <path>/supermin* etc. */
969 fprintf (stderr, "looking for supermin appliance in %s\n", pelem);
971 if (dir_contains_files (pelem,
972 supermin_name, supermin_hostfiles_name,
973 "kmod.whitelist", NULL)) {
974 if (build_supermin_appliance (g, pelem, &kernel, &initrd) == -1)
985 if (kernel == NULL || initrd == NULL) {
986 /* Search g->path for the kernel and initrd. */
987 pelem = path = safe_strdup (g, g->path);
989 pend = strchrnul (pelem, ':');
990 pmore = *pend == ':';
994 /* Empty element or "." means cwd. */
995 if (len == 0 || (len == 1 && *pelem == '.')) {
998 "looking for appliance in current directory\n");
999 if (dir_contains_files (".", kernel_name, initrd_name, NULL)) {
1000 kernel = safe_strdup (g, kernel_name);
1001 initrd = safe_strdup (g, initrd_name);
1005 /* Look at <path>/kernel etc. */
1008 fprintf (stderr, "looking for appliance in %s\n", pelem);
1010 if (dir_contains_files (pelem, kernel_name, initrd_name, NULL)) {
1011 kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
1012 initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
1013 sprintf (kernel, "%s/%s", pelem, kernel_name);
1014 sprintf (initrd, "%s/%s", pelem, initrd_name);
1025 if (kernel == NULL || initrd == NULL) {
1026 error (g, _("cannot find %s or %s on LIBGUESTFS_PATH (current path = %s)"),
1027 kernel_name, initrd_name, g->path);
1031 /* Get qemu help text and version. */
1032 if (test_qemu (g) == -1)
1035 /* Make the vmchannel socket. */
1036 snprintf (unixsock, sizeof unixsock, "%s/sock", g->tmpdir);
1039 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
1040 perrorf (g, "pipe");
1046 perrorf (g, "fork");
1054 if (r == 0) { /* Child (qemu). */
1055 char vmchannel[256];
1057 char memsize_str[256];
1059 /* Set up the full command line. Do this in the subprocess so we
1060 * don't need to worry about cleaning up.
1062 g->cmdline[0] = g->qemu;
1064 #define LINUX_CMDLINE \
1065 "panic=1 " /* force kernel to panic if daemon exits */ \
1066 "console=ttyS0 " /* serial console */ \
1067 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
1068 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
1069 "acpi=off " /* we don't need ACPI, turn it off */
1071 /* Linux kernel command line. */
1072 snprintf (append, sizeof append,
1073 LINUX_CMDLINE "guestfs=%s:%d%s%s%s",
1074 VMCHANNEL_ADDR, VMCHANNEL_PORT,
1075 g->verbose ? " guestfs_verbose=1" : "",
1076 g->append ? " " : "", g->append ? g->append : "");
1078 snprintf (memsize_str, sizeof memsize_str, "%d", g->memsize);
1080 add_cmdline (g, "-m");
1081 add_cmdline (g, memsize_str);
1082 add_cmdline (g, "-no-reboot"); /* Force exit instead of reboot on panic */
1083 add_cmdline (g, "-kernel");
1084 add_cmdline (g, g->kernel ? : (char *) kernel);
1085 add_cmdline (g, "-initrd");
1086 add_cmdline (g, (char *) initrd);
1087 add_cmdline (g, "-append");
1088 add_cmdline (g, append);
1089 add_cmdline (g, "-nographic");
1090 add_cmdline (g, "-serial");
1091 add_cmdline (g, "stdio");
1094 /* Doesn't work. See:
1095 * http://lists.gnu.org/archive/html/qemu-devel/2009-07/threads.html
1096 * Subject "guestfwd option doesn't allow supplementary ,server,nowait"
1098 if (qemu_supports (g, "guestfwd")) {
1099 /* New-style -net user,guestfwd=... syntax for vmchannel. See:
1100 * http://git.savannah.gnu.org/cgit/qemu.git/commit/?id=c92ef6a22d3c71538fcc48fb61ad353f7ba03b62
1102 snprintf (vmchannel, sizeof vmchannel,
1103 "user,vlan=0,guestfwd=tcp:%s:%d-unix:%s,server,nowait",
1104 VMCHANNEL_ADDR, VMCHANNEL_PORT, unixsock);
1106 add_cmdline (g, "-net");
1107 add_cmdline (g, vmchannel);
1110 /* Not guestfwd. HOPEFULLY this qemu uses the older -net channel
1111 * syntax, or if not then we'll get a quick failure.
1113 snprintf (vmchannel, sizeof vmchannel,
1114 "channel,%d:unix:%s,server,nowait",
1115 VMCHANNEL_PORT, unixsock);
1117 add_cmdline (g, "-net");
1118 add_cmdline (g, vmchannel);
1119 add_cmdline (g, "-net");
1120 add_cmdline (g, "user,vlan=0");
1124 add_cmdline (g, "-net");
1125 add_cmdline (g, "nic,model=virtio,vlan=0");
1127 /* These options recommended by KVM developers to improve reliability. */
1128 if (qemu_supports (g, "-no-hpet"))
1129 add_cmdline (g, "-no-hpet");
1131 if (qemu_supports (g, "-rtc-td-hack"))
1132 add_cmdline (g, "-rtc-td-hack");
1134 /* Finish off the command line. */
1135 incr_cmdline_size (g);
1136 g->cmdline[g->cmdline_size-1] = NULL;
1139 fprintf (stderr, "%s", g->qemu);
1140 for (i = 0; g->cmdline[i]; ++i)
1141 fprintf (stderr, " %s", g->cmdline[i]);
1142 fprintf (stderr, "\n");
1145 /* Set up stdin, stdout. */
1156 /* Set up a new process group, so we can signal this process
1157 * and all subprocesses (eg. if qemu is really a shell script).
1162 execv (g->qemu, g->cmdline); /* Run qemu. */
1167 /* Parent (library). */
1175 /* Fork the recovery process off which will kill qemu if the parent
1176 * process fails to do so (eg. if the parent segfaults).
1180 pid_t qemu_pid = g->pid;
1181 pid_t parent_pid = getppid ();
1183 /* Writing to argv is hideously complicated and error prone. See:
1184 * http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/utils/misc/ps_status.c?rev=1.33.2.1;content-type=text%2Fplain
1187 /* Loop around waiting for one or both of the other processes to
1188 * disappear. It's fair to say this is very hairy. The PIDs that
1189 * we are looking at might be reused by another process. We are
1190 * effectively polling. Is the cure worse than the disease?
1193 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
1195 if (kill (parent_pid, 0) == -1) {
1196 /* Parent's gone away, qemu still around, so kill qemu. */
1204 /* Don't worry, if the fork failed, this will be -1. The recovery
1205 * process isn't essential.
1209 /* Start the clock ... */
1212 /* Close the other ends of the pipe. */
1216 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
1217 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
1218 perrorf (g, "fcntl");
1222 g->fd[0] = wfd[1]; /* stdin of child */
1223 g->fd[1] = rfd[0]; /* stdout of child */
1225 /* Open the Unix socket. The vmchannel implementation that got
1226 * merged with qemu sucks in a number of ways. Both ends do
1227 * connect(2), which means that no one knows what, if anything, is
1228 * connected to the other end, or if it becomes disconnected. Even
1229 * worse, we have to wait some indeterminate time for qemu to create
1230 * the socket and connect to it (which happens very early in qemu's
1231 * start-up), so any code that uses vmchannel is inherently racy.
1232 * Hence this silly loop.
1234 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
1235 if (g->sock == -1) {
1236 perrorf (g, "socket");
1240 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
1241 perrorf (g, "fcntl");
1245 addr.sun_family = AF_UNIX;
1246 strncpy (addr.sun_path, unixsock, UNIX_PATH_MAX);
1247 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
1250 /* Always sleep at least once to give qemu a small chance to start up. */
1253 r = connect (g->sock, (struct sockaddr *) &addr, sizeof addr);
1254 if ((r == -1 && errno == EINPROGRESS) || r == 0)
1257 if (errno != ENOENT)
1258 perrorf (g, "connect");
1263 error (g, _("failed to connect to vmchannel socket"));
1267 /* Watch the file descriptors. */
1270 g->msg_in_size = g->msg_in_allocated = 0;
1274 g->msg_out_size = 0;
1278 g->main_loop->add_handle (g->main_loop, g, g->fd[1],
1279 GUESTFS_HANDLE_READABLE,
1280 stdout_event, NULL);
1281 if (g->stdout_watch == -1) {
1282 error (g, _("could not watch qemu stdout"));
1286 if (guestfs__switch_to_receiving (g) == -1)
1289 g->state = LAUNCHING;
1293 if (g->stdout_watch >= 0)
1294 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1295 if (g->sock_watch >= 0)
1296 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1305 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1306 waitpid (g->pid, NULL, 0);
1307 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1314 g->stdout_watch = -1;
1323 /* This function does the hard work of building the supermin appliance
1324 * on the fly. 'path' is the directory containing the control files.
1325 * 'kernel' and 'initrd' are where we will return the names of the
1326 * kernel and initrd (only initrd is built). The work is done by
1327 * an external script. We just tell it where to put the result.
1330 build_supermin_appliance (guestfs_h *g, const char *path,
1331 char **kernel, char **initrd)
1336 len = strlen (g->tmpdir);
1337 *kernel = safe_malloc (g, len + 8);
1338 snprintf (*kernel, len+8, "%s/kernel", g->tmpdir);
1339 *initrd = safe_malloc (g, len + 8);
1340 snprintf (*initrd, len+8, "%s/initrd", g->tmpdir);
1342 snprintf (cmd, sizeof cmd,
1344 "libguestfs-supermin-helper '%s' %s %s",
1346 path, *kernel, *initrd);
1349 if (r == -1 || WEXITSTATUS(r) != 0) {
1350 error (g, _("external command failed: %s"), cmd);
1353 *kernel = *initrd = NULL;
1360 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1362 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1363 * 'qemu -version' so we know what options this qemu supports and
1367 test_qemu (guestfs_h *g)
1372 free (g->qemu_help);
1373 free (g->qemu_version);
1374 g->qemu_help = NULL;
1375 g->qemu_version = NULL;
1377 snprintf (cmd, sizeof cmd, "'%s' -help", g->qemu);
1379 fp = popen (cmd, "r");
1380 /* qemu -help should always work (qemu -version OTOH wasn't
1381 * supported by qemu 0.9). If this command doesn't work then it
1382 * probably indicates that the qemu binary is missing.
1385 /* XXX This error is never printed, even if the qemu binary
1386 * doesn't exist. Why?
1389 perrorf (g, _("%s: command failed: If qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU environment variable."), cmd);
1393 if (read_all (g, fp, &g->qemu_help) == -1)
1396 if (pclose (fp) == -1)
1399 snprintf (cmd, sizeof cmd, "'%s' -version 2>/dev/null", g->qemu);
1401 fp = popen (cmd, "r");
1403 /* Intentionally ignore errors. */
1404 read_all (g, fp, &g->qemu_version);
1412 read_all (guestfs_h *g, FILE *fp, char **ret)
1419 *ret = safe_realloc (g, *ret, n + 1);
1424 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1426 r = fread (p, 1, BUFSIZ, fp);
1428 perrorf (g, "read");
1435 /* Test if option is supported by qemu command line (just by grepping
1439 qemu_supports (guestfs_h *g, const char *option)
1441 return g->qemu_help && strstr (g->qemu_help, option) != NULL;
1445 finish_wait_ready (guestfs_h *g, void *vp)
1448 fprintf (stderr, "finish_wait_ready called, %p, vp = %p\n", g, vp);
1451 g->main_loop->main_loop_quit (g->main_loop, g);
1455 guestfs_wait_ready (guestfs_h *g)
1457 int finished = 0, r;
1459 if (g->state == READY) return 0;
1461 if (g->state == BUSY) {
1462 error (g, _("qemu has finished launching already"));
1466 if (g->state != LAUNCHING) {
1467 error (g, _("qemu has not been launched yet"));
1471 g->launch_done_cb = finish_wait_ready;
1472 g->launch_done_cb_data = &finished;
1473 r = g->main_loop->main_loop_run (g->main_loop, g);
1474 g->launch_done_cb = NULL;
1475 g->launch_done_cb_data = NULL;
1477 if (r == -1) return -1;
1479 if (finished != 1) {
1480 error (g, _("guestfs_wait_ready failed, see earlier error messages"));
1484 /* This is possible in some really strange situations, such as
1485 * guestfsd starts up OK but then qemu immediately exits. Check for
1486 * it because the caller is probably expecting to be able to send
1487 * commands after this function returns.
1489 if (g->state != READY) {
1490 error (g, _("qemu launched and contacted daemon, but state != READY"));
1498 guestfs_kill_subprocess (guestfs_h *g)
1500 if (g->state == CONFIG) {
1501 error (g, _("no subprocess to kill"));
1506 fprintf (stderr, "sending SIGTERM to process %d\n", g->pid);
1508 kill (g->pid, SIGTERM);
1509 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1514 /* Access current state. */
1516 guestfs_is_config (guestfs_h *g)
1518 return g->state == CONFIG;
1522 guestfs_is_launching (guestfs_h *g)
1524 return g->state == LAUNCHING;
1528 guestfs_is_ready (guestfs_h *g)
1530 return g->state == READY;
1534 guestfs_is_busy (guestfs_h *g)
1536 return g->state == BUSY;
1540 guestfs_get_state (guestfs_h *g)
1546 guestfs_set_ready (guestfs_h *g)
1548 if (g->state != BUSY) {
1549 error (g, _("guestfs_set_ready: called when in state %d != BUSY"),
1558 guestfs_set_busy (guestfs_h *g)
1560 if (g->state != READY) {
1561 error (g, _("guestfs_set_busy: called when in state %d != READY"),
1570 guestfs_end_busy (guestfs_h *g)
1582 error (g, _("guestfs_end_busy: called when in state %d"), g->state);
1588 /* We don't know if stdout_event or sock_read_event will be the
1589 * first to receive EOF if the qemu process dies. This function
1590 * has the common cleanup code for both.
1593 child_cleanup (guestfs_h *g)
1596 fprintf (stderr, "stdout_event: %p: child process died\n", g);
1597 /*kill (g->pid, SIGTERM);*/
1598 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1599 waitpid (g->pid, NULL, 0);
1600 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
1601 if (g->stdout_watch >= 0)
1602 g->main_loop->remove_handle (g->main_loop, g, g->stdout_watch);
1603 if (g->sock_watch >= 0)
1604 g->main_loop->remove_handle (g->main_loop, g, g->sock_watch);
1614 g->stdout_watch = -1;
1617 if (g->subprocess_quit_cb)
1618 g->subprocess_quit_cb (g, g->subprocess_quit_cb_data);
1621 /* This function is called whenever qemu prints something on stdout.
1622 * Qemu's stdout is also connected to the guest's serial console, so
1623 * we see kernel messages here too.
1626 stdout_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1627 int watch, int fd, int events)
1635 "stdout_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1636 g, g->state, fd, events);
1639 if (g->fd[1] != fd) {
1640 error (g, _("stdout_event: internal error: %d != %d"), g->fd[1], fd);
1644 n = read (fd, buf, sizeof buf);
1646 /* Hopefully this indicates the qemu child process has died. */
1652 if (errno != EINTR && errno != EAGAIN)
1653 perrorf (g, "read");
1657 /* In verbose mode, copy all log messages to stderr. */
1661 /* It's an actual log message, send it upwards if anyone is listening. */
1662 if (g->log_message_cb)
1663 g->log_message_cb (g, g->log_message_cb_data, buf, n);
1666 /* The function is called whenever we can read something on the
1667 * guestfsd (daemon inside the guest) communication socket.
1670 sock_read_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1671 int watch, int fd, int events)
1679 "sock_read_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1680 g, g->state, fd, events);
1682 if (g->sock != fd) {
1683 error (g, _("sock_read_event: internal error: %d != %d"), g->sock, fd);
1687 if (g->msg_in_size <= g->msg_in_allocated) {
1688 g->msg_in_allocated += 4096;
1689 g->msg_in = safe_realloc (g, g->msg_in, g->msg_in_allocated);
1691 n = read (g->sock, g->msg_in + g->msg_in_size,
1692 g->msg_in_allocated - g->msg_in_size);
1700 if (errno != EINTR && errno != EAGAIN)
1701 perrorf (g, "read");
1705 g->msg_in_size += n;
1707 /* Have we got enough of a message to be able to process it yet? */
1709 if (g->msg_in_size < 4) return;
1711 xdrmem_create (&xdr, g->msg_in, g->msg_in_size, XDR_DECODE);
1712 if (!xdr_uint32_t (&xdr, &len)) {
1713 error (g, _("can't decode length word"));
1717 /* Length is normally the length of the message, but when guestfsd
1718 * starts up it sends a "magic" value (longer than any possible
1719 * message). Check for this.
1721 if (len == GUESTFS_LAUNCH_FLAG) {
1722 if (g->state != LAUNCHING)
1723 error (g, _("received magic signature from guestfsd, but in state %d"),
1725 else if (g->msg_in_size != 4)
1726 error (g, _("received magic signature from guestfsd, but msg size is %d"),
1730 if (g->launch_done_cb)
1731 g->launch_done_cb (g, g->launch_done_cb_data);
1737 /* This can happen if a cancellation happens right at the end
1738 * of us sending a FileIn parameter to the daemon. Discard. The
1739 * daemon should send us an error message next.
1741 if (len == GUESTFS_CANCEL_FLAG) {
1742 g->msg_in_size -= 4;
1743 memmove (g->msg_in, g->msg_in+4, g->msg_in_size);
1747 /* If this happens, it's pretty bad and we've probably lost
1750 if (len > GUESTFS_MESSAGE_MAX) {
1751 error (g, _("message length (%u) > maximum possible size (%d)"),
1752 len, GUESTFS_MESSAGE_MAX);
1756 if (g->msg_in_size-4 < len) return; /* Need more of this message. */
1758 /* Got the full message, begin processing it. */
1763 for (i = 0; i < g->msg_in_size; i += 16) {
1764 printf ("%04x: ", i);
1765 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1766 printf ("%02x ", (unsigned char) g->msg_in[j]);
1767 for (; j < i+16; ++j)
1770 for (j = i; j < MIN (i+16, g->msg_in_size); ++j)
1771 if (isprint (g->msg_in[j]))
1772 printf ("%c", g->msg_in[j]);
1775 for (; j < i+16; ++j)
1782 /* Not in the expected state. */
1783 if (g->state != BUSY)
1784 error (g, _("state %d != BUSY"), g->state);
1786 /* Push the message up to the higher layer. */
1788 g->reply_cb (g, g->reply_cb_data, &xdr);
1790 /* This message (probably) should never be printed. */
1791 fprintf (stderr, "libguesfs: sock_read_event: !!! dropped message !!!\n");
1793 g->msg_in_size -= len + 4;
1794 memmove (g->msg_in, g->msg_in+len+4, g->msg_in_size);
1795 if (g->msg_in_size > 0) goto again;
1798 /* Free the message buffer if it's grown excessively large. */
1799 if (g->msg_in_allocated > 65536) {
1802 g->msg_in_size = g->msg_in_allocated = 0;
1809 /* The function is called whenever we can write something on the
1810 * guestfsd (daemon inside the guest) communication socket.
1813 sock_write_event (struct guestfs_main_loop *ml, guestfs_h *g, void *data,
1814 int watch, int fd, int events)
1820 "sock_write_event: %p g->state = %d, fd = %d, events = 0x%x\n",
1821 g, g->state, fd, events);
1823 if (g->sock != fd) {
1824 error (g, _("sock_write_event: internal error: %d != %d"), g->sock, fd);
1828 if (g->state != BUSY) {
1829 error (g, _("sock_write_event: state %d != BUSY"), g->state);
1834 fprintf (stderr, "sock_write_event: writing %d bytes ...\n",
1835 g->msg_out_size - g->msg_out_pos);
1837 n = write (g->sock, g->msg_out + g->msg_out_pos,
1838 g->msg_out_size - g->msg_out_pos);
1842 perrorf (g, "write");
1843 if (err == EPIPE) /* Disconnected from guest (RHBZ#508713). */
1849 fprintf (stderr, "sock_write_event: wrote %d bytes\n", n);
1851 g->msg_out_pos += n;
1853 /* More to write? */
1854 if (g->msg_out_pos < g->msg_out_size)
1858 fprintf (stderr, "sock_write_event: done writing, calling send_cb\n");
1862 g->msg_out_pos = g->msg_out_size = 0;
1864 /* Done writing, call the higher layer. */
1866 g->send_cb (g, g->send_cb_data);
1870 guestfs_set_send_callback (guestfs_h *g,
1871 guestfs_send_cb cb, void *opaque)
1874 g->send_cb_data = opaque;
1878 guestfs_set_reply_callback (guestfs_h *g,
1879 guestfs_reply_cb cb, void *opaque)
1882 g->reply_cb_data = opaque;
1886 guestfs_set_log_message_callback (guestfs_h *g,
1887 guestfs_log_message_cb cb, void *opaque)
1889 g->log_message_cb = cb;
1890 g->log_message_cb_data = opaque;
1894 guestfs_set_subprocess_quit_callback (guestfs_h *g,
1895 guestfs_subprocess_quit_cb cb, void *opaque)
1897 g->subprocess_quit_cb = cb;
1898 g->subprocess_quit_cb_data = opaque;
1902 guestfs_set_launch_done_callback (guestfs_h *g,
1903 guestfs_launch_done_cb cb, void *opaque)
1905 g->launch_done_cb = cb;
1906 g->launch_done_cb_data = opaque;
1909 /* Access to the handle's main loop and the default main loop. */
1911 guestfs_set_main_loop (guestfs_h *g, guestfs_main_loop *main_loop)
1913 g->main_loop = main_loop;
1917 guestfs_get_main_loop (guestfs_h *g)
1919 return g->main_loop;
1923 guestfs_get_default_main_loop (void)
1925 return (guestfs_main_loop *) &default_main_loop;
1928 /* Change the daemon socket handler so that we are now writing.
1929 * This sets the handle to sock_write_event.
1932 guestfs__switch_to_sending (guestfs_h *g)
1934 if (g->sock_watch >= 0) {
1935 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1936 error (g, _("remove_handle failed"));
1943 g->main_loop->add_handle (g->main_loop, g, g->sock,
1944 GUESTFS_HANDLE_WRITABLE,
1945 sock_write_event, NULL);
1946 if (g->sock_watch == -1) {
1947 error (g, _("add_handle failed"));
1955 guestfs__switch_to_receiving (guestfs_h *g)
1957 if (g->sock_watch >= 0) {
1958 if (g->main_loop->remove_handle (g->main_loop, g, g->sock_watch) == -1) {
1959 error (g, _("remove_handle failed"));
1966 g->main_loop->add_handle (g->main_loop, g, g->sock,
1967 GUESTFS_HANDLE_READABLE,
1968 sock_read_event, NULL);
1969 if (g->sock_watch == -1) {
1970 error (g, _("add_handle failed"));
1977 /* Dispatch a call (len + header + args) to the remote daemon,
1978 * synchronously (ie. using the guest's main loop to wait until
1979 * it has been sent). Returns -1 for error, or the serial
1980 * number of the message.
1983 send_cb (guestfs_h *g, void *data)
1985 guestfs_main_loop *ml = guestfs_get_main_loop (g);
1988 ml->main_loop_quit (ml, g);
1992 guestfs__send_sync (guestfs_h *g, int proc_nr,
1993 xdrproc_t xdrp, char *args)
1995 struct guestfs_message_header hdr;
1998 int serial = g->msg_next_serial++;
2000 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2002 if (g->state != BUSY) {
2003 error (g, _("guestfs__send_sync: state %d != BUSY"), g->state);
2007 /* This is probably an internal error. Or perhaps we should just
2008 * free the buffer anyway?
2010 if (g->msg_out != NULL) {
2011 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2015 /* We have to allocate this message buffer on the heap because
2016 * it is quite large (although will be mostly unused). We
2017 * can't allocate it on the stack because in some environments
2018 * we have quite limited stack space available, notably when
2019 * running in the JVM.
2021 g->msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
2022 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);
2024 /* Serialize the header. */
2025 hdr.prog = GUESTFS_PROGRAM;
2026 hdr.vers = GUESTFS_PROTOCOL_VERSION;
2028 hdr.direction = GUESTFS_DIRECTION_CALL;
2029 hdr.serial = serial;
2030 hdr.status = GUESTFS_STATUS_OK;
2032 if (!xdr_guestfs_message_header (&xdr, &hdr)) {
2033 error (g, _("xdr_guestfs_message_header failed"));
2037 /* Serialize the args. If any, because some message types
2038 * have no parameters.
2041 if (!(*xdrp) (&xdr, args)) {
2042 error (g, _("dispatch failed to marshal args"));
2047 /* Get the actual length of the message, resize the buffer to match
2048 * the actual length, and write the length word at the beginning.
2050 len = xdr_getpos (&xdr);
2053 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2054 g->msg_out_size = len + 4;
2057 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2058 xdr_uint32_t (&xdr, &len);
2060 if (guestfs__switch_to_sending (g) == -1)
2064 guestfs_set_send_callback (g, send_cb, &sent);
2065 if (ml->main_loop_run (ml, g) == -1)
2068 error (g, _("send failed, see earlier error messages"));
2077 g->msg_out_size = 0;
2081 static int cancel = 0; /* XXX Implement file cancellation. */
2082 static int send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t len);
2083 static int send_file_data_sync (guestfs_h *g, const char *buf, size_t len);
2084 static int send_file_cancellation_sync (guestfs_h *g);
2085 static int send_file_complete_sync (guestfs_h *g);
2087 /* Synchronously send a file.
2091 * -2 daemon cancelled (we must read the error message)
2094 guestfs__send_file_sync (guestfs_h *g, const char *filename)
2096 char buf[GUESTFS_MAX_CHUNK_SIZE];
2099 fd = open (filename, O_RDONLY);
2101 perrorf (g, "open: %s", filename);
2102 send_file_cancellation_sync (g);
2103 /* Daemon sees cancellation and won't reply, so caller can
2109 /* Send file in chunked encoding. */
2111 r = read (fd, buf, sizeof buf);
2112 if (r == -1 && (errno == EINTR || errno == EAGAIN))
2115 err = send_file_data_sync (g, buf, r);
2117 if (err == -2) /* daemon sent cancellation */
2118 send_file_cancellation_sync (g);
2123 if (cancel) { /* cancel from either end */
2124 send_file_cancellation_sync (g);
2129 perrorf (g, "read: %s", filename);
2130 send_file_cancellation_sync (g);
2134 /* End of file, but before we send that, we need to close
2135 * the file and check for errors.
2137 if (close (fd) == -1) {
2138 perrorf (g, "close: %s", filename);
2139 send_file_cancellation_sync (g);
2143 return send_file_complete_sync (g);
2146 /* Send a chunk of file data. */
2148 send_file_data_sync (guestfs_h *g, const char *buf, size_t len)
2150 return send_file_chunk_sync (g, 0, buf, len);
2153 /* Send a cancellation message. */
2155 send_file_cancellation_sync (guestfs_h *g)
2157 return send_file_chunk_sync (g, 1, NULL, 0);
2160 /* Send a file complete chunk. */
2162 send_file_complete_sync (guestfs_h *g)
2165 return send_file_chunk_sync (g, 0, buf, 0);
2168 /* Send a chunk, cancellation or end of file, synchronously (ie. wait
2171 static int check_for_daemon_cancellation (guestfs_h *g);
2174 send_file_chunk_sync (guestfs_h *g, int cancel, const char *buf, size_t buflen)
2178 guestfs_chunk chunk;
2180 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2182 if (g->state != BUSY) {
2183 error (g, _("send_file_chunk_sync: state %d != READY"), g->state);
2187 /* This is probably an internal error. Or perhaps we should just
2188 * free the buffer anyway?
2190 if (g->msg_out != NULL) {
2191 error (g, _("guestfs__send_sync: msg_out should be NULL"));
2195 /* Did the daemon send a cancellation message? */
2196 if (check_for_daemon_cancellation (g)) {
2198 fprintf (stderr, "got daemon cancellation\n");
2202 /* Allocate the chunk buffer. Don't use the stack to avoid
2203 * excessive stack usage and unnecessary copies.
2205 g->msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
2206 xdrmem_create (&xdr, g->msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);
2208 /* Serialize the chunk. */
2209 chunk.cancel = cancel;
2210 chunk.data.data_len = buflen;
2211 chunk.data.data_val = (char *) buf;
2213 if (!xdr_guestfs_chunk (&xdr, &chunk)) {
2214 error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
2220 len = xdr_getpos (&xdr);
2223 /* Reduce the size of the outgoing message buffer to the real length. */
2224 g->msg_out = safe_realloc (g, g->msg_out, len + 4);
2225 g->msg_out_size = len + 4;
2228 xdrmem_create (&xdr, g->msg_out, 4, XDR_ENCODE);
2229 xdr_uint32_t (&xdr, &len);
2231 if (guestfs__switch_to_sending (g) == -1)
2235 guestfs_set_send_callback (g, send_cb, &sent);
2236 if (ml->main_loop_run (ml, g) == -1)
2239 error (g, _("send file chunk failed, see earlier error messages"));
2248 g->msg_out_size = 0;
2252 /* At this point we are sending FileIn file(s) to the guest, and not
2253 * expecting to read anything, so if we do read anything, it must be
2254 * a cancellation message. This checks for this case without blocking.
2257 check_for_daemon_cancellation (guestfs_h *g)
2267 FD_SET (g->sock, &rset);
2270 r = select (g->sock+1, &rset, NULL, NULL, &tv);
2272 perrorf (g, "select");
2278 /* Read the message from the daemon. */
2279 r = xread (g->sock, buf, sizeof buf);
2281 perrorf (g, "read");
2285 xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
2286 xdr_uint32_t (&xdr, &flag);
2289 if (flag != GUESTFS_CANCEL_FLAG) {
2290 error (g, _("check_for_daemon_cancellation: read 0x%x from daemon, expected 0x%x\n"),
2291 flag, GUESTFS_CANCEL_FLAG);
2298 /* Synchronously receive a file. */
2300 /* Returns -1 = error, 0 = EOF, 1 = more data */
2301 static int receive_file_data_sync (guestfs_h *g, void **buf, size_t *len);
2304 guestfs__receive_file_sync (guestfs_h *g, const char *filename)
2310 fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2312 perrorf (g, "open: %s", filename);
2316 /* Receive the file in chunked encoding. */
2317 while ((r = receive_file_data_sync (g, &buf, &len)) >= 0) {
2318 if (xwrite (fd, buf, len) == -1) {
2319 perrorf (g, "%s: write", filename);
2324 if (r == 0) break; /* End of file. */
2328 error (g, _("%s: error in chunked encoding"), filename);
2332 if (close (fd) == -1) {
2333 perrorf (g, "close: %s", filename);
2340 /* Send cancellation message to daemon, then wait until it
2341 * cancels (just throwing away data).
2345 uint32_t flag = GUESTFS_CANCEL_FLAG;
2348 fprintf (stderr, "%s: waiting for daemon to acknowledge cancellation\n",
2351 xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
2352 xdr_uint32_t (&xdr, &flag);
2355 if (xwrite (g->sock, fbuf, sizeof fbuf) == -1) {
2356 perrorf (g, _("write to daemon socket"));
2360 while ((r = receive_file_data_sync (g, NULL, NULL)) > 0)
2361 ; /* just discard it */
2366 /* Note that the reply callback can be called multiple times before
2367 * the main loop quits and we get back to the synchronous code. So
2368 * we have to be prepared to save multiple chunks on a list here.
2370 struct receive_file_ctx {
2371 int count; /* 0 if receive_file_cb not called, or
2372 * else count number of chunks.
2374 guestfs_chunk *chunks; /* Array of chunks. */
2378 free_chunks (struct receive_file_ctx *ctx)
2382 for (i = 0; i < ctx->count; ++i)
2383 free (ctx->chunks[i].data.data_val);
2389 receive_file_cb (guestfs_h *g, void *data, XDR *xdr)
2391 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2392 struct receive_file_ctx *ctx = (struct receive_file_ctx *) data;
2393 guestfs_chunk chunk;
2395 if (ctx->count == -1) /* Parse error occurred previously. */
2398 ml->main_loop_quit (ml, g);
2400 memset (&chunk, 0, sizeof chunk);
2402 if (!xdr_guestfs_chunk (xdr, &chunk)) {
2403 error (g, _("failed to parse file chunk"));
2410 /* Copy the chunk to the list. */
2411 ctx->chunks = safe_realloc (g, ctx->chunks,
2412 sizeof (guestfs_chunk) * (ctx->count+1));
2413 ctx->chunks[ctx->count] = chunk;
2417 /* Receive a chunk of file data. */
2418 /* Returns -1 = error, 0 = EOF, 1 = more data */
2420 receive_file_data_sync (guestfs_h *g, void **buf, size_t *len_r)
2422 struct receive_file_ctx ctx;
2423 guestfs_main_loop *ml = guestfs_get_main_loop (g);
2430 guestfs_set_reply_callback (g, receive_file_cb, &ctx);
2431 (void) ml->main_loop_run (ml, g);
2432 guestfs_set_reply_callback (g, NULL, NULL);
2434 if (ctx.count == 0) {
2435 error (g, _("receive_file_data_sync: reply callback not called\n"));
2439 if (ctx.count == -1) {
2440 error (g, _("receive_file_data_sync: parse error in reply callback\n"));
2441 /* callback already freed the chunks */
2446 fprintf (stderr, "receive_file_data_sync: got %d chunks\n", ctx.count);
2448 /* Process each chunk in the list. */
2449 if (buf) *buf = NULL; /* Accumulate data in this buffer. */
2452 for (i = 0; i < ctx.count; ++i) {
2453 if (ctx.chunks[i].cancel) {
2454 error (g, _("file receive cancelled by daemon"));
2456 if (buf) free (*buf);
2457 if (len_r) *len_r = 0;
2461 if (ctx.chunks[i].data.data_len == 0) { /* end of transfer */
2463 if (len_r) *len_r = len;
2468 *buf = safe_realloc (g, *buf, len + ctx.chunks[i].data.data_len);
2469 memcpy (*buf+len, ctx.chunks[i].data.data_val,
2470 ctx.chunks[i].data.data_len);
2472 len += ctx.chunks[i].data.data_len;
2475 if (len_r) *len_r = len;
2480 /* This is the default main loop implementation, using select(2). */
2483 select_add_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd, int events,
2484 guestfs_handle_event_cb cb, void *data)
2486 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2488 if (fd < 0 || fd >= FD_SETSIZE) {
2489 error (g, _("fd %d is out of range"), fd);
2493 if ((events & ~(GUESTFS_HANDLE_READABLE |
2494 GUESTFS_HANDLE_WRITABLE |
2495 GUESTFS_HANDLE_HANGUP |
2496 GUESTFS_HANDLE_ERROR)) != 0) {
2497 error (g, _("set of events (0x%x) contains unknown events"), events);
2502 error (g, _("set of events is empty"));
2506 if (FD_ISSET (fd, &ml->rset) ||
2507 FD_ISSET (fd, &ml->wset) ||
2508 FD_ISSET (fd, &ml->xset)) {
2509 error (g, _("fd %d is already registered"), fd);
2514 error (g, _("callback is NULL"));
2518 if ((events & GUESTFS_HANDLE_READABLE))
2519 FD_SET (fd, &ml->rset);
2520 if ((events & GUESTFS_HANDLE_WRITABLE))
2521 FD_SET (fd, &ml->wset);
2522 if ((events & GUESTFS_HANDLE_HANGUP) || (events & GUESTFS_HANDLE_ERROR))
2523 FD_SET (fd, &ml->xset);
2525 if (fd > ml->max_fd) {
2527 ml->handle_cb_data =
2528 safe_realloc (g, ml->handle_cb_data,
2529 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2531 ml->handle_cb_data[fd].cb = cb;
2532 ml->handle_cb_data[fd].g = g;
2533 ml->handle_cb_data[fd].data = data;
2537 /* Any integer >= 0 can be the handle, and this is as good as any ... */
2542 select_remove_handle (guestfs_main_loop *mlv, guestfs_h *g, int fd)
2544 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2546 if (fd < 0 || fd >= FD_SETSIZE) {
2547 error (g, _("fd %d is out of range"), fd);
2551 if (!FD_ISSET (fd, &ml->rset) &&
2552 !FD_ISSET (fd, &ml->wset) &&
2553 !FD_ISSET (fd, &ml->xset)) {
2554 error (g, _("fd %d was not registered"), fd);
2558 FD_CLR (fd, &ml->rset);
2559 FD_CLR (fd, &ml->wset);
2560 FD_CLR (fd, &ml->xset);
2562 if (fd == ml->max_fd) {
2564 ml->handle_cb_data =
2565 safe_realloc (g, ml->handle_cb_data,
2566 sizeof (struct select_handle_cb_data) * (ml->max_fd+1));
2575 select_add_timeout (guestfs_main_loop *mlv, guestfs_h *g, int interval,
2576 guestfs_handle_timeout_cb cb, void *data)
2578 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2580 abort (); /* XXX not implemented yet */
2584 select_remove_timeout (guestfs_main_loop *mlv, guestfs_h *g, int timer)
2586 //struct select_main_loop *ml = (struct select_main_loop *) mlv;
2588 abort (); /* XXX not implemented yet */
2591 /* The 'g' parameter is just used for error reporting. Events
2592 * for multiple handles can be dispatched by running the main
2596 select_main_loop_run (guestfs_main_loop *mlv, guestfs_h *g)
2598 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2600 fd_set rset2, wset2, xset2;
2602 if (ml->is_running) {
2603 error (g, _("select_main_loop_run: this cannot be called recursively"));
2609 while (ml->is_running) {
2610 if (ml->nr_fds == 0)
2616 r = select (ml->max_fd+1, &rset2, &wset2, &xset2, NULL);
2618 if (errno == EINTR || errno == EAGAIN)
2620 perrorf (g, "select");
2625 for (fd = 0; r > 0 && fd <= ml->max_fd; ++fd) {
2627 if (FD_ISSET (fd, &rset2))
2628 events |= GUESTFS_HANDLE_READABLE;
2629 if (FD_ISSET (fd, &wset2))
2630 events |= GUESTFS_HANDLE_WRITABLE;
2631 if (FD_ISSET (fd, &xset2))
2632 events |= GUESTFS_HANDLE_ERROR | GUESTFS_HANDLE_HANGUP;
2635 ml->handle_cb_data[fd].cb ((guestfs_main_loop *) ml,
2636 ml->handle_cb_data[fd].g,
2637 ml->handle_cb_data[fd].data,
2648 select_main_loop_quit (guestfs_main_loop *mlv, guestfs_h *g)
2650 struct select_main_loop *ml = (struct select_main_loop *) mlv;
2652 /* Note that legitimately ml->is_running can be zero when
2653 * this function is called.